Build a native Ziran HTML and CSS browser with Kryon
This commit is contained in:
commit
28f98dc1b7
17 files changed
+982
No files matched your search
@@ -0,0 +1,3 @@
|
||||
/build/
|
||||
/ziran.local.toml
|
||||
__pycache__/
|
||||
@@ -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.
|
||||
@@ -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"
|
||||
@@ -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/`.
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><title>Browser</title><rect width="64" height="64" rx="14" fill="#19344f"/><circle cx="32" cy="32" r="20" fill="none" stroke="#7ac9e9" stroke-width="3"/><ellipse cx="32" cy="32" rx="9" ry="20" fill="none" stroke="#7ac9e9" stroke-width="3"/><path d="M13 26h38M13 38h38" stroke="#7ac9e9" stroke-width="3"/></svg>
|
||||
|
After Width: | Height: | Size: 371 B |
@@ -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 = "<pre>" + escaping.escape(html) + "</pre>"
|
||||
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()
|
||||
@@ -0,0 +1,20 @@
|
||||
<!doctype html><html><head><title>Browser</title>
|
||||
<style>
|
||||
body { background: #f4f7fb; color: #263246; padding: 20px; }
|
||||
main { max-width: 760px; margin: 12px auto; padding: 26px; background: white; }
|
||||
h1 { font-size: 38px; color: #254c7b; }
|
||||
h2 { color: #254c7b; font-size: 26px; }
|
||||
.quiet { color: #67768b; font-size: 15px; }
|
||||
a { color: #2468bc; }
|
||||
</style></head><body><main>
|
||||
<p class="quiet">ZIRAN + KRYON</p>
|
||||
<h1>A small browser, built from scratch.</h1>
|
||||
<p>Enter a web address or a file URL above. HTML becomes a document tree, CSS styles that tree, and Kryon draws the page.</p>
|
||||
<h2>Simple pages, clearly rendered</h2>
|
||||
<p>Headings, paragraphs, lists, links, preformatted text and image descriptions work here. Text wraps to the window and the page scrolls independently.</p>
|
||||
<p>Styles can set colors, backgrounds, font sizes, spacing, widths and visibility using element, class, ID and inline selectors.</p>
|
||||
<h2>A first engine</h2>
|
||||
<p>This early browser supports embedded and inline CSS. JavaScript, forms, image decoding, external stylesheets, flexbox and grid are not implemented yet.</p>
|
||||
<a href="https://example.com">Visit example.com</a>
|
||||
<p class="quiet">No Chromium or WebKit rendering engine. Document fetching runs outside the UI thread.</p>
|
||||
</main></body></html>
|
||||
+73
@@ -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.height<viewport.y || bounds.y>viewport.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+1<State.history_count) { State.Back(1) }
|
||||
if Action(session,12,"Home",.{x+136.0,y,62.0,38.0},!State.loading) { State.Navigate("about:start") }
|
||||
field_bounds: Rectangle=.{x+210.0,y,width-280.0,38.0}
|
||||
result:=AddressField(session,field_bounds,key,modifiers,typed); State.cursor=result.cursor; State.anchor=result.anchor; State.focused=result.focused
|
||||
if result.edit.changed { State.Edit(result.edit.start,result.edit.end,result.edit.replacement) }
|
||||
Window.Record(20,"Address",field_bounds.x,field_bounds.y,field_bounds.width,field_bounds.height,true)
|
||||
if Action(session,13,ifx State.loading then "Wait" else "Go",.{x+width-62.0,y,62.0,38.0},!State.loading) || (result.committed && !State.loading) { State.Navigate(TextUntilNul(State.address[:])); State.focused=false }
|
||||
page: Rectangle=.{viewport.x,viewport.y+60.0,viewport.width,viewport.height-92.0}
|
||||
background: BoxProps; background.key=2; background.bounds=page; background.fill=ColorFromPacked(Document.page_color); Box(session,background)
|
||||
if Document.count>0 { 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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
+276
@@ -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 start<end && Space(value[start]) { start+=1 }
|
||||
while end>start && 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 {
|
||||
while i<end && (Space(value[i]) || value[i]==47) { i+=1 }
|
||||
begin:=i; while i<end && !Space(value[i]) && value[i]!=61 { i+=1 }
|
||||
name:=value[begin:i]
|
||||
while i<end && Space(value[i]) { i+=1 }
|
||||
if i>=end || value[i]!=61 { continue }; i+=1
|
||||
while i<end && Space(value[i]) { i+=1 }; if i>=end { break }
|
||||
quote: u8=0; if value[i]==34 || value[i]==39 { quote=value[i]; i+=1 }
|
||||
begin=i
|
||||
while i<end && ((quote!=0 && value[i]!=quote) || (quote==0 && !Space(value[i]))) { i+=1 }
|
||||
if Same(name,wanted) { return value[begin:i] }
|
||||
if quote!=0 && i<end { i+=1 }
|
||||
}; return ""
|
||||
}
|
||||
Add :: (parent: s32, tag: string) -> 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 i<end && n<4096 {
|
||||
c:=value[i]
|
||||
if c==38 {
|
||||
semicolon:=Find(value,";",i+1)
|
||||
if semicolon>i && 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<end { truncated=true }
|
||||
}
|
||||
ParseCSS :: (source: string) {
|
||||
i: s32=0
|
||||
while i<cast(s32)source.count && rule_count<128 {
|
||||
while i<cast(s32)source.count && Space(source[i]) { i+=1 }
|
||||
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<cast(s32)value.count && value[i]>=48 && value[i]<=57 { found=true; n=n*10.0+cast(float32)(value[i]-48); i+=1 }
|
||||
if i<cast(s32)value.count && value[i]==46 {
|
||||
i+=1; divisor: float32=10.0
|
||||
while i<cast(s32)value.count && value[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 || score<priorities[slot] { continue }; priorities[slot]=score
|
||||
if slot==0 { style.color=ColorValue(value,style.color) }
|
||||
if slot==1 { style.background=ColorValue(value,style.background) }
|
||||
if slot==2 { style.font=cast(s32)Pixels(value,cast(float32)style.font); if style.font<8 { style.font=8 }; if style.font>96 { 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<cast(s32)html.count && count<Limit {
|
||||
if html[i]!=60 {
|
||||
end:=Find(html,"<",i); if end<0 { end=cast(s32)html.count }
|
||||
value:=html[i:end]
|
||||
if Trim(value)!="" {
|
||||
node:=Add(stack[depth-1],"#text"); pre: bool
|
||||
for d: 0..depth-1 { if Same(nodes[stack[d]].tag,"pre") { pre=true } }
|
||||
DecodeText(node,value,pre)
|
||||
}; i=end; continue
|
||||
}
|
||||
if Starts(html[i:],"<!--") { end:=Find(html,"-->",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 {
|
||||
c:=html[end]
|
||||
if quote!=0 { if c==quote { quote=0 } } else if c==34 || c==39 { quote=c } else if c==62 { break }
|
||||
end+=1
|
||||
}; if 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<cast(s32)content.count && !Space(content[name_end]) && content[name_end]!=47 { name_end+=1 }
|
||||
tag:=content[:name_end]
|
||||
if closing {
|
||||
d:=depth-1; while d>=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 </p>.
|
||||
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<cast(s32)html.count { truncated=true }
|
||||
has_body: bool
|
||||
for n: 1..count-1 { if Same(nodes[n].tag,"body") { has_body=true } }
|
||||
if !has_body { nodes[0].tag="body" }
|
||||
Resolve()
|
||||
}
|
||||
TextValue :: (index: s32) -> 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.width<width { width=style.width }
|
||||
left:=x+style.margin; if style.centered { left=x+(available-width)/2.0 }
|
||||
top:=y+style.margin; cursor:=top+style.padding
|
||||
if nodes[index].size>0 {
|
||||
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)
|
||||
}
|
||||
@@ -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 || end<start || end>length || 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] }
|
||||
}
|
||||
@@ -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]) }
|
||||
@@ -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("<!doctype html><title>Fixture</title><style>p { color: #123456; font-size: 20px } .notice {color: #abcdef} #target {color: #fedcba}</style><body><p class='notice' id='target'>A & B</p><p style='color: #123;'>Inline</p><script>bad</p>still bad</script><a href='next.html?x=>'>Next</a><div style='display:none'><p>Hidden</p></div></body>")
|
||||
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("<style>#x {color:red} p {font-size:24px;color:blue}</style><p id=x>Priority</p><pre> a\n b</pre><h1>Heading</h1><p>Normal</p>")
|
||||
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("<p><b>Malformed</p><p>Still readable<!--unterminated")
|
||||
Check(FindText("Malformed")>=0 && FindText("Still readable")>=0,"malformed nesting and comments recover")
|
||||
if failures==0 { print("HTML tree, CSS specificity, inheritance, inline styles, raw scripts, entities and malformed input verified\n") }
|
||||
return failures
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
spec = importlib.util.spec_from_file_location("fetch", Path(__file__).resolve().parents[1] / "scripts/fetch.py")
|
||||
fetch = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(fetch)
|
||||
|
||||
|
||||
class FetchTests(unittest.TestCase):
|
||||
def test_relative_urls_and_default_scheme(self):
|
||||
self.assertEqual(fetch.destination("../next.html", "https://example.com/a/index.html"), "https://example.com/next.html")
|
||||
self.assertEqual(fetch.destination("example.com"), "https://example.com")
|
||||
for url in ("javascript:alert(1)", "ftp://example.com", "https://name:[email protected]", "file://foreign/tmp/page"):
|
||||
with self.assertRaises(ValueError):
|
||||
fetch.destination(url)
|
||||
|
||||
def test_start_page_and_file_limit(self):
|
||||
self.assertIn("<h1>", fetch.fetch({"url": "about:start"})["html"])
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "page.html"
|
||||
path.write_text("<h1>Local HTML</h1>")
|
||||
self.assertEqual(fetch.fetch({"url": path.as_uri()})["html"], path.read_text())
|
||||
path.write_bytes(b"x" * (fetch.LIMIT + 1))
|
||||
with self.assertRaises(ValueError):
|
||||
fetch.fetch({"url": path.as_uri()})
|
||||
|
||||
def test_redirect_cannot_open_local_files(self):
|
||||
from urllib.request import Request
|
||||
with self.assertRaises(ValueError):
|
||||
fetch.Redirects().redirect_request(Request("https://example.com"), None, 302, "", {}, "file:///private")
|
||||
|
||||
def test_http_fetch_follows_redirect_and_preserves_final_base(self):
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import threading
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
if self.path == "/redirect":
|
||||
self.send_response(302)
|
||||
self.send_header("Location", "/pages/index.html")
|
||||
self.end_headers()
|
||||
else:
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.end_headers()
|
||||
self.wfile.write(b"<h1>HTTP document</h1><a href='next.html'>Next</a>")
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
origin = f"http://127.0.0.1:{server.server_port}"
|
||||
result = fetch.fetch({"url": origin + "/redirect"})
|
||||
self.assertEqual(result["url"], origin + "/pages/index.html")
|
||||
self.assertIn("HTTP document", result["html"])
|
||||
self.assertEqual(fetch.destination("next.html", result["url"]), origin + "/pages/next.html")
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join(2)
|
||||
server.server_close()
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Exercise the new engine through its own window and disposable documents."""
|
||||
import ast
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
assert os.environ.get("BROWSER_PRIVATE_XVFB") == "1", "Use make window-test"
|
||||
output = ROOT / "build/screenshots"
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
process = subprocess.Popen([str(ROOT / "build/browser-desktop")], cwd=ROOT, stderr=subprocess.PIPE)
|
||||
|
||||
|
||||
def xdo(*args):
|
||||
return subprocess.check_output(["xdotool", *map(str, args)], text=True).strip()
|
||||
|
||||
|
||||
def state(url=None):
|
||||
deadline = time.monotonic() + 10
|
||||
while time.monotonic() < deadline:
|
||||
raw = subprocess.check_output(["xprop", "-id", window, "_HARMONY_APP_STATE"], text=True)
|
||||
if " = " in raw:
|
||||
value = json.loads(ast.literal_eval(raw.split(" = ", 1)[1].strip()))
|
||||
if not value["loading"] and value["nodes"] > 0 and (url is None or value["url"] == url):
|
||||
return value
|
||||
time.sleep(.1)
|
||||
raise AssertionError("Browser did not load " + str(url))
|
||||
|
||||
|
||||
def action(label):
|
||||
control = next(c for c in state()["controls"] if c["label"] == label and c["enabled"])
|
||||
xdo("mousemove", "--window", window, int(control["x"] + control["width"] / 2), int(control["y"] + control["height"] / 2))
|
||||
xdo("click", "1")
|
||||
time.sleep(.2)
|
||||
|
||||
|
||||
try:
|
||||
deadline = time.monotonic() + 10
|
||||
window = ""
|
||||
while time.monotonic() < deadline:
|
||||
assert process.poll() is None, process.stderr.read().decode()
|
||||
result = subprocess.run(["xdotool", "search", "--onlyvisible", "--pid", str(process.pid)], capture_output=True, text=True)
|
||||
if result.returncode == 0:
|
||||
window = result.stdout.splitlines()[0]
|
||||
break
|
||||
time.sleep(.1)
|
||||
assert window, "Browser window did not open"
|
||||
xdo("windowsize", window, 1060, 800)
|
||||
state("about:start")
|
||||
subprocess.run(["import", "-window", window, str(output / "start.png")], check=True)
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "index.html"
|
||||
second = Path(folder) / "next.html"
|
||||
path.write_text("<title>Fixture page</title><style>body{background:#f4f7fb}main{max-width:760px;margin:12px auto;padding:20px;background:white}h1{color:#2468bc}</style><main><h1>A native HTML page</h1><p>The browser owns this document.</p><a href='next.html'>Next page</a>" + "<p>A paragraph for independent document scrolling.</p>" * 35 + "</main>")
|
||||
second.write_text("<title>Linked page</title><h1>Links stay in Browser</h1><p>Relative file navigation works.</p>")
|
||||
action("Address")
|
||||
xdo("key", "ctrl+a")
|
||||
xdo("type", "--clearmodifiers", path.as_uri())
|
||||
xdo("key", "Return")
|
||||
assert state(path.as_uri())["title"] == "Fixture page"
|
||||
subprocess.run(["import", "-window", window, str(output / "html-css.png")], check=True)
|
||||
action("Next page")
|
||||
state(second.as_uri())
|
||||
action("Back")
|
||||
state(path.as_uri())
|
||||
xdo("mousemove", "--window", window, 700, 600)
|
||||
xdo("click", "--repeat", "4", "--delay", "60", "5")
|
||||
time.sleep(.5)
|
||||
assert state()["scroll"] > 0
|
||||
action("Next")
|
||||
state(second.as_uri())
|
||||
action("Back")
|
||||
assert state(path.as_uri())["scroll"] > 0, "Back lost the page position"
|
||||
xdo("windowsize", window, 640, 800)
|
||||
time.sleep(.5)
|
||||
subprocess.run(["import", "-window", window, str(output / "narrow.png")], check=True)
|
||||
print("Native HTML/CSS rendering, address input, relative links, Back/Next, independent scrolling and narrow window verified")
|
||||
finally:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"format": 1,
|
||||
"packages": [
|
||||
{
|
||||
"commit": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e",
|
||||
"dependencies": {},
|
||||
"id": "p5a77c9c35110e925",
|
||||
"name": "raylib",
|
||||
"ref": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e",
|
||||
"source": true,
|
||||
"url": "https://github.com/raysan5/raylib.git"
|
||||
},
|
||||
{
|
||||
"commit": "86c366c9e183cd152683d24cac6a2603cad64ab9",
|
||||
"dependencies": {"kryon": "pd248f12b8b051e7f"},
|
||||
"id": "padff2d5df1fdb5ee",
|
||||
"name": "Kss",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/kryonlabs/kss.git"
|
||||
},
|
||||
{
|
||||
"commit": "579744b7b78e7c40e40454462b4e6795d9e0d4a0",
|
||||
"dependencies": {"raylib": "p5a77c9c35110e925"},
|
||||
"id": "pd248f12b8b051e7f",
|
||||
"name": "kryon",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/kryonlabs/kryon.git"
|
||||
}
|
||||
],
|
||||
"root": {
|
||||
"dependencies": {"kryon": "pd248f12b8b051e7f", "kss": "padff2d5df1fdb5ee"},
|
||||
"name": "browser"
|
||||
},
|
||||
"toolchain": {
|
||||
"commit": "f337ae809fa96a43f5bb36307b8f5abb21ac7dd4",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/ziranlang/ziran.git"
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
[package]
|
||||
name = "browser"
|
||||
tool = "kryon"
|
||||
entry = "src/app.zi"
|
||||
module_roots = ["src", "tests"]
|
||||
bridge_modules = ["app"]
|
||||
|
||||
[toolchain]
|
||||
git = "https://github.com/ziranlang/ziran.git"
|
||||
ref = "master"
|
||||
|
||||
[tool.kryon]
|
||||
default_profile = "desktop"
|
||||
|
||||
[tool.kryon.profiles.desktop]
|
||||
backend = "desktop"
|
||||
library = "X11"
|
||||
|
||||
[install]
|
||||
bin = "kryon-browser"
|
||||
|
||||
[tool.kryon.install]
|
||||
profile = "desktop"
|
||||
name = "Browser"
|
||||
comment = "Native HTML and CSS browser"
|
||||
categories = "Network;WebBrowser;"
|
||||
|
||||
[dependencies.kryon]
|
||||
git = "https://github.com/kryonlabs/kryon.git"
|
||||
ref = "master"
|
||||
|
||||
[dependencies.kss]
|
||||
git = "https://github.com/kryonlabs/kss.git"
|
||||
ref = "master"
|
||||
Reference in new issue
Block a user