From 28f98dc1b7540aaa87e88c2d79c95d8e0334641a Mon Sep 17 00:00:00 2001
From: Waozi
Date: Mon, 5 Oct 2026 21:22:57 -0300
Subject: [PATCH] Build a native Ziran HTML and CSS browser with Kryon
---
.gitignore | 3 +
AGENTS.md | 8 ++
Makefile | 23 ++++
README.md | 41 ++++++
assets/browser.svg | 1 +
scripts/fetch.py | 77 ++++++++++++
scripts/start.html | 20 +++
src/app.zi | 73 +++++++++++
src/desktop.zi | 44 +++++++
src/document.zi | 276 +++++++++++++++++++++++++++++++++++++++++
src/state.zi | 72 +++++++++++
src/transport.zi | 93 ++++++++++++++
tests/document_test.zi | 29 +++++
tests/test_fetch.py | 62 +++++++++
tests/window_test.py | 87 +++++++++++++
ziran.lock | 39 ++++++
ziran.toml | 34 +++++
17 files changed, 982 insertions(+)
create mode 100644 .gitignore
create mode 100644 AGENTS.md
create mode 100644 Makefile
create mode 100644 README.md
create mode 100644 assets/browser.svg
create mode 100644 scripts/fetch.py
create mode 100644 scripts/start.html
create mode 100644 src/app.zi
create mode 100644 src/desktop.zi
create mode 100644 src/document.zi
create mode 100644 src/state.zi
create mode 100644 src/transport.zi
create mode 100644 tests/document_test.zi
create mode 100644 tests/test_fetch.py
create mode 100644 tests/window_test.py
create mode 100644 ziran.lock
create mode 100644 ziran.toml
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 @@
+
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.