Host Three.js-style staged pages in an optional WebKit island
The zx player gains a WebView host module (WebKitGTK 4.1 on Linux): a staged page runs in an owned python island child, maps its window into the player, and answers bounds, seek, play, pause, stop and tick commands over a versioned bridge; closing the player reaps the child. Repin the toolchain and starter templates to the Ziran commit that lets the direct backend lower expression-less UNUSED statements, and stage the island script and assets beside the player.
This commit is contained in:
1 parent
3f37001acf
commit
dc4ac53c46
19 files changed
+962
-20
No files matched your search
@@ -240,6 +240,13 @@ zx-test: build/bin/kryon zx-player zx-linked-test zx-nested-test
|
||||
@env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS \
|
||||
ZIRAN_ROOT=$(abspath $(ZIRAN_DIR)) python3 tests/zx_project_test.py
|
||||
|
||||
# The optional WebKit island: a real staged-page round-trip through the
|
||||
# player on a private display; skipped where WebKitGTK is unavailable.
|
||||
.PHONY: webview-island-test
|
||||
webview-island-test: zx-player
|
||||
@env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS \
|
||||
ZIRAN_ROOT=$(abspath $(ZIRAN_DIR)) python3 tests/webview_island_test.py
|
||||
|
||||
ZX_LINKED_TEST := build/test/zx-linked
|
||||
zx-linked-test: zx-player
|
||||
mkdir -p $(ZX_LINKED_TEST)
|
||||
@@ -609,6 +616,12 @@ install-user: build/bin/kryon zx-player zx-window-host
|
||||
mkdir -p "$(PREFIX)/lib/kryon"
|
||||
cp $(PLAYER) "$(PREFIX)/lib/kryon/zx-desktop.new"
|
||||
mv -f "$(PREFIX)/lib/kryon/zx-desktop.new" "$(PREFIX)/lib/kryon/zx-desktop"
|
||||
mkdir -p "$(PREFIX)/lib/kryon/webview-assets"
|
||||
cp $(KRYON_DIR)/scripts/island.py "$(PREFIX)/lib/kryon/kryon-island.py.new"
|
||||
mv -f "$(PREFIX)/lib/kryon/kryon-island.py.new" "$(PREFIX)/lib/kryon/kryon-island.py"
|
||||
cp $(KRYON_DIR)/assets/webview/bridge.js $(KRYON_DIR)/assets/webview/island.css \
|
||||
$(KRYON_DIR)/assets/webview/scene.html $(KRYON_DIR)/assets/webview/scene.js \
|
||||
"$(PREFIX)/lib/kryon/webview-assets/"
|
||||
cp $(WINDOW_HOST) "$(PREFIX)/lib/kryon/libkryon-desktop.so.new"
|
||||
mv -f "$(PREFIX)/lib/kryon/libkryon-desktop.so.new" "$(PREFIX)/lib/kryon/libkryon-desktop.so"
|
||||
$(RM) "$(PREFIX)/lib/kryon/libkryon-pixmap.so"
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
// Kryon island protocol v1. No eval, no native methods exposed to content.
|
||||
// A staged page installs window.KryonPage (receive/state) and calls
|
||||
// KryonIsland.ready() once its handlers exist; commands sent earlier wait in
|
||||
// the island until then. Focus supplies the shared visibility lifecycle.
|
||||
const send = value => window.webkit.messageHandlers.kryon.postMessage(JSON.stringify({ v: 1, ...value }));
|
||||
let active = true;
|
||||
const browserHidden = Object.getOwnPropertyDescriptor(Document.prototype, 'hidden')?.get;
|
||||
Object.defineProperty(document, 'hidden', { configurable: true, get: () => !active || !!browserHidden?.call(document) });
|
||||
function lifecycle(value) {
|
||||
active = value;
|
||||
document.dispatchEvent(new Event('visibilitychange'));
|
||||
const scene = window.KryonScene;
|
||||
if (scene) { cancelAnimationFrame(scene.frame); scene.frame = 0; if (active && scene.draw) scene.frame = requestAnimationFrame(scene.draw); }
|
||||
}
|
||||
async function receive(command) {
|
||||
try {
|
||||
if (!command || command.v !== 1) throw Error('Unsupported island protocol version');
|
||||
if (command.type === 'focus') {
|
||||
if (typeof command.active !== 'boolean') throw Error('Invalid focus state');
|
||||
lifecycle(command.active);
|
||||
}
|
||||
const page = window.KryonPage;
|
||||
if (page?.receive) await page.receive(command);
|
||||
send({ type: 'ack', id: command.id, command: command.type,
|
||||
state: page?.state ? page.state(active) : { active, viewport: { width: innerWidth, height: innerHeight } } });
|
||||
} catch (error) { send({ type: 'error', id: command?.id, message: error.message }); }
|
||||
}
|
||||
window.KryonIsland = {
|
||||
receive,
|
||||
ready(state) { send({ type: 'ready', state: state || {} }); },
|
||||
fail(message) { send({ type: 'error', message: String(message) }); }
|
||||
};
|
||||
window.addEventListener('error', event => send({ type: 'error', message: event.message }));
|
||||
window.addEventListener('unhandledrejection', event => send({ type: 'error', message: String(event.reason) }));
|
||||
@@ -0,0 +1,3 @@
|
||||
html, body { margin: 0; width: 100%; height: 100%; }
|
||||
body[data-island] { overflow: hidden; background: transparent; }
|
||||
body[data-island] canvas { display: block; width: 100%; height: 100%; }
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html><head><meta charset="utf-8"><title>Kryon Three.js island</title><link rel="stylesheet" href="/island.css"></head><body data-island="scene"><canvas aria-label="Interactive Three.js scene"></canvas><script type="module" src="/bridge.js"></script><script type="module" src="/scene.js"></script></body></html>
|
||||
@@ -0,0 +1,76 @@
|
||||
// The staged demo page: an ordinary WebGL cube on the island vocabulary.
|
||||
// spin sets the rotation speed; focus pauses and resumes the frame loop;
|
||||
// state reports what a native host needs to verify the render loop. No
|
||||
// third-party module is used, so the staged demo needs no downloads.
|
||||
let speed = 1, last = 0, frames = 0, active = true, rotation = 0;
|
||||
const start = async () => {
|
||||
const canvas = document.querySelector('canvas');
|
||||
const gl = canvas.getContext('webgl', { antialias: true });
|
||||
if (!gl) throw Error('WebGL is unavailable');
|
||||
const make = (kind, source) => {
|
||||
const shader = gl.createShader(kind);
|
||||
gl.shaderSource(shader, source); gl.compileShader(shader);
|
||||
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) throw Error(gl.getShaderInfoLog(shader) || 'Shader did not compile');
|
||||
return shader;
|
||||
};
|
||||
const program = gl.createProgram();
|
||||
gl.attachShader(program, make(gl.VERTEX_SHADER,
|
||||
'attribute vec3 point; uniform mat4 spin; void main() { gl_Position = spin * vec4(point, 1.0); }'));
|
||||
gl.attachShader(program, make(gl.FRAGMENT_SHADER,
|
||||
'precision mediump float; void main() { gl_FragColor = vec4(0.38, 0.93, 1.0, 1.0); }'));
|
||||
gl.linkProgram(program);
|
||||
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw Error('Shader program did not link');
|
||||
gl.useProgram(program);
|
||||
const corners = new Float32Array([
|
||||
-1, -1, -1, 1, -1, -1, 1, 1, -1, -1, -1, -1, 1, 1, -1, -1, 1, -1,
|
||||
-1, -1, 1, 1, -1, 1, 1, 1, 1, -1, -1, 1, 1, 1, 1, -1, 1, 1,
|
||||
-1, -1, -1, -1, -1, 1, -1, 1, 1, -1, -1, -1, -1, 1, 1, -1, 1, -1,
|
||||
1, -1, -1, 1, -1, 1, 1, 1, 1, 1, -1, -1, 1, 1, 1, 1, 1, -1,
|
||||
-1, 1, -1, -1, 1, 1, 1, 1, 1, -1, 1, -1, 1, 1, 1, 1, 1, -1,
|
||||
-1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, -1, 1, -1, 1, -1, -1, 1]);
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
|
||||
gl.bufferData(gl.ARRAY_BUFFER, corners, gl.STATIC_DRAW);
|
||||
const point = gl.getAttribLocation(program, 'point');
|
||||
gl.enableVertexAttribArray(point);
|
||||
gl.vertexAttribPointer(point, 3, gl.FLOAT, false, 0, 0);
|
||||
const spin = gl.getUniformLocation(program, 'spin');
|
||||
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
|
||||
gl.clearColor(0.063, 0.094, 0.153, 1);
|
||||
const draw = () => {
|
||||
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
|
||||
gl.enable(gl.DEPTH_TEST);
|
||||
const angle = rotation, cosine = Math.cos(angle), sine = Math.sin(angle);
|
||||
gl.uniformMatrix4fv(spin, false, new Float32Array([
|
||||
cosine, 0, sine, 0,
|
||||
0, 1, 0, 0,
|
||||
-sine, 0, cosine, 0,
|
||||
0, 0, -4, 1]));
|
||||
gl.drawArrays(gl.TRIANGLES, 0, corners.length / 3);
|
||||
};
|
||||
const scene = window.KryonScene = { frame: 0 };
|
||||
const resize = () => { canvas.width = innerWidth; canvas.height = innerHeight; draw(); };
|
||||
scene.draw = time => {
|
||||
scene.frame = 0; if (!active) return;
|
||||
rotation += Math.min(.1, (time - last) / 1000) * speed; last = time;
|
||||
draw(); frames++;
|
||||
scene.frame = requestAnimationFrame(scene.draw);
|
||||
};
|
||||
window.addEventListener('resize', resize); resize();
|
||||
window.KryonPage = {
|
||||
receive(command) {
|
||||
if (command.type === 'spin') {
|
||||
if (!Number.isFinite(command.speed) || Math.abs(command.speed) > 100) throw Error('Invalid spin speed');
|
||||
speed = command.speed; return;
|
||||
}
|
||||
if (command.type === 'focus') { active = command.active; last = performance.now(); }
|
||||
},
|
||||
state(islandActive) {
|
||||
return { mode: 'scene', active: islandActive, frames, speed, rotation,
|
||||
width: canvas.width, height: canvas.height };
|
||||
}
|
||||
};
|
||||
scene.frame = requestAnimationFrame(scene.draw);
|
||||
window.KryonIsland.ready({ mode: 'scene' });
|
||||
};
|
||||
start().catch(error => window.KryonIsland.fail(error?.message || String(error)));
|
||||
@@ -0,0 +1,53 @@
|
||||
# Web view
|
||||
|
||||
The optional web view runs one approved staged page in an owned WebKit child
|
||||
beside the application window. The application never touches URLs, scripts or
|
||||
the network: it names a staged page, moves a rectangle, sends bounded JSON
|
||||
commands and receives bounded JSON events. The child is a literal argv spawn
|
||||
with parent-death supervision, an AF_UNIX SEQPACKET socket pair and a pidfd,
|
||||
so a closed player always reaps it. There is no listening port; the island
|
||||
serves its staged assets from a loopback server bound per process.
|
||||
|
||||
## Application API (`kryon/WebView`)
|
||||
|
||||
- `Open(content, x, y, width, height) -> bool` spawns the island for one
|
||||
staged page name (lowercase letters and dashes, at most 64 bytes) and asks
|
||||
for its first bounds.
|
||||
- `Bounds(x, y, width, height, visible)` moves or hides the island rectangle
|
||||
in host window coordinates; unchanged rectangles are ignored.
|
||||
- `Send(command) -> bool` delivers one JSON command packet (4 KiB limit).
|
||||
- `Event() -> string` returns one queued event packet, or empty.
|
||||
- `Close()` terminates and reaps the child.
|
||||
|
||||
The capability is Linux-only today; a program imports it as `kryon/WebView`
|
||||
and the player's `Supported` check grants or refuses the foreign functions,
|
||||
so other hosts report it as unsupported instead of failing.
|
||||
|
||||
## Island protocol (v1)
|
||||
|
||||
Every packet is a JSON object with a version field set to 1. Host commands
|
||||
name a `type` in the shared vocabulary (`spin`, `state`, `focus`, `seek`,
|
||||
`play`, `pause`, `select`, `next`, `previous`, `stop`, `volume`) and may
|
||||
carry an `id`. Page events are `ready`, `ack` (echoing `id` and `command`
|
||||
with the page's `state`), `state`, `click`, `error` and `frame`. `focus`
|
||||
carries `active` and drives the shared visibility lifecycle, including the
|
||||
page's `document.hidden`.
|
||||
|
||||
## Staged pages
|
||||
|
||||
Assets live beside the player executable in `webview-assets/` (or where the
|
||||
`KRYON_WEBVIEW_ASSETS` environment variable names). `make zx-player` stages
|
||||
`kryon-island.py` and `assets/webview/` (`bridge.js`, `island.css`, and the
|
||||
demo `scene.html` with `scene.js`). A page loads `/bridge.js`, installs
|
||||
`window.KryonPage` with `receive(command)` and `state(active)`, then reports
|
||||
`window.KryonIsland.ready(state)` once its handlers exist; commands sent
|
||||
before that wait in the island. The island serves only files inside the
|
||||
staged directory, refuses dotfiles and directory listings, sends restrictive
|
||||
content headers, and answers range requests so pages can stream media.
|
||||
|
||||
## Checks
|
||||
|
||||
`make webview-island-test` builds the probe bundle against this checkout and
|
||||
runs it on a private Xvfb display: the island child spawns, maps its window
|
||||
into the player, reports ready, answers a spin command with an ack reporting
|
||||
rendered frames, and is reaped on close. It skips itself without WebKitGTK.
|
||||
+11
-1
@@ -22,7 +22,7 @@ PLAYER := $(KRYON_DIR)/build/bin/zx
|
||||
PLAYER_SOURCES := $(KRYON_DIR)/tools/zx.zi $(wildcard $(KRYON_DIR)/src/backend/*.zi) $(shell find $(KRYON_DIR)/src/ui -name '*.zi') $(wildcard $(ZIRAN_DIR)/std/*.zi)
|
||||
|
||||
.PHONY: zx-player
|
||||
zx-player: $(PLAYER)
|
||||
zx-player: $(PLAYER) webview-stage
|
||||
|
||||
$(PLAYER): $(PLAYER_SOURCES) $(KRYON_DIR)/mk/zx-player.mk $(KRYON_DIR)/ziran.toml $(KRYON_DIR)/ziran.lock $(ZIRAN_DIR)/build/libziran.a $(ZIRAN) $(OPUS_A)
|
||||
mkdir -p $(PLAYER_DIR) $(KRYON_DIR)/build/bin
|
||||
@@ -35,6 +35,16 @@ $(PLAYER): $(PLAYER_SOURCES) $(KRYON_DIR)/mk/zx-player.mk $(KRYON_DIR)/ziran.tom
|
||||
$(PLAYER_LIBS) -o "$$temporary" && \
|
||||
chmod 755 "$$temporary" && mv "$$temporary" $@
|
||||
|
||||
# The optional island: its owned child script and approved staged pages live
|
||||
# beside the player executable, with KRYON_WEBVIEW_ASSETS as an override.
|
||||
.PHONY: webview-stage
|
||||
webview-stage:
|
||||
mkdir -p $(KRYON_DIR)/build/bin/webview-assets
|
||||
cp $(KRYON_DIR)/scripts/island.py $(KRYON_DIR)/build/bin/kryon-island.py
|
||||
cp $(KRYON_DIR)/assets/webview/bridge.js $(KRYON_DIR)/assets/webview/island.css \
|
||||
$(KRYON_DIR)/assets/webview/scene.html $(KRYON_DIR)/assets/webview/scene.js \
|
||||
$(KRYON_DIR)/build/bin/webview-assets/
|
||||
|
||||
# The desktop host library: Kryon's native SDL2/GPU/Cairo window, frame-loop,
|
||||
# raster, font, clipboard, theme, clock and service capabilities, which a ZX
|
||||
# program's native executable (`zx2native`) links by name once install-user
|
||||
|
||||
Executable
+306
@@ -0,0 +1,306 @@
|
||||
#!/usr/bin/python3
|
||||
"""Kryon WebKit island: approved staged pages, owned X child, bounded JSON packets."""
|
||||
import argparse
|
||||
import ctypes as c
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import signal
|
||||
import socket
|
||||
import threading
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
MAX_PACKET = 4096
|
||||
COMMANDS = {'spin', 'state', 'focus', 'seek', 'play', 'pause', 'select', 'next', 'previous', 'stop', 'volume'}
|
||||
|
||||
|
||||
def validate_command(value):
|
||||
if not isinstance(value, dict) or type(value.get('v')) is not int or value['v'] != 1 or value.get('type') not in COMMANDS:
|
||||
raise ValueError('Unsupported island protocol version or command')
|
||||
if len(json.dumps(value).encode()) > MAX_PACKET:
|
||||
raise ValueError('Island command is too large')
|
||||
return value
|
||||
|
||||
|
||||
class Assets(SimpleHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
if any(part.startswith('.') for part in Path(urlsplit(self.path).path).parts):
|
||||
self.send_error(404)
|
||||
return
|
||||
super().do_GET()
|
||||
|
||||
def list_directory(self, path):
|
||||
self.send_error(404)
|
||||
return None
|
||||
|
||||
def send_head(self):
|
||||
self.range_remaining = None
|
||||
requested = self.headers.get('Range', '')
|
||||
match = re.fullmatch(r'bytes=(\d*)-(\d*)', requested)
|
||||
path = Path(self.translate_path(self.path))
|
||||
if not match or not any(match.groups()) or not path.is_file():
|
||||
return super().send_head()
|
||||
try:
|
||||
stream = path.open('rb')
|
||||
except OSError:
|
||||
self.send_error(404)
|
||||
return None
|
||||
size = os.fstat(stream.fileno()).st_size
|
||||
first, last = match.groups()
|
||||
if first:
|
||||
start = int(first)
|
||||
end = min(int(last), size - 1) if last else size - 1
|
||||
else:
|
||||
suffix = int(last)
|
||||
start, end = max(0, size - suffix), size - 1
|
||||
if size == 0 or start >= size or end < start:
|
||||
stream.close()
|
||||
self.send_response(416)
|
||||
self.send_header('Content-Range', f'bytes */{size}')
|
||||
self.send_header('Content-Length', '0')
|
||||
self.end_headers()
|
||||
return None
|
||||
stream.seek(start)
|
||||
self.range_remaining = end - start + 1
|
||||
self.send_response(206)
|
||||
self.send_header('Content-Type', self.guess_type(str(path)))
|
||||
self.send_header('Content-Range', f'bytes {start}-{end}/{size}')
|
||||
self.send_header('Content-Length', str(self.range_remaining))
|
||||
self.end_headers()
|
||||
return stream
|
||||
|
||||
def copyfile(self, source, output):
|
||||
if self.range_remaining is None:
|
||||
return super().copyfile(source, output)
|
||||
remaining = self.range_remaining
|
||||
while remaining:
|
||||
data = source.read(min(65536, remaining))
|
||||
if not data:
|
||||
break
|
||||
output.write(data)
|
||||
remaining -= len(data)
|
||||
|
||||
def end_headers(self):
|
||||
self.send_header('Accept-Ranges', 'bytes')
|
||||
self.send_header('Cache-Control', 'no-store')
|
||||
self.send_header('X-Content-Type-Options', 'nosniff')
|
||||
self.send_header('Content-Security-Policy',
|
||||
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; "
|
||||
"img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; "
|
||||
"object-src 'none'; frame-src 'none'; base-uri 'none'")
|
||||
super().end_headers()
|
||||
|
||||
|
||||
class Island:
|
||||
def __init__(self, options):
|
||||
import gi
|
||||
gi.require_version('Gtk', '3.0')
|
||||
gi.require_version('WebKit2', '4.1')
|
||||
gi.require_version('GdkX11', '3.0')
|
||||
from gi.repository import Gtk, GLib, WebKit2, GdkX11
|
||||
self.Gtk, self.GLib = Gtk, GLib
|
||||
self.socket = socket.socket(fileno=options.fd)
|
||||
self.socket.setblocking(False)
|
||||
self.ready = False
|
||||
self.pending = []
|
||||
self.visible = True
|
||||
self.focused = None
|
||||
self.closed = False
|
||||
self.root = (options.assets or Path(__file__).parent / 'webview-assets').resolve()
|
||||
if not self.root.is_dir():
|
||||
raise ValueError('Build the staged island assets first')
|
||||
self.server = ThreadingHTTPServer(('127.0.0.1', 0), partial(Assets, directory=str(self.root)))
|
||||
self.server.daemon_threads = True
|
||||
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
||||
self.origin = f'http://127.0.0.1:{self.server.server_port}'
|
||||
self.parent = options.parent
|
||||
self.window = Gtk.Window(title='Kryon webview island')
|
||||
self.window.set_default_size(640, 400)
|
||||
self.window.set_decorated(False)
|
||||
self.window.connect('destroy', lambda *_: self.close())
|
||||
manager = WebKit2.UserContentManager()
|
||||
manager.connect('script-message-received::kryon', self.message)
|
||||
if not manager.register_script_message_handler('kryon'):
|
||||
raise RuntimeError('Could not register the island bridge')
|
||||
context = WebKit2.WebContext.new_ephemeral()
|
||||
self.view = WebKit2.WebView(web_context=context, user_content_manager=manager)
|
||||
self.view.get_settings().set_enable_webgl(True)
|
||||
self.view.get_settings().set_media_playback_requires_user_gesture(True)
|
||||
self.view.connect('decide-policy', self.policy)
|
||||
self.view.connect('permission-request', self.permission)
|
||||
self.view.connect('load-failed', lambda *_: self.send({'v': 1, 'type': 'error', 'message': 'Island page failed to load'}) or False)
|
||||
self.view.connect('web-process-terminated', lambda *_: self.send({'v': 1, 'type': 'error', 'message': 'Island web process terminated'}))
|
||||
self.window.add(self.view)
|
||||
self.window.realize()
|
||||
self.xid = GdkX11.X11Window.get_xid(self.window.get_window())
|
||||
self.x = c.CDLL('libX11.so.6')
|
||||
self.x.XOpenDisplay.argtypes = [c.c_char_p]
|
||||
self.x.XOpenDisplay.restype = c.c_void_p
|
||||
self.display = self.x.XOpenDisplay(None)
|
||||
if not self.display:
|
||||
raise RuntimeError('An X11 display is required for the desktop island')
|
||||
self.x.XReparentWindow.argtypes = [c.c_void_p, c.c_ulong, c.c_ulong, c.c_int, c.c_int]
|
||||
self.x.XMoveResizeWindow.argtypes = [c.c_void_p, c.c_ulong, c.c_int, c.c_int, c.c_uint, c.c_uint]
|
||||
self.x.XFlush.argtypes = [c.c_void_p]
|
||||
self.x.XGetInputFocus.argtypes = [c.c_void_p, c.POINTER(c.c_ulong), c.POINTER(c.c_int)]
|
||||
self.x.XQueryTree.argtypes = [c.c_void_p, c.c_ulong, c.POINTER(c.c_ulong), c.POINTER(c.c_ulong), c.POINTER(c.POINTER(c.c_ulong)), c.POINTER(c.c_uint)]
|
||||
self.x.XFree.argtypes = [c.c_void_p]
|
||||
self.x.XCloseDisplay.argtypes = [c.c_void_p]
|
||||
# Reparent while still hidden: this child never maps on the live root.
|
||||
self.window.get_window().set_override_redirect(True)
|
||||
self.x.XReparentWindow(self.display, self.xid, self.parent, 0, 0)
|
||||
self.x.XFlush(self.display)
|
||||
self.window.show_all()
|
||||
if re.fullmatch(r'[a-z0-9-]+', options.content or ''):
|
||||
uri = self.origin + '/' + options.content + '.html'
|
||||
else:
|
||||
raise ValueError('Only staged island content is supported')
|
||||
self.view.load_uri(uri)
|
||||
GLib.io_add_watch(self.socket.fileno(), GLib.IO_IN | GLib.IO_HUP | GLib.IO_ERR, self.input)
|
||||
GLib.timeout_add(100, self.focus)
|
||||
GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM, self.close)
|
||||
|
||||
def policy(self, view, decision, kind):
|
||||
from gi.repository import WebKit2
|
||||
if kind == WebKit2.PolicyDecisionType.NAVIGATION_ACTION:
|
||||
if not decision.get_navigation_action().get_request().get_uri().startswith(self.origin + '/'):
|
||||
decision.ignore()
|
||||
return True
|
||||
if kind == WebKit2.PolicyDecisionType.NEW_WINDOW_ACTION:
|
||||
decision.ignore()
|
||||
return True
|
||||
return False
|
||||
|
||||
def permission(self, view, request):
|
||||
request.deny()
|
||||
return True
|
||||
|
||||
def send(self, value):
|
||||
packet = json.dumps(value, separators=(',', ':'), ensure_ascii=True).encode()
|
||||
if len(packet) > MAX_PACKET:
|
||||
return False
|
||||
try:
|
||||
return self.socket.send(packet) == len(packet)
|
||||
except (BlockingIOError, BrokenPipeError, OSError):
|
||||
return False
|
||||
|
||||
def message(self, manager, result):
|
||||
try:
|
||||
text = result.get_js_value().to_string()
|
||||
if len(text.encode()) > MAX_PACKET:
|
||||
raise ValueError('Island event is too large')
|
||||
value = json.loads(text)
|
||||
if not isinstance(value, dict) or value.get('v') != 1 or value.get('type') not in {'ready', 'ack', 'state', 'click', 'error', 'frame'}:
|
||||
raise ValueError('Invalid island event')
|
||||
if value['type'] == 'ready':
|
||||
value['native'] = {'pid': os.getpid(), 'xid': self.xid, 'parent': self.parent}
|
||||
self.send(value)
|
||||
if value['type'] == 'ready':
|
||||
self.ready = True
|
||||
waiting, self.pending = self.pending, []
|
||||
for command in waiting:
|
||||
self.evaluate(command)
|
||||
self.focused = None
|
||||
self.focus()
|
||||
except (ValueError, AttributeError):
|
||||
self.send({'v': 1, 'type': 'error', 'message': 'Invalid island event'})
|
||||
|
||||
def evaluate(self, command):
|
||||
if not self.ready:
|
||||
if len(self.pending) >= 32:
|
||||
raise ValueError('Island is not ready; queue is full')
|
||||
self.pending.append(command)
|
||||
return
|
||||
# JSON encoding keeps data out of executable script source.
|
||||
self.view.evaluate_javascript('window.KryonIsland.receive(' + json.dumps(command, ensure_ascii=True) + ')', -1, None, None, None, None, None)
|
||||
|
||||
def input(self, fd, condition):
|
||||
try:
|
||||
packet = self.socket.recv(MAX_PACKET + 1)
|
||||
if not packet:
|
||||
self.close()
|
||||
return False
|
||||
if len(packet) > MAX_PACKET:
|
||||
raise ValueError('Island command is too large')
|
||||
value = json.loads(packet)
|
||||
if isinstance(value, dict) and value.get('v') == 1 and value.get('type') == 'host-bounds':
|
||||
x, y, width, height = (value[k] for k in ('x', 'y', 'width', 'height'))
|
||||
if any(type(n) is not int or abs(n) > 16384 for n in (x, y, width, height)) or width < 1 or height < 1 or type(value.get('visible')) is not bool:
|
||||
raise ValueError('Invalid island bounds')
|
||||
self.visible = value['visible']
|
||||
self.x.XMoveResizeWindow(self.display, self.xid, x if self.visible else -width - 1, y if self.visible else -height - 1, width, height)
|
||||
self.x.XFlush(self.display)
|
||||
self.focused = None
|
||||
self.focus()
|
||||
else:
|
||||
self.evaluate(validate_command(value))
|
||||
except BlockingIOError:
|
||||
return True
|
||||
except (ValueError, KeyError, TypeError, json.JSONDecodeError):
|
||||
self.send({'v': 1, 'type': 'error', 'message': 'Invalid island command'})
|
||||
except OSError:
|
||||
self.close()
|
||||
return False
|
||||
return True
|
||||
|
||||
def focus(self):
|
||||
if self.closed:
|
||||
return False
|
||||
focused, revert = c.c_ulong(), c.c_int()
|
||||
self.x.XGetInputFocus(self.display, c.byref(focused), c.byref(revert))
|
||||
window = focused.value
|
||||
active = False
|
||||
for _ in range(32):
|
||||
if window == self.parent or window == self.xid:
|
||||
active = self.visible
|
||||
break
|
||||
if window <= 1:
|
||||
break
|
||||
root, parent, count = c.c_ulong(), c.c_ulong(), c.c_uint()
|
||||
children = c.POINTER(c.c_ulong)()
|
||||
if not self.x.XQueryTree(self.display, window, c.byref(root), c.byref(parent), c.byref(children), c.byref(count)):
|
||||
break
|
||||
if children:
|
||||
self.x.XFree(children)
|
||||
if parent.value == window:
|
||||
break
|
||||
window = parent.value
|
||||
if active != self.focused:
|
||||
self.focused = active
|
||||
self.evaluate({'v': 1, 'type': 'focus', 'active': active})
|
||||
return True
|
||||
|
||||
def close(self):
|
||||
if self.closed:
|
||||
return False
|
||||
self.closed = True
|
||||
self.server.shutdown()
|
||||
self.server.server_close()
|
||||
self.socket.close()
|
||||
self.x.XCloseDisplay(self.display)
|
||||
self.Gtk.main_quit()
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--fd', type=int, required=True)
|
||||
parser.add_argument('--parent', type=int, required=True)
|
||||
parser.add_argument('--content', default='scene')
|
||||
parser.add_argument('--assets', type=Path)
|
||||
parser.add_argument('--embedded', action='store_true')
|
||||
options = parser.parse_args()
|
||||
if options.parent <= 1:
|
||||
parser.error('An owned native parent window is required')
|
||||
island = Island(options)
|
||||
island.Gtk.main()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -22,6 +22,7 @@ UiTheme :: #import "theme";
|
||||
Service :: #import "service_linux";
|
||||
Theme :: #import "system_theme_host_linux";
|
||||
Background :: #import "background_window_linux";
|
||||
WebView :: #import "webview_linux";
|
||||
}
|
||||
Watch :: #import "bundle_watch";
|
||||
AppPlayer :: #import "app_player";
|
||||
@@ -125,6 +126,13 @@ Supported :: (module: string, function: string) -> bool {
|
||||
function == "MediaMessageHost" || function == "FetchTextHost" ||
|
||||
function == "FetchTextStateHost" || function == "FetchTextResultHost"
|
||||
}
|
||||
#if OS == .LINUX {
|
||||
if ModuleName(module, "webview") {
|
||||
return function == "WebViewOpenHost" || function == "WebViewBoundsHost" ||
|
||||
function == "WebViewSendHost" || function == "WebViewEventHost" ||
|
||||
function == "WebViewCloseHost"
|
||||
}
|
||||
}
|
||||
if ModuleName(module, "bitmap_image") {
|
||||
return function == "BitmapImageCreateHost" || function == "BitmapImageUpdateHost" || function == "BitmapImageReleaseHost"
|
||||
}
|
||||
@@ -147,6 +155,33 @@ PlayerCall :: (context: *void, module_name: *u8, function_name: *u8,
|
||||
if ModuleName(module, "media") {
|
||||
return BundleMediaCall(*player.media, module, function, args, count, result)
|
||||
}
|
||||
#if OS == .LINUX {
|
||||
if ModuleName(module, "webview") {
|
||||
if function == "WebViewOpenHost" && count == 5 && args[0].kind == HostString &&
|
||||
args[1].kind == HostInteger && args[2].kind == HostInteger &&
|
||||
args[3].kind == HostInteger && args[4].kind == HostInteger {
|
||||
result.kind = HostInteger
|
||||
result.integer = cast(s64)WebView.WebViewOpenHost(TextValue(args[0]), cast(s32)args[1].integer, cast(s32)args[2].integer, cast(s32)args[3].integer, cast(s32)args[4].integer)
|
||||
return 1
|
||||
}
|
||||
if function == "WebViewBoundsHost" && count == 5 && args[0].kind == HostInteger &&
|
||||
args[1].kind == HostInteger && args[2].kind == HostInteger &&
|
||||
args[3].kind == HostInteger && args[4].kind == HostInteger {
|
||||
WebView.WebViewBoundsHost(cast(s32)args[0].integer, cast(s32)args[1].integer, cast(s32)args[2].integer, cast(s32)args[3].integer, args[4].integer != 0)
|
||||
return 1
|
||||
}
|
||||
if function == "WebViewSendHost" && count == 1 && args[0].kind == HostString {
|
||||
result.kind = HostInteger; result.integer = cast(s64)WebView.WebViewSendHost(TextValue(args[0])); return 1
|
||||
}
|
||||
if function == "WebViewEventHost" && count == 0 {
|
||||
value := WebView.WebViewEventHost()
|
||||
result.kind = HostString; result.length = cast(usize)value.count
|
||||
descriptor := cast(*TextDescriptor)(*value)
|
||||
result.data = descriptor.data; return 1
|
||||
}
|
||||
if function == "WebViewCloseHost" && count == 0 { WebView.WebViewCloseHost(); return 1 }
|
||||
}
|
||||
}
|
||||
if ModuleName(module, "clock") && function == "ClockMillisecondsHost" && count == 0 {
|
||||
result.kind = HostInteger; result.integer = MonotonicMilliseconds(); return 1
|
||||
}
|
||||
@@ -309,6 +344,9 @@ PlayerCall :: (context: *void, module_name: *u8, function_name: *u8,
|
||||
player.key = key
|
||||
player.modifiers = modifiers
|
||||
BundleMediaTick(*player.media)
|
||||
#if OS == .LINUX {
|
||||
WebView.WebViewTickHost()
|
||||
}
|
||||
BeginDesktopFrame()
|
||||
SetRasterBackground(BundleThemeBackground)
|
||||
viewport := DesktopViewport()
|
||||
@@ -823,6 +861,7 @@ RunFrameBundle :: (bundle_path: string, opened_bundle: *void, check: bool,
|
||||
BundleMediaClose(*player.media)
|
||||
Video.VideoStopHost()
|
||||
#if OS == .LINUX {
|
||||
WebView.WebViewCloseHost()
|
||||
Service.CloseService()
|
||||
}
|
||||
CloseDesktop()
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
// Optional transport to Kryon's reusable WebKit island: an exact owned child
|
||||
// process, bounded JSON packets, literal argv, no shell and no listening
|
||||
// port. The staged script and pages live beside the player executable, or
|
||||
// where KRYON_WEBVIEW_ASSETS names them.
|
||||
#import "std/byte_text_linux"
|
||||
#import "std/c_string"
|
||||
#import "std/text"
|
||||
#import "std/vec"
|
||||
Background :: #import "background_window_linux";
|
||||
libc :: #system_library "libc";
|
||||
glib :: #system_library "glib-2.0";
|
||||
Setup :: #type (data: *void) #c_call;
|
||||
Argument :: struct { value: *u8 }
|
||||
ParentDeath :: (option: s32, signal: u64, b: u64, c: u64, d: u64) -> s32 #foreign libc "prctl";
|
||||
GetPid :: () -> s32 #foreign libc "getpid";
|
||||
GetParent :: () -> s32 #foreign libc "getppid";
|
||||
Exit :: (code: s32) #foreign libc "_exit";
|
||||
Wait :: (pid: s32, status: *s32, options: s32) -> s32 #foreign libc "waitpid";
|
||||
CloseFd :: (fd: s32) #foreign libc "close";
|
||||
PidFd :: (pid: s32, flags: u32) -> s32 #foreign libc "pidfd_open";
|
||||
SignalFd :: (fd: s32, signal: s32, info: *void, flags: u32) -> s32 #foreign libc "pidfd_send_signal";
|
||||
Kill :: (pid: s32, signal: s32) -> s32 #foreign libc "kill";
|
||||
Spawn :: (cwd: *u8, args: *Argument, env: *Argument, flags: s32, setup: Setup, data: *void, input_fd: s32, output_fd: s32, error_fd: s32, source_fds: *s32, target_fds: *s32, fd_count: usize, pid: *s32, input: *s32, output: *s32, error_pipe: *s32, error: **void) -> s32 #foreign glib "g_spawn_async_with_pipes_and_fds";
|
||||
Environment :: (name: *u8) -> *u8 #foreign libc "getenv";
|
||||
owner: s32;
|
||||
OwnedChild :: (data: *void) { unused data; if ParentDeath(1, 9, 0, 0, 0) != 0 || GetParent() != owner { Exit(126) } }
|
||||
|
||||
SocketPair :: (domain: s32, kind: s32, protocol: s32, fds: *s32) -> s32 #foreign libc "socketpair";
|
||||
Send :: (fd: s32, bytes: *u8, count: usize, flags: s32) -> s64 #foreign libc "send";
|
||||
Receive :: (fd: s32, bytes: *u8, count: usize, flags: s32) -> s64 #foreign libc "recv";
|
||||
ReadLink :: (path: *u8, bytes: *u8, count: usize) -> s64 #foreign libc "readlink";
|
||||
Access :: (path: *u8, mode: s32) -> s32 #foreign libc "access";
|
||||
Free :: (pointer: *void) #foreign libc "free";
|
||||
FreeText :: (value: string) { if value.count > 0 { descriptor := cast(*TextDescriptor)(*value); Free(cast(*void)descriptor.data) } }
|
||||
pid: s32;
|
||||
handle: s32 = -1;
|
||||
transport: s32 = -1;
|
||||
event_bytes: [4096]u8;
|
||||
assets_bytes: [4096]u8;
|
||||
last_x: s32 = -1;
|
||||
last_y: s32;
|
||||
last_width: s32;
|
||||
last_height: s32;
|
||||
last_visible: bool;
|
||||
Join :: (a: string, b: string) -> string { v: Vec(u8); unused BuilderAppend(v, a); unused BuilderAppend(v, b); return BuilderFinish(v) }
|
||||
|
||||
|
||||
#program_export
|
||||
WebViewTickHost :: () {
|
||||
if pid <= 0 { return }
|
||||
status: s32;
|
||||
if Wait(pid, *status, 1) != 0 {
|
||||
if handle >= 0 { CloseFd(handle) }; if transport >= 0 { CloseFd(transport) }
|
||||
pid = 0; handle = -1; transport = -1;
|
||||
}
|
||||
}
|
||||
#program_export
|
||||
WebViewSendHost :: (command: string) -> bool {
|
||||
WebViewTickHost(); if transport < 0 || command.count == 0 || command.count > 4096 { return false }
|
||||
descriptor := cast(*TextDescriptor)(*command);
|
||||
return Send(transport, descriptor.data, cast(usize)command.count, 16448) == command.count
|
||||
}
|
||||
#program_export
|
||||
WebViewBoundsHost :: (x: s32, y: s32, width: s32, height: s32, visible: bool) {
|
||||
if x == last_x && y == last_y && width == last_width && height == last_height && visible == last_visible { return }
|
||||
v: Vec(u8); BuilderPrint(*v, "{\"v\":1,\"type\":\"host-bounds\",\"x\":%,\"y\":%,\"width\":%,\"height\":%,\"visible\":%}", x, y, width, height, ifx visible then "true" else "false");
|
||||
message := BuilderFinish(v); accepted := WebViewSendHost(message); FreeText(message);
|
||||
if accepted { last_x = x; last_y = y; last_width = width; last_height = height; last_visible = visible }
|
||||
}
|
||||
#program_export
|
||||
WebViewCloseHost :: () {
|
||||
if pid > 0 {
|
||||
if handle >= 0 { unused SignalFd(handle, 15, null, 0) }
|
||||
status: s32; unused Wait(pid, *status, 0)
|
||||
}
|
||||
if handle >= 0 { CloseFd(handle) }; if transport >= 0 { CloseFd(transport) }
|
||||
pid = 0; handle = -1; transport = -1; last_x = -1
|
||||
}
|
||||
assets_size: s64;
|
||||
AssetsFromExecutable :: (directory_bytes: []u8) -> bool {
|
||||
if directory_bytes.count > 4080 { return false }
|
||||
assets_size = 0;
|
||||
for byte: directory_bytes { assets_bytes[assets_size] = byte; assets_size += 1 }
|
||||
for byte: "webview-assets" { assets_bytes[assets_size] = byte; assets_size += 1 }
|
||||
return true
|
||||
}
|
||||
#program_export
|
||||
WebViewOpenHost :: (content: string, x: s32, y: s32, width: s32, height: s32) -> bool {
|
||||
WebViewTickHost(); if pid > 0 || width <= 0 || height <= 0 || content.count == 0 || content.count > 64 { return false }
|
||||
// Content names one staged page; the island serves only that allowlist.
|
||||
for byte: content {
|
||||
lower := byte >= cast(u8)97 && byte <= cast(u8)122
|
||||
dash := byte == cast(u8)45
|
||||
if !lower && !dash { return false }
|
||||
}
|
||||
info: Background.BackgroundInfo; if !Background.BackgroundConnection(*info) { return false }
|
||||
path: [4096]u8; link: [32]u8; unused CopyCString("/proc/self/exe", link[:]);
|
||||
size := ReadLink(*link[0], *path[0], 4095); if size <= 0 { return false }
|
||||
end := size - 1; while end >= 0 && path[end] != cast(u8)47 { end -= 1 }
|
||||
if end < 0 { return false }
|
||||
script := Join(TextFromBytes(path[:end + 1]), "kryon-island.py"); script_bytes: [4096]u8;
|
||||
if !CopyCString(script, script_bytes[:]) { FreeText(script); return false }
|
||||
if Access(*script_bytes[0], 4) != 0 { FreeText(script); return false }
|
||||
name: [32]u8; unused CopyCString("KRYON_WEBVIEW_ASSETS", name[:]);
|
||||
override_pointer := Environment(*name[0]);
|
||||
if override_pointer != null {
|
||||
assets_size = 0;
|
||||
while assets_size < 4095 && override_pointer[assets_size] != 0 { assets_size += 1 }
|
||||
if assets_size == 0 { FreeText(script); return false }
|
||||
for i: 0..cast(s32)assets_size - 1 { assets_bytes[i] = override_pointer[i] }
|
||||
} else if !AssetsFromExecutable(path[:end + 1]) { FreeText(script); return false }
|
||||
if Access(*assets_bytes[0], 4) != 0 { FreeText(script); return false }
|
||||
assets := TextFromBytes(assets_bytes[:assets_size]);
|
||||
values: [11][4096]u8; arguments: [12]Argument;
|
||||
parent: Vec(u8); BuilderPrint(*parent, "%", info.window); parent_text := BuilderFinish(parent);
|
||||
script_text := TextFromBytes(script_bytes[:script.count]);
|
||||
labels: [11]string = .{"/usr/bin/python3", script_text, "--fd", "3", "--parent", parent_text, "--content", content, "--assets", assets, "--embedded"};
|
||||
for i: 0..10 {
|
||||
if !CopyCString(labels[i], values[i][:]) { FreeText(script); FreeText(parent_text); return false }
|
||||
arguments[i].value = *values[i][0]
|
||||
}
|
||||
FreeText(script); FreeText(parent_text);
|
||||
pair: [2]s32; if SocketPair(1, 524293, 0, *pair[0]) != 0 { return false }
|
||||
source: [1]s32 = .{pair[1]}; target: [1]s32 = .{3};
|
||||
owner = GetPid(); setup: Setup = OwnedChild;
|
||||
started := Spawn(null, *arguments[0], null, 6, setup, null, -1, -1, -1, *source[0], *target[0], 1, *pid, null, null, null, null);
|
||||
CloseFd(pair[1]);
|
||||
if started == 0 { CloseFd(pair[0]); pid = 0; return false }
|
||||
transport = pair[0]; handle = PidFd(pid, 0);
|
||||
if handle < 0 { unused Kill(pid, 15); status: s32; unused Wait(pid, *status, 0); CloseFd(transport); transport = -1; pid = 0; return false }
|
||||
last_x = -1; WebViewBoundsHost(x, y, width, height, true); return true
|
||||
}
|
||||
#program_export
|
||||
WebViewEventHost :: () -> string {
|
||||
WebViewTickHost(); if transport < 0 { return "" }
|
||||
size := Receive(transport, *event_bytes[0], 4096, 64);
|
||||
if size <= 0 { return "" }; return TextFromBytes(event_bytes[:size])
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Optional native web view: the host serves approved staged pages in an
|
||||
// owned WebKit child and exchanges versioned JSON, never scripts or URLs.
|
||||
// Coordinates are host window coordinates. Content selects one staged page
|
||||
// by name; pages declare their own commands inside the shared vocabulary.
|
||||
host_api :: #system_library "host_api";
|
||||
WebViewOpenHost :: (content: string, x: s32, y: s32, width: s32, height: s32) -> bool #foreign host_api;
|
||||
WebViewBoundsHost :: (x: s32, y: s32, width: s32, height: s32, visible: bool) #foreign host_api;
|
||||
WebViewSendHost :: (command: string) -> bool #foreign host_api;
|
||||
WebViewEventHost :: () -> string #foreign host_api;
|
||||
WebViewCloseHost :: () #foreign host_api;
|
||||
|
||||
#program_export
|
||||
Open :: (content: string, x: s32, y: s32, width: s32, height: s32) -> bool {
|
||||
return WebViewOpenHost(content, x, y, width, height)
|
||||
}
|
||||
#program_export
|
||||
Bounds :: (x: s32, y: s32, width: s32, height: s32, visible: bool) {
|
||||
WebViewBoundsHost(x, y, width, height, visible)
|
||||
}
|
||||
#program_export
|
||||
Send :: (command: string) -> bool { return WebViewSendHost(command) }
|
||||
#program_export
|
||||
Event :: () -> string { return WebViewEventHost() }
|
||||
#program_export
|
||||
Close :: () { WebViewCloseHost() }
|
||||
@@ -7,7 +7,7 @@ tool = "kryon"
|
||||
|
||||
[toolchain]
|
||||
git = "https://git.waozi.xyz/ziranlang/ziran.git"
|
||||
ref = "bb0323cef6c7b144eeea5ad1670ccf7a3fbde253"
|
||||
ref = "4413456221aa5a9bc00a368762e9e50aaf6e7b6b"
|
||||
|
||||
[dependencies.kryon]
|
||||
git = "https://git.waozi.xyz/kryonlabs/kryon.git"
|
||||
|
||||
@@ -7,7 +7,7 @@ tool = "kryon"
|
||||
|
||||
[toolchain]
|
||||
git = "https://git.waozi.xyz/ziranlang/ziran.git"
|
||||
ref = "bb0323cef6c7b144eeea5ad1670ccf7a3fbde253"
|
||||
ref = "4413456221aa5a9bc00a368762e9e50aaf6e7b6b"
|
||||
|
||||
[dependencies.kryon]
|
||||
git = "https://git.waozi.xyz/kryonlabs/kryon.git"
|
||||
|
||||
@@ -7,7 +7,7 @@ tool = "kryon"
|
||||
|
||||
[toolchain]
|
||||
git = "https://git.waozi.xyz/ziranlang/ziran.git"
|
||||
ref = "bb0323cef6c7b144eeea5ad1670ccf7a3fbde253"
|
||||
ref = "4413456221aa5a9bc00a368762e9e50aaf6e7b6b"
|
||||
|
||||
[dependencies.kryon]
|
||||
git = "https://git.waozi.xyz/kryonlabs/kryon.git"
|
||||
|
||||
@@ -7,7 +7,7 @@ tool = "kryon"
|
||||
|
||||
[toolchain]
|
||||
git = "https://git.waozi.xyz/ziranlang/ziran.git"
|
||||
ref = "bb0323cef6c7b144eeea5ad1670ccf7a3fbde253"
|
||||
ref = "4413456221aa5a9bc00a368762e9e50aaf6e7b6b"
|
||||
|
||||
[dependencies.kryon]
|
||||
git = "https://git.waozi.xyz/kryonlabs/kryon.git"
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
"""The reusable WebKit island: a staged page round-trip through the zx player.
|
||||
|
||||
Builds the webview probe bundle against this checkout, then runs it on a
|
||||
private Xvfb display: the island child starts, maps its window into the
|
||||
player, reports ready, answers a spin command with rendered frames, and is
|
||||
reaped on close. Skipped where WebKitGTK is unavailable."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WORK = ROOT / 'build/test/webview-island'
|
||||
|
||||
|
||||
def webkit_available():
|
||||
probe = subprocess.run(['/usr/bin/python3', '-c',
|
||||
"import gi; gi.require_version('WebKit2', '4.1');"
|
||||
"import gi.repository.WebKit2"], capture_output=True)
|
||||
return probe.returncode == 0
|
||||
|
||||
|
||||
def children(pid):
|
||||
try:
|
||||
return [int(value) for value in
|
||||
Path(f'/proc/{pid}/task/{pid}/children').read_text().split()]
|
||||
except (FileNotFoundError, ProcessLookupError):
|
||||
return []
|
||||
|
||||
|
||||
def island_pid(player_pid):
|
||||
for pid in children(player_pid):
|
||||
try:
|
||||
if Path(f'/proc/{pid}/comm').read_text().strip() == 'python3':
|
||||
return pid
|
||||
except (FileNotFoundError, ProcessLookupError):
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def wait_until(predicate, timeout, player=None, log=None):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
result = predicate()
|
||||
if result:
|
||||
return result
|
||||
if player is not None and player.poll() is not None:
|
||||
raise AssertionError(
|
||||
f'Player exited early with {player.returncode}:\n{log_text(log)}')
|
||||
time.sleep(0.1)
|
||||
raise AssertionError(f'Timed out after {timeout}s:\n{log_text(log)}')
|
||||
|
||||
|
||||
def log_text(path):
|
||||
try:
|
||||
return path.read_text(errors='replace')
|
||||
except FileNotFoundError:
|
||||
return ''
|
||||
|
||||
|
||||
def drive(bundle, player):
|
||||
assert os.environ.get('KRYON_PRIVATE_XVFB') == '1'
|
||||
assert not os.environ.get('WAYLAND_DISPLAY')
|
||||
WORK.mkdir(parents=True, exist_ok=True)
|
||||
home = WORK / 'home'
|
||||
home.mkdir(exist_ok=True)
|
||||
log = WORK / 'probe.log'
|
||||
env = dict(os.environ,
|
||||
HOME=str(home), XDG_CONFIG_HOME=str(WORK / 'config'),
|
||||
XDG_CACHE_HOME=str(WORK / 'cache'),
|
||||
LIBGL_ALWAYS_SOFTWARE='1', GALLIUM_DRIVER='llvmpipe',
|
||||
WEBKIT_DISABLE_DMABUF_RENDERER='1', YUE_DESKTOP_RECOVERY='0')
|
||||
with log.open('w') as stream:
|
||||
player_process = subprocess.Popen([str(player), str(bundle)],
|
||||
stdout=stream, stderr=subprocess.STDOUT, env=env, cwd=str(WORK))
|
||||
try:
|
||||
island = wait_until(lambda: island_pid(player_process.pid),
|
||||
25, player_process, log)
|
||||
arguments = Path(f'/proc/{island}/cmdline').read_bytes()
|
||||
assert b'kryon-island.py' in arguments, 'The island child is not the staged script'
|
||||
window = wait_until(lambda: subprocess.run(
|
||||
['xdotool', 'search', '--onlyvisible', '--name', 'Kryon webview island'],
|
||||
capture_output=True, text=True, env=env).stdout.strip() or None,
|
||||
45, player_process, log)
|
||||
wait_until(lambda: 'probe: webview island passed' in log_text(log),
|
||||
90, player_process, log)
|
||||
text = log_text(log)
|
||||
assert 'probe: island failed to open' not in text, text
|
||||
assert 'probe: island reported an error' not in text, text
|
||||
assert 'probe: island timed out' not in text, text
|
||||
frames = [int(match) for match in
|
||||
re.findall(r'"frames":(\d+)', text)]
|
||||
assert frames and max(frames) > 0, \
|
||||
f'The ack state reported no rendered frames: {text}'
|
||||
ready = [json.loads(line.split('probe: event ', 1)[1])
|
||||
for line in text.splitlines() if 'probe: event ' in line]
|
||||
kinds = {event.get('type') for event in ready}
|
||||
assert 'ready' in kinds and 'ack' in kinds, kinds
|
||||
spin = [event for event in ready
|
||||
if event.get('command') == 'spin']
|
||||
assert spin and spin[0].get('state', {}).get('mode') == 'scene', spin
|
||||
assert spin[0]['state'].get('speed') == 3, spin
|
||||
code = player_process.wait(timeout=30)
|
||||
assert code == 0, f'Probe exited {code}: {log_text(log)}'
|
||||
assert island_pid(player_process.pid) is None and not children(player_process.pid), \
|
||||
'The island child leaked after close'
|
||||
assert not Path(f'/proc/{island}').exists(), 'The island child leaked'
|
||||
print('Webview island: staged scene ready, spin ack with rendered '
|
||||
f'frames, window {window}, child reaped: passed', flush=True)
|
||||
(WORK / 'receipt.json').write_text(json.dumps(dict(
|
||||
state='verified', island_protocol=1, page='scene',
|
||||
frames=max(frames), checks=['child spawn', 'island window',
|
||||
'ready event', 'spin ack', 'reaped on close']), indent=2))
|
||||
finally:
|
||||
if player_process.poll() is None:
|
||||
player_process.terminate()
|
||||
try:
|
||||
player_process.wait(timeout=15)
|
||||
except subprocess.TimeoutExpired:
|
||||
player_process.kill()
|
||||
player_process.wait(timeout=10)
|
||||
return 0
|
||||
|
||||
|
||||
def build_probe():
|
||||
from toolchain import ZIRAN, fixture_identity, fixture_overrides
|
||||
shutil.rmtree(WORK, ignore_errors=True)
|
||||
project = WORK / 'probe'
|
||||
(project / 'src').mkdir(parents=True)
|
||||
shutil.copyfile(ROOT / 'tests/webview_probe.zi', project / 'src/app.zi')
|
||||
(project / 'ziran.toml').write_text(
|
||||
'[package]\nname = "webview_probe"\nentry = "src/app.zi"\n'
|
||||
'module_roots = ["src"]\nbridge_modules = ["app"]\ntool = "kryon"\n'
|
||||
+ fixture_identity()
|
||||
+ '[tool.kryon]\ndefault_profile = "portable"\n'
|
||||
'[tool.kryon.profiles.portable]\nbackend = "desktop"\ncodegen = "zx"\n')
|
||||
(project / 'ziran.local.toml').write_text(fixture_overrides())
|
||||
def run(args, ok=True):
|
||||
result = subprocess.run([str(value) for value in args], cwd=project,
|
||||
capture_output=True, text=True)
|
||||
if ok:
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
return result
|
||||
run([ZIRAN, 'lock'])
|
||||
run([ZIRAN, 'tool', 'kryon', 'build', 'portable'])
|
||||
bundle = project / 'build/webview_probe-portable.zx'
|
||||
assert bundle.is_file() and bundle.stat().st_size > 0, 'The probe built no bundle'
|
||||
player = ROOT / 'build/bin/zx'
|
||||
assert player.is_file(), 'Build the zx player first (make zx-player)'
|
||||
staged = player.parent / 'webview-assets/scene.html'
|
||||
assert staged.is_file(), 'Stage the island assets first (make zx-player)'
|
||||
return bundle, player
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) > 1 and sys.argv[1] == '--drive':
|
||||
return drive(Path(sys.argv[2]), Path(sys.argv[3]))
|
||||
if not webkit_available():
|
||||
print('WebKitGTK 4.1 is unavailable: skipping the island test', flush=True)
|
||||
return 0
|
||||
bundle, player = build_probe()
|
||||
env = os.environ.copy()
|
||||
for key in ('DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY',
|
||||
'DBUS_SESSION_BUS_ADDRESS', 'SESSION_MANAGER', 'GDK_DISPLAY',
|
||||
'ICEAUTHORITY'):
|
||||
env.pop(key, None)
|
||||
env['KRYON_PRIVATE_XVFB'] = '1'
|
||||
subprocess.run(['dbus-run-session', '--', 'xvfb-run', '-a', '-s',
|
||||
'-screen 0 1024x768x24 -nolisten tcp',
|
||||
sys.executable, str(Path(__file__).resolve()),
|
||||
'--drive', str(bundle), str(player)],
|
||||
env=env, check=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,61 @@
|
||||
// The webview island probe: opens the staged demo scene through the host
|
||||
// bridge, waits for the page ready event, spins it, checks that the ack
|
||||
// reports rendered frames, then closes the island and quits for the harness.
|
||||
App :: #import "kryon/app";
|
||||
Clock :: #import "kryon/Clock";
|
||||
WebView :: #import "kryon/WebView";
|
||||
#import "Window"
|
||||
#import "std/text_tools"
|
||||
|
||||
// 1 opening, 2 ready, 3 spin sent, 4 passed, 5 failed.
|
||||
phase: s32;
|
||||
deadline: s64;
|
||||
|
||||
Frame :: (frame: App.Frame) {
|
||||
if frame.first && phase == 0 {
|
||||
deadline = Clock.Milliseconds() + 30000
|
||||
if WebView.Open("scene", 40, 40, 480, 320) {
|
||||
phase = 1
|
||||
print("probe: island opening\n")
|
||||
} else {
|
||||
phase = 5
|
||||
print("probe: island failed to open\n")
|
||||
}
|
||||
}
|
||||
for attempt: 0..31 {
|
||||
event := WebView.Event()
|
||||
if event == "" { break }
|
||||
print("probe: event %\n", event)
|
||||
if TextContains(event, "\"type\":\"error\"") && phase < 4 {
|
||||
phase = 5
|
||||
print("probe: island reported an error\n")
|
||||
}
|
||||
if TextContains(event, "\"type\":\"ready\"") && phase == 1 {
|
||||
phase = 2
|
||||
if !WebView.Send("{\"v\":1,\"id\":7,\"type\":\"spin\",\"speed\":3}") {
|
||||
phase = 5
|
||||
print("probe: spin send failed\n")
|
||||
}
|
||||
}
|
||||
if TextContains(event, "\"command\":\"spin\"") && phase == 2 {
|
||||
if TextFind(event, "\"frames\":") < 0 || TextContains(event, "\"frames\":0") {
|
||||
phase = 5
|
||||
print("probe: spin ack reports no rendered frames\n")
|
||||
} else {
|
||||
phase = 4
|
||||
print("probe: webview island passed\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
if phase > 0 && phase < 4 && Clock.Milliseconds() > deadline {
|
||||
phase = 5
|
||||
print("probe: island timed out in phase %\n", phase)
|
||||
}
|
||||
if phase >= 4 || phase == 5 {
|
||||
WebView.Close()
|
||||
WindowQuit()
|
||||
}
|
||||
}
|
||||
|
||||
main :: () -> s32 { return App.Run(App.Window.{.title = "Webview island probe",
|
||||
.width = 640, .height = 480}, Frame) }
|
||||
+14
-14
@@ -65,17 +65,17 @@
|
||||
"url": "https://github.com/xiph/opus.git"
|
||||
},
|
||||
{
|
||||
"commit": "b5c6b56b71172c4361ae01e3afdd2118bdac0975",
|
||||
"commit": "149670762082c5cfc802e496f707f08abdf88ad9",
|
||||
"dependencies": {"libopus": "src_github_com_xiph_opus_ddbe48383984", "libsamplerate": "src_github_com_libsndfile_libsamplerate_c96f5e3de9c4"},
|
||||
"dependency_refs": {"libopus": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6", "libsamplerate": "c96f5e3de9c4488f4e6c97f59f5245f22fda22f7"},
|
||||
"id": "waozi_xyz_ziranlang_audio_b5c6b56b7117",
|
||||
"id": "waozi_xyz_ziranlang_audio_149670762082",
|
||||
"name": "audio",
|
||||
"ref": "b5c6b56b71172c4361ae01e3afdd2118bdac0975",
|
||||
"url": "https://git.waozi.xyz/ziranlang/audio.git"
|
||||
},
|
||||
{
|
||||
"commit": "bed54d12dc5a8cf8e6a514b2a49d3592d6cecb65",
|
||||
"dependencies": {"dav1d": "src_github_com_videolan_dav1d_54706fc6bc0c", "image_codec": "waozi_xyz_ziranlang_image_codec_3017f0d1cc56", "libaom": "src_aomedia_googlesource_com_aom_b141d9c45db2"},
|
||||
"dependencies": {"dav1d": "src_github_com_videolan_dav1d_54706fc6bc0c", "image_codec": "waozi_xyz_ziranlang_image_codec_5182c32ce2e2", "libaom": "src_aomedia_googlesource_com_aom_b141d9c45db2"},
|
||||
"dependency_refs": {"dav1d": "54706fc6bc0cdecab7e9593974a4039cc038fca7", "image_codec": "3017f0d1cc56975aa29c600a1f55a62e1193cf7b", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937"},
|
||||
"id": "waozi_xyz_ziranlang_av1_bed54d12dc5a",
|
||||
"name": "av1",
|
||||
@@ -83,40 +83,40 @@
|
||||
"url": "https://git.waozi.xyz/ziranlang/av1.git"
|
||||
},
|
||||
{
|
||||
"commit": "6ff696d436b6b4f142eb1e3ecf210de7adfa048f",
|
||||
"dependencies": {"av1": "waozi_xyz_ziranlang_av1_bed54d12dc5a", "dav1d": "src_github_com_videolan_dav1d_54706fc6bc0c", "image_codec": "waozi_xyz_ziranlang_image_codec_3017f0d1cc56", "libaom": "src_aomedia_googlesource_com_aom_b141d9c45db2", "libavif": "src_github_com_AOMediaCodec_libavif_1aadfad932c9"},
|
||||
"commit": "ae965034b368090fc060185f91ac8b5eb33ad822",
|
||||
"dependencies": {"av1": "waozi_xyz_ziranlang_av1_bed54d12dc5a", "dav1d": "src_github_com_videolan_dav1d_54706fc6bc0c", "image_codec": "waozi_xyz_ziranlang_image_codec_5182c32ce2e2", "libaom": "src_aomedia_googlesource_com_aom_b141d9c45db2", "libavif": "src_github_com_AOMediaCodec_libavif_1aadfad932c9"},
|
||||
"dependency_refs": {"av1": "bed54d12dc5a8cf8e6a514b2a49d3592d6cecb65", "dav1d": "54706fc6bc0cdecab7e9593974a4039cc038fca7", "image_codec": "3017f0d1cc56975aa29c600a1f55a62e1193cf7b", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199"},
|
||||
"id": "waozi_xyz_ziranlang_avif_6ff696d436b6",
|
||||
"id": "waozi_xyz_ziranlang_avif_ae965034b368",
|
||||
"name": "avif",
|
||||
"ref": "6ff696d436b6b4f142eb1e3ecf210de7adfa048f",
|
||||
"url": "https://git.waozi.xyz/ziranlang/avif.git"
|
||||
},
|
||||
{
|
||||
"commit": "3017f0d1cc56975aa29c600a1f55a62e1193cf7b",
|
||||
"commit": "5182c32ce2e2d51f01df9f9fdd4a641f93ffd1d2",
|
||||
"dependencies": {},
|
||||
"id": "waozi_xyz_ziranlang_image_codec_3017f0d1cc56",
|
||||
"id": "waozi_xyz_ziranlang_image_codec_5182c32ce2e2",
|
||||
"name": "image-codec",
|
||||
"ref": "3017f0d1cc56975aa29c600a1f55a62e1193cf7b",
|
||||
"url": "https://git.waozi.xyz/ziranlang/image-codec.git"
|
||||
},
|
||||
{
|
||||
"commit": "4b9a61d32460d481624fe0f83996a7de50327dfe",
|
||||
"dependencies": {"image_codec": "waozi_xyz_ziranlang_image_codec_3017f0d1cc56", "libwebp": "src_github_com_webmproject_libwebp_1844042d1ca7"},
|
||||
"commit": "8aea16b56edb1182a196eb7daffff0e1d13ab666",
|
||||
"dependencies": {"image_codec": "waozi_xyz_ziranlang_image_codec_5182c32ce2e2", "libwebp": "src_github_com_webmproject_libwebp_1844042d1ca7"},
|
||||
"dependency_refs": {"image_codec": "3017f0d1cc56975aa29c600a1f55a62e1193cf7b", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339"},
|
||||
"id": "waozi_xyz_ziranlang_webp_4b9a61d32460",
|
||||
"id": "waozi_xyz_ziranlang_webp_8aea16b56edb",
|
||||
"name": "webp",
|
||||
"ref": "4b9a61d32460d481624fe0f83996a7de50327dfe",
|
||||
"url": "https://git.waozi.xyz/ziranlang/webp.git"
|
||||
}
|
||||
],
|
||||
"root": {
|
||||
"dependencies": {"audio": "waozi_xyz_ziranlang_audio_b5c6b56b7117", "avif": "waozi_xyz_ziranlang_avif_6ff696d436b6", "image_codec": "waozi_xyz_ziranlang_image_codec_3017f0d1cc56", "libaom": "src_aomedia_googlesource_com_aom_b141d9c45db2", "libavif": "src_github_com_AOMediaCodec_libavif_1aadfad932c9", "libwebp": "src_github_com_webmproject_libwebp_1844042d1ca7", "sdl3": "src_github_com_libsdl_org_SDL_829a65d769d9", "webp": "waozi_xyz_ziranlang_webp_4b9a61d32460"},
|
||||
"dependencies": {"audio": "waozi_xyz_ziranlang_audio_149670762082", "avif": "waozi_xyz_ziranlang_avif_ae965034b368", "image_codec": "waozi_xyz_ziranlang_image_codec_5182c32ce2e2", "libaom": "src_aomedia_googlesource_com_aom_b141d9c45db2", "libavif": "src_github_com_AOMediaCodec_libavif_1aadfad932c9", "libwebp": "src_github_com_webmproject_libwebp_1844042d1ca7", "sdl3": "src_github_com_libsdl_org_SDL_829a65d769d9", "webp": "waozi_xyz_ziranlang_webp_8aea16b56edb"},
|
||||
"dependency_refs": {"audio": "b5c6b56b71172c4361ae01e3afdd2118bdac0975", "avif": "6ff696d436b6b4f142eb1e3ecf210de7adfa048f", "image_codec": "3017f0d1cc56975aa29c600a1f55a62e1193cf7b", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339", "sdl3": "829a65d769d935c4852f8159e964312c0957260a", "webp": "4b9a61d32460d481624fe0f83996a7de50327dfe"},
|
||||
"name": "kryon"
|
||||
},
|
||||
"toolchain": {
|
||||
"commit": "bb0323cef6c7b144eeea5ad1670ccf7a3fbde253",
|
||||
"ref": "bb0323cef6c7b144eeea5ad1670ccf7a3fbde253",
|
||||
"commit": "4413456221aa5a9bc00a368762e9e50aaf6e7b6b",
|
||||
"ref": "4413456221aa5a9bc00a368762e9e50aaf6e7b6b",
|
||||
"url": "https://git.waozi.xyz/ziranlang/ziran.git"
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -5,7 +5,7 @@ module_roots = ["src/ui", "src/backend", "src/ui/alert", "src/ui/avatar", "src/u
|
||||
|
||||
[toolchain]
|
||||
git = "https://git.waozi.xyz/ziranlang/ziran.git"
|
||||
ref = "bb0323cef6c7b144eeea5ad1670ccf7a3fbde253"
|
||||
ref = "4413456221aa5a9bc00a368762e9e50aaf6e7b6b"
|
||||
|
||||
[dependencies.libwebp]
|
||||
git = "https://github.com/webmproject/libwebp.git"
|
||||
@@ -241,6 +241,8 @@ drawing_props = "src/ui/drawing_props.zi"
|
||||
shape = "src/ui/shape/shape.zi"
|
||||
Window = "src/ui/window.zi"
|
||||
Media = "src/ui/media.zi"
|
||||
WebView = "src/ui/webview.zi"
|
||||
WebViewLinux = "src/backend/webview_linux.zi"
|
||||
media_audio = "src/ui/media_audio.zi"
|
||||
media_audio_host = "src/backend/media_audio_host.zi"
|
||||
Video = "src/ui/video.zi"
|
||||
|
||||
Reference in new issue
Block a user