commit 28f98dc1b7540aaa87e88c2d79c95d8e0334641a
Author: Waozi
Date: Mon Oct 5 21:22:57 2026 -0300
Build a native Ziran HTML and CSS browser with Kryon
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..1cea8f1
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
+/build/
+/ziran.local.toml
+__pycache__/
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000..a9b7f08
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,8 @@
+# Browser
+
+The HTML parser, CSS cascade, document model, layout and product UI belong in
+this repository, written in Ziran with Kryon. The Python worker only fetches
+documents and resolves URLs; it never renders a page or invokes another browser.
+Keep credentials out of logs. Do not run page scripts or submitted forms as
+shell commands. Tests and screenshots run on private Xvfb with inherited
+display and session variables removed. Never edit dependency checkouts.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..08c0e6b
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,23 @@
+.DEFAULT_GOAL := build
+ZIRAN ?= ziran
+PREFIX ?= $(HOME)/.local
+.PHONY: build check test window-test install
+build:
+ $(ZIRAN) build
+ cp scripts/fetch.py scripts/start.html build/
+check:
+ $(ZIRAN) check
+test: check
+ python3 -m unittest discover -s tests -v
+ $(ZIRAN) build --project --root tests --target=c --entry document_test:Main --exe -o build/document-test tests/document_test.zi
+ build/document-test/document_test
+window-test: build
+ env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS -u SESSION_MANAGER YUE_DESKTOP_RECOVERY=0 xvfb-run -a -s '-screen 0 1280x1024x24' env BROWSER_PRIVATE_XVFB=1 python3 tests/window_test.py
+install: build
+ mkdir -p "$(PREFIX)/bin" "$(PREFIX)/lib/browser" "$(PREFIX)/share/applications" "$(PREFIX)/share/icons/hicolor/scalable/apps"
+ install -m 755 build/browser-desktop "$(PREFIX)/lib/browser/browser-desktop"
+ install -m 644 scripts/fetch.py scripts/start.html "$(PREFIX)/lib/browser/"
+ install -m 644 assets/browser.svg "$(PREFIX)/share/icons/hicolor/scalable/apps/kryon-browser.svg"
+ printf '%s\n' '#!/bin/sh' 'exec "$(PREFIX)/lib/browser/browser-desktop" "$$@"' > "$(PREFIX)/bin/kryon-browser"
+ chmod 755 "$(PREFIX)/bin/kryon-browser"
+ printf '%s\n' '[Desktop Entry]' 'Type=Application' 'Name=Browser' 'Exec=$(PREFIX)/bin/kryon-browser' 'Icon=kryon-browser' 'Terminal=false' 'Categories=Network;WebBrowser;' > "$(PREFIX)/share/applications/kryon-browser.desktop"
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..a9e6490
--- /dev/null
+++ b/README.md
@@ -0,0 +1,41 @@
+# Browser
+
+A native document browser written in Ziran with Kryon, built from its own
+HTML parser, CSS cascade and block layout. Its separate repository is
+`kryonlabs/browser`. Harmony embeds its window; `kryon-browser` runs it
+independently from the desktop. No Chromium or WebKit engine renders pages.
+
+Enter an HTTP(S) address or local `file:///` URL. Links navigate within the app.
+Back and Next restore history and scroll positions. Pages wrap to the window
+and scroll independently. Ctrl+L selects the address. Fetching runs outside the
+UI frame in a Python IO worker; parsing and rendering stay in Ziran.
+
+The initial engine supports headings, paragraphs, lists, links, preformatted
+text, image descriptions and malformed HTML recovery. Embedded/inline CSS
+supports element/class/ID selectors, per-property specificity, inheritance,
+colors, backgrounds, font sizes, margins, padding, width/max-width and
+display:none. Colors include short/full hex and basic named colors.
+
+This is a basic document engine. Inline elements currently participate in block
+flow. JavaScript, forms, external stylesheets, decoded images, flexbox, grid,
+cookies and authentication remain future work. Limits are 512 KiB of input and
+240 tree nodes, with a visible notice when the tree preview is truncated.
+
+## Build and verify
+
+Install Ziran, SDL2, Cairo, FreeType, X11 and Python 3. Dependencies and compiler
+are pinned in `ziran.lock`; local development uses ignored package overrides.
+
+```sh
+ziran fetch --locked
+make test
+make window-test
+make install
+kryon-browser
+```
+
+Parser/CSS tests execute the production Ziran engine. Transport tests use
+disposable files. Window tests scrub inherited display/session variables and
+start private Xvfb, then exercise address input, HTML/CSS rendering, relative
+links, history, scrolling and a narrow window. Screenshots are written under
+`build/screenshots/`.
diff --git a/assets/browser.svg b/assets/browser.svg
new file mode 100644
index 0000000..1acfee7
--- /dev/null
+++ b/assets/browser.svg
@@ -0,0 +1 @@
+Browser
diff --git a/scripts/fetch.py b/scripts/fetch.py
new file mode 100644
index 0000000..bd016aa
--- /dev/null
+++ b/scripts/fetch.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python3
+"""Document IO only. Ziran owns HTML, CSS, layout and rendering."""
+import json
+import os
+from pathlib import Path
+import sys
+import tempfile
+from urllib.parse import urljoin, urlsplit, unquote
+from urllib.request import Request, urlopen, build_opener, HTTPRedirectHandler
+
+LIMIT = 524288
+
+
+def destination(value, base=""):
+ if value == "about:start":
+ return value
+ if ":" not in value and not base:
+ value = "https://" + value
+ url = urljoin(base, value)
+ parts = urlsplit(url)
+ if parts.scheme not in ("http", "https", "file") or parts.username or parts.password:
+ raise ValueError("Enter an HTTP(S) address or a local file URL.")
+ if parts.scheme == "file" and parts.netloc not in ("", "localhost"):
+ raise ValueError("Only local file URLs are supported.")
+ if parts.scheme in ("http", "https") and not parts.netloc:
+ raise ValueError("Enter a complete website address.")
+ return url
+
+
+class Redirects(HTTPRedirectHandler):
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ url = destination(newurl, req.full_url)
+ if urlsplit(url).scheme not in ("http", "https"):
+ raise ValueError("A website cannot redirect to a local file.")
+ return super().redirect_request(req, fp, code, msg, headers, url)
+
+
+def fetch(request):
+ url = destination(request.get("url", "about:start"), request.get("base", ""))
+ if url == "about:start":
+ content = (Path(__file__).resolve().parent / "start.html").read_bytes()
+ elif urlsplit(url).scheme == "file":
+ with Path(unquote(urlsplit(url).path)).open("rb") as source:
+ content = source.read(LIMIT + 1)
+ else:
+ req = Request(url, headers={"User-Agent": "KryonBrowser/0.1", "Accept": "text/html,text/plain;q=0.9"})
+ with build_opener(Redirects()).open(req, timeout=15) as response:
+ url = response.url
+ if response.headers.get_content_type() not in ("text/html", "text/plain", "application/xhtml+xml"):
+ raise ValueError("This resource is not an HTML or text document.")
+ content = response.read(LIMIT + 1)
+ if len(content) > LIMIT:
+ raise ValueError("This document exceeds the 512 KiB page limit.")
+ html = content.decode("utf-8", errors="replace")
+ if urlsplit(url).path.endswith(('.txt', '.zi', '.css')):
+ import html as escaping
+ html = "" + escaping.escape(html) + " "
+ return {"url": url, "html": html, "error": ""}
+
+
+def main():
+ os.umask(0o077)
+ output = Path(sys.argv[2])
+ try:
+ result = fetch(json.loads(Path(sys.argv[1]).read_text()))
+ except ValueError as exc:
+ result = {"error": str(exc)}
+ except Exception:
+ result = {"error": "Could not load this page. Check the address and your connection."}
+ fd, filename = tempfile.mkstemp(dir=output.parent)
+ with os.fdopen(fd, "w") as stream:
+ json.dump(result, stream, ensure_ascii=False)
+ os.replace(filename, output)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/start.html b/scripts/start.html
new file mode 100644
index 0000000..6f35d1d
--- /dev/null
+++ b/scripts/start.html
@@ -0,0 +1,20 @@
+Browser
+
+ZIRAN + KRYON
+A small browser, built from scratch.
+Enter a web address or a file URL above. HTML becomes a document tree, CSS styles that tree, and Kryon draws the page.
+Simple pages, clearly rendered
+Headings, paragraphs, lists, links, preformatted text and image descriptions work here. Text wraps to the window and the page scrolls independently.
+Styles can set colors, backgrounds, font sizes, spacing, widths and visibility using element, class, ID and inline selectors.
+A first engine
+This early browser supports embedded and inline CSS. JavaScript, forms, image decoding, external stylesheets, flexbox and grid are not implemented yet.
+Visit example.com
+No Chromium or WebKit rendering engine. Document fetching runs outside the UI thread.
+
diff --git a/src/app.zi b/src/app.zi
new file mode 100644
index 0000000..78f74b5
--- /dev/null
+++ b/src/app.zi
@@ -0,0 +1,73 @@
+using UI :: #import "kryon/Widgets";
+using Document :: #import "document";
+State :: #import "state";
+Window :: #import "desktop";
+Desktop :: #import "kryon/Desktop";
+ScrollDevice :: #import "kryon/ScrollDevice";
+SystemStyle :: #import "kss/SystemStyle";
+SystemThemeLinux :: #import "kryon/SystemThemeLinux";
+#import "std/text_buffer"
+#import "std/timer_linux"
+theme_ready: bool;
+base: StyleRules;
+
+Action :: (session: Session, id: s32, label: string, bounds: Rectangle, enabled: bool) -> bool {
+ Window.Record(id,label,bounds.x,bounds.y,bounds.width,bounds.height,enabled)
+ props: ButtonProps; props.key=cast(u64)id; props.id=id; props.bounds=bounds; props.label=label; props.disabled=!enabled
+ return Button(session,props)==1
+}
+Paint :: (session: Session, viewport: Rectangle) {
+ Document.height=Document.LayoutNode(0,viewport.x,0.0,viewport.width)
+ pointer:=Desktop.PollPointer()
+ ScrollDevice.BeginScrollFrame(session,.{pointer.x,pointer.y},pointer.pressed,pointer.down,pointer.released,PointerWheelTake(session,viewport),cast(float64)MonotonicMilliseconds()/1000.0)
+ scroll_props: ScrollProps; scroll_props.key=200; scroll_props.bounds=viewport; scroll_props.content_height=cast(s32)Document.height; scroll_props.scroll_offset=State.scroll
+ scrolling:=Scroll(session,scroll_props); State.scroll=scrolling.scroll_offset
+ for i: 0..Document.count-1 {
+ node: *Node=*Document.nodes[i]; bounds:=node.bounds; bounds.y+=viewport.y-cast(float32)State.scroll
+ if node.style.hidden || bounds.height<=0.0 || bounds.y+bounds.heightviewport.y+viewport.height { continue }
+ if node.style.background!=0 { box: BoxProps; box.key=cast(u64)(300+i); box.bounds=bounds; box.fill=ColorFromPacked(node.style.background); Box(session,box) }
+ if node.size==0 { continue }
+ link:=node.parent
+ while link>0 && Document.nodes[link].href=="" { link=Document.nodes[link].parent }
+ if link>0 {
+ props: LinkProps; props.key=cast(u64)(1000+i); props.class_name=1000+i; props.bounds=bounds; props.text=Document.TextValue(i); props.link=Document.nodes[link].href; props.focus_id=1000+i; props.disabled=State.loading
+ Window.Record(1000+i,props.text,bounds.x,bounds.y,bounds.width,bounds.height,!State.loading)
+ result:=Link(session,props); if result.open_url { State.Navigate(result.url); break }
+ } else {
+ props: TextProps; props.key=cast(u64)(1000+i); props.class_name=1000+i; props.bounds=bounds; props.text=Document.TextValue(i); props.font=node.style.font; props.selectable=true
+ Text(session,props)
+ }
+ }
+ if scrolling.opened { unused End(session) }
+}
+#program_export
+Frame :: (session: Session, viewport: Rectangle) -> s32 {
+ Window.control_count=0; defer { Window.Publish() }
+ if !theme_ready {
+ SystemStyle.StyleInstallSystem(SystemThemeLinux.SystemPaletteRead()); base=ActiveStyleRules(); theme_ready=true
+ }
+ State.Tick()
+ if State.changed { Document.InstallTextStyles(base); State.changed=false }
+ key:=KeyboardTake(session); modifiers:=KeyboardModifiers(session); typed_bytes: [256]u8; typed:=TypedTextTake(session,typed_bytes[:])
+ if (modifiers & KeyModifierControl)!=0 && key==76 { State.focused=true; State.anchor=0; State.cursor=cast(s32)TextUntilNul(State.address[:]).count }
+ chrome: BoxProps; chrome.key=1; chrome.bounds=viewport; chrome.fill=StyleTokenColor("surface"); Box(session,chrome)
+ x:=viewport.x+12.0; y:=viewport.y+10.0; width:=viewport.width-24.0
+ if Action(session,10,"Back",.{x,y,62.0,38.0},!State.loading && State.position>0) { State.Back(-1) }
+ if Action(session,11,"Next",.{x+68.0,y,62.0,38.0},!State.loading && State.position+10 { Paint(session,page) }
+ status: TextProps; status.key=3; status.bounds=.{x,viewport.y+viewport.height-26.0,width,22.0}; status.text=TextUntilNul(State.message[:]); status.font=13; status.wrap=TextWrap.TextWrapNone; Text(session,status)
+ return 0
+}
+AddressField :: (session: Session, bounds: Rectangle, key: s32, modifiers: s32, typed: string) -> TextFieldResult {
+ field: TextFieldProps; field.key=20; field.focus_id=20; field.bounds=bounds; field.value=TextUntilNul(State.address[:]); field.label="Address"; field.placeholder="https://example.com or file:///path/page.html"; field.cursor=State.cursor; field.anchor=State.anchor; field.focused=State.focused; field.max_bytes=4096
+ if field.focused { field.input=TextFieldInputFor(key,modifiers,typed) }
+ return TextField(session,field)
+}
diff --git a/src/desktop.zi b/src/desktop.zi
new file mode 100644
index 0000000..0c41cae
--- /dev/null
+++ b/src/desktop.zi
@@ -0,0 +1,44 @@
+// Inspect and publish only the native window Kryon created for this app.
+Desktop :: #import "kryon/Desktop";
+Model :: #import "state";
+Document :: #import "document";
+#import "std/text"
+#import "std/byte_text_linux"
+SDL :: #system_library "SDL2";
+X11 :: #system_library "X11";
+SetTitle :: (window: *void, value: *u8) #foreign SDL "SDL_SetWindowTitle";
+Version :: (version: *u8) #foreign SDL "SDL_GetVersion";
+WMInfo :: struct { version: [3]u8; padding: u8; subsystem: s32; display: *void; window: u64; rest: [48]u8 }
+WindowInfo :: (window: *void, info: *WMInfo) -> s32 #foreign SDL "SDL_GetWindowWMInfo";
+Atom :: (connection: *void, name: *u8, existing: s32) -> u64 #foreign X11 "XInternAtom";
+Property :: (connection: *void, window: u64, atom: u64, kind: u64, format: s32, mode: s32, bytes: *u8, count: s32) -> s32 #foreign X11 "XChangeProperty";
+Flush :: (connection: *void) -> s32 #foreign X11 "XFlush";
+control_ids: [64]s32;
+control_labels: [64][513]u8;
+control_bounds: [64][4]float32;
+control_enabled: [64]bool;
+control_count: s32;
+frames: s32;
+
+Record :: (id: s32, label: string, x: float32, y: float32, width: float32, height: float32, enabled: bool) {
+ if control_count>=64 { return }; i:=control_count; control_count+=1
+ control_ids[i]=id; Model.Set(control_labels[i][:],label); control_bounds[i]=.{x,y,width,height}; control_enabled[i]=enabled
+}
+Publish :: () {
+ frames+=1; if frames%10!=0 { return }
+ window:=Desktop.DesktopWindow(); if window==null { return }
+ title_bytes: [16]u8; Model.Set(title_bytes[:],"Browser"); SetTitle(window,*title_bytes[0])
+ info: WMInfo; Version(*info.version[0])
+ if WindowInfo(window,*info)==0 || info.subsystem!=2 || info.window==0 { return }
+ name: [32]u8; Model.Set(name[:],"_HARMONY_APP_STATE"); atom:=Atom(info.display,*name[0],0)
+ out: Vec(u8); BuilderPrint(*out,"{\"interface\":\"harmony.app-state.v1\",\"app\":\"browser\",\"loading\":%",Model.loading)
+ Model.Property(*out,"url",TextFromCString(*Model.url[0])); Model.Property(*out,"title",TextFromCString(*Document.title[0]))
+ BuilderPrint(*out,",\"scroll\":%,\"nodes\":%,\"controls\":[",Model.scroll,Document.count)
+ for i: 0..control_count-1 {
+ BuilderPrint(*out,"%{\"control\":\"%\",\"role\":1,\"enabled\":%,\"x\":%,\"y\":%,\"width\":%,\"height\":%,\"label\":",ifx i==0 then "" else ",",control_ids[i],control_enabled[i],control_bounds[i][0],control_bounds[i][1],control_bounds[i][2],control_bounds[i][3])
+ Model.Quoted(*out,TextFromCString(*control_labels[i][0])); BuilderPrint(*out,"}")
+ }
+ BuilderPrint(*out,"]}"); value:=BuilderFinish(out); descriptor:=cast(*TextDescriptor)(*value)
+ if value.count<=65535 { unused Property(info.display,info.window,atom,31,8,0,descriptor.data,cast(s32)value.count); unused Flush(info.display) }
+ Model.Release(value)
+}
diff --git a/src/document.zi b/src/document.zi
new file mode 100644
index 0000000..3e0d845
--- /dev/null
+++ b/src/document.zi
@@ -0,0 +1,276 @@
+// A small HTML tree, CSS cascade and block layout. No external page engine.
+using UI :: #import "kryon/Widgets";
+#import "std/text_buffer"
+
+Limit :: 240;
+Style :: struct {
+ color: u32
+ background: u32
+ font: s32
+ margin: float32
+ padding: float32
+ width: float32
+ hidden: bool
+ centered: bool
+}
+Node :: struct {
+ tag: string
+ id: string
+ classes: string
+ href: string
+ inline_style: string
+ parent: s32
+ first: s32
+ last: s32
+ next: s32
+ text: [4097]u8
+ size: s32
+ style: Style
+ bounds: Rectangle
+}
+Rule :: struct { selector: string; declarations: string; specificity: s32 }
+nodes: [Limit]Node;
+count: s32;
+rules: [128]Rule;
+rule_count: s32;
+title: [257]u8;
+page_color: u32;
+height: float32;
+truncated: bool;
+
+Copy :: (out: []u8, value: string) {
+ n:=cast(s32)value.count; if n>=cast(s32)out.count { n=cast(s32)out.count-1 }
+ for i: 0..n-1 { out[i]=value[i] }; out[n]=0
+}
+Space :: (c: u8) -> bool { return c==32 || c==9 || c==10 || c==13 }
+Trim :: (value: string) -> string {
+ start: s32=0; end:=cast(s32)value.count
+ while startstart && Space(value[end-1]) { end-=1 }
+ return value[start:end]
+}
+Lower :: (c: u8) -> u8 { if c>=65 && c<=90 { return c+32 }; return c }
+Same :: (a: string, b: string) -> bool {
+ if a.count!=b.count { return false }
+ for i: 0..cast(s32)a.count-1 { if Lower(a[i])!=Lower(b[i]) { return false } }; return true
+}
+Starts :: (value: string, prefix: string) -> bool { return value.count>=prefix.count && Same(value[:prefix.count],prefix) }
+Find :: (value: string, needle: string, start: s32) -> s32 {
+ for i: start..cast(s32)(value.count-needle.count) { if Same(value[i:i+cast(s32)needle.count],needle) { return i } }; return -1
+}
+Attribute :: (value: string, wanted: string) -> string {
+ i: s32=0; end:=cast(s32)value.count
+ while i=end || value[i]!=61 { continue }; i+=1
+ while i=end { break }
+ quote: u8=0; if value[i]==34 || value[i]==39 { quote=value[i]; i+=1 }
+ begin=i
+ while i s32 {
+ if count>=Limit { truncated=true; return -1 }
+ i:=count; count+=1; nodes[i]=.{}; nodes[i].tag=tag; nodes[i].parent=parent; nodes[i].first=-1; nodes[i].last=-1; nodes[i].next=-1
+ if parent>=0 {
+ if nodes[parent].first<0 { nodes[parent].first=i } else { nodes[nodes[parent].last].next=i }
+ nodes[parent].last=i
+ }; return i
+}
+DecodeText :: (index: s32, value: string, pre: bool) {
+ n: s32=0; i: s32=0; end:=cast(s32)value.count; was_space: bool
+ while ii && semicolon-i<12 {
+ entity:=value[i:semicolon+1]; replacement: string
+ if entity=="&" { replacement="&" } else if entity=="<" { replacement="<" } else if entity==">" { replacement=">" }
+ else if entity==""" { replacement="\"" } else if entity=="'" || entity=="'" { replacement="'" } else if entity==" " { replacement=" " }
+ if replacement!="" { c=replacement[0]; i=semicolon }
+ }
+ }
+ if !pre && Space(c) { if !was_space { nodes[index].text[n]=32; n+=1 }; was_space=true }
+ else { nodes[index].text[n]=c; n+=1; was_space=false }
+ i+=1
+ }
+ nodes[index].text[n]=0; nodes[index].size=n
+ if i=cast(s32)source.count { break }
+ if Starts(source[i:],"/*") { close:=Find(source,"*/",i+2); if close<0 { break }; i=close+2; continue }
+ open:=Find(source,"{",i); if open<0 { break }; close:=Find(source,"}",open+1); if close<0 { break }
+ selectors:=Trim(source[i:open]); declarations:=source[open+1:close]; start: s32=0
+ for j: 0..cast(s32)selectors.count {
+ if j==cast(s32)selectors.count || selectors[j]==44 {
+ selector:=Trim(selectors[start:j]); start=j+1
+ if selector=="" || selector[0]==64 || rule_count>=128 { continue }
+ score: s32=1; if selector[0]==46 { score=10 }; if selector[0]==35 { score=100 }
+ rules[rule_count]=.{selector,declarations,score}; rule_count+=1
+ }
+ }; i=close+1
+ }
+}
+Class :: (value: string, wanted: string) -> bool {
+ start: s32=0
+ for i: 0..cast(s32)value.count {
+ if i==cast(s32)value.count || Space(value[i]) { if value[start:i]==wanted { return true }; start=i+1 }
+ }; return false
+}
+Matches :: (node: Node, selector: string) -> bool {
+ if selector=="*" { return true }
+ if selector[0]==35 { return node.id==selector[1:] }
+ if selector[0]==46 { return Class(node.classes,selector[1:]) }
+ return Same(node.tag,selector)
+}
+Hex :: (c: u8) -> s32 {
+ if c>=48 && c<=57 { return cast(s32)c-48 }; c2:=Lower(c)
+ if c2>=97 && c2<=102 { return cast(s32)c2-87 }; return -1
+}
+ColorValue :: (value: string, fallback: u32) -> u32 {
+ if value=="transparent" { return 0 }
+ if value=="white" { return 0xffffffff }; if value=="black" { return 0x000000ff }
+ if value=="red" { return 0xff0000ff }; if value=="blue" { return 0x0000ffff }; if value=="green" { return 0x008000ff }
+ if value.count!=4 && value.count!=7 { return fallback }; if value[0]!=35 { return fallback }
+ color: u32=0
+ for i: 1..cast(s32)value.count-1 {
+ digit:=Hex(value[i]); if digit<0 { return fallback }
+ if value.count==4 { color=(color<<8) | cast(u32)(digit*17) } else { color=(color<<4) | cast(u32)digit }
+ }; return (color<<8) | 255
+}
+Pixels :: (value: string, fallback: float32) -> float32 {
+ n: float32=0.0; found: bool; i: s32=0
+ while i=48 && value[i]<=57 { found=true; n=n*10.0+cast(float32)(value[i]-48); i+=1 }
+ if i=48 && value[i]<=57 { found=true; n+=cast(float32)(value[i]-48)/divisor; divisor*=10.0; i+=1 }
+ }
+ suffix:=Trim(value[i:]); if suffix!="" && !Starts(suffix,"px") && !Starts(suffix,"auto") { return fallback }
+ if !found { return fallback }; if n>4096.0 { n=4096.0 }; return n
+}
+Declarations :: (style: *Style, source: string, priorities: []s32, score: s32) {
+ start: s32=0
+ for i: 0..cast(s32)source.count {
+ if i!=cast(s32)source.count && source[i]!=59 { continue }
+ declaration:=Trim(source[start:i]); start=i+1; colon:=Find(declaration,":",0); if colon<0 { continue }
+ property:=Trim(declaration[:colon]); value:=Trim(declaration[colon+1:]); slot: s32=-1
+ if Same(property,"color") { slot=0 } else if Same(property,"background") || Same(property,"background-color") { slot=1 }
+ else if Same(property,"font-size") { slot=2 } else if Same(property,"margin") || Same(property,"margin-top") || Same(property,"margin-bottom") { slot=3 }
+ else if Same(property,"padding") { slot=4 } else if Same(property,"max-width") || Same(property,"width") { slot=5 }
+ else if Same(property,"display") { slot=6 }
+ if slot<0 || score96 { style.font=96 } }
+ if slot==3 { style.margin=Pixels(value,style.margin); if Find(value,"auto",0)>=0 { style.centered=true } }
+ if slot==4 { style.padding=Pixels(value,style.padding) }
+ if slot==5 { style.width=Pixels(value,style.width) }
+ if slot==6 { style.hidden=Same(value,"none") }
+ }
+}
+Resolve :: () {
+ nodes[0].style=.{.font=18,.color=0x263246ff,.background=0xffffffff,.padding=24.0}
+ for i: 0..count-1 {
+ style:=nodes[0].style
+ if i>0 { parent:=nodes[nodes[i].parent].style; style=.{.font=parent.font,.color=parent.color,.hidden=parent.hidden} }
+ tag:=nodes[i].tag
+ if Same(tag,"h1") { style.font=36; style.margin=14.0 }
+ if Same(tag,"h2") { style.font=28; style.margin=12.0 }
+ if Same(tag,"h3") { style.font=22; style.margin=10.0 }
+ if Same(tag,"p") || Same(tag,"li") || Same(tag,"pre") { style.margin=8.0 }
+ if Same(tag,"ul") || Same(tag,"ol") { style.padding=16.0 }
+ if Same(tag,"a") { style.color=0x2563ebff }
+ priority: [7]s32
+ for r: 0..rule_count-1 { if Matches(nodes[i],rules[r].selector) { Declarations(*style,rules[r].declarations,priority[:],rules[r].specificity) } }
+ Declarations(*style,nodes[i].inline_style,priority[:],1000)
+ nodes[i].style=style
+ if Same(tag,"body") && style.background!=0 { page_color=style.background }
+ }
+}
+Load :: (html: string) {
+ count=0; rule_count=0; truncated=false; title[0]=0; page_color=0xffffffff
+ unused Add(-1,"document"); stack: [64]s32; depth: s32=1; stack[0]=0; i: s32=0
+ while i",i+4); if end<0 { break }; i=end+3; continue }
+ // A quoted attribute may contain >; it does not end its start tag.
+ end:=i+1; quote: u8=0
+ while end=cast(s32)html.count { break }
+ content:=Trim(html[i+1:end]); i=end+1; if content=="" || content[0]==33 || content[0]==63 { continue }
+ closing:=content[0]==47; if closing { content=Trim(content[1:]) }
+ name_end: s32=0; while name_end=1 { if Same(nodes[stack[d]].tag,tag) { depth=d; break }; d-=1 }; continue
+ }
+ if Same(tag,"script") || Same(tag,"style") || Same(tag,"title") {
+ close:=Find(html,"",i)
+ // Raw-text elements may contain strings such as
.
+ while close>=0 && !Starts(html[close+2:],tag) { close=Find(html,"",close+2) }
+ if close<0 { break }
+ if Same(tag,"style") { ParseCSS(html[i:close]) }
+ if Same(tag,"title") { Copy(title[:],Trim(html[i:close])) }
+ ending:=Find(html,">",close); if ending<0 { break }; i=ending+1; continue
+ }
+ if Same(tag,"head") { continue }
+ node:=Add(stack[depth-1],tag); if node<0 { break }
+ attributes:=content[name_end:]; nodes[node].id=Attribute(attributes,"id"); nodes[node].classes=Attribute(attributes,"class"); nodes[node].href=Attribute(attributes,"href"); nodes[node].inline_style=Attribute(attributes,"style")
+ empty:=Same(tag,"br") || Same(tag,"hr") || Same(tag,"img") || Same(tag,"meta") || Same(tag,"link") || Same(tag,"input") || content[content.count-1]==47
+ if Same(tag,"img") { alt:=Attribute(attributes,"alt"); if alt!="" { text:=Add(node,"#text"); if text>=0 { DecodeText(text,alt,false) } } }
+ if !empty && depth<64 { stack[depth]=node; depth+=1 }
+ }
+ if i string { return TextUntilNul(nodes[index].text[:]) }
+LayoutNode :: (index: s32, x: float32, y: float32, available: float32) -> float32 {
+ style:=nodes[index].style
+ if style.hidden { nodes[index].bounds=.{}; return y }
+ width:=available-2.0*style.margin; if width<24.0 { width=24.0 }
+ if style.width>0.0 && style.width0 {
+ props: TextProps; props.bounds=.{left,top,width,0.0}; props.text=TextValue(index); props.font=style.font; props.class_name=1000+index
+ prepared:=PrepareText(props,TextFaceFor(props,DefaultTextFace())); cursor=top+prepared.bounds.height+4.0
+ } else if Same(nodes[index].tag,"br") { cursor+=cast(float32)style.font }
+ else {
+ child:=nodes[index].first
+ while child>=0 { cursor=LayoutNode(child,left+style.padding,cursor,width-2.0*style.padding); child=nodes[child].next }
+ cursor+=style.padding
+ }
+ nodes[index].bounds=.{left,top,width,cursor-top}; return cursor+style.margin
+}
+InstallTextStyles :: (base: StyleRules) {
+ active:=base
+ for i: 1..count-1 {
+ if nodes[i].size==0 || active.count>=320 { continue }
+ rule: StyleRule; rule.selector=StyleDefaultSelector(); rule.selector.class_name=1000+i; rule.state=StyleStateAny(); rule.layer=10; rule.order=i
+ rule.style.fields=cast(u32)StyleField.StyleForeground | cast(u32)StyleField.StyleFontSize; rule.style.foreground=nodes[i].style.color; rule.style.font_size=cast(float32)nodes[i].style.font
+ active.items[active.count]=rule; active.count+=1
+ }; unused InstallStyleRules(active)
+}
diff --git a/src/state.zi b/src/state.zi
new file mode 100644
index 0000000..ce21173
--- /dev/null
+++ b/src/state.zi
@@ -0,0 +1,72 @@
+Transport :: #import "transport";
+Document :: #import "document";
+#import "std/json_scan"
+#import "std/text"
+#import "std/text_buffer"
+#import "std/byte_text_linux"
+libc :: #system_library "libc";
+Free :: (memory: *void) #foreign libc "free";
+started: bool;
+loading: bool;
+changed: bool;
+url: [4097]u8;
+address: [4097]u8;
+message: [513]u8;
+html: [524289]u8;
+history: [64][4097]u8;
+history_scroll: [64]s32;
+position: s32=-1;
+history_count: s32;
+cursor: s32;
+anchor: s32;
+focused: bool;
+scroll: s32;
+
+Release :: (value: string) { descriptor:=cast(*TextDescriptor)(*value); Free(cast(*void)descriptor.data) }
+Quoted :: (out: *Vec(u8), value: string) {
+ BuilderPrint(out,"\"")
+ for i: 0..cast(s32)value.count-1 {
+ byte:=value[i]
+ if byte==34 { BuilderPrint(out,"\\\"") } else if byte==92 { BuilderPrint(out,"\\\\") }
+ else if byte==10 { BuilderPrint(out,"\\n") } else if byte>=32 { BuilderPrint(out,"%",value[i:i+1]) }
+ }; BuilderPrint(out,"\"")
+}
+Property :: (out: *Vec(u8), key: string, value: string) { BuilderPrint(out,",\"%\":",key); Quoted(out,value) }
+Set :: (out: []u8, value: string) { Document.Copy(out,value) }
+Navigate :: (target: string, remember: bool=true) {
+ if loading || target=="" { return }
+ if remember && position>=0 { history_scroll[position]=scroll }
+ if remember {
+ if position>=63 { for i: 0..cast(s32)62 { history[i]=history[i+1]; history_scroll[i]=history_scroll[i+1] }; position=62 }
+ position+=1; history_count=position+1; Set(history[position][:],target); history_scroll[position]=0
+ }
+ out: Vec(u8); BuilderPrint(*out,"{\"url\":"); Quoted(*out,target); Property(*out,"base",TextUntilNul(url[:])); BuilderPrint(*out,"}")
+ request:=BuilderFinish(out); loading=Transport.Start(request); Release(request)
+ Set(message[:],ifx loading then "Loading…" else Transport.error)
+}
+Back :: (delta: s32) {
+ if loading || position+delta<0 || position+delta>=history_count { return }
+ history_scroll[position]=scroll; position+=delta; target: [4097]u8; Set(target[:],TextUntilNul(history[position][:])); Navigate(TextUntilNul(target[:]),false)
+}
+Decode :: (key: string, out: []u8) {
+ value:=Transport.Value(); size:=ReadStringText(value,FieldAt(value,0,key),out)
+ if size<0 || size>=cast(s32)out.count { out[0]=0 } else { out[size]=0 }
+}
+Tick :: () {
+ if !started { started=true; Navigate("about:start") }
+ if !Transport.Poll() { return }; loading=false
+ if Transport.error!="" { Set(message[:],Transport.error); return }
+ Decode("error",message[:]); if message[0]!=0 { return }
+ Decode("url",url[:]); Decode("html",html[:]); Set(address[:],TextUntilNul(url[:])); Set(history[position][:],TextUntilNul(url[:]))
+ Document.Load(TextUntilNul(html[:])); changed=true; scroll=history_scroll[position]; cursor=cast(s32)TextUntilNul(address[:]).count; anchor=cursor
+ Set(message[:],ifx Document.truncated then "Page preview limit reached" else TextUntilNul(Document.title[:]))
+}
+Edit :: (start: s32, end: s32, replacement: string) {
+ copied: [4097]u8; Set(copied[:],replacement)
+ length:=cast(s32)TextUntilNul(address[:]).count; inserted:=cast(s32)replacement.count
+ if start<0 || endlength || length-(end-start)+inserted>=4097 { return }
+ shift:=inserted-(end-start)
+ if shift>0 { i:=length; while i>=end { address[i+shift]=address[i]; i-=1 } }
+ else { for i: end..length { address[i+shift]=address[i] } }
+ for i: 0..inserted-1 { address[start+i]=copied[i] }
+}
diff --git a/src/transport.zi b/src/transport.zi
new file mode 100644
index 0000000..c7a1dfa
--- /dev/null
+++ b/src/transport.zi
@@ -0,0 +1,93 @@
+// A single asynchronous worker keeps network IO outside the UI frame.
+#import "std/byte_text_linux"
+#import "std/text_buffer"
+libc :: #system_library "libc";
+Open :: (path: *u8, flags: s32, mode: ..any) -> s32 #foreign libc "open";
+Read :: (descriptor: s32, output: *u8, length: u64) -> s64 #foreign libc "read";
+Write :: (descriptor: s32, input: *u8, length: u64) -> s64 #foreign libc "write";
+Close :: (descriptor: s32) -> s32 #foreign libc "close";
+Fork :: () -> s32 #foreign libc "fork";
+Exec :: (file: *u8, arg0: *u8, args: ..any) -> s32 #foreign libc "execlp";
+Exit :: (code: s32) #foreign libc "_exit";
+Wait :: (process: s32, status: *s32, options: s32) -> s32 #foreign libc "waitpid";
+Temporary :: (pattern: *u8) -> *u8 #foreign libc "mkdtemp";
+Unlink :: (path: *u8) -> s32 #foreign libc "unlink";
+Environment :: (name: *u8) -> *u8 #foreign libc "getenv";
+ReadExecutableLink :: (path: *u8, out: *u8, size: u64) -> s64 #foreign libc "readlink";
+Access :: (path: *u8, mode: s32) -> s32 #foreign libc "access";
+
+pid: s32;
+request_path: [4096]u8;
+response_path: [4096]u8;
+helper: [4096]u8;
+data: [1048576]u8;
+size: s32;
+error: string;
+initialized: bool;
+
+Copy :: (out: []u8, value: string) {
+ count := cast(s32)value.count; if count >= cast(s32)out.count { count = cast(s32)out.count - 1 }
+ for i: 0..count - 1 { out[i] = value[i] }; out[count] = 0
+}
+
+Init :: () -> bool {
+ if initialized { return true }
+ folder: [64]u8; Copy(folder[:], "/tmp/kryon-browser-XXXXXX")
+ if Temporary(*folder[0]) == null { error = "Cannot create private request storage"; return false }
+ root := TextUntilNul(folder[:]); prefix := cast(s32)root.count
+ Copy(request_path[:],root); Copy(request_path[prefix:],"/request.json")
+ Copy(response_path[:],root); Copy(response_path[prefix:],"/response.json")
+ name: [64]u8; Copy(name[:], "KRYON_BROWSER_FETCH")
+ override := Environment(*name[0])
+ if override != null { Copy(helper[:], TextFromCString(override)) }
+ else {
+ Copy(name[:], "/proc/self/exe")
+ length := cast(s32)ReadExecutableLink(*name[0], *helper[0], 4000)
+ if length <= 0 { error="Cannot locate the Browser transport"; return false }
+ while length > 0 && helper[length-1] != 47 { length -= 1 }
+ Copy(helper[length:], "fetch.py")
+ }
+ if Access(*helper[0],4) != 0 { error="Browser transport is missing; rebuild or reinstall the app"; return false }
+ initialized = true; return true
+}
+
+Start :: (request: string) -> bool {
+ if pid > 0 || !Init() { return false }
+ error=""; size=0; unused Unlink(*response_path[0])
+ descriptor := Open(*request_path[0], 577, cast(u32)384)
+ if descriptor < 0 { error="Cannot write Browser request"; return false }
+ bytes := cast(*TextDescriptor)(*request); written: s64
+ while written < request.count {
+ n := Write(descriptor, *bytes.data[written], cast(u64)(request.count-written))
+ if n <= 0 { break }; written += n
+ }
+ unused Close(descriptor)
+ if written != request.count { error="Cannot write complete Browser request"; return false }
+ pid=Fork()
+ if pid < 0 { pid=0; error="Cannot start Browser transport"; return false }
+ if pid == 0 {
+ command: [16]u8; Copy(command[:],"python3")
+ unused Exec(*command[0], *command[0], *helper[0], *request_path[0], *response_path[0], cast(*u8)null)
+ Exit(127)
+ }
+ return true
+}
+
+Poll :: () -> bool {
+ if pid <= 0 { return false }
+ status: s32; done := Wait(pid,*status,1)
+ if done == 0 { return false }; pid=0
+ if done < 0 || status != 0 { error="Browser transport stopped unexpectedly. Refresh to retry."; return true }
+ descriptor := Open(*response_path[0],0)
+ if descriptor < 0 { error="Browser returned no response. Refresh to retry."; return true }
+ size=0
+ while size < 1048575 {
+ n := Read(descriptor,*data[size],cast(u64)(1048575-size))
+ if n <= 0 { break }; size += cast(s32)n
+ }
+ extra: u8; remaining := Read(descriptor,*extra,1); unused Close(descriptor)
+ if remaining > 0 { error="Browser response exceeded the preview limit"; size=0 }
+ data[size]=0; unused Unlink(*request_path[0]); unused Unlink(*response_path[0])
+ return true
+}
+Value :: () -> string { return TextFromBytes(data[:size]) }
diff --git a/tests/document_test.zi b/tests/document_test.zi
new file mode 100644
index 0000000..6a2adec
--- /dev/null
+++ b/tests/document_test.zi
@@ -0,0 +1,29 @@
+using Document :: #import "document";
+#import "std/text"
+#import "std/text_buffer"
+failures: s32;
+Check :: (ok: bool, name: string) { if !ok { print("FAIL: %\n",name); failures+=1 } }
+FindText :: (wanted: string) -> s32 {
+ for i: 0..Document.count-1 { if Trim(TextValue(i))==wanted { return i } }; return -1
+}
+Main :: () -> s32 {
+ Load("Fixture A & B
Inline
Next ")
+ Check(TextUntilNul(title[:])=="Fixture","document title")
+ target:=FindText("A & B"); Check(target>=0,"text entities")
+ if target>=0 { Check(nodes[target].style.color==0xfedcbaff && nodes[target].style.font==20,"ID specificity and inherited font size") }
+ base: StyleRules; InstallTextStyles(base)
+ if target>=0 { props: TextProps; props.class_name=1000+target; face:=TextFaceFor(props,DefaultTextFace()); Check(face.value.foreground==0xfedcbaff,"CSS reaches Kryon text rendering") }
+ inline:=FindText("Inline"); if inline>=0 { Check(nodes[inline].style.color==0x112233ff,"inline style and short hex") } else { Check(false,"inline text") }
+ Check(FindText("bad")<0 && FindText("still bad")<0,"scripts remain raw and invisible")
+ next:=FindText("Next"); if next>=0 { Check(nodes[nodes[next].parent].href=="next.html?x=>","quoted angle brackets in attributes") }
+ hidden:=FindText("Hidden"); Check(hidden>=0 && nodes[hidden].style.hidden,"hidden subtree")
+ Load("Priority
a\n b Heading Normal
")
+ priority:=FindText("Priority"); Check(priority>=0,"unquoted attributes")
+ if priority>=0 { Check(nodes[priority].style.color==0xff0000ff && nodes[priority].style.font==24,"property-specific cascade") }
+ Check(FindText("a\n b")>=0,"preformatted whitespace")
+ Check(!truncated && count>0,"second page replaces previous tree")
+ Load("Malformed
Still readable