code wiki / _hdl_build / nx_browser_render.nx
nx_browser_render.nx source
↩ module page · 1721 lines · 99533 B
1// nx_browser_render.nx -- REUSABLE sovereign CSS render core. Holds nx_browser's OS-AGNOSTIC pipeline:
2// br_layout (HTML body -> CSS cascade -> box/flex/float layout -> LayoutTree + computed styles) and
3// br_draw_fb / br_shot_png (paint the laid-out page into an RGBA framebuffer / PNG). NO X11, NO network --
4// pure compute over sys_mmap, so it compiles into the native-Windows GUI PE exactly as into the WSL/X11
5// browser. The window/blit/input + fetch live in the consumers. CSS-on-native-Windows arc R2.
6// NOTE (R3 dedup pending): these fns are still ALSO defined in runtime/_hdl_build/nx_browser.nx; once this
7// organ is proven, nx_browser.nx imports this and drops its copies. license_tier: ORIGINAL
8import "nx_syscalls.nx"
9import "nx_font8x8.nx"
10import "nx_html_tokenizer.nx"
11import "nx_dom_query.nx"
12import "nx_srcset_lib.nx" // BR14: bi_img_source/bi_srcset -- WHICH url an <img> actually points at
13import "nx_html_entities.nx"
14import "nx_render_html.nx"
15import "nx_css_color_decode.nx"
16import "nx_layout_box.nx"
17import "nx_layout_default_display.nx"
18import "nx_layout_from_dom.nx"
19import "nx_layout_block.nx"
20import "nx_paint_solid_rect.nx"
21import "nx_paint_text.nx"
22import "nx_png_write.nx"
23import "nx_font.nx" // sovereign stroke-VECTOR font (modern heading typeface) + metrics
24import "nx_aa_raster.nx" // AA contour rasterizer for the vector glyphs
25import "nx_ttf_fontlib.nx" // REAL TrueType faces (BR4, 2026-09-02): outlines + hmtx + kern through the same atlas
26
27struct Page {
28 buf: *u8,
29 tree: *LayoutTree,
30 computed: *CssComputedDecl,
31 ncomp: i64,
32 page_h: i64,
33 bhref_off: *i64, // per box_idx: href byte-offset into buf, or -1
34 bhref_len: *i64,
35 ok: i64,
36 raw: *u8, // fetched response body (kept so resize can re-layout WITHOUT re-fetching)
37 raw_len: i64,
38 bsrc_off: *i64, // per box_idx: <img src> byte-offset into buf, or -1
39 bsrc_len: *i64,
40 bimg: *i64, // per box_idx: decoded RGB (w*h*3) pointer, or 0 (filled by the consumer)
41 bimg_w: *i64, // per box_idx: decoded image width
42 bimg_h: *i64, // per box_idx: decoded image height
43 find_ptr: i64, // FIND-IN-PAGE: search-term bytes (as i64 ptr), 0 = no active find
44 find_len: i64, // search-term length
45 vec_headings: i64, // 1 = paint headings with the sovereign stroke-VECTOR font (modern typeface);
46 // 0 = bitmap (default; native-GUI 60fps stays alloc-free). Set by once-render organs.
47 dark_mode: i64, // 1 = dark reader theme (the OLED look): dark bg + light text default stylesheet.
48 // Set BEFORE br_layout (it selects the injected default CSS). 0 = light (default).
49 bcanvas: *i64 // per box_idx: 1 = <canvas> -- a FIRST-CLASS SOURCELESS render surface (seq103):
50 // the consumer fills page.bimg[i]/bimg_w/bimg_h each FRAME and repaints; the
51 // image pass blits the CURRENT buffer at the laid-out box (the game substrate).
52 bsrc_lazy: *i64, // per box_idx: 1 = the <img> declared loading="lazy" (BR14). A REPORT, never a
53 // filter: a renderer painting the whole document must still fetch these, and
54 // suppressing them is precisely how a media page renders blank. Its use is
55 // ORDERING -- a consumer with a BOUNDED fetch budget spends it eager-first.
56 dpr_permil: i64 // device pixels per CSS pixel, in permil, for srcset density selection.
57 // 0 = UNSET, which this core reads as 1x (BI_PERMIL_ONE) -- the identity, not
58 // a tuned default. A consumer that paints at scale N sets N*BI_PERMIL_ONE.
59}
60// COUNT THE FIELDS ABOVE, do not hand-count the bytes. Every Page field is one i64 or one pointer, so
61// the size is DERIVED from the field count -- the previous literal 160 was a second copy of the struct's
62// shape that could (and now would) drift the moment a field was added.
63const NX_PAGE_FIELDS: i64 = 22
64const NX_PAGE_FIELD_BYTES: i64 = 8
65const NX_PAGE_BYTES: i64 = NX_PAGE_FIELDS * NX_PAGE_FIELD_BYTES
66const NX_CHROME_H: i64 = 44 // browser chrome (toolbar + address bar) height; page viewport is below it
67
68func br_slen(s: *u8) -> i64 { var k: i64=0; while s[k]!=(0 as u8){k=k+1} return k }
69
70// ---- PER-BOX COMPUTED-DECL INDEX (the eagler paint-cliff fix): br_comp_* used to scan ALL ncomp decls
71// per lookup, per box, per ancestor hop -- O(boxes x ancestors x ncomp) exploded on Next.js-scale CSS
72// (layout <20s, paint >170s). br_cidx_build buckets the computed array BY ELEMENT (stable copy = cascade
73// order preserved within each element, so reverse scan = the same last-wins winner), and every br_comp_*
74// then scans only that box's bucket. OFF by default (statics 0) -> gates with hand-built arrays are
75// byte-identical; br_layout switches it off during its run and rebuilds at the end. ----
76static br_cidx_on: i64
77static br_cidx_arr: i64 // *CssComputedDecl grouped copy (alloc once, reused)
78static br_cidx_first: i64 // *i64 per box: bucket start
79static br_cidx_cnt: i64 // *i64 per box: bucket len
80static br_cidx_cur: i64 // *i64 scratch cursor
81static br_cidx_nbox: i64
82static br_cidx_src: i64 // the computed-array pointer the index was built FROM: every window guard
83 // checks it, so querying a DIFFERENT page's array (multi-page gates) falls
84 // back to the full scan instead of reading a stale index (self-validating)
85
86func br_cidx_build(tree: *LayoutTree, computed: *CssComputedDecl, ncomp: i64) -> i64 {
87 let nbox: i64 = tree.count
88 if br_cidx_arr == 0 {
89 br_cidx_arr = sys_mmap((NX_CSS_COMPUTED_DECL_BYTES * 262144) as nx_size) as i64
90 br_cidx_first = sys_mmap((16384 * 8) as nx_size) as i64
91 br_cidx_cnt = sys_mmap((16384 * 8) as nx_size) as i64
92 br_cidx_cur = sys_mmap((16384 * 8) as nx_size) as i64
93 }
94 if nbox > 16384 { br_cidx_on = 0; return 0 }
95 if ncomp > 262144 { br_cidx_on = 0; return 0 }
96 let ff: *i64 = br_cidx_first as *i64
97 let cc: *i64 = br_cidx_cnt as *i64
98 let cu: *i64 = br_cidx_cur as *i64
99 var i: i64 = 0
100 while i < nbox { cc[i] = 0; i = i + 1 }
101 var j: i64 = 0
102 while j < ncomp {
103 let cd: *CssComputedDecl = ((computed as i64) + j * NX_CSS_COMPUTED_DECL_BYTES) as *CssComputedDecl
104 let e: i64 = cd.element_idx
105 if e >= 0 { if e < nbox { cc[e] = cc[e] + 1 } }
106 j = j + 1
107 }
108 var acc: i64 = 0
109 i = 0
110 while i < nbox { ff[i] = acc; cu[i] = acc; acc = acc + cc[i]; i = i + 1 }
111 // stable grouped copy (struct copy field-by-field; 64B decls)
112 let dst0: i64 = br_cidx_arr
113 j = 0
114 while j < ncomp {
115 let cd2: *CssComputedDecl = ((computed as i64) + j * NX_CSS_COMPUTED_DECL_BYTES) as *CssComputedDecl
116 let e2: i64 = cd2.element_idx
117 if e2 >= 0 { if e2 < nbox {
118 let dp: *CssComputedDecl = (dst0 + cu[e2] * NX_CSS_COMPUTED_DECL_BYTES) as *CssComputedDecl
119 dp.element_idx = cd2.element_idx
120 dp.prop_off = cd2.prop_off
121 dp.prop_len = cd2.prop_len
122 dp.val_kind = cd2.val_kind
123 dp.val_off = cd2.val_off
124 dp.val_len = cd2.val_len
125 dp.unit_off = cd2.unit_off
126 dp.unit_len = cd2.unit_len
127 cu[e2] = cu[e2] + 1
128 } }
129 j = j + 1
130 }
131 br_cidx_nbox = nbox
132 br_cidx_src = computed as i64
133 br_cidx_on = 1
134 return 0
135}
136func br_comp_int(src: *u8, computed: *CssComputedDecl, ncomp: i64, box_idx: i64, prop: *u8, plen: i64, dflt: i64) -> i64 {
137 var base: i64 = computed as i64
138 var lo: i64 = 0
139 var hi: i64 = ncomp
140 if br_cidx_on == 1 { if (computed as i64) == br_cidx_src { if box_idx >= 0 { if box_idx < br_cidx_nbox {
141 let ff: *i64 = br_cidx_first as *i64
142 let cc: *i64 = br_cidx_cnt as *i64
143 base = br_cidx_arr
144 lo = ff[box_idx]
145 hi = lo + cc[box_idx]
146 } } } }
147 var j: i64 = hi - 1
148 while j >= lo {
149 let cd: *CssComputedDecl = (base + j * NX_CSS_COMPUTED_DECL_BYTES) as *CssComputedDecl
150 if cd.element_idx == box_idx { if cd.prop_len == plen {
151 var ok: i64 = 1; var k: i64 = 0
152 while k < plen { if (src[cd.prop_off+k]&0xff) != (prop[k]&0xff) { ok=0; k=plen } else { k=k+1 } }
153 if ok == 1 {
154 // integer-truncate at the decimal point ("13.5px" is 13, NOT 135 -- the same skip-the-dot
155 // digit-accumulator bug fixed in _layout_fontsize_decl_px; measure==paint requires both)
156 var v: i64 = 0; var any: i64 = 0; var i: i64 = 0
157 while i < cd.val_len {
158 let c: i64 = src[cd.val_off+i]&0xff
159 if c == 46 { i = cd.val_len }
160 else { if c>=48 { if c<=57 { v=v*10+(c-48); any=1 } } i=i+1 }
161 }
162 if any == 1 { return v }
163 return dflt
164 }
165 } }
166 j = j - 1
167 }
168 return dflt
169}
170func br_comp_color(src: *u8, computed: *CssComputedDecl, ncomp: i64, box_idx: i64, prop: *u8, plen: i64) -> i64 {
171 var base: i64 = computed as i64
172 var lo: i64 = 0
173 var hi: i64 = ncomp
174 if br_cidx_on == 1 { if (computed as i64) == br_cidx_src { if box_idx >= 0 { if box_idx < br_cidx_nbox {
175 let ff: *i64 = br_cidx_first as *i64
176 let cc: *i64 = br_cidx_cnt as *i64
177 base = br_cidx_arr
178 lo = ff[box_idx]
179 hi = lo + cc[box_idx]
180 } } } }
181 var j: i64 = hi - 1
182 while j >= lo {
183 let cd: *CssComputedDecl = (base + j * NX_CSS_COMPUTED_DECL_BYTES) as *CssComputedDecl
184 if cd.element_idx == box_idx { if cd.prop_len == plen {
185 var ok: i64 = 1; var k: i64 = 0
186 while k < plen { if (src[cd.prop_off+k]&0xff) != (prop[k]&0xff) { ok=0; k=plen } else { k=k+1 } }
187 if ok == 1 {
188 let col: *CssColor = (sys_mmap(NX_CSS_COLOR_BYTES as nx_size)) as *CssColor
189 var got: i64 = 0
190 if cd.val_kind == NX_CSS_VAL_HEXCOLOR { got = nx_css_color_decode(src, cd.val_off, cd.val_len, col) }
191 else { if cd.val_kind == NX_CSS_VAL_IDENT { got = nx_css_color_named(src, cd.val_off, cd.val_len, col); if got != 1 { got = nx_css_color_rgb_func(src, cd.val_off, cd.val_len, col) } } }
192 if got == 1 { if col.a >= 128 { return (col.r << 16) | (col.g << 8) | col.b } } // SOLID painter: <50% alpha = tint, not paint (linkedin rgba(0,0,0,0.08) painted BLACK, 2026-07-28)
193 return 0 - 1
194 }
195 } }
196 j = j - 1
197 }
198 return 0 - 1
199}
200
201// INHERITED color resolve (CSS: `color` inherits): walk up the parent chain to the nearest box with a
202// computed color decl. Without this, author colors on body/.doc never reached p/li/td TEXT (the UA sheet
203// only "worked" because it fakes inheritance with explicit p{color}/li{color} rules -- measured 07-09).
204// FONT-SIZE resolver for one element: matches `font-size` (integer-truncating parse) OR the `font`
205// SHORTHAND when the value leads with a size ("15px/1.55 system-ui") -- one bucketed reverse scan across
206// both = last-wins cascade between them. MIRRORS _layout_fontsize_decl_px exactly (measure==paint law).
207// `pct_out[0]` <- 1 when the declared value is a PERCENTAGE; the return is then the percentage
208// number itself, which br_comp_fontsize_inh resolves against the parent. Mirrors the layout-side
209// _layout_fontsize_decl_px signature exactly (measure==paint law: if only one side learned about
210// percentages, every styled run would overflow its reserved box and split mid-word).
211func br_comp_fontsize_own(src: *u8, computed: *CssComputedDecl, ncomp: i64, box_idx: i64, pct_out: *i64) -> i64 {
212 var base: i64 = computed as i64
213 var lo: i64 = 0
214 var hi: i64 = ncomp
215 if br_cidx_on == 1 { if (computed as i64) == br_cidx_src { if box_idx >= 0 { if box_idx < br_cidx_nbox {
216 let ff: *i64 = br_cidx_first as *i64
217 let cc: *i64 = br_cidx_cnt as *i64
218 base = br_cidx_arr
219 lo = ff[box_idx]
220 hi = lo + cc[box_idx]
221 } } } }
222 var j: i64 = hi - 1
223 while j >= lo {
224 let cd: *CssComputedDecl = (base + j * NX_CSS_COMPUTED_DECL_BYTES) as *CssComputedDecl
225 if cd.element_idx == box_idx {
226 if cd.prop_len == 4 { if br_prop_eq(src, cd.prop_off, "font\x00" as *u8, 4) == 1 {
227 let c0: i64 = (src[cd.val_off] as i64) & 255
228 if c0 >= 48 { if c0 <= 57 {
229 var v4: i64 = 0
230 var j4: i64 = 0
231 var g4: i64 = 1
232 while g4 == 1 {
233 if j4 >= cd.val_len { g4 = 0 }
234 else {
235 let c4: i64 = (src[cd.val_off + j4] as i64) & 255
236 if c4 >= 48 { if c4 <= 57 { v4 = v4 * 10 + (c4 - 48); j4 = j4 + 1 } else { g4 = 0 } } else { g4 = 0 }
237 }
238 }
239 if v4 > 0 { return v4 }
240 } }
241 } }
242 if cd.prop_len == 9 { if br_prop_eq(src, cd.prop_off, "font-size\x00" as *u8, 9) == 1 {
243 // ONE value resolver, shared with the measure side (nx_fontsize_value_px lives in
244 // nx_layout_block.nx which this file imports): px/%/em/rem/fractions, calc()/keywords
245 // dropped (-1) -> fall through to the older cascade decl. measure==paint BY CONSTRUCTION.
246 let fv: i64 = nx_fontsize_value_px(src, cd.val_off, cd.val_len, cd.unit_off, cd.unit_len, pct_out)
247 if fv >= 0 { return fv }
248 } }
249 }
250 j = j - 1
251 }
252 return 0 - 1
253}
254// LINE-HEIGHT resolver (paint mirror of _layout_lineheight_decl_px/_layout_lineheight_px -- measure==paint
255// law): `line-height: 1.55` unitless multiplier of fs / `line-height: 24px` / the `font` shorthand's /N.
256// Bucketed reverse scan per element; nearest ancestor with a decl wins. Returns px or -1.
257func br_comp_lineheight_own(src: *u8, computed: *CssComputedDecl, ncomp: i64, box_idx: i64, fs: i64) -> i64 {
258 var base: i64 = computed as i64
259 var lo: i64 = 0
260 var hi: i64 = ncomp
261 if br_cidx_on == 1 { if (computed as i64) == br_cidx_src { if box_idx >= 0 { if box_idx < br_cidx_nbox {
262 let ff: *i64 = br_cidx_first as *i64
263 let cc: *i64 = br_cidx_cnt as *i64
264 base = br_cidx_arr
265 lo = ff[box_idx]
266 hi = lo + cc[box_idx]
267 } } } }
268 var j: i64 = hi - 1
269 while j >= lo {
270 let cd: *CssComputedDecl = (base + j * NX_CSS_COMPUTED_DECL_BYTES) as *CssComputedDecl
271 if cd.element_idx == box_idx {
272 if cd.prop_len == 11 { if br_prop_eq(src, cd.prop_off, "line-height\x00" as *u8, 11) == 1 {
273 var nl: i64 = 0
274 var ns: i64 = 1
275 while ns == 1 {
276 if nl >= cd.val_len { ns = 0 }
277 else {
278 let c: i64 = (src[cd.val_off + nl] as i64) & 255
279 var isn: i64 = 0
280 if c >= 48 { if c <= 57 { isn = 1 } }
281 if c == 46 { isn = 1 }
282 if isn == 1 { nl = nl + 1 } else { ns = 0 }
283 }
284 }
285 if nl == 0 { return 0 - 1 }
286 let q3: i64 = nx_css_number_parse(src, cd.val_off, nl)
287 if q3 == NX_CSS_NUMBER_PARSE_ERROR { return 0 - 1 }
288 // px unit: DIMENSION tokens carry it in the SEPARATE unit fields (val = digits only);
289 // swept spans carry it inline after the digits. Check both. Unitless requires the value
290 // to be EXACTLY the number (no trailing unit we don't understand -> miss, not 16x).
291 if cd.unit_len == 2 {
292 if ((src[cd.unit_off] as i64) & 255) == 112 { if ((src[cd.unit_off + 1] as i64) & 255) == 120 {
293 return q3 / 1000
294 } }
295 }
296 if nl + 1 < cd.val_len {
297 if ((src[cd.val_off + nl] as i64) & 255) == 112 { if ((src[cd.val_off + nl + 1] as i64) & 255) == 120 {
298 return q3 / 1000
299 } }
300 }
301 if cd.unit_len == 0 { if nl == cd.val_len { return (q3 * fs) / 1000 } }
302 return 0 - 1
303 } }
304 if cd.prop_len == 4 { if br_prop_eq(src, cd.prop_off, "font\x00" as *u8, 4) == 1 {
305 let c0: i64 = (src[cd.val_off] as i64) & 255
306 if c0 >= 48 { if c0 <= 57 {
307 var j2: i64 = 0
308 var sl: i64 = 0 - 1
309 var g: i64 = 1
310 while g == 1 {
311 if j2 >= cd.val_len { g = 0 }
312 else {
313 let cj: i64 = (src[cd.val_off + j2] as i64) & 255
314 if cj == 47 { sl = j2; g = 0 }
315 else { if cj == 32 { g = 0 } else { j2 = j2 + 1 } }
316 }
317 }
318 if sl >= 0 {
319 let vo: i64 = cd.val_off + sl + 1
320 let vmax: i64 = cd.val_len - sl - 1
321 var n2: i64 = 0
322 var g2: i64 = 1
323 while g2 == 1 {
324 if n2 >= vmax { g2 = 0 }
325 else {
326 let c2: i64 = (src[vo + n2] as i64) & 255
327 var isn2: i64 = 0
328 if c2 >= 48 { if c2 <= 57 { isn2 = 1 } }
329 if c2 == 46 { isn2 = 1 }
330 if isn2 == 1 { n2 = n2 + 1 } else { g2 = 0 }
331 }
332 }
333 if n2 > 0 {
334 let q32: i64 = nx_css_number_parse(src, vo, n2)
335 if q32 != NX_CSS_NUMBER_PARSE_ERROR {
336 if n2 + 1 < vmax {
337 if ((src[vo + n2] as i64) & 255) == 112 { if ((src[vo + n2 + 1] as i64) & 255) == 120 {
338 return q32 / 1000
339 } }
340 }
341 return (q32 * fs) / 1000
342 }
343 }
344 }
345 } }
346 } }
347 }
348 j = j - 1
349 }
350 return 0 - 1
351}
352func br_comp_lineheight_px(src: *u8, computed: *CssComputedDecl, ncomp: i64, tree: *LayoutTree, box_idx: i64, fs: i64) -> i64 {
353 var cur: i64 = box_idx
354 var guard: i64 = 0
355 while cur >= 0 {
356 if guard > 64 { return 0 - 1 }
357 guard = guard + 1
358 let v: i64 = br_comp_lineheight_own(src, computed, ncomp, cur, fs)
359 if v >= 0 { return v }
360 let b: *LayoutBox = ((tree.boxes as i64) + cur * NX_LAYOUT_BOX_BYTES) as *LayoutBox
361 cur = b.parent_idx
362 }
363 return 0 - 1
364}
365// INHERITED font-size: nearest ancestor with a font-size OR font-shorthand decl, else dflt.
366func br_comp_fontsize_inh(src: *u8, computed: *CssComputedDecl, ncomp: i64, tree: *LayoutTree, box_idx: i64, dflt: i64) -> i64 {
367 let pct: *i64 = sys_mmap(16) as *i64
368 var cur: i64 = box_idx
369 var guard: i64 = 0
370 while cur >= 0 {
371 if guard > 64 { return dflt }
372 guard = guard + 1
373 pct[0] = 0
374 let v: i64 = br_comp_fontsize_own(src, computed, ncomp, cur, pct)
375 if v >= 0 {
376 if pct[0] == 0 { return v }
377 let bp: *LayoutBox = ((tree.boxes as i64) + cur * NX_LAYOUT_BOX_BYTES) as *LayoutBox
378 let parent_px: i64 = br_comp_fontsize_inh(src, computed, ncomp, tree, bp.parent_idx, dflt)
379 var r: i64 = (parent_px * v) / 100
380 if r < 1 { r = 1 }
381 return r
382 }
383 let b: *LayoutBox = ((tree.boxes as i64) + cur * NX_LAYOUT_BOX_BYTES) as *LayoutBox
384 cur = b.parent_idx
385 }
386 return dflt
387}
388func br_comp_color_inh(src: *u8, computed: *CssComputedDecl, ncomp: i64, tree: *LayoutTree, box_idx: i64) -> i64 {
389 var cur: i64 = box_idx
390 var guard: i64 = 0
391 while cur >= 0 {
392 if guard > 64 { return 0 - 1 }
393 guard = guard + 1
394 let c: i64 = br_comp_color(src, computed, ncomp, cur, "color\x00" as *u8, 5)
395 if c >= 0 { return c }
396 let b: *LayoutBox = ((tree.boxes as i64) + cur * NX_LAYOUT_BOX_BYTES) as *LayoutBox
397 cur = b.parent_idx
398 }
399 return 0 - 1
400}
401
402// background resolve: background-color, else the `background` SHORTHAND's hex value (a single-hex shorthand
403// like background:#eef1f5 tokenizes as HEXCOLOR and decodes; complex shorthands fail closed to -1). bg does
404// NOT inherit in CSS, so no parent walk.
405func br_prop_eq(src: *u8, off: i64, lit: *u8, len: i64) -> i64 {
406 var k: i64 = 0
407 while k < len { if (src[off+k]&0xff) != (lit[k]&0xff) { return 0 } k=k+1 }
408 return 1
409}
410// S21 fix: background must respect CASCADE ORDER across BOTH `background-color` and the `background` shorthand.
411// The old version tried `background-color` first -> the UA sheet's body{background-color:#fff} ALWAYS beat an
412// author body{background:var(--bg)} shorthand -> our dark-theme pages rendered light-text-on-white (invisible).
413// Now: scan from the END (highest cascade) for the LAST decl of EITHER property and decode that.
414func br_comp_bg(src: *u8, computed: *CssComputedDecl, ncomp: i64, box_idx: i64) -> i64 {
415 var base: i64 = computed as i64
416 var lo: i64 = 0
417 var hi: i64 = ncomp
418 if br_cidx_on == 1 { if (computed as i64) == br_cidx_src { if box_idx >= 0 { if box_idx < br_cidx_nbox {
419 let ff: *i64 = br_cidx_first as *i64
420 let cc: *i64 = br_cidx_cnt as *i64
421 base = br_cidx_arr
422 lo = ff[box_idx]
423 hi = lo + cc[box_idx]
424 } } } }
425 var j: i64 = hi - 1
426 while j >= lo {
427 let cd: *CssComputedDecl = (base + j * NX_CSS_COMPUTED_DECL_BYTES) as *CssComputedDecl
428 if cd.element_idx == box_idx {
429 var isbg: i64 = 0
430 if cd.prop_len == 16 { if br_prop_eq(src, cd.prop_off, "background-color\x00" as *u8, 16)==1 { isbg=1 } }
431 if isbg == 0 { if cd.prop_len == 10 { if br_prop_eq(src, cd.prop_off, "background\x00" as *u8, 10)==1 { isbg=1 } } }
432 if isbg == 1 {
433 let col: *CssColor = (sys_mmap(NX_CSS_COLOR_BYTES as nx_size)) as *CssColor
434 var got: i64 = 0
435 if cd.val_kind == NX_CSS_VAL_HEXCOLOR { got = nx_css_color_decode(src, cd.val_off, cd.val_len, col) }
436 else { if cd.val_kind == NX_CSS_VAL_IDENT { got = nx_css_color_named(src, cd.val_off, cd.val_len, col); if got != 1 { got = nx_css_color_rgb_func(src, cd.val_off, cd.val_len, col) } } }
437 if got == 1 { if col.a >= 128 { return (col.r << 16) | (col.g << 8) | col.b } } // SOLID painter: <50% alpha = tint, not paint (linkedin rgba(0,0,0,0.08) painted BLACK, 2026-07-28)
438 return 0 - 1
439 }
440 }
441 j = j - 1
442 }
443 return 0 - 1
444}
445
446// `border` SHORTHAND resolve: the computed value is a swept span like "1px solid #cbd5e1" -- parse the
447// leading width int + the #hex color out of the span. Returns the color (wout[0]=width px, clamped 1..8)
448// or -1 when the box has no parseable border. (border-style variants beyond solid paint as solid -- v1.)
449func br_comp_border(src: *u8, computed: *CssComputedDecl, ncomp: i64, box_idx: i64, wout: *i64) -> i64 {
450 var base: i64 = computed as i64
451 var lo: i64 = 0
452 var hi: i64 = ncomp
453 if br_cidx_on == 1 { if (computed as i64) == br_cidx_src { if box_idx >= 0 { if box_idx < br_cidx_nbox {
454 let ff: *i64 = br_cidx_first as *i64
455 let cc: *i64 = br_cidx_cnt as *i64
456 base = br_cidx_arr
457 lo = ff[box_idx]
458 hi = lo + cc[box_idx]
459 } } } }
460 var j: i64 = hi - 1
461 while j >= lo {
462 let cd: *CssComputedDecl = (base + j * NX_CSS_COMPUTED_DECL_BYTES) as *CssComputedDecl
463 if cd.element_idx == box_idx { if cd.prop_len == 6 {
464 let P: *u8 = "border\x00" as *u8
465 var ok: i64 = 1
466 var k: i64 = 0
467 while k < 6 { if (src[cd.prop_off+k]&0xff) != (P[k]&0xff) { ok=0; k=6 } else { k=k+1 } }
468 if ok == 1 {
469 var wv: i64 = 0
470 var i2: i64 = cd.val_off
471 let e2: i64 = cd.val_off + cd.val_len
472 while i2 < e2 { let ch: i64 = src[i2]&0xff; if ch>=48 { if ch<=57 { wv=wv*10+(ch-48); i2=i2+1 } else { i2=e2 } } else { i2=e2 } }
473 if wv <= 0 { wv = 1 }
474 if wv > 8 { wv = 8 }
475 var hp: i64 = 0 - 1
476 var i3: i64 = cd.val_off
477 while i3 < e2 { if src[i3]==(35 as u8) { hp=i3; i3=e2 } else { i3=i3+1 } }
478 if hp >= 0 {
479 let col: *CssColor = (sys_mmap(NX_CSS_COLOR_BYTES as nx_size)) as *CssColor
480 if nx_css_color_decode(src, hp+1, 6, col) == 1 {
481 wout[0] = wv
482 return (col.r << 16) | (col.g << 8) | col.b
483 }
484 }
485 return 0 - 1
486 }
487 } }
488 j = j - 1
489 }
490 return 0 - 1
491}
492
493// Extract elements (tag/id/class) AND per-element href, mirroring rh_extract's chrome-skip EXACTLY (so the
494// element order == the layout box order). ehref_off/ehref_len get the <a href> span, or -1.
495func br_extract(html: *u8, hlen: i64, elements: *CssElement, ehref_off: *i64, ehref_len: *i64, esrc_off: *i64, esrc_len: *i64, elazy: *i64, vw: i64, dpr_permil: i64, maxn: i64) -> i64 {
496 let c: *HtmlCursor=sys_mmap(24) as *HtmlCursor; nx_html_cursor_init(c,html,hlen)
497 let tok: *HtmlToken=sys_mmap(56) as *HtmlToken
498 let ao: *i64=sys_mmap(8) as *i64; let al: *i64=sys_mmap(8) as *i64; let bo: *i64=sys_mmap(8) as *i64; let bl: *i64=sys_mmap(8) as *i64
499 let ho: *i64=sys_mmap(8) as *i64; let hl: *i64=sys_mmap(8) as *i64
500 // BR14 scratch, allocated ONCE for the whole token walk. nx_srcset_lib deliberately takes its
501 // scratch from the caller so that selecting a source costs no allocation per <img> -- a page with
502 // a thousand figures must not buy a thousand mmaps to answer the same question.
503 let bisc: *i64=sys_mmap(8 * BI_SCRATCH_SLOTS) as *i64
504 var n: i64=0
505 var cskip: i64=0
506 while 1==1 {
507 nx_html_next_token(c,tok)
508 if tok.kind==NX_HTML_TOK_EOF { return n }
509 if n>=maxn { return n }
510 var ie: i64=0
511 if cskip > 0 {
512 // void START tags never get an END -- exempt from depth (MIRRORS nx_layout_from_dom exactly)
513 if tok.kind==NX_HTML_TOK_START_TAG { if _lfd_is_void_tag(html, tok.name_off, tok.name_len) == 0 { cskip = cskip + 1 } }
514 if tok.kind==NX_HTML_TOK_END_TAG { cskip = cskip - 1 }
515 } else {
516 if tok.kind==NX_HTML_TOK_START_TAG {
517 if _lfd_is_chrome_start(html, tok.name_off, tok.name_len, tok.src_off, tok.src_len) == 1 { cskip = 1 }
518 else { ie = 1 }
519 }
520 if tok.kind==NX_HTML_TOK_SELF_CLOSING { ie = 1 }
521 }
522 // RAW-TEXT bodies (script/style/textarea/title) must be consumed with the HTML5 raw-text
523 // scanner, EXACTLY as nx_layout_from_dom does -- br_extract was the consumer that forgot.
524 // Without this, tag-like text inside a JS string ("<div class=...>") mints PHANTOM elements
525 // here that from_dom never boxed, and the positional box<->element pairing in br_layout
526 // SKEWS at the first such script: every later box wears the WRONG identity (wrong classes ->
527 // wrong widths/heights/colors). Control-probe proven 2026-07-28: one phantom-bearing script
528 // before a div shifted even <body> off its own UA padding (x=44 -> 0). The k-map's two
529 // walkers must see the SAME element stream, so this mirror is a CORRECTNESS invariant.
530 if tok.kind==NX_HTML_TOK_START_TAG {
531 if nx_html_is_raw_text_tag(html, tok.name_off, tok.name_len) == 1 {
532 let rawtok: *HtmlToken = sys_mmap(56) as *HtmlToken
533 nx_html_consume_raw_text(c, ((html as i64) + tok.name_off) as *u8, tok.name_len, rawtok)
534 // cursor is left AT the close tag (tokenizer contract) -- the arriving END_TAG token
535 // balances cskip naturally, so NO depth fixup here (a fixup would double-decrement).
536 }
537 }
538 if ie==1 {
539 let e: *CssElement=((elements as i64)+n*NX_CSS_ELEMENT_BYTES) as *CssElement
540 e.src=html; e.tag_off=tok.name_off; e.tag_len=tok.name_len
541 if nx_dom_find_attr(html,tok.src_off,tok.src_len,"id\x00" as *u8,ao,al)==1 { e.id_off=ao[0]; e.id_len=al[0] } else { e.id_off=0; e.id_len=0 }
542 if nx_dom_find_attr(html,tok.src_off,tok.src_len,"class\x00" as *u8,bo,bl)==1 { e.class_off=bo[0]; e.class_len=bl[0] } else { e.class_off=0; e.class_len=0 }
543 ehref_off[n] = 0 - 1; ehref_len[n] = 0 - 1
544 if tok.name_len==1 { if (html[tok.name_off]&0xff)==97 { // <a>
545 if nx_dom_find_attr(html,tok.src_off,tok.src_len,"href\x00" as *u8,ho,hl)==1 { ehref_off[n]=ho[0]; ehref_len[n]=hl[0] }
546 } }
547 esrc_off[n] = 0 - 1; esrc_len[n] = 0 - 1; elazy[n] = 0
548 if tok.name_len==3 { if (html[tok.name_off]&0xff)==105 { if (html[tok.name_off+1]&0xff)==109 { if (html[tok.name_off+2]&0xff)==103 { // <img>
549 // BR14. This line used to read `src` AND NOTHING ELSE, which is the whole of the
550 // `images-lazy` defect: a lazy-loaded <img> parks a data: URI in src and keeps the real
551 // URL in srcset / data-src, so the renderer was handed a placeholder and painted
552 // nothing -- with byte-exact decoders sitting one correct URL away. bi_img_source asks
553 // the browser's question instead ("which source does THIS element resolve to at THIS
554 // viewport") and answers with a byte range into this same buffer, so nothing downstream
555 // of esrc_off changes shape. An <img> carrying only a plain src still takes the src
556 // branch and selects exactly the bytes this line selected before BR14 existed.
557 bi_img_source(html, tok.src_off, tok.src_len, vw, dpr_permil, bisc, ho, hl)
558 esrc_off[n]=ho[0]; esrc_len[n]=hl[0]
559 elazy[n] = bi_img_lazy(html, tok.src_off, tok.src_len, bisc)
560 } } } }
561 n=n+1
562 }
563 }
564 return n
565}
566
567// layout-only pass: (re)build the style buffer + lay out page.raw at viewport width `vw`.
568// Split from the fetch so a window RESIZE re-lays-out at the new width with NO network round-trip.
569func br_layout(page: *Page, vw: i64) -> i64 {
570 page.ok = 0
571 br_cidx_on = 0 // index describes the PREVIOUS layout's array -- off until rebuilt below
572 let body: *u8 = page.raw
573 let body_len: i64 = page.raw_len
574
575 // UA sheet note (07-09): headings + p/li carry NO color -- like real UA sheets they INHERIT body color
576 // (br_comp_color_inh), so author header{color:#fff} / body{color:...} reach them. body keeps the default.
577 var css: *u8 = "h1{margin-top:30px;margin-bottom:16px;font-size:40px}h2{margin-top:28px;margin-bottom:12px;font-size:28px}h3{margin-top:20px;margin-bottom:8px;font-size:22px}body{background-color:#ffffff;color:#2a2a33;padding-left:44px;padding-right:44px;padding-top:22px}p{margin-top:14px;margin-bottom:14px}ul{padding-left:20px;margin-top:6px;margin-bottom:6px}ol{padding-left:28px;margin-top:6px;margin-bottom:6px}li{margin-bottom:5px}table{display:table}tr{display:flex}th{font-weight:bold;padding-left:4px;padding-right:4px}td{padding-left:4px;padding-right:4px}h1{font-weight:bold}h2{font-weight:bold}h3{font-weight:bold}h4{font-weight:bold}h5{font-weight:bold}h6{font-weight:bold}a{color:#2563eb}b{font-weight:bold}strong{font-weight:bold}i{font-style:italic}em{font-style:italic}.vector-menu-content-list{display:none}.vector-dropdown{display:none}.mw-interlanguage-selector{display:none}.wbc-editpage{display:none}.vector-toc{display:none}.vector-toc-list{display:none}.vector-toc-list-item{display:none}.vector-toc-link{display:none}.vector-page-toolbar{display:none}.infobox{float:right;width:300px;margin-left:8px;background-color:#f7f7fa}.nishi-buyguard{background-color:#fff3cd;color:#332701;padding-left:14px;padding-right:14px;padding-top:8px;padding-bottom:8px;margin-bottom:10px;font-size:18px}\x00"
578 // DARK READER THEME (the OLED look): near-black bg + light text; same structure so layout is identical.
579 if page.dark_mode == 1 {
580 css = "h1{margin-top:30px;margin-bottom:16px;font-size:40px}h2{margin-top:28px;margin-bottom:12px;font-size:28px}h3{margin-top:20px;margin-bottom:8px;font-size:22px}body{background-color:#0e1116;color:#d4dae3;padding-left:44px;padding-right:44px;padding-top:22px}p{margin-top:14px;margin-bottom:14px}ul{padding-left:20px;margin-top:6px;margin-bottom:6px}ol{padding-left:28px;margin-top:6px;margin-bottom:6px}li{margin-bottom:5px}table{display:table}tr{display:flex}th{font-weight:bold;padding-left:4px;padding-right:4px}td{padding-left:4px;padding-right:4px}h1{font-weight:bold}h2{font-weight:bold}h3{font-weight:bold}h4{font-weight:bold}h5{font-weight:bold}h6{font-weight:bold}a{color:#6aa3ff}b{font-weight:bold}strong{font-weight:bold}i{font-style:italic}em{font-style:italic}.vector-menu-content-list{display:none}.vector-dropdown{display:none}.mw-interlanguage-selector{display:none}.wbc-editpage{display:none}.vector-toc{display:none}.vector-toc-list{display:none}.vector-toc-list-item{display:none}.vector-toc-link{display:none}.vector-page-toolbar{display:none}.infobox{float:right;width:300px;margin-left:8px;background-color:#1a1f28}.nishi-buyguard{background-color:#2a2410;color:#ffe08a;padding-left:14px;padding-right:14px;padding-top:8px;padding-bottom:8px;margin-bottom:10px;font-size:18px}\x00"
581 }
582 let clen: i64 = br_slen(css)
583 let STYCAP: i64 = 262144
584 let buf: *u8 = sys_mmap(body_len + STYCAP + clen + 16)
585 var bi: i64 = 0
586 while bi < body_len { buf[bi]=body[bi]; bi=bi+1 }
587 // CASCADE ORIGIN ORDER (07-09 root fix): UA defaults FIRST, author <style> AFTER -- the resolvers take
588 // the LAST matching decl, so author rules now OVERRIDE the defaults with UA as the fallback (correct CSS
589 // origin order). Before this swap the appended defaults silently beat every author color on styled pages
590 // (measured: identical palettes with and without author colors -- the dfb probes, 2026-07-09).
591 var ci: i64 = 0
592 while ci < clen { buf[body_len + ci] = css[ci]; ci=ci+1 }
593 let rawsty: *u8 = sys_mmap(STYCAP)
594 let rawstylen: i64 = rh_extract_styles(body, body_len, rawsty, STYCAP)
595 var stylen: i64 = rh_filter_media(rawsty, 0, rawstylen, ((buf as i64)+body_len+clen) as *u8, STYCAP, vw)
596 // STYLED-PAGE UA CORRECTION (2026-07-28): our UA body padding (44px) is a READABILITY choice for
597 // unstyled pages; Chrome's real UA default is body margin 8px. On a page that ships author CSS,
598 // keeping 44px shifted ALL content right of Chrome (measured: chrome first-ink x=24, ours 68 on
599 // styled wikipedia). Inject the Chrome-parity body box AFTER our UA sheet (wins over it) but
600 // BEFORE author styles (so the page's own body rules still win over both). +padding-bottom for
601 // symmetry; sites that set body padding override all of this normally.
602 if stylen > 0 { if stylen + 100 < STYCAP {
603 let uafix: *u8 = "body{padding-left:8px;padding-right:8px;padding-top:8px;padding-bottom:8px}\x00" as *u8
604 var ufl: i64 = 0
605 while uafix[ufl] != (0 as u8) { ufl = ufl + 1 }
606 // shift the author block right by ufl and place the fix between UA and author
607 var mv: i64 = stylen - 1
608 while mv >= 0 { buf[body_len + clen + ufl + mv] = buf[body_len + clen + mv]; mv = mv - 1 }
609 var uc: i64 = 0
610 while uc < ufl { buf[body_len + clen + uc] = uafix[uc]; uc = uc + 1 }
611 stylen = stylen + ufl
612 } }
613 let total: i64 = body_len + clen + stylen
614
615 var VW: i64 = vw
616 if VW < 200 { VW = 200 }
617 let boxes: *LayoutBox = (sys_mmap(NX_LAYOUT_BOX_BYTES*16384+16)) as *LayoutBox
618 let tree: *LayoutTree = (sys_mmap(64)) as *LayoutTree
619 nx_layout_tree_init(tree, boxes, 16384)
620 let stk: *LayoutFromDomStack = (sys_mmap(NX_LAYOUT_FROM_DOM_STACK_BYTES+8)) as *LayoutFromDomStack
621 let sidx: *i64 = (sys_mmap(8*128)) as *i64
622 nx_layout_from_dom_stack_init(stk, sidx, 128)
623 nx_layout_from_dom(buf, body_len, tree, stk)
624
625 let ext: *CssElement = (sys_mmap(NX_CSS_ELEMENT_BYTES*16384 as nx_size)) as *CssElement
626 let ehoff: *i64 = sys_mmap(8*16384) as *i64
627 let ehlen: *i64 = sys_mmap(8*16384) as *i64
628 let esoff: *i64 = sys_mmap(8*16384) as *i64
629 let eslen: *i64 = sys_mmap(8*16384) as *i64
630 let eslazy: *i64 = sys_mmap(8*16384) as *i64
631 // BR14: the density the fetched image has to cover. 0 means the consumer never declared one, and
632 // this core then reads it as the IDENTITY (one device pixel per CSS pixel) rather than inventing a
633 // display -- a consumer that paints at scale N sets page.dpr_permil = N * BI_PERMIL_ONE.
634 var dpr: i64 = page.dpr_permil
635 if dpr <= 0 { dpr = BI_PERMIL_ONE }
636 let n_ext: i64 = br_extract(buf, body_len, ext, ehoff, ehlen, esoff, eslen, eslazy, VW, dpr, 16384)
637 let boxel: *CssElement = (sys_mmap((NX_CSS_ELEMENT_BYTES*(tree.count+1)) as nx_size)) as *CssElement
638 let bhoff: *i64 = sys_mmap(8*(tree.count+1)) as *i64
639 let bhlen: *i64 = sys_mmap(8*(tree.count+1)) as *i64
640 let bsoff: *i64 = sys_mmap(8*(tree.count+1)) as *i64
641 let bslen: *i64 = sys_mmap(8*(tree.count+1)) as *i64
642 let bslazy: *i64 = sys_mmap(8*(tree.count+1)) as *i64
643 let bimg: *i64 = sys_mmap(8*(tree.count+1)) as *i64
644 let bimw: *i64 = sys_mmap(8*(tree.count+1)) as *i64
645 let bimh: *i64 = sys_mmap(8*(tree.count+1)) as *i64
646 let bcvs: *i64 = sys_mmap(8*(tree.count+1)) as *i64
647 var k: i64 = 0
648 var ii: i64 = 0
649 while ii < tree.count {
650 let b: *LayoutBox = ((tree.boxes as i64)+ii*NX_LAYOUT_BOX_BYTES) as *LayoutBox
651 let e: *CssElement = ((boxel as i64)+ii*NX_CSS_ELEMENT_BYTES) as *CssElement
652 e.src = buf
653 bhoff[ii] = 0 - 1; bhlen[ii] = 0 - 1
654 bsoff[ii] = 0 - 1; bslen[ii] = 0 - 1; bslazy[ii] = 0
655 bimg[ii] = 0; bimw[ii] = 0; bimh[ii] = 0; bcvs[ii] = 0
656 var mapped: i64 = 0
657 if rh_is_elem(b.kind)==1 { if b.parent_idx != (0-1) { if k < n_ext {
658 let s: *CssElement = ((ext as i64)+k*NX_CSS_ELEMENT_BYTES) as *CssElement
659 e.tag_off=s.tag_off; e.tag_len=s.tag_len; e.id_off=s.id_off; e.id_len=s.id_len; e.class_off=s.class_off; e.class_len=s.class_len
660 bhoff[ii] = ehoff[k]; bhlen[ii] = ehlen[k]
661 bsoff[ii] = esoff[k]; bslen[ii] = eslen[k]; bslazy[ii] = eslazy[k]
662 // <canvas> = sourceless render surface (seq103): match the element's own tag bytes in buf
663 if s.tag_len==6 { if (buf[s.tag_off]&0xff)==99 { if (buf[s.tag_off+1]&0xff)==97 { if (buf[s.tag_off+2]&0xff)==110 { if (buf[s.tag_off+3]&0xff)==118 { if (buf[s.tag_off+4]&0xff)==97 { if (buf[s.tag_off+5]&0xff)==115 { bcvs[ii]=1 } } } } } } }
664 k=k+1; mapped=1
665 } } }
666 if mapped==0 { e.tag_off=0; e.tag_len=0; e.id_off=0; e.id_len=0; e.class_off=0; e.class_len=0 }
667 ii = ii + 1
668 }
669
670 let cur: *CssCursor = (sys_mmap(NX_CSS_CURSOR_BYTES) as nx_size) as *CssCursor
671 nx_css_cursor_init(cur, buf, total); cur.pos = body_len
672 let tok: *CssToken = (sys_mmap(NX_CSS_TOKEN_BYTES) as nx_size) as *CssToken
673 let rules: *CssRule = (sys_mmap(NX_CSS_RULE_BYTES*8192 as nx_size)) as *CssRule
674 let decls: *CssDeclaration = (sys_mmap(NX_CSS_DECLARATION_BYTES*32768 as nx_size)) as *CssDeclaration
675 let st: *CssParseState = (sys_mmap(128) as nx_size) as *CssParseState
676 nx_css_parse_state_init(st, cur, tok, rules, 8192, decls, 32768)
677 nx_css_parse(st)
678 let computed: *CssComputedDecl = (sys_mmap(NX_CSS_COMPUTED_DECL_BYTES*262144 as nx_size)) as *CssComputedDecl
679 let cb: *i64 = (sys_mmap(8)) as *i64
680 rh_cascade(buf, rules, st.rule_count, decls, st.decl_count, boxel, tree.count, tree, computed, 262144, cb)
681 let ncomp: i64 = cb[0]
682 rh_promote_display_kinds(tree, computed, ncomp, buf) // inline + display:flex/grid/block -> BLOCK (sized + painted)
683
684 let pbuf: *u8 = sys_mmap(256)
685 let ltable: *LayoutPropTable = (sys_mmap(NX_LAYOUT_PROP_TABLE_BYTES)) as *LayoutPropTable
686 nx_layout_prop_table_init(ltable, pbuf)
687 let resolve: *CssResolveCtx = (sys_mmap(NX_CSS_RESOLVE_CTX_BYTES)) as *CssResolveCtx
688 resolve.root_font_size_px = 16; resolve.parent_font_size_px = 16; resolve.parent_dimension_px = VW
689 let lctx: *LayoutCtx = (sys_mmap(NX_LAYOUT_CTX_BYTES)) as *LayoutCtx
690 // ---- FOLD-BEFORE-LAYOUT (2026-08-25): THE ROOT FIX FOR measure != paint ----
691 // Layout used to measure the RAW DOM bytes while paint decoded entities and folded to ASCII
692 // before drawing. `café` was therefore ELEVEN characters to layout and FOUR to paint,
693 // and any run holding an accent, a curly quote or an em-dash FAILED layout's coverage test
694 // (font_run_has_ext over raw bytes) while PASSING paint's (the same test over folded bytes) --
695 // so layout reserved 8x8 BITMAP widths for text that paint then drew in the VECTOR font. That
696 // split is the ceiling on every other metric fix in this file: the two stages did not agree on
697 // what the text IS, so they could never agree on how wide it is. Folding HERE, once, before a
698 // single width is measured, makes both stages read the SAME BYTES by construction.
699 // IN-PLACE IS SAFE: decode and fold both SHRINK-or-equal (é -> e; one multi-byte UTF-8
700 // codepoint -> one ASCII byte), so the result never outgrows the run it overwrites, and only
701 // that run's own extent is touched -- the href/src offsets recorded elsewhere in buf, and the
702 // cascade that already ran above, are untouched.
703 // PAINT NEEDS NO EDIT: its decode+fold is IDEMPOTENT on this output (no '&' remains and the
704 // bytes are ASCII, which nx_fold_ascii documents as identity for ASCII), so it becomes a no-op.
705 // The `fd1 <= text_len` guard is fail-safe, not decoration: if the shrink property were ever
706 // violated the run is left RAW rather than overflowing its extent.
707 // PROVEN by nx_inline_vec_measure_gate T5/T6 (GREEN 6/6): a café run measures 28px at
708 // text_len=4 -- the decoded length -- where it previously measured the 11 raw bytes.
709 var fli: i64 = 0
710 var flcap: i64 = 1
711 while fli < tree.count {
712 let flb0: *LayoutBox = ((tree.boxes as i64) + fli * NX_LAYOUT_BOX_BYTES) as *LayoutBox
713 if flb0.text_len > flcap { flcap = flb0.text_len }
714 fli = fli + 1
715 }
716 flcap = flcap + 2
717 let flscratch: *u8 = sys_mmap(flcap)
718 fli = 0
719 while fli < tree.count {
720 let flb: *LayoutBox = ((tree.boxes as i64) + fli * NX_LAYOUT_BOX_BYTES) as *LayoutBox
721 if flb.text_len > 0 {
722 let fd0: i64 = nx_html_decode_entities(buf, flb.text_off, flb.text_len, flscratch, flcap)
723 let fd1: i64 = br_fold_text(flscratch, 0, fd0, flscratch, flcap) // BR30: fold only what the face lacks (same policy as paint)
724 if fd1 <= flb.text_len {
725 var flk: i64 = 0
726 while flk < fd1 { buf[flb.text_off + flk] = flscratch[flk]; flk = flk + 1 }
727 flb.text_len = fd1
728 }
729 }
730 fli = fli + 1
731 }
732 nx_layout_ctx_init(lctx, tree, computed, ncomp, buf, VW, resolve)
733 // PROPORTIONAL text. text_measured=1 selects the 8x8 BITMAP metric; this line's comment used
734 // to claim it measured "with the same font metrics the paint draws with", and that was FALSE:
735 // paint runs the VECTOR font (page.vec_headings = 2 below, font_adv_em), so layout measured
736 // with one table and painted with another INSIDE THIS FUNCTION. vec-measure makes the claim
737 // true -- layout now reserves and BREAKS on the same advances paint draws. It is guarded per
738 // run by font_run_has_ext, the same coverage test the paint side uses, so any run the vector
739 // font does not cover keeps its bitmap metric and measure==paint holds in BOTH modes.
740 lctx.text_measured = 1
741 nx_layout_default_vec_measure(1)
742 let page_h: i64 = nx_layout_block_layout(lctx, ltable, 0)
743
744 page.buf = buf; page.tree = tree; page.computed = computed; page.ncomp = ncomp
745 br_cidx_build(tree, computed, ncomp) // paint-cliff fix: per-box decl buckets for br_comp_* lookups
746 page.page_h = page_h; page.bhref_off = bhoff; page.bhref_len = bhlen; page.ok = 1
747 page.bsrc_off = bsoff; page.bsrc_len = bslen; page.bimg = bimg; page.bimg_w = bimw; page.bimg_h = bimh
748 page.bsrc_lazy = bslazy
749 page.bcanvas = bcvs
750 page.find_ptr = 0; page.find_len = 0
751 // MATCH THE DAILY DRIVER (2026-07-27). This was hardcoded 0 = the crude 8x8 BITMAP font for
752 // EVERYTHING, while nishi.exe (nishi_gui.nx:530) paints vec_headings=2 = the proportional
753 // VECTOR font. So every headless shot taken through this path UNDERSOLD the real browser --
754 // it already produced one wrong conclusion in this ecosystem ("body font is THE rock",
755 // later DISPROVEN: the vector body font is at Chrome parity). An instrument that does not
756 // render what the user sees is a liar; default to what ships.
757 // Callers that deliberately want the bitmap font set vec_headings themselves AFTER this
758 // call (nx_browser_bg_gate does exactly that at :20/:59/:97), so they are unaffected.
759 page.vec_headings = 2
760 return 0
761}
762
763// find the next <canvas> box at or after `from` (-1 = none). The canvas CONTRACT (seq103, the game substrate):
764// the consumer renders into its OWN RGB buffer each frame, points page.bimg[idx] (+bimg_w/bimg_h) at it, and
765// repaints (br_draw_fb / br_shot_png); the image pass blits the CURRENT buffer at the box's laid-out position.
766func br_find_canvas(page: *Page, from: i64) -> i64 {
767 var i: i64 = from
768 if i < 0 { i = 0 }
769 while i < page.tree.count { if page.bcanvas[i] == 1 { return i } i = i + 1 }
770 return 0 - 1
771}
772
773// paint a heading run with the sovereign stroke-VECTOR font (modern typeface). Word-wraps by the vector
774// metrics within avail_w px, renders each line via font_text -> aa_render -> alpha-blend onto the RGBA fb
775// at (x0,y0), em size = empx px. Vector advances are TIGHTER than the bitmap the layout reserved with, so
776// the run always fits the box (never overflows). Allocation-bearing -> only called on opt-in once-render
777// paths. Returns the drawn width of the FIRST line (for the link underline; headings rarely link).
778// REUSED vector-paint scratch (was sys_mmap PER LINE -> per-box -> gigabytes committed under the PE's
779// VirtualAlloc, hanging the native GUI on a full page). Allocated ONCE, reused across every box + line.
780static bpv_xs: i64
781static bpv_ys: i64
782static bpv_cst: i64
783static bpv_cln: i64
784static bpv_cov: i64
785static bpv_cs2: i64
786static bpv_sn2: i64
787static bpv_np: i64
788static bpv_nc: i64
789// ---- GLYPH-ATLAS FAST PATH (GUI-only, gated by bpv_fast_on) ------------------------------------------
790// Rasterize each (char,size) glyph ONCE into a cached coverage cell, then just alpha-blend the cell per
791// draw. Turns O(glyphs drawn) rasterization into O(unique glyph x size). Pixel-snapped positioning (no
792// sub-pixel phase) -> crisp, ~visually-identical, MUCH faster. The EXACT per-line path (used by the shot /
793// NishiOS / OCR / polish gates) is untouched: they never set bpv_fast_on, so the dispatch below is a no-op
794// for them -> zero gate regression. Only nishi_gui (br_set_fast_vec(1)) opts in.
795static bpv_fast_on: i64
796static bpv_line_adv: i64 // wrapped-line advance override (px at paint scale; 0 = legacy (empx*12)/10+2).
797 // Set by the TEXT paint pass from the CSS line-height so paint fills exactly
798 // the lines layout reserved (measure==paint); single-threaded paint -> safe.
799static atk: i64 // hash keys (ch*100000+empx), -1 = empty slot
800static atcov: i64 // per-slot coverage buffer ptr
801static atgw: i64 // per-slot cell width (px)
802static atgh: i64 // per-slot cell height (px)
803static atmg: i64 // per-slot left margin (px) baked into the cell
804static atcap: i64
805func br_set_fast_vec(v: i64) -> i64 { bpv_fast_on = v; return 0 }
806// ---- REAL FACE (2026-09-02, BR4 first half: /compare/browser "Real font files + shaping") -------------
807// A loaded TrueType face replaces the parametric stroke glyphs for every byte it covers, and hands its
808// hmtx advances + kern pairs to the ONE measure ruler in nx_font (font_set_face), so layout, wrap and
809// paint agree by construction. Cells cache in the same atlas keyed (ch, empx); a face is set ONCE before
810// the first layout, so a key can never mean two glyphs. With NO face set every path below is byte-unchanged.
811// The face lands advances AND outlines AND kern TOGETHER -- the 07-29 A/B proved advances alone under
812// the stroke glyphs wreck legibility (OCR 881 -> 591); this is the pair that A/B asked for.
813static br_face: i64 // tf handle of the SELECTED face (0 = no face)
814static br_faces: i64 // *i64[FS_FACE_MAX] tf handles by slot (BR27); 0 = slot empty
815static br_face_cur: i64 // the selected slot (effective)
816static br_face_adv: i64 // *i64[BR_FACE_BYTES] 1000-em advances handed to nx_font
817static br_face_kern: i64 // *i64[BR_FACE_BYTES^2] 1000-em pair kern handed to nx_font
818const BR_FACE_BYTES: i64 = 256
819// register a parsed face into slot idx (font_face_pick order: +1 bold, +2 italic, +4 serif); slot 0 is the
820// default and is selected on registration. Each slot owns its own advance and kern tables.
821func br_face_register(idx: i64, fh: *i64) -> i64 {
822 if (fh as i64) == 0 { return 0 }
823 if idx < 0 { return 0 }
824 if idx >= FS_FACE_MAX { return 0 }
825 if br_faces == 0 { br_faces = sys_mmap(8*FS_FACE_MAX) as i64 }
826 let adv: *i64 = sys_mmap(8*FS_FACE_CPS) as *i64 // BR30: indexed by CODEPOINT (U+0000..FS_FACE_CPS-1)
827 let kern: *i64 = sys_mmap(8*BR_FACE_BYTES*BR_FACE_BYTES) as *i64
828 var i: i64 = 0
829 while i < FS_FACE_CPS { adv[i] = 0; i = i + 1 }
830 i = 0
831 while i < BR_FACE_BYTES*BR_FACE_BYTES { kern[i] = 0; i = i + 1 }
832 var a: i64 = TF_ASCII_LO
833 while a <= TF_ASCII_HI {
834 adv[a] = tf_adv_em1000(fh, a)
835 if adv[a] <= 0 { adv[a] = 1 } // a covered byte with a zero advance still counts as COVERED (never fall back mid-run)
836 var c: i64 = TF_ASCII_LO
837 while c <= TF_ASCII_HI { kern[a*BR_FACE_BYTES + c] = tf_kern_em1000(fh, a, c); c = c + 1 }
838 a = a + 1
839 }
840 // BR30: every codepoint the face's cmap maps (up to FS_FACE_CPS) is COVERED with its real advance; an
841 // unmapped one stays 0 so the run folds THAT character to ASCII -- the same rule as an ASCII gap.
842 var u: i64 = TF_ASCII_HI + 1
843 while u < FS_FACE_CPS {
844 if tf_gid(fh, u) > 0 { adv[u] = tf_adv_em1000(fh, u); if adv[u] <= 0 { adv[u] = 1 } }
845 u = u + 1
846 }
847 // BR39: slot 0 = the notdef (gid 0) advance, so a codepoint beyond the table measures and paints as the
848 // face box. A face whose notdef has no advance leaves the slot 0 and such codepoints fold as before.
849 adv[0] = (tf_adv_units_gid(fh, 0) * 1000) / tf_upem(fh)
850 if adv[0] < 0 { adv[0] = 0 }
851 let hs: *i64 = br_faces as *i64
852 hs[idx] = fh as i64
853 font_face_register(idx, adv, kern)
854 if idx == 0 { br_face = fh as i64; br_face_cur = 0 }
855 return 1
856}
857// select the face for the run about to be painted (the SAME rule layout used); returns the effective slot
858func br_face_select(idx: i64) -> i64 {
859 if br_faces == 0 { return 0 }
860 let e: i64 = font_face_select(idx)
861 let hs: *i64 = br_faces as *i64
862 br_face = hs[e]
863 br_face_cur = e
864 return e
865}
866// compatibility: ONE face = slot 0; 0 clears everything
867func br_set_face(fh: *i64) -> i64 {
868 if (fh as i64) == 0 { br_face = 0; br_face_cur = 0; if br_faces != 0 { let hs: *i64 = br_faces as *i64; var i: i64 = 0; while i < FS_FACE_MAX { hs[i] = 0; i = i + 1 } } font_set_face(0 as *i64, 0 as *i64); return 0 }
869 let r: i64 = br_face_register(0, fh)
870 br_face_select(0)
871 return r
872}
873// BR27 contract symbol: resolve the face for the text under box_idx by the ONE rule layout used
874// (nx_layout_face_for_box: font-weight / font-style / font-family, inherited) and SELECT it for paint.
875// Returns the effective slot (0 when no family is registered).
876func br_face_resolve(src: *u8, computed: *CssComputedDecl, ncomp: i64, tree: *LayoutTree, box_idx: i64) -> i64 {
877 if br_faces == 0 { return 0 }
878 return br_face_select(nx_layout_face_for_box(src, computed, ncomp, tree, box_idx))
879}
880func br_face_load_idx(idx: i64, path: *u8) -> i64 {
881 let fh: *i64 = tf_load(path)
882 if (fh as i64) == 0 { return 0 }
883 return br_face_register(idx, fh)
884}
885// load a .ttf from a path and make it THE face; 0 when absent/unparseable (the stroke font stays)
886func br_face_load(path: *u8) -> i64 {
887 let fh: *i64 = tf_load(path)
888 if (fh as i64) == 0 { return 0 }
889 return br_set_face(fh)
890}
891func br_face_on() -> i64 { if br_face != 0 { return 1 } return 0 }
892// the CONTENT height of a text line at em size px -- the face (ascender - descender) when one is on,
893// else the stroke font 1.2em+2 band. CSS centres this inside the line box (half-leading); the caller
894// uses it for both stages so measure and paint place the baseline identically.
895func br_face_line_h(px: i64) -> i64 { if br_face == 0 { return (px * 12) / 10 + 2 } return tf_content_px(br_face as *i64, px) }
896static bpv_fold_cp: i64
897// BR30 (2026-09-02): the fold policy BOTH stages call. With NO face every non-ASCII codepoint folds to
898// ASCII (nx_fold_ascii, the legacy behaviour). With a face, a codepoint the face COVERS keeps its UTF-8
899// bytes (measured and painted from the face's own outline) and only an uncovered one folds. Layout's
900// pre-pass and paint call THIS, so the bytes layout measured are the bytes paint draws, and paint's
901// second call is idempotent on the first's output. In-place safe: the output cursor never runs ahead
902// of the input cursor (copy or shrink per codepoint). Coverage is read from the SELECTED slot; the
903// faces of one family share a cmap, so bold/italic/serif answer alike.
904func br_fold_text(src: *u8, off: i64, len: i64, out: *u8, out_cap: i64) -> i64 {
905 if font_face_on() == 0 { return nx_fold_ascii(src, off, len, out, out_cap) }
906 if bpv_fold_cp == 0 { bpv_fold_cp = sys_mmap(8) as i64 }
907 let cpo: *i64 = bpv_fold_cp as *i64
908 let end: i64 = off + len
909 var i: i64 = off
910 var o: i64 = 0
911 while i < end {
912 let i0: i64 = i
913 i = font_next_cp(src, i, end, cpo)
914 let cp: i64 = cpo[0]
915 if cp < 128 { if o < out_cap { out[o] = src[i0]; o = o + 1 } }
916 else { if font_face_has(cp) == 1 {
917 var k: i64 = i0
918 while k < i { if o < out_cap { out[o] = src[k]; o = o + 1 } k = k + 1 }
919 } else {
920 o = o + nx_fold_ascii(src, i0, i - i0, ((out as i64) + o) as *u8, out_cap - o)
921 } }
922 }
923 return o
924}
925// BR30 contract symbol (browser board, "Unicode text pipeline beyond ASCII"): the ONE place paint turns
926// bytes into the codepoint it draws. It delegates to the measure ruler's decoder (font_next_cp) so a run
927// is decoded identically for measure and paint; a malformed sequence yields its lead byte, which no face
928// covers, so the run folds rather than painting garbage. Returns the index after the codepoint.
929func br_text_cp(text: *u8, i: i64, len: i64, cp: *i64) -> i64 { return font_next_cp(text, i, len, cp) }
930func bpv_atlas_init() -> i64 {
931 if bpv_xs == 0 {
932 bpv_xs = sys_mmap(8*200000) as i64; bpv_ys = sys_mmap(8*200000) as i64
933 bpv_cst = sys_mmap(8*20000) as i64; bpv_cln = sys_mmap(8*20000) as i64
934 bpv_cov = sys_mmap(4194304) as i64
935 bpv_cs2 = sys_mmap(8*16) as i64; bpv_sn2 = sys_mmap(8*16) as i64
936 bpv_np = sys_mmap(16) as i64; bpv_nc = sys_mmap(16) as i64
937 }
938 if atk == 0 {
939 atcap = 8192
940 atk = sys_mmap(8*atcap) as i64; atcov = sys_mmap(8*atcap) as i64
941 atgw = sys_mmap(8*atcap) as i64; atgh = sys_mmap(8*atcap) as i64; atmg = sys_mmap(8*atcap) as i64
942 let ka: *i64 = atk as *i64; var z: i64 = 0
943 while z < atcap { ka[z] = 0 - 1; z = z + 1 }
944 }
945 return 0
946}
947// get-or-build the cached coverage cell for (ch,empx). out[0]=covptr out[1]=gw out[2]=gh out[3]=leftmargin_px
948func bpv_cell(ch: i64, empx: i64, cs: *i64, sn: *i64, out: *i64) -> i64 {
949 let ka: *i64 = atk as *i64
950 var kc: i64 = ch
951 if ch >= FS_FACE_CPS { kc = 0 } // BR39: every beyond-table codepoint shares the notdef cell, keyed on codepoint 0
952 if ch >= FS_FACE_LATIN_END { if ch < FS_FACE_CPS { if font_face_has(ch) == 1 { let fta: *i64 = fs_face_adv_ptr(); if fta[ch] == 0 { kc = 0 } } } } // in-table unmapped non-Latin: the same notdef cell
953 let key: i64 = (br_face_cur * FS_FACE_CPS + kc) * 100000 + empx // slot 0 / no face keeps the legacy key; BR30: ch is a CODEPOINT
954 var h: i64 = key % atcap
955 if h < 0 { h = 0 - h }
956 var probes: i64 = 0
957 while probes < atcap {
958 let cova: *i64 = atcov as *i64; let gwa: *i64 = atgw as *i64; let gha: *i64 = atgh as *i64; let mga: *i64 = atmg as *i64
959 if ka[h] == key { out[0]=cova[h]; out[1]=gwa[h]; out[2]=gha[h]; out[3]=mga[h]; return 0 }
960 if ka[h] == (0 - 1) {
961 if br_face != 0 { if font_face_has(ch) == 1 {
962 // REAL FACE cell: the TTF engine coverage record (row 0 = ascender line, left margin =
963 // negative lsb) is adopted into the atlas as-is -- no re-raster, no second copy.
964 var frec: *i64 = 0 as *i64
965 if ch >= FS_FACE_CPS { frec = tf_glyph_notdef(br_face as *i64, empx) } // BR39: the face box for a codepoint the table cannot hold
966 else { if ch <= TF_ASCII_HI { frec = tf_glyph(br_face as *i64, ch, empx) } else { frec = tf_glyph_cp(br_face as *i64, ch, empx) } } // BR30: non-ASCII cells raster once and cache HERE (the engine caches ASCII only)
967 if frec == (0 as *i64) { if ch >= FS_FACE_LATIN_END { frec = tf_glyph_notdef(br_face as *i64, empx) } } // BR39: an in-table non-Latin codepoint the face lacks draws the box too (measure reserved the notdef advance)
968 if frec != (0 as *i64) {
969 ka[h]=key; cova[h]=frec[TF_R_COV]; gwa[h]=frec[TF_R_CW]; gha[h]=frec[TF_R_CHH]; mga[h]=frec[TF_R_LM]
970 out[0]=frec[TF_R_COV]; out[1]=frec[TF_R_CW]; out[2]=frec[TF_R_CHH]; out[3]=frec[TF_R_LM]
971 return 0
972 }
973 } }
974 let ss: i64 = 3
975 let S: i64 = empx * ss
976 let mgn: i64 = 4
977 let adv: i64 = font_vec_adv_px2(ch, empx)
978 var gw: i64 = adv + 2*mgn
979 if gw < empx + 2*mgn { gw = empx + 2*mgn }
980 let gh: i64 = empx + (empx*35)/100 + 2
981 let xs: *i64 = bpv_xs as *i64; let ys: *i64 = bpv_ys as *i64
982 let cstart: *i64 = bpv_cst as *i64; let clen: *i64 = bpv_cln as *i64
983 let np: *i64 = bpv_np as *i64; np[0]=0
984 let nc: *i64 = bpv_nc as *i64; nc[0]=0
985 font_emit(ch, xs, ys, cstart, clen, np, nc, cs, sn, mgn*ss, 2*ss, S)
986 let cov: *u8 = sys_mmap(gw*gh + 16)
987 var zi: i64 = 0
988 while zi < gw*gh { cov[zi]=0 as u8; zi=zi+1 }
989 aa_render(xs, ys, cstart, clen, nc[0], cov, gw, gh, ss)
990 ka[h]=key; cova[h]=cov as i64; gwa[h]=gw; gha[h]=gh; mga[h]=mgn
991 out[0]=cov as i64; out[1]=gw; out[2]=gh; out[3]=mgn
992 return 0
993 }
994 h = h + 1; if h >= atcap { h = 0 }
995 probes = probes + 1
996 }
997 out[0]=0; return 1
998}
999// alpha-blend a coverage cell onto the RGBA framebuffer (matches br_paint_vec's blend exactly)
1000func bpv_blit_rgba(fb: *Framebuffer, ox: i64, oy: i64, cov: *u8, gw: i64, gh: i64, cr: i64, cg: i64, cb: i64) -> i64 {
1001 let fw: i64 = fb.width; let fh: i64 = fb.height; let pxb: *u8 = fb.pixels
1002 var y: i64 = 0
1003 while y < gh {
1004 let fyr: i64 = oy + y
1005 if fyr >= 0 { if fyr < fh {
1006 var x: i64 = 0
1007 while x < gw {
1008 let a: i64 = cov[y*gw + x] & 0xff
1009 if a > 0 {
1010 let fxr: i64 = ox + x
1011 if fxr >= 0 { if fxr < fw {
1012 let o: i64 = (fyr*fw + fxr) * 4
1013 let ia: i64 = 255 - a
1014 pxb[o] = (((pxb[o] as i64)*ia + cr*a)/255) as u8
1015 pxb[o+1] = (((pxb[o+1] as i64)*ia + cg*a)/255) as u8
1016 pxb[o+2] = (((pxb[o+2] as i64)*ia + cb*a)/255) as u8
1017 pxb[o+3] = 255 as u8
1018 } }
1019 }
1020 x = x + 1
1021 }
1022 } }
1023 y = y + 1
1024 }
1025 return 0
1026}
1027func br_paint_vec_atlas(fb: *Framebuffer, x0: i64, y0: i64, text: *u8, text_len: i64, empx: i64, color: *CssColor, avail_w: i64) -> i64 {
1028 bpv_atlas_init()
1029 let cs: *i64 = bpv_cs2 as *i64
1030 let sn: *i64 = bpv_sn2 as *i64
1031 font_trig_init(cs, sn)
1032 let cr: i64 = color.r & 255
1033 let cg: i64 = color.g & 255
1034 let cb: i64 = color.b & 255
1035 var lineh: i64 = br_face_line_h(empx)
1036 if bpv_line_adv >= 8 { lineh = bpv_line_adv } // CSS line-height (already paint-scaled by the caller)
1037 var aw: i64 = avail_w
1038 if aw < empx { aw = empx }
1039 let cell: *i64 = sys_mmap(64) as *i64
1040 let bpv_cpo: *i64 = ((cell as i64) + 56) as *i64 // slot 7 of the cell scratch: the decoded codepoint (no per-glyph allocation)
1041 var pos: i64 = 0
1042 var li: i64 = 0
1043 var w1: i64 = 0
1044 while pos < text_len {
1045 var e: i64 = font_vec_next_break_px(text, text_len, aw, pos, empx)
1046 if e <= pos { e = text_len }
1047 let basey: i64 = y0 + li * lineh
1048 var penpx: i64 = x0
1049 var prev: i64 = 0 - 1
1050 var k: i64 = pos
1051 while k < e {
1052 var ch: i64 = text[k] & 0xff
1053 if br_face != 0 { k = br_text_cp(text, k, e, bpv_cpo) - 1; ch = bpv_cpo[0] } // BR30: a face paints CODEPOINTS; k lands on the run's last byte and the k+1 below steps past it
1054 penpx = penpx + (font_pair_kern_em(prev, ch) * empx) / 1000 // pair kern: the SAME term the measure added, in the same order
1055 bpv_cell(ch, empx, cs, sn, cell)
1056 let covp: i64 = cell[0]
1057 var shp: i64 = (((((font_sp_shift_disp(ch) * font_ws()) / 100) * font_wdth()) / 100) * empx) / 1000
1058 if font_face_has(ch) == 1 { shp = 0 } // a real face carries its side bearings inside the outline
1059 if covp != 0 { bpv_blit_rgba(fb, penpx + shp - cell[3], basey, covp as *u8, cell[1], cell[2], cr, cg, cb) }
1060 penpx = penpx + font_vec_adv_px2(ch, empx)
1061 prev = ch
1062 k = k + 1
1063 }
1064 if li == 0 { w1 = penpx - x0 }
1065 pos = e
1066 li = li + 1
1067 // DERIVED loop bound (see the note at the paint wrap): termination insurance, not a
1068 // line budget. A line consumes >= 1 char, so li > text_len is structurally impossible.
1069 if li > text_len { pos = text_len }
1070 }
1071 return w1
1072}
1073func br_paint_vec(fb: *Framebuffer, x0: i64, y0: i64, text: *u8, text_len: i64, empx: i64, color: *CssColor, avail_w: i64) -> i64 {
1074 if bpv_fast_on == 1 { return br_paint_vec_atlas(fb, x0, y0, text, text_len, empx, color, avail_w) }
1075 if br_face != 0 { return br_paint_vec_atlas(fb, x0, y0, text, text_len, empx, color, avail_w) } // a real face always paints through the (deterministic) atlas
1076 let ss: i64 = 3
1077 let S: i64 = empx * ss
1078 if bpv_xs == 0 {
1079 bpv_xs = sys_mmap(8*200000) as i64
1080 bpv_ys = sys_mmap(8*200000) as i64
1081 bpv_cst = sys_mmap(8*20000) as i64
1082 bpv_cln = sys_mmap(8*20000) as i64
1083 bpv_cov = sys_mmap(4194304) as i64
1084 bpv_cs2 = sys_mmap(8*16) as i64
1085 bpv_sn2 = sys_mmap(8*16) as i64
1086 bpv_np = sys_mmap(16) as i64
1087 bpv_nc = sys_mmap(16) as i64
1088 }
1089 let cs: *i64 = bpv_cs2 as *i64
1090 let sn: *i64 = bpv_sn2 as *i64
1091 font_trig_init(cs, sn)
1092 let fw: i64 = fb.width
1093 let fh: i64 = fb.height
1094 let pxb: *u8 = fb.pixels
1095 let cr: i64 = color.r & 255
1096 let cg: i64 = color.g & 255
1097 let cb: i64 = color.b & 255
1098 let lineh: i64 = (empx * 12) / 10 + 2 // ~1.2em line height
1099 var aw: i64 = avail_w
1100 if aw < empx { aw = empx }
1101 var pos: i64 = 0
1102 var li: i64 = 0
1103 var w1: i64 = 0
1104 while pos < text_len {
1105 var e: i64 = font_vec_next_break_px(text, text_len, aw, pos, empx)
1106 if e <= pos { e = text_len }
1107 // render this line [pos,e) into a coverage buffer sized to its width x (em band)
1108 let lw: i64 = font_vec_text_w_px(text, pos, e, empx) + empx
1109 let GH: i64 = empx + (empx*35)/100 // ascender..descender band
1110 var GW: i64 = lw
1111 if GW < empx { GW = empx }
1112 if GW > fw { GW = fw }
1113 let xs: *i64 = bpv_xs as *i64 // reused (was sys_mmap per line)
1114 let ys: *i64 = bpv_ys as *i64
1115 let cstart: *i64 = bpv_cst as *i64
1116 let clen: *i64 = bpv_cln as *i64
1117 let np: *i64 = bpv_np as *i64; np[0]=0
1118 let nc: *i64 = bpv_nc as *i64; nc[0]=0
1119 font_text(((text as i64)+pos) as *u8, e-pos, xs, ys, cstart, clen, np, nc, cs, sn, 2*ss, 2*ss, S)
1120 if GW*GH > 4194288 { GW = 4194288 / GH } // clamp to the reused cov buffer (4 MB) -- defensive
1121 let cov: *u8 = bpv_cov as *u8
1122 var zi: i64 = 0
1123 while zi < GW*GH { cov[zi]=0 as u8; zi=zi+1 }
1124 aa_render(xs, ys, cstart, clen, nc[0], cov, GW, GH, ss)
1125 // alpha-blend coverage onto the RGBA fb
1126 let basey: i64 = y0 + li * lineh
1127 var gy: i64 = 0
1128 while gy < GH {
1129 let fyr: i64 = basey + gy
1130 if fyr >= 0 { if fyr < fh {
1131 var gx: i64 = 0
1132 while gx < GW {
1133 let a: i64 = cov[gy*GW+gx] & 0xff
1134 if a > 0 {
1135 let fxr: i64 = x0 + gx
1136 if fxr >= 0 { if fxr < fw {
1137 let o: i64 = (fyr*fw+fxr)*4
1138 let ia: i64 = 255 - a
1139 pxb[o] = (((pxb[o] as i64)*ia + cr*a)/255) as u8
1140 pxb[o+1] = (((pxb[o+1] as i64)*ia + cg*a)/255) as u8
1141 pxb[o+2] = (((pxb[o+2] as i64)*ia + cb*a)/255) as u8
1142 pxb[o+3] = 255 as u8
1143 } }
1144 }
1145 gx = gx + 1
1146 }
1147 } }
1148 gy = gy + 1
1149 }
1150 if li == 0 { w1 = lw }
1151 pos = e
1152 li = li + 1
1153 // DERIVED loop bound (see the note at the paint wrap): termination insurance, not a
1154 // line budget. A line consumes >= 1 char, so li > text_len is structurally impossible.
1155 if li > text_len { pos = text_len }
1156 }
1157 return w1
1158}
1159// vector metrics in absolute px (em size empx), for the paint's own wrap
1160func font_vec_adv_px2(ch: i64, empx: i64) -> i64 { return (font_adv_em(ch) * empx) / 1000 }
1161// DELEGATED 2026-09-02: these were a second copy of the nx_font width/break arithmetic (font_adv_em*px/1000);
1162// pair kerning landed in the ONE ruler and a copy here would have drifted the instant it did.
1163func font_vec_text_w_px(text: *u8, start: i64, end: i64, empx: i64) -> i64 { return font_vec_text_w_fs(text, start, end, empx) }
1164func font_vec_next_break_px(text: *u8, len: i64, avail_px: i64, start: i64, empx: i64) -> i64 { return font_vec_next_break_fs(text, len, avail_px, start, empx) }
1165
1166// FIND-IN-PAGE (Ctrl+F, a universally-expected browser feature): case-insensitive search of the laid-out
1167// text for `term`. Sets page.find_ptr/find_len so br_draw_fb_at highlights every matching text box; returns
1168// the match count and, via yb, the page-y of the FIRST match (for scroll-to). A term absent from the page
1169// returns 0 (highlights nothing). Matching is per-text-box substring (the layout already split text into
1170// boxes at inline boundaries) -- the same units the render + hit-test use.
1171func br_ci(a: i64) -> i64 { if a >= 65 { if a <= 90 { return a + 32 } } return a }
1172func br_box_has_term(buf: *u8, off: i64, len: i64, term: *u8, tlen: i64) -> i64 {
1173 if tlen <= 0 { return 0 }
1174 var i: i64 = 0
1175 while i + tlen <= len {
1176 var j: i64 = 0
1177 var ok: i64 = 1
1178 while j < tlen { if br_ci(buf[off+i+j]&0xff) != br_ci(term[j]&0xff) { ok=0; j=tlen } else { j=j+1 } }
1179 if ok == 1 { return 1 }
1180 i = i + 1
1181 }
1182 return 0
1183}
1184func br_find(page: *Page, term: *u8, tlen: i64, yb: *i64) -> i64 {
1185 page.find_ptr = term as i64
1186 page.find_len = tlen
1187 yb[0] = 0 - 1
1188 if tlen <= 0 { page.find_ptr = 0; return 0 }
1189 let tree: *LayoutTree = page.tree
1190 var matches: i64 = 0
1191 var i: i64 = 0
1192 while i < tree.count {
1193 let b: *LayoutBox = ((tree.boxes as i64) + i * NX_LAYOUT_BOX_BYTES) as *LayoutBox
1194 if b.kind == NX_LAYOUT_BOX_TEXT { if b.text_len > 0 {
1195 if br_box_has_term(page.buf, b.text_off, b.text_len, term, tlen) == 1 {
1196 matches = matches + 1
1197 if yb[0] < 0 { yb[0] = b.y }
1198 }
1199 } }
1200 i = i + 1
1201 }
1202 if matches == 0 { page.find_ptr = 0 } // nothing to highlight
1203 return matches
1204}
1205
1206func br_color_from_int(c: i64) -> *CssColor {
1207 let col: *CssColor = sys_mmap(NX_CSS_COLOR_BYTES) as *CssColor
1208 col.r = (c >> 16) & 0xff
1209 col.g = (c >> 8) & 0xff
1210 col.b = c & 0xff
1211 col.a = 255
1212 return col
1213}
1214
1215func br_bit(ft8: *u8, go: i64, col: i64, row: i64) -> i64 {
1216 if col < 0 { return 0 }
1217 if col > 7 { return 0 }
1218 if row < 0 { return 0 }
1219 if row > 7 { return 0 }
1220 if ((ft8[go + row] >> col) & 1) == 1 { return 255 }
1221 return 0
1222}
1223// bilinear coverage of glyph `go` at bit-space (fx256,fy256) in 1/256 fixed point (bit centers on integers)
1224func br_glyph_cov(ft8: *u8, go: i64, fx256: i64, fy256: i64) -> i64 {
1225 let x0: i64 = fx256 >> 8
1226 let y0: i64 = fy256 >> 8
1227 let fxr: i64 = fx256 & 255
1228 let fyr: i64 = fy256 & 255
1229 let v00: i64 = br_bit(ft8, go, x0, y0)
1230 let v10: i64 = br_bit(ft8, go, x0+1, y0)
1231 let v01: i64 = br_bit(ft8, go, x0, y0+1)
1232 let v11: i64 = br_bit(ft8, go, x0+1, y0+1)
1233 let top: i64 = v00*(256-fxr) + v10*fxr
1234 let bot: i64 = v01*(256-fxr) + v11*fxr
1235 return (top*(256-fyr) + bot*fyr) >> 16
1236}
1237// SHARPEN the raw bilinear coverage: solidify stroke interiors (>= BR_HI -> 255, keeps thin 1-bit stems
1238// crisp = legibility) while KEEPING the outer edge ramp as intermediate gray (= anti-aliasing). This is
1239// the knob that makes both the OCR judge (legibility) AND the polish census (AA) happy at once.
1240const BR_LO: i64 = 40
1241const BR_HI: i64 = 165
1242func br_sharpen(c: i64) -> i64 {
1243 if c <= BR_LO { return 0 }
1244 if c >= BR_HI { return 255 }
1245 return ((c - BR_LO) * 255) / (BR_HI - BR_LO)
1246}
1247// coverage for one output pixel: INTERIOR pixels (nearest bit + its 4 orthogonal neighbors all set) stay
1248// SOLID 255 -- pixel-exact, no resample shift, so legibility is preserved; only EDGE pixels take the
1249// sharpened bilinear ramp = anti-aliasing. This is what holds 984 OCR AND closes the polish gap.
1250func br_cov_hybrid(ft8: *u8, go: i64, fx256: i64, fy256: i64) -> i64 {
1251 let cc: i64 = (fx256 + 128) >> 8 // nearest bit col
1252 let rr: i64 = (fy256 + 128) >> 8 // nearest bit row
1253 if br_bit(ft8, go, cc, rr) == 255 {
1254 if br_bit(ft8, go, cc-1, rr) == 255 { if br_bit(ft8, go, cc+1, rr) == 255 {
1255 if br_bit(ft8, go, cc, rr-1) == 255 { if br_bit(ft8, go, cc, rr+1) == 255 {
1256 return 255
1257 } }
1258 } }
1259 }
1260 return br_sharpen(br_glyph_cov(ft8, go, fx256, fy256))
1261}
1262
1263// PROPORTIONAL + ANTI-ALIASED bitmap text: bilinear coverage of the glyph field (smooth edges) + a
1264// sharpening curve (solid interiors), alpha-blended onto the RGBA framebuffer. Closes the polish gap vs
1265// Chrome AND holds the 984 legibility. Pen advance = font8x8_adv (measured-layout SSOT), layout truthful.
1266func br_paint_text2x(fb: *Framebuffer, x: i64, y: i64, text: *u8, text_len: i64, color: *CssColor, scale: i64) -> i64 {
1267 let ft8: *u8 = font8x8_table()
1268 let blk: i64 = scale
1269 let GH: i64 = 8 * blk // glyph render height in px
1270 let fw: i64 = fb.width
1271 let fh: i64 = fb.height
1272 let pxb: *u8 = fb.pixels
1273 let cr: i64 = color.r & 255
1274 let cg: i64 = color.g & 255
1275 let cb: i64 = color.b & 255
1276 var pen: i64 = x
1277 var i: i64 = 0
1278 while i < text_len {
1279 let ch: i64 = text[i] & 0xff
1280 if ch > 0x20 { if ch <= 0x7E {
1281 let go: i64 = (ch - 0x20) * 8
1282 let iw: i64 = font8x8_ink_w(ft8, ch) // ink columns (proportional)
1283 var GW: i64 = iw * blk
1284 if GW < blk { GW = blk }
1285 let sxn: i64 = (iw * 256) / GW // bit-cols per output px * 256
1286 let syn: i64 = (8 * 256) / GH // bit-rows per output px * 256
1287 var oy: i64 = 0
1288 while oy < GH {
1289 let fy256: i64 = ((oy * 2 + 1) * syn) / 2 - 128 // (oy+0.5)*syn - 0.5 bit
1290 let fyr: i64 = y + oy
1291 if fyr >= 0 { if fyr < fh {
1292 var ox: i64 = 0
1293 while ox < GW {
1294 let fx256: i64 = ((ox * 2 + 1) * sxn) / 2 - 128
1295 let a: i64 = br_cov_hybrid(ft8, go, fx256, fy256)
1296 if a > 0 {
1297 let fxr: i64 = pen + ox
1298 if fxr >= 0 { if fxr < fw {
1299 let o: i64 = (fyr * fw + fxr) * 4
1300 let ia: i64 = 255 - a
1301 pxb[o] = (((pxb[o] as i64) * ia + cr * a) / 255) as u8
1302 pxb[o+1] = (((pxb[o+1] as i64) * ia + cg * a) / 255) as u8
1303 pxb[o+2] = (((pxb[o+2] as i64) * ia + cb * a) / 255) as u8
1304 pxb[o+3] = 255 as u8
1305 } }
1306 }
1307 ox = ox + 1
1308 }
1309 } }
1310 oy = oy + 1
1311 }
1312 } }
1313 pen = pen + font8x8_adv(ft8, ch) * blk
1314 i = i + 1
1315 }
1316 return pen - x
1317}
1318
1319// Blit a decoded RGB image (src = w*h*3, row-major) into the RGBA framebuffer at (dx,dy), nearest-neighbor
1320// scaled to boxW x boxH, clipped to fb bounds. The missing image-paint primitive (nx_paint_solid_rect does
1321// solid fills; this does image copy). A=255 (opaque). RGB source because nx_img_to_rgb/JPEG emit w*h*3.
1322func br_blit_rgb(fb: *Framebuffer, dx: i64, dy: i64, boxW: i64, boxH: i64, src: *u8, sw: i64, sh: i64) -> i64 {
1323 if boxW <= 0 { return 0 }
1324 if boxH <= 0 { return 0 }
1325 if sw <= 0 { return 0 }
1326 if sh <= 0 { return 0 }
1327 let fw: i64 = fb.width
1328 let fh: i64 = fb.height
1329 let px: *u8 = fb.pixels
1330 var ty: i64 = 0
1331 while ty < boxH {
1332 let py: i64 = dy + ty
1333 if py >= 0 { if py < fh {
1334 let sy: i64 = (ty * sh) / boxH
1335 var tx: i64 = 0
1336 while tx < boxW {
1337 let pxx: i64 = dx + tx
1338 if pxx >= 0 { if pxx < fw {
1339 let sx: i64 = (tx * sw) / boxW
1340 let so: i64 = (sy * sw + sx) * 3
1341 let dof: i64 = (py * fw + pxx) * 4
1342 px[dof + 0] = src[so + 0]
1343 px[dof + 1] = src[so + 1]
1344 px[dof + 2] = src[so + 2]
1345 px[dof + 3] = 255 as u8
1346 } }
1347 tx = tx + 1
1348 }
1349 } }
1350 ty = ty + 1
1351 }
1352 return 0
1353}
1354
1355// OFF-SCREEN render: rasterize the laid-out page into an in-memory RGBA framebuffer (no X server). Uses the
1356// 5x7 bitmap-font paint primitives (for verifying colors/layout/chrome). The same fn the GUI calls to paint.
1357// draw with a vertical SCROLL offset (page-space px): content shifts up by scroll_y, chrome stays fixed.
1358// br_draw_fb delegates with scroll 0, so existing callers (incl the parallel-owned GUI) are unaffected.
1359func br_draw_fb_at(fb: *Framebuffer, page: *Page, win_w: i64, cur_url: *u8, ulen: i64, scale: i64, scroll_y: i64) -> i64 {
1360 let tree: *LayoutTree = page.tree
1361 let src: *u8 = page.buf
1362 let computed: *CssComputedDecl = page.computed
1363 let ncomp: i64 = page.ncomp
1364 // DERIVED decode buffer (2026-08-25). Sized from the LONGEST text run actually in this tree, so
1365 // no run can be truncated. The bound is EXACT, not a guess: entity decoding and ASCII folding
1366 // both SHRINK-or-equal (&->&, a multi-byte UTF-8 codepoint -> one ASCII byte), so a decoded
1367 // run is never longer than its source. This replaces a hand-picked TRIO -- sys_mmap(1100), a
1368 // 1024 cap and a 960 input clamp -- that silently truncated any text box over 960 bytes while
1369 // LAYOUT had measured and reserved the full height for it, so paint dropped text the page had
1370 // already made room for. mmap faults pages in on demand, so the headroom costs address space,
1371 // not resident memory.
1372 var fdcap: i64 = 1
1373 var fdi: i64 = 0
1374 while fdi < tree.count {
1375 let fdb: *LayoutBox = ((tree.boxes as i64) + fdi * NX_LAYOUT_BOX_BYTES) as *LayoutBox
1376 if fdb.text_len > fdcap { fdcap = fdb.text_len }
1377 fdi = fdi + 1
1378 }
1379 fdcap = fdcap + 2
1380 let fdec: *u8 = sys_mmap(fdcap) // reused per text box: decode HTML entities before painting
1381 var base_bg: i64 = 0x00FFFFFF
1382 if page.dark_mode == 1 { base_bg = 0x000E1116 } // dark base so uncovered margin areas match the theme
1383 // CSS BACKGROUND PROPAGATION (SPEC semantics): the canvas takes the background of the ROOT elements
1384 // ONLY -- html/body (boxes 0..1) -- exactly like Chrome. The first version scanned ALL blocks for the
1385 // first non-white bg; the top-20 suite caught it painting google.com's whole canvas dark off a banner
1386 // div (coarse parity 0.0%). var() bgs on body resolve through cx_expand, so /experiential's dark body
1387 // still propagates. Gated on dark_mode==0 (explicit reader theme keeps its base).
1388 if page.dark_mode == 0 {
1389 // walk the ROOT CHAIN: from the parentless root, descend while the current box has exactly ONE
1390 // full-width BLOCK child (html -> wrapper -> body in our tree); the first background on that chain
1391 // is the canvas (spec: html/body propagate). A box with SIBLING blocks (google's banner divs) ends
1392 // the chain -- content never propagates. (The first-non-white-anywhere version painted google's
1393 // canvas dark off a banner; the parentless-root-only version missed body at depth 2 -- both caught
1394 // by the top-20 suite + the /experiential void-luma regression check.)
1395 var cur: i64 = 0 - 1
1396 var cbi: i64 = 0
1397 while cbi < tree.count {
1398 if cur < 0 {
1399 let cb0: *LayoutBox = ((tree.boxes as i64) + cbi * NX_LAYOUT_BOX_BYTES) as *LayoutBox
1400 if cb0.kind == NX_LAYOUT_BOX_BLOCK { if cb0.parent_idx < 0 { cur = cbi } }
1401 }
1402 cbi = cbi + 1
1403 }
1404 var hops: i64 = 0
1405 while cur >= 0 {
1406 if hops >= 6 { cur = 0 - 1 }
1407 else {
1408 hops = hops + 1
1409 let cb: *LayoutBox = ((tree.boxes as i64) + cur * NX_LAYOUT_BOX_BYTES) as *LayoutBox
1410 let cbg: i64 = br_comp_bg(src, computed, ncomp, cur)
1411 if cbg >= 0 { if cbg != 0x00FFFFFF { base_bg = cbg; cur = 0 - 1 } }
1412 if cur >= 0 {
1413 // exactly one full-width BLOCK child continues the chain
1414 var only: i64 = 0 - 1
1415 var nfull: i64 = 0
1416 var ci: i64 = cb.first_child_idx
1417 var guard: i64 = 0
1418 while ci >= 0 {
1419 if guard >= 4096 { ci = 0 - 1 }
1420 else {
1421 guard = guard + 1
1422 let cc: *LayoutBox = ((tree.boxes as i64) + ci * NX_LAYOUT_BOX_BYTES) as *LayoutBox
1423 if cc.kind == NX_LAYOUT_BOX_BLOCK { if cc.w == cb.w { nfull = nfull + 1; only = ci } }
1424 ci = cc.next_sibling_idx
1425 }
1426 }
1427 if nfull == 1 { cur = only } else { cur = 0 - 1 }
1428 }
1429 }
1430 }
1431 }
1432 nx_paint_solid_rect(fb, 0, 0, win_w * scale, fb.height, br_color_from_int(base_bg))
1433 var i: i64 = 0
1434 let bwp: *i64 = sys_mmap(16) as *i64 // border width out-slot (hoisted: no mmap in the loop)
1435 while i < tree.count {
1436 let b: *LayoutBox = ((tree.boxes as i64) + i * NX_LAYOUT_BOX_BYTES) as *LayoutBox
1437 var _pbx: i64 = 0
1438 if b.kind == NX_LAYOUT_BOX_BLOCK { _pbx = 1 }
1439 if b.kind == NX_LAYOUT_BOX_INLINE_BLOCK { _pbx = 1 } // atomic inline-block (chips/tags/buttons) now paint bg+border
1440 if _pbx == 1 { if b.w > 0 { if b.h > 0 {
1441 let bg: i64 = br_comp_bg(src, computed, ncomp, i)
1442 if bg >= 0 { if bg != 0x00FFFFFF { nx_paint_solid_rect(fb, b.x * scale, (b.y - scroll_y + NX_CHROME_H) * scale, b.w * scale, b.h * scale, br_color_from_int(bg)) } }
1443 // CSS borders (the `border` shorthand): stroke the 4 edges -- tables/cards get real lines
1444 let bc: i64 = br_comp_border(src, computed, ncomp, i, bwp)
1445 if bc >= 0 {
1446 let bw2: i64 = bwp[0]
1447 nx_paint_solid_rect(fb, b.x * scale, (b.y - scroll_y + NX_CHROME_H) * scale, b.w * scale, bw2 * scale, br_color_from_int(bc))
1448 nx_paint_solid_rect(fb, b.x * scale, (b.y - scroll_y + NX_CHROME_H + b.h - bw2) * scale, b.w * scale, bw2 * scale, br_color_from_int(bc))
1449 nx_paint_solid_rect(fb, b.x * scale, (b.y - scroll_y + NX_CHROME_H) * scale, bw2 * scale, b.h * scale, br_color_from_int(bc))
1450 nx_paint_solid_rect(fb, (b.x + b.w - bw2) * scale, (b.y - scroll_y + NX_CHROME_H) * scale, bw2 * scale, b.h * scale, br_color_from_int(bc))
1451 }
1452 } } }
1453 i = i + 1
1454 }
1455 // FIND-IN-PAGE highlight pass: a yellow band behind every text box matching the active search term
1456 // (drawn under the text so the glyphs stay readable). Only runs when a find is active.
1457 if page.find_ptr != 0 {
1458 let fterm: *u8 = page.find_ptr as *u8
1459 i = 0
1460 while i < tree.count {
1461 let b: *LayoutBox = ((tree.boxes as i64) + i * NX_LAYOUT_BOX_BYTES) as *LayoutBox
1462 if b.kind == NX_LAYOUT_BOX_TEXT { if b.text_len * b.h > 0 { // h==0 = never laid out (hidden subtree) -> no highlight
1463 if br_box_has_term(src, b.text_off, b.text_len, fterm, page.find_len) == 1 {
1464 var hw: i64 = b.w
1465 if hw < 8 { hw = 8 }
1466 nx_paint_solid_rect(fb, b.x * scale, (b.y - scroll_y + NX_CHROME_H) * scale, hw * scale, 17 * scale, br_color_from_int(0x00FFE066))
1467 }
1468 } }
1469 i = i + 1
1470 }
1471 }
1472 i = 0
1473 while i < tree.count {
1474 let b: *LayoutBox = ((tree.boxes as i64) + i * NX_LAYOUT_BOX_BYTES) as *LayoutBox
1475 let syt: i64 = (b.y - scroll_y + NX_CHROME_H) * scale // VIEWPORT CULL: off-screen text boxes skip the
1476 var vis: i64 = 1 // expensive vector/bitmap raster (fb.height = full
1477 if syt > fb.height { vis = 0 } // page for the shot path -> renders all; = 720 for
1478 if syt + (b.h + 80) * scale < 0 { vis = 0 } // the GUI -> only ~visible boxes -> fast + no hang)
1479 if vis == 1 {
1480 // NEVER-LAID GUARD (seq1130): a text box under a display:none ancestor is never reached by
1481 // _layout_block_recurse -- it keeps x=0,y=0,w=0,h=0 from tree init. Painting it wraps the run
1482 // at the w=0 minimum and stacks every hidden run at the origin = the "blob rail". Layout is the
1483 // only writer of b.h and always sets it > 0 for a placed text box, so h==0 means NOT LAID OUT.
1484 // text_len*h > 0 == (text_len > 0 AND h > 0) for the non-negative fields.
1485 if b.kind == NX_LAYOUT_BOX_TEXT { if b.text_len * b.h > 0 {
1486 let par: i64 = b.parent_idx
1487 var col: i64 = br_comp_color_inh(src, computed, ncomp, tree, par) // CSS-inherited color
1488 if col < 0 { col = 0 }
1489 let nn: i64 = b.text_len
1490 let dn0: i64 = nx_html_decode_entities(src, b.text_off, nn, fdec, fdcap)
1491 let dn: i64 = br_fold_text(fdec, 0, dn0, fdec, fdcap) // BR30: fold only what the face lacks (same policy as layout's pre-pass); no face: UTF-8 -> renderable ASCII (accents->base, curly->straight, mdash->-): real pages render in the vector font. Identity for ASCII -> gate pages byte-unchanged.
1492 let fs: i64 = br_comp_fontsize_inh(src, computed, ncomp, tree, par, 16) // PROPORTIONAL: size text by the INHERITED cascade incl the `font` shorthand (same rule as layout -> measure==paint)
1493 let lh_run: i64 = br_comp_lineheight_px(src, computed, ncomp, tree, par, fs) // CSS line-height (same resolver rule as layout)
1494 var tscale: i64 = 1
1495 if fs >= 24 { tscale = 2 } // MUST match _layout_scale_for_px (24/36 buckets)
1496 if fs >= 36 { tscale = 3 } // so painted glyph size == the layout's reserved metrics
1497 // VECTOR TEXT: opt-in; any run (headings AND body -- vector is now OCR-legible to 14px, proven by
1498 // nx_vecfont_body_bench's size ladder) whose chars all have vector glyphs is painted with the
1499 // proportional stroke font instead of the bitmap monospace (the "typewriter" body). empx = the
1500 // cascade font-size x paint scale (exact). Vector is proportional+tighter than the bitmap the
1501 // layout reserved -> fits the box. vec_headings==2 forces body-too; ==1 keeps headings-only.
1502 var did_vec: i64 = 0
1503 var vec_ok: i64 = 0
1504 if page.vec_headings == 1 { if tscale >= 2 { vec_ok = 1 } }
1505 if page.vec_headings == 2 { vec_ok = 1 }
1506 if vec_ok == 1 {
1507 br_face_resolve(src, computed, ncomp, tree, par) // BR27: the same face layout measured with, selected for paint
1508 var run_ok: i64 = font_run_has(fdec, dn)
1509 if bpv_fast_on == 1 { run_ok = font_run_has_ext(fdec, dn) } // GUI/atlas covers % [ ] ; " = + too
1510 if br_face != 0 { run_ok = font_run_vec_ok(fdec, dn) } // a real face covers every printable ASCII byte -- the SAME test layout used
1511 if run_ok == 1 {
1512 let empx: i64 = fs * scale
1513 // HALF-LEADING: CSS centers the glyph line inside the line box; without this, text
1514 // sits at box top and every line lands ~leading/2 higher than Chrome.
1515 var hl: i64 = 0
1516 if lh_run >= 8 {
1517 let gl: i64 = br_face_line_h(fs) // the face (asc - desc) when a face is on, else the stroke band
1518 if lh_run > gl { hl = (lh_run - gl) / 2 }
1519 }
1520 if lh_run >= 8 { bpv_line_adv = lh_run * scale } else { bpv_line_adv = 0 }
1521 br_paint_vec(fb, (b.x + 4) * scale, (b.y + hl - scroll_y + NX_CHROME_H) * scale, fdec, dn, empx, br_color_from_int(col), b.w * scale)
1522 bpv_line_adv = 0
1523 did_vec = 1
1524 }
1525 }
1526 if did_vec == 0 {
1527 // WORD-WRAP long runs by MEASURED advances -- the SAME font8x8_next_break the measured layout
1528 // reserved lines with, over the same avail budget (b.w/tscale in 1x units), so painted lines
1529 // exactly fill the reserved box. Short runs take the single-line path unchanged.
1530 let wtab: *u8 = font8x8_table()
1531 var avail_u: i64 = b.w / tscale
1532 if avail_u < 4 { avail_u = 4 }
1533 var lhadv: i64 = 17 * tscale
1534 if lh_run >= 8 { lhadv = lh_run } // CSS line-height: advance wrapped lines exactly as layout reserved
1535 var hl2: i64 = 0
1536 if lhadv > 17 * tscale { hl2 = (lhadv - 17 * tscale) / 2 } // half-leading (center in the line box)
1537 var pos: i64 = 0
1538 var li: i64 = 0
1539 var w1: i64 = 0 // drawn width of the first line (underline = text width)
1540 while pos < dn {
1541 var e: i64 = font8x8_next_break(wtab, fdec, dn, avail_u, pos)
1542 if e <= pos { e = dn }
1543 let dw: i64 = br_paint_text2x(fb, (b.x + 4) * scale, (b.y + hl2 - scroll_y + NX_CHROME_H + 1 + li * lhadv) * scale, ((fdec as i64)+pos) as *u8, e - pos, br_color_from_int(col), tscale * scale)
1544 if li == 0 { w1 = dw }
1545 pos = e
1546 li = li + 1
1547 // DERIVED loop bound: a line consumes at least one character, so li can never
1548 // legitimately exceed dn. It is termination insurance, NOT a line budget -- the
1549 // hand-picked 60 here silently dropped every line past the 60th that layout had
1550 // already reserved height for.
1551 if li > dn { pos = dn }
1552 }
1553 var is_link: i64 = 0
1554 if col == 0x2563eb { is_link = 1 } // light-theme link blue
1555 if col == 0x6aa3ff { is_link = 1 } // dark-theme link blue
1556 if is_link == 1 { nx_paint_solid_rect(fb, (b.x + 4) * scale, (b.y - scroll_y + NX_CHROME_H + 1 + 14 * tscale) * scale, w1, tscale * scale, br_color_from_int(col)) } // underline links (drawn-text width)
1557 }
1558 } } }
1559 i = i + 1
1560 }
1561 // IMAGE pass: blit decoded <img> pixels (the consumer fills page.bimg via fetch+decode) at each img
1562 // box's laid-out position. ADDITIVE -- the layout algorithm is untouched; images paint over the flow.
1563 i = 0
1564 while i < tree.count {
1565 let ib: *LayoutBox = ((tree.boxes as i64) + i * NX_LAYOUT_BOX_BYTES) as *LayoutBox
1566 let ip: i64 = page.bimg[i]
1567 if ip != 0 {
1568 let iw: i64 = page.bimg_w[i]
1569 let ih: i64 = page.bimg_h[i]
1570 var dw: i64 = iw
1571 // HIDDEN-SUBTREE GUARD, CORRECTED (2026-07-29). The seq1130 rule "h<=0 ⇒ never laid ⇒
1572 // don't paint" is right for TEXT but WRONG for <img>: an image with no CSS width/height
1573 // legitimately has h=0 until its intrinsic size is known (only after fetch+decode), so
1574 // that guard silently killed 100% of images on every page (measured: imgsrc=11,
1575 // imgsrc_laid=0). Ask the RIGHT question instead — is the image's CONTAINER laid out? A
1576 // hidden subtree has a 0-height PARENT; a not-yet-sized <img> sits inside a laid parent.
1577 if ib.h <= 0 {
1578 var par_laid: i64 = 0
1579 if ib.parent_idx >= 0 {
1580 let ipb: *LayoutBox = ((tree.boxes as i64) + ib.parent_idx * NX_LAYOUT_BOX_BYTES) as *LayoutBox
1581 if ipb.h > 0 { par_laid = 1 }
1582 }
1583 if par_laid == 0 { dw = 0 }
1584 }
1585 let avail: i64 = win_w - ib.x - 8
1586 if dw > avail { dw = avail } // cap to viewport width
1587 var dh: i64 = ih
1588 if dw < iw { if iw > 0 { dh = ih * dw / iw } } // preserve aspect on downscale
1589 if dw > 0 { if dh > 0 {
1590 br_blit_rgb(fb, ib.x * scale, (ib.y - scroll_y + NX_CHROME_H) * scale, dw * scale, dh * scale, ip as *u8, iw, ih)
1591 } }
1592 }
1593 i = i + 1
1594 }
1595 // chrome (all coords * scale) -- Chrome-palette grays, same geometry (hit-tests unchanged). Dark theme
1596 // swaps the palette (near-black toolbar + light glyphs) so the whole browser is coherent in dark mode.
1597 var c_bar: i64 = 0x00F1F3F4
1598 var c_edge: i64 = 0x00DADCE0
1599 var c_btn: i64 = 0x00F6F8FA
1600 var c_field: i64 = 0x00FFFFFF
1601 var c_ink: i64 = 0x00202124
1602 if page.dark_mode == 1 { c_bar=0x001A1F28; c_edge=0x00303845; c_btn=0x00232833; c_field=0x000E1116; c_ink=0x00D4DAE3 }
1603 nx_paint_solid_rect(fb, 0, 0, win_w * scale, NX_CHROME_H * scale, br_color_from_int(c_bar))
1604 nx_paint_solid_rect(fb, 0, (NX_CHROME_H - 1) * scale, win_w * scale, scale, br_color_from_int(c_edge))
1605 nx_paint_solid_rect(fb, 8 * scale, 8 * scale, 30 * scale, 28 * scale, br_color_from_int(c_btn))
1606 nx_paint_solid_rect(fb, 44 * scale, 8 * scale, 30 * scale, 28 * scale, br_color_from_int(c_btn))
1607 nx_paint_solid_rect(fb, 80 * scale, 8 * scale, 30 * scale, 28 * scale, br_color_from_int(c_btn))
1608 br_paint_text2x(fb, 18 * scale, 16 * scale, "<\x00" as *u8, 1, br_color_from_int(c_ink), scale)
1609 br_paint_text2x(fb, 54 * scale, 16 * scale, ">\x00" as *u8, 1, br_color_from_int(c_ink), scale)
1610 br_paint_text2x(fb, 90 * scale, 16 * scale, "R\x00" as *u8, 1, br_color_from_int(c_ink), scale)
1611 let bx: i64 = 118
1612 nx_paint_solid_rect(fb, bx * scale, 8 * scale, (win_w - bx - 10) * scale, 28 * scale, br_color_from_int(c_field))
1613 var un: i64 = ulen
1614 if un > 110 { un = 110 }
1615 br_paint_text2x(fb, (bx + 6) * scale, 14 * scale, cur_url, un, br_color_from_int(c_ink), scale)
1616 return 0
1617}
1618
1619// the un-scrolled draw every existing caller uses (delegates; page top at the viewport top).
1620func br_draw_fb(fb: *Framebuffer, page: *Page, win_w: i64, cur_url: *u8, ulen: i64, scale: i64) -> i64 {
1621 return br_draw_fb_at(fb, page, win_w, cur_url, ulen, scale, 0)
1622}
1623
1624// render the laid-out page to a 1000xSH RGBA framebuffer and write it as a PNG at `path`
1625// FULL-PAGE SHOT (2026-07-27). SH was hardcoded 1000 = ONE SCREENFUL, while Chrome's
1626// --screenshot captures the WHOLE document. Comparing the two graded Nishi on ~21% of a
1627// page against Chrome on 100% of it -- so the only honest fixes are to raise Nishi to
1628// Chrome's behaviour (this) or to cripple the oracle (never). Capture the full laid-out
1629// height, clamped: floor 1000 (an empty/short page still yields a normal-looking shot),
1630// ceiling 20000 (a runaway page_h can't ask for a gigabyte framebuffer).
1631func br_shot_png(page: *Page, cur_url: *u8, ulen: i64, path: *u8) -> i64 {
1632 let SW: i64 = 1000
1633 var SH: i64 = page.page_h
1634 if SH < 1000 { SH = 1000 }
1635 if SH > 20000 { SH = 20000 }
1636 let fb: *Framebuffer = sys_mmap(NX_FRAMEBUFFER_BYTES) as *Framebuffer
1637 let px: *u8 = sys_mmap(SW * SH * 4 + 64)
1638 nx_framebuffer_init(fb, px, SW, SH)
1639 br_draw_fb(fb, page, SW, cur_url, ulen, 1)
1640 let rgb: *u8 = sys_mmap(SW * SH * 3 + 64)
1641 var p: i64 = 0
1642 while p < SW * SH {
1643 rgb[p * 3 + 0] = px[p * 4 + 0]
1644 rgb[p * 3 + 1] = px[p * 4 + 1]
1645 rgb[p * 3 + 2] = px[p * 4 + 2]
1646 p = p + 1
1647 }
1648 nx_png_write_rgb(path, rgb, SW, SH)
1649 return 0
1650}
1651
1652// hit-test: find a box with an href whose rect contains doc-point (dx,dy). 1 + sets off/len, else 0.
1653// CONTAINER ANCHORS (2026-07-03): an <a> wrapping block children (e.g. a card link: <a><h3>..</h3>
1654// <p>..</p></a>) lays out with a ZERO own-rect -- its geometry lives in its DESCENDANT boxes. Such
1655// links were dead to clicks (found by nx_aw_browser_gate on the real andelinwest pages). For an href
1656// box with no height, hit-test the UNION of its descendants' rects instead. Purely additive: boxes
1657// with real rects behave exactly as before; zero-rect href boxes previously matched NOTHING.
1658func br_hit_link(page: *Page, dx: i64, dy: i64, off: *i64, len: *i64) -> i64 {
1659 let tree: *LayoutTree = page.tree
1660 var i: i64 = 0
1661 while i < tree.count {
1662 if page.bhref_off[i] >= 0 {
1663 let b: *LayoutBox = ((tree.boxes as i64) + i * NX_LAYOUT_BOX_BYTES) as *LayoutBox
1664 var bx: i64 = b.x
1665 var by: i64 = b.y
1666 var bw: i64 = b.w
1667 var bh: i64 = b.h
1668 if bh <= 0 {
1669 // SIBLING-SPAN effective rect: the layout FLATTENS a container anchor's children to
1670 // its SIBLINGS (observed: card content boxes follow the zero-rect anchor box under
1671 // the same parent). Union the rects of the boxes AFTER i while they stay inside i's
1672 // parent's subtree, stopping at the next href-carrying box (= the next link).
1673 let par: i64 = b.parent_idx
1674 var x0: i64 = 0
1675 var y0: i64 = 0
1676 var x1: i64 = 0
1677 var y1: i64 = 0
1678 var any: i64 = 0
1679 var j: i64 = i + 1
1680 var span: i64 = 1
1681 while span == 1 {
1682 if j >= tree.count { span = 0 }
1683 else { if page.bhref_off[j] >= 0 { span = 0 }
1684 else {
1685 let cb: *LayoutBox = ((tree.boxes as i64) + j * NX_LAYOUT_BOX_BYTES) as *LayoutBox
1686 // is j inside par's subtree? (bounded parent-chain walk, cycle-safe)
1687 var p: i64 = cb.parent_idx
1688 var hop: i64 = 0
1689 var inside: i64 = 0
1690 while hop < 64 {
1691 if p == (0 - 1) { hop = 64 }
1692 else { if p == par { inside = 1; hop = 64 }
1693 else { let pb: *LayoutBox = ((tree.boxes as i64) + p * NX_LAYOUT_BOX_BYTES) as *LayoutBox; p = pb.parent_idx; hop = hop + 1 } }
1694 }
1695 if inside == 0 { span = 0 }
1696 else {
1697 if cb.w > 0 { if cb.h > 0 {
1698 if any == 0 { x0 = cb.x; y0 = cb.y; x1 = cb.x + cb.w; y1 = cb.y + cb.h; any = 1 }
1699 else {
1700 if cb.x < x0 { x0 = cb.x }
1701 if cb.y < y0 { y0 = cb.y }
1702 if cb.x + cb.w > x1 { x1 = cb.x + cb.w }
1703 if cb.y + cb.h > y1 { y1 = cb.y + cb.h }
1704 }
1705 } }
1706 j = j + 1
1707 }
1708 } }
1709 }
1710 if any == 1 { bx = x0; by = y0; bw = x1 - x0; bh = y1 - y0 }
1711 }
1712 var hitw: i64 = bw // layout metric now matches the 9px render font, so b.w is the true width
1713 if hitw < 12 { hitw = 12 }
1714 if dx >= bx { if dx < bx + hitw { if dy >= by { if dy < by + bh {
1715 off[0] = page.bhref_off[i]; len[0] = page.bhref_len[i]; return 1
1716 } } } }
1717 }
1718 i = i + 1
1719 }
1720 return 0
1721}