Compare commits

..
Author SHA1 Message Date
waozi c26b7ec943 Fix web build: include <stddef.h> for NULL in platform_thread.c
platform_thread.c uses NULL but only included <stdlib.h> under _WIN32.
On native, <pthread.h> (pulled in by platform.h) transitively provides
NULL, so the build passed. Emscripten's stricter header setup under
-DUI_EMBEDDED_ONLY does not, causing:

  error: use of undeclared identifier 'NULL'

Add the standard <stddef.h> include unconditionally.
2026-07-26 10:58:16 -05:00
2930 changed files with 46238 additions and 372323 deletions

No files matched your search

-39
View File
@@ -1,39 +0,0 @@
name: Compile cache
description: >-
Reuses C objects through ccache and Emscripten's generated system libraries
between runs. Run it after the setup action, which installs ccache.
inputs:
key:
description: Separates the jobs' caches, since each compiles different programs.
required: true
runs:
using: composite
steps:
- name: Name today's compiler cache
id: day
shell: bash
run: echo "day=$(date -u +%F)" >> "$GITHUB_OUTPUT"
# One entry a day per job keeps the repository's 10 GB cache allowance safe.
- name: Restore C objects
uses: actions/cache@v6
with:
path: ~/.ccache
key: ccache-${{ runner.os }}-${{ inputs.key }}-${{ steps.day.outputs.day }}
restore-keys: ccache-${{ runner.os }}-${{ inputs.key }}-
- name: Restore Emscripten system libraries
uses: actions/cache@v6
with:
path: |
kryon/build/emscripten-cache
kryon/build/ziran/emscripten-cache
key: emscripten-cache-${{ inputs.key }}-6.0.6
- name: Compile through the cache
shell: bash
run: |
echo /usr/lib/ccache >> "$GITHUB_PATH"
{
echo "CCACHE_DIR=$HOME/.ccache"
echo "CCACHE_MAXSIZE=150M"
echo "CCACHE_BASEDIR=$GITHUB_WORKSPACE"
echo "CCACHE_NOHASHDIR=true"
} >> "$GITHUB_ENV"
-30
View File
@@ -1,30 +0,0 @@
name: Google-free Android editions
description: >-
Fails when a normal or F-Droid APK, or a Gradle file their builds read,
holds a Google library; only the -gplay edition may (scripts/check-google-free.py).
inputs:
packages:
description: APKs (or globs) of the normal and -fdroid editions to search.
default: ''
source:
description: Folder whose Gradle files are checked as F-Droid scans them; empty skips it.
default: '.'
expect-google:
description: "'true' when the packages are -gplay: fail unless Play Billing is found, proving the search works."
default: 'false'
runs:
using: composite
steps:
- shell: bash
env:
PACKAGES: ${{ inputs.packages }}
SOURCE: ${{ inputs.source }}
EXPECT_GOOGLE: ${{ inputs.expect-google }}
run: |
set -euo pipefail
arguments=()
if [ -n "$SOURCE" ]; then arguments+=(--source "$SOURCE"); fi
if [ "$EXPECT_GOOGLE" = true ]; then arguments+=(--expect-google); fi
# Globs in PACKAGES expand here; a glob matching nothing stays as
# written and fails as a missing file.
python3 "$GITHUB_ACTION_PATH/../../../scripts/check-google-free.py" "${arguments[@]}" $PACKAGES
-358
View File
@@ -1,358 +0,0 @@
name: CI
on:
push:
branches: [master]
pull_request:
workflow_dispatch:
# Several sessions push master many times an hour, longer apart than a run
# takes; cancelling on master left no finished run. Only pull requests
# replace their older runs.
concurrency:
group: ci-${{ github.ref }}-${{ github.event_name == 'pull_request' && 'pr' || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
ZIRAN_ROOT: ${{ github.workspace }}/ziran
jobs:
# A broken host link fails here in minutes, before the long jobs start.
push-check:
name: Source rules and host links
runs-on: ubuntu-latest
outputs:
code: ${{ steps.changes.outputs.code }}
defaults:
run:
working-directory: kryon
steps:
- name: Checkout Kryon
uses: actions/checkout@v7
with:
path: kryon
- name: Name the checked-out Kryon commit master
run: git checkout -B master
# Every job that builds the AVIF decoder needs Meson and Ninja for dav1d,
# and on x86-64 nasm for dav1d's and libaom's SIMD; arm64 builds assemble
# with the C compiler.
- name: Set up the locked Ziran, its packages and the build tools
uses: ziranlang/ziran/.github/actions/setup@4135e07fae33bcd0c00dd66b5716fdfe19c1fca5
with:
project: kryon
path: ziran
fetch: true
recommends: true
packages: >-
build-essential python3 ripgrep pkg-config libsdl2-dev libcairo2-dev libglib2.0-dev
libpango1.0-dev libdrm-dev libgbm-dev libegl-dev libgles-dev libegl-mesa0
libgl1-mesa-dri libx11-dev libxt-dev libxext-dev libfontconfig1-dev libfreetype-dev
libxkbcommon-x11-0
libcurl4-openssl-dev fonts-dejavu-core fonts-wqy-zenhei xvfb xdotool x11-apps x11-utils
imagemagick xfwm4 dbus-x11 cmake nasm meson ninja-build libwebpdemux2
- name: Prepare locked toolchain ref
run: git -C "$ZIRAN_ROOT" checkout -B master
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version: '1.25.x'
- name: Source rules and host links
run: make push-check
# A push touching only prose or the site skips the long jobs: this job
# still checks the docs, and the Pages workflow tests the site. Anything
# unknown runs everything.
- name: Decide whether the long jobs apply
id: changes
env:
GH_TOKEN: ${{ github.token }}
BEFORE: ${{ github.event.before }}
run: |
code=true
if [ "$GITHUB_EVENT_NAME" = push ] && files=$(gh api "repos/$GITHUB_REPOSITORY/compare/$BEFORE...$GITHUB_SHA" --jq '.files[].filename'); then
count=$(printf '%s\n' "$files" | grep -c . || true)
other=$(printf '%s\n' "$files" | grep -vE '^docs/|\.md$' || true)
if [ "$count" -gt 0 ] && [ "$count" -lt 300 ] && [ -z "$other" ]; then code=false; fi
fi
echo "code=$code" >> "$GITHUB_OUTPUT"
test-macos-zx:
name: macOS native ZX build and display-free execution
needs: push-check
if: needs.push-check.outputs.code == 'true'
runs-on: macos-latest
defaults:
run:
working-directory: kryon
steps:
- name: Checkout Kryon
uses: actions/checkout@v7
with:
path: kryon
# The locked compiler comes prebuilt, and the package checkouts cached.
- name: Set up the locked Ziran and fetch packages
uses: ziranlang/ziran/.github/actions/setup@4135e07fae33bcd0c00dd66b5716fdfe19c1fca5
with:
project: kryon
path: ziran
fetch: true
- name: Install the AVIF decoder's dav1d build tools
run: brew install meson ninja pkgconf sdl2 cairo pango fontconfig freetype gdk-pixbuf webp $([ "$RUNNER_ARCH" = X64 ] && echo nasm)
# No GUI launch or screenshot can reach a runner's inherited display.
- name: Build native player and execute the portable VM with CPU pixels
run: |
export PATH="$ZIRAN_ROOT/build/bin:$PATH"
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS \
make zx-headless-test zx-player
build/bin/zx --check build/scratch/zx-headless/app.zx
test-linux:
name: Ziran library and host tests (${{ matrix.shard }})
needs: push-check
if: needs.push-check.outputs.code == 'true'
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
shard: [zx, check, web, site, hosts]
defaults:
run:
working-directory: kryon
steps:
- name: Checkout Kryon
uses: actions/checkout@v7
with:
path: kryon
# Template tests serve the checkouts through local Git URLs and use
# their master refs.
- name: Name the checked-out Kryon commit master
run: git checkout -B master
# The locked compiler comes prebuilt, the package checkouts cached, and
# Ubuntu packages from the canonical archive.
- name: Set up the locked Ziran, its packages and the build tools
uses: ziranlang/ziran/.github/actions/setup@4135e07fae33bcd0c00dd66b5716fdfe19c1fca5
with:
project: kryon
path: ziran
fetch: true
recommends: true
packages: >-
build-essential ccache python3 ripgrep xvfb pkg-config libsdl2-dev libcairo2-dev
libfreetype-dev libfontconfig1-dev libcurl4-openssl-dev libdrm-dev libgbm-dev
libegl-dev libgles-dev libegl-mesa0 libgl1-mesa-dri imagemagick xclip xdotool
libxkbcommon-x11-0
x11-xserver-utils python3-gi python3-gi-cairo python3-cairo python3-pil python3-xlib ffmpeg gir1.2-gtk-3.0 gir1.2-atspi-2.0
libglib2.0-dev libpango1.0-dev at-spi2-core dbus-x11 gstreamer1.0-plugins-base
gstreamer1.0-plugins-good gstreamer1.0-libav cmake nasm meson ninja-build libwebpdemux2 libopus-dev
# SDL3's GPU renderer needs Vulkan even on a software-only runner.
- name: Install native host test tools
if: matrix.shard == 'hosts'
run: sudo apt-get install -y libvulkan-dev mesa-vulkan-drivers libx11-dev libxext-dev libxtst-dev xauth libgtk-3-dev
# Template tests serve this checkout through local Git URLs and use
# the manifest's master ref. Keep that ref at the locked commit.
- name: Prepare locked toolchain ref
run: git -C "$ZIRAN_ROOT" checkout -B master
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version: '1.25.x'
- name: Set up Node
uses: actions/setup-node@v6
with:
node-version: '22'
# The pay-per-import test and the gallery build these examples as
# applications of this checkout, as ziran.local.toml does locally.
- name: Build the in-tree examples from this checkout
if: matrix.shard == 'hosts' || matrix.shard == 'site'
run: |
python3 - <<'PY'
import os, subprocess
from pathlib import Path
ziran = Path(os.environ['ZIRAN_ROOT'])
settings = f'[overrides]\nkryon = "{Path.cwd()}"\nziran = "{ziran}"\n'
for project in ('examples/box', 'examples/button', 'examples/image', 'examples/textfield', 'examples/gallery'):
(Path(project) / 'ziran.local.toml').write_text(settings)
subprocess.run([str(ziran / 'build/bin/ziran'), 'lock'], cwd=project, check=True)
PY
# The Canvas2D and DOM tests compile to Wasm with emscripten and run
# in private headless Chrome; the tests look for ~/emsdk.
- name: Restore emsdk
id: emsdk
uses: actions/cache@v6
with:
path: ~/emsdk
key: emsdk-${{ runner.os }}-6.0.6
- name: Install emsdk
if: steps.emsdk.outputs.cache-hit != 'true'
working-directory: .
run: |
git clone https://github.com/emscripten-core/emsdk.git ~/emsdk
~/emsdk/emsdk install 6.0.6
~/emsdk/emsdk activate 6.0.6
- name: Keep compile results between runs
uses: ./kryon/.github/actions/compile-cache
with:
key: ${{ matrix.shard }}
# The behavior suite executes the Windows storage regression under Wine.
- name: Install Windows storage test tools
if: matrix.shard == 'check'
run: sudo apt-get install -y gcc-mingw-w64-x86-64 wine wine64
- name: Test opt-in SDL3 GPU renderer on a private display
if: matrix.shard == 'hosts'
env:
LIBGL_ALWAYS_SOFTWARE: '1'
run: |
set -- /usr/share/vulkan/icd.d/lvp_icd*.json
test -f "$1"
export VK_DRIVER_FILES="$1"
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS YUE_DESKTOP_RECOVERY=0 make sdl3-test
- name: Build and test
if: matrix.shard != 'site'
env:
CHROMIUM: google-chrome
run: env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS YUE_DESKTOP_RECOVERY=0 make test-shard-${{ matrix.shard }}
- name: Check repeatable frame workloads
if: matrix.shard == 'hosts'
run: python3 tools/performance.py --budget-ms 64
- name: Test SVG example
if: matrix.shard == 'hosts'
run: env -u DISPLAY -u WAYLAND_DISPLAY make -C examples test
# The whole site is rebuilt from this checkout, so the live editor's
# embedded examples match the gallery under test. Nothing is deployed.
- name: Build and test the widget gallery
if: matrix.shard == 'site'
env:
CHROMIUM: google-chrome
run: |
export PATH="$ZIRAN_ROOT/build/bin:$PATH"
make site
python3 tests/gallery_modules_test.py
make site-browser-test
- name: Show how much the compile cache saved
if: always()
run: ccache --show-stats || true
test-sanitizers:
name: Behavior tests under AddressSanitizer and UndefinedBehaviorSanitizer
needs: push-check
if: needs.push-check.outputs.code == 'true'
runs-on: ubuntu-latest
defaults:
run:
working-directory: kryon
steps:
- name: Checkout Kryon
uses: actions/checkout@v7
with:
path: kryon
# Template tests serve the checkouts through local Git URLs and use
# their master refs.
- name: Name the checked-out Kryon commit master
run: git checkout -B master
# The locked compiler comes prebuilt, the package checkouts cached, and
# Ubuntu packages from the canonical archive.
- name: Set up the locked Ziran, its packages and the build tools
uses: ziranlang/ziran/.github/actions/setup@4135e07fae33bcd0c00dd66b5716fdfe19c1fca5
with:
project: kryon
path: ziran
fetch: true
recommends: true
packages: >-
build-essential python3 python3-pil ripgrep ffmpeg pkg-config libsdl2-dev
libcairo2-dev libglib2.0-dev libpango1.0-dev libfreetype-dev libfontconfig1-dev
gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-libav cmake
nasm meson ninja-build libwebpdemux2
- name: Prepare locked toolchain ref
run: git -C "$ZIRAN_ROOT" checkout -B master
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version: '1.25.x'
- name: Install Windows storage test tools
run: sudo apt-get install -y gcc-mingw-w64-x86-64 wine wine64 xvfb xauth
- name: Run the behavior tests with sanitized C
run: env -u DISPLAY -u WAYLAND_DISPLAY make sanitize-test TEST_JOBS=4
test-desktop-hosts:
name: Desktop hosts on private Xvfb
needs: push-check
if: needs.push-check.outputs.code == 'true'
runs-on: ubuntu-latest
defaults:
run:
working-directory: kryon
steps:
- name: Checkout Kryon
uses: actions/checkout@v7
with:
path: kryon
# Template tests serve the checkouts through local Git URLs and use
# their master refs.
- name: Name the checked-out Kryon commit master
run: git checkout -B master
# The locked compiler comes prebuilt, the package checkouts cached, and
# Ubuntu packages from the canonical archive.
- name: Set up the locked Ziran, its packages and the build tools
uses: ziranlang/ziran/.github/actions/setup@4135e07fae33bcd0c00dd66b5716fdfe19c1fca5
with:
project: kryon
path: ziran
fetch: true
recommends: true
packages: >-
build-essential python3 pkg-config libsdl2-dev libcairo2-dev libglib2.0-dev
libpango1.0-dev libdrm-dev libgbm-dev libegl-dev libgles-dev libegl-mesa0
libgl1-mesa-dri libx11-dev libxt-dev libxext-dev libxtst-dev libfontconfig1-dev libfreetype-dev
libxkbcommon-x11-0
fonts-dejavu-core fonts-wqy-zenhei xvfb xdotool x11-apps x11-utils imagemagick xfwm4
dbus-x11 cmake nasm meson ninja-build libwebpdemux2 libopus-dev
- name: Prepare locked toolchain ref
run: git -C "$ZIRAN_ROOT" checkout -B master
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version: '1.25.x'
# Each test starts its own display with xvfb-run -a; none may reach a
# real one.
- name: Desktop host
run: env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY make desktop-project-test
- name: Desktop frame input snapshots
run: make desktop-frame-input-test
+124
View File
@@ -0,0 +1,124 @@
name: Netlify
on:
push:
branches:
- master
pull_request:
workflow_dispatch:
permissions:
contents: read
concurrency:
group: netlify-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
name: Build Site
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
with:
submodules: recursive
- name: Install Packages
run: |
set -euo pipefail
sudo apt-get update
sudo apt-get install -y build-essential cmake cmark zlib1g-dev zip
- name: Set Up Emscripten
run: |
set -euo pipefail
git clone --depth 1 https://github.com/emscripten-core/emsdk.git "$HOME/emsdk"
"$HOME/emsdk/emsdk" install latest
"$HOME/emsdk/emsdk" activate latest
echo "EMSDK=$HOME/emsdk" >> "$GITHUB_ENV"
echo "EM_CONFIG=$HOME/emsdk/.emscripten" >> "$GITHUB_ENV"
echo "$HOME/emsdk" >> "$GITHUB_PATH"
echo "$HOME/emsdk/upstream/emscripten" >> "$GITHUB_PATH"
- name: Build Site
run: |
set -euo pipefail
make docs-site CMAKE=/usr/bin/cmake
test -f build/site/index.html
test -f build/site/api.html
test -f build/site/icons/kryon.png
test -f build/site/icons/c.png
test ! -f build/site/API.md
- name: Upload Site Artifact
uses: actions/upload-artifact@v4
with:
name: kryon-site
path: build/site
if-no-files-found: error
deploy-preview:
name: Deploy Preview
runs-on: ubuntu-latest
needs: build
if: github.event_name == 'pull_request'
steps:
- name: Download Site Artifact
uses: actions/download-artifact@v4
with:
name: kryon-site
path: build/site
- name: Install Netlify CLI
run: npm install --global netlify-cli
- name: Deploy Preview To Netlify
run: |
set -euo pipefail
auth_token="$(printf '%s' "$NETLIFY_AUTH_TOKEN" | tr -d '\r\n')"
site_id="$(printf '%s' "$NETLIFY_SITE_ID" | tr -d '\r\n')"
test -n "$auth_token" || { echo "::error::NETLIFY_AUTH_TOKEN is empty or missing"; exit 1; }
test -n "$site_id" || { echo "::error::NETLIFY_SITE_ID is empty or missing; use the Netlify Site ID, not the site URL"; exit 1; }
netlify deploy \
--dir build/site \
--alias "pr-${{ github.event.pull_request.number }}" \
--message "Preview ${{ github.event.pull_request.number }}" \
--auth "$auth_token" \
--site "$site_id"
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
deploy-production:
name: Deploy Production
runs-on: ubuntu-latest
needs: build
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/master'
steps:
- name: Download Site Artifact
uses: actions/download-artifact@v4
with:
name: kryon-site
path: build/site
- name: Install Netlify CLI
run: npm install --global netlify-cli
- name: Deploy Production To Netlify
run: |
set -euo pipefail
auth_token="$(printf '%s' "$NETLIFY_AUTH_TOKEN" | tr -d '\r\n')"
site_id="$(printf '%s' "$NETLIFY_SITE_ID" | tr -d '\r\n')"
test -n "$auth_token" || { echo "::error::NETLIFY_AUTH_TOKEN is empty or missing"; exit 1; }
test -n "$site_id" || { echo "::error::NETLIFY_SITE_ID is empty or missing; use the Netlify Site ID, not the site URL"; exit 1; }
netlify deploy \
--dir build/site \
--prod \
--message "Production ${{ github.sha }}" \
--auth "$auth_token" \
--site "$site_id"
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
-209
View File
@@ -1,209 +0,0 @@
name: Cloudflare Pages
on:
push:
branches: [master]
paths:
- docs/site/**
- examples/gallery/**
- src/**
- mk/**
- ziran.toml
- scripts/gallery.py
- scripts/build-gallery.py
- scripts/build-site.py
- scripts/site-metadata.py
- tests/site_browser_test.py
- ziran.lock
- tests/portable_format_runtime.cjs
- .github/workflows/pages.yml
workflow_dispatch:
permissions:
contents: read
concurrency:
group: pages-${{ github.ref }}
cancel-in-progress: true
jobs:
browser-runtime:
name: Build ZX website
runs-on: ubuntu-latest
env:
MAKEFLAGS: -j2
defaults:
run:
working-directory: kryonlabs/kryon
steps:
- uses: actions/checkout@v7
with:
path: kryonlabs/kryon
# The locked compiler comes prebuilt.
- name: Set up the locked Ziran
uses: ziranlang/ziran/.github/actions/setup@4135e07fae33bcd0c00dd66b5716fdfe19c1fca5
with:
project: kryonlabs/kryon
path: ziranlang/ziran
packages: python3-pil
- uses: actions/setup-node@v6
with:
node-version: '22'
- uses: emscripten-core/setup-emsdk@v15
with:
version: '6.0.6'
- name: Select these source revisions
run: |
python3 - <<'PY'
from pathlib import Path
import os
import subprocess
root = Path(os.environ['GITHUB_WORKSPACE'])
settings = '[overrides]\nkryon = "' + str(root / 'kryonlabs/kryon') + '"\nziran = "' + str(root / 'ziranlang/ziran') + '"\n'
for project in ('.', 'docs/site/demo', 'examples/gallery'):
(Path(project) / 'ziran.local.toml').write_text(settings)
# An override can add dependency edges absent from the saved
# consumer lock. Resolve the selected checkout before building.
subprocess.run([str(root / 'ziranlang/ziran/build/bin/ziran'), 'lock'],
cwd=project, check=True)
PY
- name: Build and verify portable browser assets
run: |
export PATH="$GITHUB_WORKSPACE/ziranlang/ziran/build/bin:$PATH"
export ZIRAN_ROOT="$GITHUB_WORKSPACE/ziranlang/ziran"
python3 scripts/build-site.py
node tests/portable_format_runtime.cjs
ZIRAN_PLAYGROUND_RUNTIME="$PWD/docs/site/runtime/playground-runtime.js" node "$GITHUB_WORKSPACE/ziranlang/ziran/tests/web_bundle_runtime.cjs"
- name: Stage public website files
run: |
python3 - <<'PY'
from pathlib import Path
import json, shutil, subprocess
site = Path('docs/site')
output = Path('build/scratch/website-deploy')
paths = {Path(p) for p in subprocess.check_output(['git', 'ls-files', '-z', '--', str(site)]).decode().split('\0') if p}
paths.add(site / 'gallery-data.js')
paths.update((site / 'gallery-sources').rglob('*.zi'))
# The build numbers runtime assets; stage every one it lists, since
# a newly bundled asset is not tracked yet.
paths.update(site / name for _, name in json.loads((site / 'runtime/assets.json').read_text()))
for source in paths:
destination = output / source.relative_to(site)
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, destination)
PY
- uses: actions/upload-artifact@v6
with:
name: kryon-website
path: kryonlabs/kryon/build/scratch/website-deploy/
if-no-files-found: error
verify:
name: Website
needs: browser-runtime
runs-on: ubuntu-latest
defaults:
run:
working-directory: kryonlabs/kryon
steps:
- name: Checkout repository
uses: actions/checkout@v7
with:
path: kryonlabs/kryon
- uses: actions/download-artifact@v6
with:
name: kryon-website
path: kryonlabs/kryon/docs/site
# The portable source test invokes the locked compiler directly.
- name: Set up the locked Ziran
uses: ziranlang/ziran/.github/actions/setup@4135e07fae33bcd0c00dd66b5716fdfe19c1fca5
with:
project: kryonlabs/kryon
path: ziranlang/ziran
# Source-preservation tests regenerate the gallery manifest in this job.
# Select the same Kryon and Ziran sources as the website build job.
- name: Select source revisions for gallery verification
working-directory: kryonlabs/kryon/examples/gallery
run: |
ziran_root="$GITHUB_WORKSPACE/ziranlang/ziran"
printf '[overrides]\nkryon = "%s"\nziran = "%s"\n' \
"$GITHUB_WORKSPACE/kryonlabs/kryon" "$ziran_root" > ziran.local.toml
"$ziran_root/build/bin/ziran" lock
- name: Set up Node
uses: actions/setup-node@v6
with:
node-version: '22'
- name: Install private display tools
timeout-minutes: 10
run: |
sudo apt-get update
sudo apt-get install -y build-essential python3 python3-pil
# Test and deploy the same runtime built from the locked compiler.
- name: Check static site assets
run: |
test -f docs/site/index.html
test -f docs/site/runtime/playground-runtime.js
test -f docs/site/runtime/playground-runtime.wasm
test -f docs/site/demo-theme.js
test -f docs/site/current.css
test -f docs/site/favicon.svg
test -f docs/site/favicon-32.png
test -f docs/site/og.png
test -f docs/site/assets/brand/mark.svg
test -f docs/site/widgets.html
test -f docs/site/gallery-data.js
test -f docs/site/gallery-sources/kryon/0.zi
- name: Test the Canvas website
timeout-minutes: 45
env:
CHROMIUM: google-chrome
# Chrome creates Unix sockets below TMPDIR; keep them clear of the
# runner's deeply nested checkout path.
KRYON_TEST_RUNTIME: ${{ runner.temp }}
run: |
export PATH="$GITHUB_WORKSPACE/ziranlang/ziran/build/bin:$PATH"
export ZIRAN_ROOT="$GITHUB_WORKSPACE/ziranlang/ziran"
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS \
YUE_DESKTOP_RECOVERY=0 python3 -u tests/site_browser_test.py
- name: Save browser startup diagnostics
if: failure()
uses: actions/upload-artifact@v6
with:
name: website-browser-log
path: kryonlabs/kryon/build/scratch/site-browser/profile/chromium.log
if-no-files-found: ignore
deploy-production:
name: Deploy Kryon Labs
needs: verify
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v7
with:
path: kryonlabs/kryon
- uses: actions/download-artifact@v6
with:
name: kryon-website
path: kryonlabs/kryon/docs/site
- name: Set up Node
uses: actions/setup-node@v6
with:
node-version: '22'
- name: Publish to Cloudflare Pages
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy kryonlabs/kryon/docs/site --project-name=kryon --branch=master
+154 -20
View File
@@ -1,40 +1,174 @@
name: Release
on:
push:
branches:
- master
tags:
- "v*"
paths:
- "include/kryon_version.h"
workflow_dispatch:
inputs:
version:
description: "Release version, for example v0.1.0"
required: true
type: string
prerelease:
description: "Mark the GitHub release as a prerelease"
required: false
default: false
type: boolean
permissions:
contents: write
concurrency:
group: kryon-release
cancel-in-progress: false
jobs:
tag:
name: Tag new version
create-tag:
name: Create Release Tag
runs-on: ubuntu-latest
if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/heads/')
outputs:
tag: ${{ steps.version.outputs.tag }}
steps:
- uses: actions/checkout@v4
- name: Checkout Repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Create the release for a new VERSION
env:
GH_TOKEN: ${{ github.token }}
submodules: recursive
- name: Resolve Version
id: version
run: |
set -eu
VERSION=$(cat VERSION)
TAG="v$VERSION"
if git rev-parse "$TAG" >/dev/null 2>&1; then
echo "$TAG already exists, nothing to release"
set -euo pipefail
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
tag="${{ inputs.version }}"
else
tag="$(sed -n 's/^#define KRYON_VERSION_STRING "\([^"]*\)".*/\1/p' include/kryon_version.h)"
fi
case "$tag" in
v[0-9]*.[0-9]*.[0-9]*) ;;
*) echo "Version must look like v0.1.0" >&2; exit 1 ;;
esac
if git rev-parse -q --verify "refs/tags/$tag" >/dev/null; then
echo "Tag $tag already exists; nothing to release."
echo "tag=" >> "$GITHUB_OUTPUT"
exit 0
fi
NOTES=$(awk -v v="$VERSION" '$0 ~ "^## \\[" v "\\]" {found=1; next} found && /^## / {exit} found' CHANGELOG.md)
test -n "$NOTES"
echo "tag=$tag" >> "$GITHUB_OUTPUT"
- name: Ensure CHANGELOG Entry
if: steps.version.outputs.tag != ''
run: |
set -euo pipefail
tag="${{ steps.version.outputs.tag }}"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git tag -a "$TAG" -m "Kryon $VERSION"
git push origin "$TAG"
gh release create "$TAG" --title "Kryon $VERSION" --notes "$NOTES"
# If the entry already exists (hand-written by a maintainer), use it as-is.
if grep -q "^## $tag " CHANGELOG.md; then
echo "CHANGELOG entry for $tag already present."
exit 0
fi
# Otherwise generate one from commits since the most recent tag.
prev_tag="$(git describe --tags --abbrev=0 2>/dev/null || true)"
date="$(date +%Y-%m-%d)"
range="${prev_tag:+$prev_tag..}HEAD"
range="${range:-HEAD}"
{
printf '## %s - %s\n\n' "$tag" "$date"
printf '### Changed\n\n'
git log "$range" --no-merges --pretty=format:'- %s' \
| sed -E 's/^- ([a-z])/- \u\1/'
printf '\n\n'
} > /tmp/new_entry.md
# Insert the generated block immediately after the "# Changelog" heading.
cp CHANGELOG.md CHANGELOG.md.bak
awk -v entry=/tmp/new_entry.md '
FNR==1 && /^# Changelog/ {
print
while ((getline line < entry) > 0) print line
next
}
{ print }
' CHANGELOG.md.bak > CHANGELOG.md
rm -f CHANGELOG.md.bak
git add CHANGELOG.md
git commit -m "Update CHANGELOG for $tag" || echo "No CHANGELOG changes to commit."
git push origin "HEAD:${GITHUB_REF_NAME}"
- name: Create And Push Tag
if: steps.version.outputs.tag != ''
run: |
set -euo pipefail
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git tag -a "${{ steps.version.outputs.tag }}" -m "Release ${{ steps.version.outputs.tag }}"
git push origin "${{ steps.version.outputs.tag }}"
build-release:
name: Build Release Artifacts
runs-on: ubuntu-latest
needs: create-tag
if: always() && (startsWith(github.ref, 'refs/tags/') || needs.create-tag.outputs.tag != '')
steps:
- name: Resolve Tag
id: ref
run: |
set -euo pipefail
if [ -n "${{ needs.create-tag.outputs.tag }}" ]; then
tag="${{ needs.create-tag.outputs.tag }}"
else
tag="${GITHUB_REF_NAME}"
fi
echo "tag=$tag" >> "$GITHUB_OUTPUT"
- name: Checkout Repository
uses: actions/checkout@v4
with:
ref: ${{ steps.ref.outputs.tag }}
submodules: recursive
fetch-depth: 0
- name: Install Packages
run: |
set -euo pipefail
sudo apt-get update
sudo apt-get install -y build-essential cmake libssl-dev pkg-config zlib1g-dev libzstd-dev libbrotli-dev libsdl2-dev libdrm-dev libgbm-dev libegl1-mesa-dev libgles2-mesa-dev
- name: Build And Test
run: |
set -euo pipefail
make clean CMAKE=/usr/bin/cmake
make all CMAKE=/usr/bin/cmake
make test CMAKE=/usr/bin/cmake
- name: Package Static Library
run: |
set -euo pipefail
make dist-static CMAKE=/usr/bin/cmake VERSION="${{ steps.ref.outputs.tag }}"
make check-static-package CMAKE=/usr/bin/cmake VERSION="${{ steps.ref.outputs.tag }}"
archive="$(find dist -maxdepth 1 -type f -name kryon-*-static.tar.gz | head -n 1)"
test -n "$archive"
echo "KRYON_STATIC_ARCHIVE=$archive" >> "$GITHUB_ENV"
- name: Upload Static Library Artifact
uses: actions/upload-artifact@v4
with:
name: kryon-static-library-${{ steps.ref.outputs.tag }}
path: ${{ env.KRYON_STATIC_ARCHIVE }}
if-no-files-found: error
- name: Publish GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.ref.outputs.tag }}
name: Kryon ${{ steps.ref.outputs.tag }}
prerelease: ${{ github.event_name == 'workflow_dispatch' && inputs.prerelease || false }}
files: ${{ env.KRYON_STATIC_ARCHIVE }}
-25
View File
@@ -2,38 +2,13 @@
*.o
*.so
*.dll
*.pyc
*~
*.tmp
__pycache__/
ziran.local.toml
.zcode
.kryon-ide-state
# Local managed session state
/.yue/
# Test-owned scratch and logs
/work/
# Build output
build/
dist/
backup/
assets/fonts/*
!assets/fonts/LiberationSans-Regular.ttf
!assets/fonts/LiberationMono-Regular.ttf
!assets/fonts/LICENSE-Liberation
!assets/fonts/DejaVuSans.ttf
!assets/fonts/LICENSE-DejaVu
!assets/fonts/NotoSansSymbols-Regular.ttf
!assets/fonts/NotoSansSymbols2-Regular.ttf
!assets/fonts/LICENSE-Noto
tools/otfchop/otfchop
.wrangler/
# Gallery metadata and editable snippets are generated from examples/gallery.
/docs/site/gallery-data.js
/docs/site/gallery-sources/
+15
View File
@@ -0,0 +1,15 @@
[submodule "vendor/raylib"]
path = vendor/raylib
url = https://github.com/raysan5/raylib.git
[submodule "vendor/liboqs"]
path = vendor/liboqs
url = https://github.com/open-quantum-safe/liboqs.git
[submodule "vendor/curl"]
path = vendor/curl
url = https://github.com/curl/curl.git
[submodule "vendor/cmark-gfm"]
path = vendor/cmark-gfm
url = https://github.com/github/cmark-gfm.git
[submodule "vendor/clay"]
path = vendor/clay
url = https://github.com/nicbarker/clay.git
-81
View File
@@ -1,81 +0,0 @@
# Kryon repository rules
Kryon is a reusable UI library written in Ziran. The Ziran language, compiler,
`.zir`, `.zx` and portable runtime live in the separate Ziran repository
(`~/Projects/ziranlang/ziran`); applications import Kryon as an ordinary
package, and the compiler never recognizes Kryon widget names.
## Layout
| Path | Contents |
| --- | --- |
| `src/ui/<widget>/` | Widget packages: `Props`, `Draw`, behavior, `*_laws.zi` proofs |
| `src/ui/*.zi` + `src/ui/modules.txt` | Shared core (tree, session, style, input, paint, theme); the list compiles into `libkryon.a` |
| `src/backend/*.zi` | Hosts and platform integration: desktop, terminal, Canvas, Android, components |
| `src/project/*.zi` | The `kryon` project tool |
| `tests/`, `examples/`, `templates/` | Behavior tests, sample programs, `kryon new` scaffolds |
| `docs/` | Reference documentation, indexed below |
## Rules
- Handwritten implementation, platform integration and examples are Ziran
(`.zi`); no new handwritten C, C++ or Go; `build/` output is not source.
- Use current Ziran syntax and APIs directly. No compatibility wrappers,
aliases, fallback runtimes, or removed KIR, `.kry` or `.krb` paths; a missing
general capability is implemented in Ziran first, never as a Kryon compiler
special case.
- One widget concept has one public implementation (`Text.Draw(Text.Props)`,
`Image.Draw(Image.Props)`); no parallel wrappers or raw texture draw APIs.
Nothing is imported by default: a program carries only what it imports,
and optional parts load at import or first use through small slot modules
(`frame_driver`, `image_lookup`, `text_editing`, `scroll_sampling`), never
runtime flags.
- Hosts observe input, own windows and present pixels; focus, hit testing,
layout, semantics, styling and paint decisions stay in `src/ui/`. App
screens, assets, copy and state stay in the application repository.
## Commands
```sh
make # check modules, generate C/Go, build libkryon.a
make test # source, saved-.zir and .zx behavior tests, headless
make test-focus TEST=name # one test script; skips the full rebuild
make desktop-project-test # graphical capture and input on private Xvfb
make laws # prove every src/ui/**/*_laws.zi
make sanitize-test # ASan/UBSan behavior tests
make docs-check # docs/FEATURE_MATRIX.html is current
make push-check # minutes; links the hosts; run before pushing
```
Never run tests or binaries that can send X/Wayland requests against the live
desktop. Scrub inherited display/auth/session variables and use a private
Xvfb/Xephyr display, as the test targets above do.
## Documentation index
| Question | File |
| --- | --- |
| Writing an app: one-page cheat sheet (start here) | docs/CHEATSHEET.md |
| Widget APIs, drawing, packages | docs/API.md |
| Architecture; Ziran/Kryon/app boundaries | docs/ARCHITECTURE.md, docs/BOUNDARIES.md |
| `kryon` CLI, manifests, profiles, ZX apps | docs/PROJECTS.md |
| Hosts, renderers, Android, web canvas, image codecs | docs/BACKENDS.md, docs/canvas.md |
| Supported coverage; widget verification policy | docs/FEATURE_MATRIX.md, docs/WIDGET_CONFORMANCE.md |
| Input components; overlays; navigation | docs/INPUT_COMPONENTS.md, docs/OVERLAYS.md, docs/navigation.md |
| Portable ZX components; accessibility | docs/COMPONENTS.md, docs/ACCESSIBILITY.md |
| Theming, zoom, cursor, clipboard, focus, IME | docs/THEMING.md, docs/ZOOM.md, docs/CURSOR.md, docs/CLIPBOARD.md, docs/window-focus.md, docs/COMPOSITION_INPUT.md |
| Frame capture/replay; raster workers; benchmarks | docs/FRAME_REPLAY.md, docs/THREADING.md, docs/PERFORMANCE.md |
| Examples and gallery | examples/README.md |
| Open work | plans/open-work.md |
## Shared checkout
- Work on `master` in this checkout. Never create or use clones, worktrees or
temporary Kryon/Ziran checkouts; change dependencies upstream first.
- The git index is shared and often stale, so `git status` lists hundreds of
false edits. Check `git diff HEAD -- <file>` before touching a file, skip
files another lane is editing, and stage only your own files through a
private `GIT_INDEX_FILE` built from HEAD; never `git add -A`.
- Commit as Waozi <waozi@proton.me> with no AI attribution. Keep ordinary
changes in `Unreleased`; release only on explicit request.
- Put one-off experiment builds in `build/scratch/<name>/`; `make clean-scratch` removes idle output.
+81 -1234
View File
File diff suppressed because it is too large. Load diff
+324 -1216
View File
File diff suppressed because it is too large. Load diff
+133 -58
View File
@@ -1,74 +1,149 @@
# Kryon
Kryon is a UI library for [Ziran](https://github.com/ziranlang/ziran): write
ordinary Ziran modules that import Kryon widgets, and run them on the desktop,
in a terminal, in a browser or on Android. The language, compiler, `.zir`,
`.zx` bundles and portable runtime belong to Ziran; Kryon is an imported
package, so a program carries only the widgets it imports.
Kryon is a small C support library for raylib-style applications. It keeps a
raylib-compatible public surface available through `kryon.h`, then adds the
pieces shared by downstream apps: UI controls, Tk-style toolkit widgets, layout
helpers, text rendering, themes, embedded assets, locale loading, file dialogs,
desktop tray support, runtime asset downloads, and Lyra account/sync helpers.
## Start an application
## Layout
Install the `ziran` command (`make install-user` in the Ziran checkout) and
the `kryon` command (`make install-user` here), then:
- `include/` - public headers, including `kryon.h` and generated raylib
compatibility declarations
- `src/` - Kryon implementation files, with reusable UI modules under `src/ui/`
- `icons/` and `pfp/` - PNG icon inputs embedded into `src/ui/ui_icon_assets.c`
- `themes/` - built-in theme files for the runtime theme loader
- `fonts/noto/` - bundled Noto Sans TTF/OTF font assets
- `mk/` - Make fragments for native, web, Android, Windows, packaging, and
vendored dependency builds
- `scripts/` - asset embedding, icon embedding, raylib preparation, and boundary
check helpers
- `examples/` - small programs that exercise Kryon UI features
- `tests/` - focused C tests for account, sync, and transition helpers
- `vendor/raylib`, `vendor/curl`, `vendor/liboqs` - source submodules used by
downstream app builds
```sh
kryon new hello # desktop app; --template tui|pages|web picks another
cd hello
kryon run # default profile; kryon run web selects another
kryon run shot --png build/shot.png --width 390 --height 844 # offscreen, any size
## Building
Kryon builds with the repository Makefile:
```bash
make
```
New to Kryon? [docs/CHEATSHEET.md](docs/CHEATSHEET.md) is one page with the app
shell, every widget, the layout recipe, theme tokens and a driver test.
On FreeBSD, use the repository `makefile` entrypoint. It delegates to the GNU
Make build while keeping `make` as the command downstream apps can run:
`kryon build portable` exports one `build/<name>-portable.zx` that opens with
`ziran run` on any supported platform. Manifests, profiles and every `kryon`
command are documented in [docs/PROJECTS.md](docs/PROJECTS.md).
## Build and test this repository
```sh
make # check modules, generate C/Go, build libkryon.a
make test # headless behavior tests
```bash
make bsd-check
```
The build uses the Ziran revision locked in `ziran.lock`. `make test-focus
TEST=name` gives a quick edit loop; experiments go in `build/scratch/`. The
widget gallery lives in `examples/gallery/`
([examples/README.md](examples/README.md)); `make site` packages the website
and gallery into `docs/site/`.
Run the focused tests with:
```bash
make test
```
Build a distributable static-library archive with:
```bash
make dist-static
```
The archive is an extracted SDK layout. It contains `libkryon.a`,
`libraylib.a`, vendored static dependency libraries, public headers, API docs,
example consumers, CMake and pkg-config metadata, third-party notices, a package
manifest, and the submodule revisions used to build it. Validate it with:
```bash
make check-static-package
```
`libkryon.a` stays focused on Kryon object files. Companion libraries are shipped
beside it and linked through `lib/pkgconfig/kryon.pc`. OpenSSL is still treated
as an external system/toolchain dependency unless explicit OpenSSL static library
paths are supplied at build time.
## Releases
Kryon releases are tag-driven. Run the `Release` GitHub Actions workflow with a
version such as `v0.1.0`; the workflow validates the version, creates and pushes
the annotated tag, checks out that tag, builds and tests Kryon, packages the
static-library archive, uploads it as an artifact, and attaches it to the GitHub
release. Pushing a `v*` tag manually uses the same build-and-publish path.
## Integration
To integrate Kryon into your project:
1. Add `include/` to your header search paths
2. Include `kryon.h` for the raylib-compatible API plus Kryon modules
3. Compile Kryon sources from `src/` and `src/ui/`, or use the `mk/` fragments
to let Kryon assemble source lists and platform flags
4. Use `scripts/embed-icons.sh` and `scripts/embed-assets.sh` when your app
needs custom embedded icons, locale files, fonts, themes, or image/audio
assets
5. Include `mk/vendor.mk` when your app enables curl or liboqs-backed features
Applications should keep build artifacts in their own build directories, but
the dependency source of truth and common build recipes should live under Kryon.
For TLS-enabled curl builds, `mk/vendor.mk` passes the `OPENSSL_*` make
variables through to the vendored curl CMake build.
## App Builds
Kryon owns the app command surface through `kryon-app`. From an app repository:
```sh
kryon-app build native
kryon-app build web
kryon-app build android-debug
kryon-app package appimage
kryon-app preview
```
App `project.kryon` files should use `target` entries that call `kryon-app`
rather than embedding platform-specific build commands directly. Existing app
Makefiles can remain as backend glue while repeated native, web, Android, and
packaging logic moves into Kryon `mk/` fragments.
## Preview Projects
Kryon IDE can host richer project previews without requiring the project to be
rewritten as `.kry` screens. A project can add `project.kryon` metadata such as
`preview_size`, `preview_asset_root`, and `preview_scene`, then provide a
`build_live` command that builds `build/kryon/live_preview.so`. The live module
continues to expose the normal `CreateKryonLivePreview`/`AppHost` entry point,
and can optionally expose `CreateKryonPreviewHost` for future scene/layer editing
metadata. This keeps gameplay or simulation code in the app while letting Kryon
IDE select scenes, draw interactive previews, and eventually edit shared preview
layers.
## Conventions
Kryon follows raylib-style C conventions where practical: lowercase module
filenames, simple C structs, and public functions named like raylib APIs
(`InitWindow`, `DrawTexture`, `BeginUIFrame`, `DrawUIButton`). Internal helpers
stay private to `src/` unless a downstream app needs the API in `include/`.
## Documentation
| Question | File |
| --- | --- |
| First app: shell, widgets, layout, tokens, screenshot, driver test | docs/CHEATSHEET.md |
| Widget APIs and drawing | docs/API.md |
| Architecture and boundaries | docs/ARCHITECTURE.md, docs/BOUNDARIES.md |
| Projects, hosts, web canvas | docs/PROJECTS.md, docs/BACKENDS.md, docs/canvas.md |
| Supported coverage | docs/FEATURE_MATRIX.md, docs/WIDGET_CONFORMANCE.md |
| Input components, overlays, navigation | docs/INPUT_COMPONENTS.md, docs/OVERLAYS.md, docs/navigation.md |
| Portable components; accessibility | docs/COMPONENTS.md, docs/ACCESSIBILITY.md |
| Theming, zoom, cursor, clipboard, focus, IME | docs/THEMING.md, docs/ZOOM.md, docs/CURSOR.md, docs/CLIPBOARD.md, docs/window-focus.md, docs/COMPOSITION_INPUT.md |
| Frame capture/replay; threading; performance | docs/FRAME_REPLAY.md, docs/THREADING.md, docs/PERFORMANCE.md |
| Open work | plans/open-work.md |
- `docs/API.md` documents the public API.
- `docs/site/` contains the static documentation website.
- `docs/AGENTS.md` documents how downstream apps should use Kryon, including
modal/input capture and submodule update rules.
Charts, tables, trees, source coloring and style sheets are separate packages:
`ziran add https://github.com/kryonlabs/plot.git`,
`https://github.com/kryonlabs/data-views.git`,
`https://github.com/kryonlabs/css.git` or
`https://github.com/ziranlang/syntax.git`, imported as `plot/Plot`,
`data_views/TableView`, `data_views/TreeView`, `css/Css` or `syntax/Syntax`.
Kryon exports the building blocks they draw with; see
[widget packages](docs/WIDGET_PACKAGES.md#widget-packages). Ziran language and runtime gaps
are listed in Ziran's [implementation
status](https://github.com/ziranlang/ziran/blob/master/docs/IMPLEMENTATION_STATUS.md).
## Toolkit Direction
The optional GStreamer service (`kryon/Video`, `kryon/VideoLinux`) decodes
local video with synchronized audio; draw frames with `Image.Draw`. The app
owns playback controls and access checks, and an expiring lease revokes both
audio and decoded frames when authorization stops being renewed;
`make test-focus TEST=ziran_video_linux_test` checks it.
The `ui_tk.h` layer is Kryon's pragmatic Tk replacement surface. It stays in the
raylib style: one direct struct-and-call path per widget, caller-owned state,
immediate-mode drawing, and no builder objects or scripting runtime. The numbered
examples `09_geometry` through `18_accessibility` demonstrate each toolkit
feature family.
Commit Kryon changes upstream here first; applications pick them up by
updating their `ziran.lock`.
## Kry Language Direction
`docs/KRY_LANGUAGE_PLAN.md` describes the migration path for making `.kry` a
C-close, C-transpiled app language with direct C interoperability. The goal is
for apps to move product UI and screen controllers into Kry while keeping native
platform, storage, and performance-sensitive code in C.
+12 -9
View File
@@ -1,13 +1,16 @@
# Third-Party Notices
The Kryon static package includes third-party code pinned by its package lock.
The Kryon static package includes third-party code built from the repository
submodules listed in `SUBMODULES.txt`.
- raylib: zlib/libpng license, see `vendor/raylib/LICENSE` in the source tree.
- liboqs: MIT license, see `vendor/liboqs/LICENSE.txt` in the source tree.
- curl/libcurl: curl license, see `vendor/curl/COPYING` in the source tree.
- cmark-gfm: BSD-style license, see `vendor/cmark-gfm/COPYING` in the source tree.
- Clay: zlib/libpng license, see `vendor/clay/LICENSE.md` in the source tree.
- Noto fonts: SIL Open Font License 1.1, see `fonts/noto/LICENSE.txt` in the source tree.
- Liberation Sans: SIL Open Font License 1.1, see `assets/fonts/LICENSE-Liberation`.
`src/backend/pixmap_font.zi` holds outlines of its Latin glyphs for the
pixmap host.
- MingCute Core icons: Apache License 2.0, see
`licenses/mingcute/LICENSE.txt` in the source tree. Kryon embeds only the
selected, renamed monochrome subset used by its UI in `icons/ui.webp`.
Apache 2.0 does not grant rights to third-party trademarks depicted by some
brand icons; applications remain responsible for appropriate trademark use.
OpenSSL is not vendored into the package by default. When `kryon.pc` lists
`-lssl -lcrypto`, those libraries are expected to come from the target system or
from paths supplied with `OPENSSL_ROOT_DIR`, `OPENSSL_SSL_LIBRARY`, and
`OPENSSL_CRYPTO_LIBRARY` at build time.
-1
View File
@@ -1 +0,0 @@
0.6.0
Binary file not shown.

Before

Width:  |  Height:  |  Size: 847 KiB

-91
View File
@@ -1,91 +0,0 @@
{
"project": "Kryon",
"request": "One original friendly full-body dragon mascot for the Kryon UI toolkit, in the Ziran capybara's flat warm illustration feel, followed by a pastel-only color revision that preserves the accepted character.",
"pastel_follow_up_request": "okay but the colors should be more pastel — for the mascot",
"generation_mode": "built-in image_gen",
"generation_calls_planned": 1,
"conditional_retry_allowed": 1,
"generation_calls_completed": 3,
"attempt_count": 3,
"pastel_edit_calls_planned": 1,
"pastel_edit_calls_completed": 1,
"retry_reason": "The first attempt had extra body shading and tighter margins, a clear style/composition mismatch; the one permitted retry fixed the flat-ink direction.",
"proposals": [
{
"id": "01-dragon-v1",
"version": "v1",
"attempt_count": 2,
"animal": "Dragon",
"direction": "Rounded approachable full-body dragon in three-quarter view, facing right, with a calm warm personality and strong small-icon silhouette.",
"prompt": "Use case: logo-brand\nAsset type: final original mascot bitmap for Kryon, a UI toolkit and Ziran sister project; exactly one finished character.\nPrimary request: Create one entirely original friendly cartoon dragon mascot for Kryon. KDE inspiration is limited only to the broad idea of a rounded, approachable open-source cartoon dragon body and shape. This must not copy or trace Konqi and must not reuse Konqi's exact face, anatomy, pose, or proportions.\nScene/backdrop: None. A genuinely transparent square canvas with no background pixels, ground, shadow, border, or decoration.\nSubject: One full-body dragon in three-quarter view, facing right, standing in a relaxed welcoming pose. Big friendly head, short rounded snout, small rounded horns, small wings, a soft row of rounded back spines, four simple grounded feet without claws, and one clear tapering tail. Calm warm expression, small gentle eyes rendered only with earth-brown marks, closed mouth, no teeth. Nothing in its hands.\nStyle/medium: Confident hand-drawn flat illustration in the same visual family as Ziran's capybara mascot: bold deep earth-brown outline of consistent apparent weight, large quiet solid color areas, minimal interior marks, slight purposeful hand-drawn irregularity, calm warm character, strong sticker-like silhouette readable as a tiny website icon. Absolutely flat ink fills: no lighting, highlights, shadows, secondary shades, gray, cream, white fill, texture, or tonal modeling.\nComposition/framing: Center the single complete dragon on a 1:1 square canvas. The entire silhouette should occupy about 72–76% of the canvas width and height, leaving a clean 12–15% transparent border on every side. Every horn, wing, spine, foot, and tail is wholly visible and comfortably clear of the edge. Three-quarter view faces right.\nColor palette: Exactly four visual ink colors and no others except edge antialiasing between them and transparency: jade green #63B190 for the entire body and wings; exactly one continuous lake-blue underside/belly plane #77B7EA; deep earth-brown #502511 for every outline, eye, nostril, and minimal interior mark; one restrained muted light-orange #A48B62 used only on the small horn tips. Do not create light and dark variants of any color. Do not use orange on wings or elsewhere.\nText: NONE.\nConstraints: One original approachable rounded dragon; one character only; genuine alpha transparency; strong readable silhouette; generous clear margins; four flat source-family inks only; exactly one lake-blue belly plane; orange limited to horn tips; eyes use brown with no white eye fill.\nAvoid: Konqi likeness, KDE logo, gear, fire, smoke, teeth, aggressive claws, K monogram, letter-shaped body, props, clothing, scenery, borders, frames, solid or patterned background, gradients, glow, glossy 3D, textures, shading, highlights, drop shadows, extra characters, extra limbs, cropped anatomy. Absolutely no text, letters, numbers, labels, signatures, logos, or watermark anywhere.",
"file": null,
"transparent_background": true,
"status": "removed-at-owner-request",
"retained": false,
"actual": {
"dimensions": [1254, 1254],
"mode": "RGBA",
"alpha_extrema": [0, 255],
"content_bbox_alpha_gt_1": [107, 63, 1125, 1197],
"bytes": 877306,
"sha256": "aa041bbfe0fa60b97736fff724be5922f6b178607cfab5514b6cc4a17295da89"
},
"visual_review": {
"no_text_verified": true,
"transparent_background_verified": true,
"not_konqi_copy": true,
"style_matches_ziran": true,
"original_character": true
}
},
{
"id": "02-dragon-v2-pastel",
"version": "v2",
"attempt_count": 1,
"animal": "Dragon",
"direction": "Pastel-only color revision of the accepted v1 dragon, preserving the same friendly character, pose, proportions, framing, linework, expression, wings, spines, and transparent background.",
"prompt": "Use case: precise-object-edit\nAsset type: pastel color revision of the accepted Kryon dragon mascot bitmap.\nInput images: Image 1 is the sole edit target, the accepted v1 Kryon dragon mascot.\nPrimary request: Change ONLY the four flat ink colors of Image 1 to a softer pastel palette. Do not redraw, reinterpret, restyle, simplify, or add anything.\nColor palette: body pastel mint/jade approximately #A9DCC5; the single existing belly/underside plane pastel sky blue approximately #BCDDF6; the existing horn-tip accents pastel peach approximately #F5C7A1; all existing outline, eye, nostril, and interior marks deep earth-brown/warm cocoa approximately #6B4434. Use at most these four flat visual inks plus edge antialiasing and transparency.\nTransparency: Preserve the genuinely transparent background and all current alpha edges. No background pixels, ground, or shadow.\nInvariants: Preserve the exact same original character, pose, anatomy, proportions, framing, silhouette, linework geometry and apparent weight, expression, gaze, wings, rounded back spines, horns, feet, tail, belly-plane shape, detail placement, canvas dimensions, and transparent margins. Change only colors. Keep every existing element in the exact same position and size. No added or removed details.\nAvoid: gradients, extra shades, texture, highlights, shadows, glow, glossy rendering, new marks, altered outlines, altered anatomy, text, letters, numbers, logos, signatures, or watermark. Do not introduce a Konqi likeness, KDE logo, gear, props, clothing, scenery, border, fire, teeth, or claws.",
"file": "mascot-dragon.png",
"transparent_background": true,
"status": "complete",
"actual": {
"dimensions": [1254, 1254],
"mode": "RGBA",
"alpha_extrema": [0, 255],
"content_bbox_alpha_gt_1": [107, 64, 1127, 1197],
"bytes": 867648,
"sha256": "9537921d73713caccd9c991b4998224207f5ad21a079dcebc2f57cfc111daae4"
},
"target_palette": {
"body_pastel_mint_jade": "#A9DCC5",
"belly_pastel_sky_blue": "#BCDDF6",
"horn_tips_pastel_peach": "#F5C7A1",
"outline_warm_cocoa": "#6B4434"
},
"visual_review": {
"exact_character_preserved": true,
"pixel_identical_to_v1": false,
"transparent_background_verified": true,
"no_text_verified": true,
"not_konqi_copy": true,
"style_matches_ziran": true,
"pastel_palette_verified": true,
"at_most_four_visual_inks": true,
"original_character": true,
"notes": "The same accepted character, pose, anatomy, expression, linework design, and framing are preserved. Built-in image editing re-antialiased some edge pixels: the alpha>128 silhouette IoU is 99.53710%, ink-region agreement is 99.69063%, and the content bounding box moved by at most two pixels; v2 is therefore not claimed to be pixel-identical to v1."
}
}
],
"validation": {
"local_tests": "passed",
"tests": [
"The retained pastel mascot is a decodable 1254x1254 8-bit RGBA PNG with alpha extrema [0, 255].",
"The retained pastel mascot SHA-256 is 9537921d73713caccd9c991b4998224207f5ad21a079dcebc2f57cfc111daae4 and matches its proposal record.",
"Visible content above alpha 1 has bounding box [107, 64, 1127, 1197], wholly inside the canvas with transparent clearance on every side.",
"OCR returned no text; visual review found no text, letters, numbers, labels, signatures, or watermark.",
"Visual and palette review confirmed the same accepted original dragon, no Konqi copy, the Ziran flat warm style, and the requested pastel mint, sky-blue, peach, and warm-cocoa direction."
],
"scope": "Local validation of the sole retained asset assets/brand/mascot-dragon.png and assets/brand/prompts.json.",
"notes": "The earlier darker bitmap was removed at the owner's request; its prompt and digest remain as provenance only. The retained pastel mascot used one built-in image_gen edit call and its generated binary was copied without retouching."
}
}
Binary file not shown.
-78
View File
@@ -1,78 +0,0 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: DejaVu fonts
Upstream-Author: Stepan Roh <[email protected]> (original author),
see /usr/share/doc/fonts-dejavu-core/AUTHORS for full list
Source: https://dejavu-fonts.github.io/
Files: *
Copyright: Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved.
Bitstream Vera is a trademark of Bitstream, Inc.
DejaVu changes are in public domain.
License: bitstream-vera
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license ("Fonts") and associated
documentation files (the "Font Software"), to reproduce and distribute the
Font Software, including without limitation the rights to use, copy, merge,
publish, distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to the
following conditions:
.
The above copyright and trademark notices and this permission notice shall
be included in all copies of one or more of the Font Software typefaces.
.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional glyphs or characters may be added to the Fonts, only if the fonts
are renamed to names not containing either the words "Bitstream" or the word
"Vera".
.
This License becomes null and void to the extent applicable to Fonts or Font
Software that has been modified and is distributed under the "Bitstream
Vera" names.
.
The Font Software may be sold as part of a larger software package but no
copy of one or more of the Font Software typefaces may be sold by itself.
.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
FONT SOFTWARE.
.
Except as contained in this notice, the names of Gnome, the Gnome
Foundation, and Bitstream Inc., shall not be used in advertising or
otherwise to promote the sale, use or other dealings in this Font Software
without prior written authorization from the Gnome Foundation or Bitstream
Inc., respectively. For further information, contact: fonts at gnome dot
org.
Files: debian/*
Copyright: (C) 2005-2006 Peter Cernak <[email protected]>
(C) 2006-2011 Davide Viti <[email protected]>
(C) 2011-2013 Christian Perrier <[email protected]>
(C) 2013 Fabian Greffrath <[email protected]>
License: GPL-2+
This program is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later
version.
.
This program is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the GNU General Public License for more
details.
.
You should have received a copy of the GNU General Public
License along with this package; if not, write to the Free
Software Foundation, Inc., 51 Franklin St, Fifth Floor,
Boston, MA 02110-1301 USA
.
On Debian systems, the full text of the GNU General Public
License version 2 can be found in the file
/usr/share/common-licenses/GPL-2'.
-130
View File
@@ -1,130 +0,0 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: Liberation Fonts
Source: https://github.com/liberationfonts
Files: *
Copyright:
Digitized data copyright (c) 2010 Google Corporation with Reserved Font Arimo, Tinos and Cousine.
Copyright (c) 2012 Red Hat, Inc. with Reserved Font Name Liberation.
License: SIL-OFL-1.1
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
.
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
.
PREAMBLE The goals of the Open Font License (OFL) are to stimulate
worldwide development of collaborative font projects, to support the font
creation efforts of academic and linguistic communities, and to provide
a free and open framework in which fonts may be shared and improved in
partnership with others.
.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves.
The fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply to
any document created using the fonts or their derivatives.
.
.
.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such.
This may include source files, build scripts and documentation.
.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
.
"Original Version" refers to the collection of Font Software components
as distributed by the Copyright Holder(s).
.
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting ? in part or in whole ?
any of the components of the Original Version, by changing formats or
by porting the Font Software to a new environment.
.
"Author" refers to any designer, engineer, programmer, technical writer
or other person who contributed to the Font Software.
.
.
PERMISSION & CONDITIONS
.
Permission is hereby granted, free of charge, to any person obtaining a
copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
.
1) Neither the Font Software nor any of its individual components,in
Original or Modified Versions, may be sold by itself.
.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the
corresponding Copyright Holder. This restriction only applies to the
primary font name as presented to the users.
.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
.
5) The Font Software, modified or unmodified, in part or in whole, must
be distributed entirely under this license, and must not be distributed
under any other license. The requirement for fonts to remain under
this license does not apply to any document created using the Font
Software.
.
.
.
TERMINATION
This license becomes null and void if any of the above conditions are not met.
.
.
.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER
DEALINGS IN THE FONT SOFTWARE.
.
Files: debian/*
Copyright:
2008 Alan Baghumian <[email protected]>
2008-2018 Holger Levsen <[email protected]>
2009-2012 Christian Perrier <[email protected]>
2011-2023 Fabian Greffrath <[email protected]>
2018 Rene Engelhard <[email protected]>
License: GPL-2+
This package is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>
.
On Debian systems, the complete text of the GNU General
Public License version 2 can be found in "/usr/share/common-licenses/GPL-2".
-278
View File
@@ -1,278 +0,0 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: Noto
Upstream-Contact: https://github.com/googlei18n/noto-fonts/issues
http://groups.google.com/group/noto-font
Source: https://github.com/googlei18n/noto-fonts
Files: *
Copyright:
2010,2012-2020, Google Inc.
2015-2020, Google LLC.
License-Grant:
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
License: OFL-1.1
Files:
debian/*
Copyright:
2013-2020, Jonas Smedegaard <[email protected]>
2020, Purism, SPC
2013, Vasudev Kamath <[email protected]>
License-Grant:
This program is free software;
you can redistribute it and/or modify it
under the terms of the GNU General Public License
as published by the Free Software Foundation;
either version 3, or (at your option) any later version.
License: GPL-3+
Files:
debian/NotoMono/NotoMono-Regular.ttf
Copyright:
2007, Google Inc.
License-Grant:
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
License: OFL-1.1
License: OFL-1.1
PREAMBLE
.
The goals of the Open Font License (OFL) are to stimulate
worldwide development of collaborative font projects,
to support the font creation efforts
of academic and linguistic communities,
and to provide a free and open framework
in which fonts may be shared and improved
in partnership with others.
.
The OFL allows the licensed fonts to be used, studied,
modified and redistributed freely
as long as they are not sold by themselves.
The fonts, including any derivative works,
can be bundled, embedded,
redistributed and/or sold with any software
provided that any reserved names are not used
by derivative works.
The fonts and derivatives, however,
cannot be released under any other type of license.
The requirement for fonts to remain under this license
does not apply to any document
created using the fonts or their derivatives.
.
DEFINITIONS
.
"Font Software" refers to the set of files
released by the Copyright Holder(s) under this license
and clearly marked as such.
This may include source files, build scripts and documentation.
.
"Reserved Font Name" refers to any names specified as such
after the copyright statement(s).
.
"Original Version" refers to the collection
of Font Software components
as distributed by the Copyright Holder(s).
.
"Modified Version" refers to any derivative
made by adding to, deleting, or substituting --
in part or in whole --
any of the components of the Original Version,
by changing formats
or by porting the Font Software to a new environment.
.
"Author" refers to any designer, engineer, programmer,
technical writer or other person
who contributed to the Font Software.
.
PERMISSION & CONDITIONS
.
Permission is hereby granted, free of charge,
to any person obtaining a copy of the Font Software,
to use, study, copy, merge, embed, modify, redistribute,
and sell modified and unmodified copies of the Font Software,
subject to the following conditions:
.
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions,
may be sold by itself.
.
2) Original or Modified Versions of the Font Software
may be bundled, redistributed and/or sold with any software,
provided that each copy contains the above copyright notice
and this license.
These can be included either as stand-alone text files,
human-readable headers or in the appropriate
machine-readable metadata fields within text or binary files
as long as those fields can be easily viewed by the user.
.
3) No Modified Version of the Font Software may use
the Reserved Font Name(s)
unless explicit written permission is granted
by the corresponding Copyright Holder.
This restriction only applies to the primary font name
as presented to the users.
.
4) The name(s) of the Copyright Holder(s)
or the Author(s) of the Font Software
shall not be used to promote,
endorse or advertise any Modified Version,
except to acknowledge the contribution(s)
of the Copyright Holder(s) and the Author(s)
or with their explicit written permission.
.
5) The Font Software,
modified or unmodified, in part or in whole,
must be distributed entirely under this license,
and must not be distributed under any other license.
The requirement for fonts to remain under this license
does not apply to any document
created using the Font Software.
.
TERMINATION
.
This license becomes null and void
if any of the above conditions are not met.
.
DISCLAIMER
.
THE FONT SOFTWARE IS PROVIDED "AS IS",
WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO
ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT.
IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF THE USE OR INABILITY TO USE
THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
License: GPL-3+
License-Reference: /usr/share/common-licenses/GPL-3
# Noto Color Emoji (used to generate src/backend/pixmap_emoji.zi)
Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: noto-emoji
Source: https://github.com/googlefonts/noto-emoji
Files-Excluded: fonts/*.ttf
Files: *
Copyright: 2013-2017 Google Inc.
Arjen Nienhuis <[email protected]>
License: Apache-2.0
Files: fonts/*
Copyright: 2013-2017 Google Inc.
Arjen Nienhuis <[email protected]>
License: SIL-1.1
License: Apache-2.0
Licensed under the Apache License, Version 2.0
https://www.apache.org/licenses/
.
On Debian systems, the complete text of the Apache License can be found in
/usr/share/common-licenses/Apache-2.0'.
License: SIL-1.1
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
.
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
.
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font
creation efforts of academic and linguistic communities, and to provide
a free and open framework in which fonts may be shared and improved in
partnership with others.
.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply to
any document created using the fonts or their derivatives.
.
DEFINITIONS
.
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
.
"Original Version" refers to the collection of Font Software components
as distributed by the Copyright Holder(s).
.
"Modified Version" refers to any derivative made by adding to,deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software
to a new environment.
.
"Author" refers to any designer, engineer, programmer, technical writer
or other person who contributed to the Font Software.
.
PERMISSION & CONDITIONS
.
Permission is hereby granted, free of charge, to any person obtaining a
copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
.
1) Neither the Font Software nor any of its individual components, in
Original or Modified Versions, may be sold by itself.
.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or in
the appropriate machine-readable metadata fields within text or binary
files as long as those fields can be easily viewed by the user.
.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the
corresponding Copyright Holder. This restriction only applies to the
primary font name as presented to the users.
.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
.
5) The Font Software, modified or unmodified, in part or in whole, must
be distributed entirely under this license, and must not be distributed
under any other license. The requirement for fonts to remain under this
license does not apply to any document created using the Font Software.
.
TERMINATION
.
This license becomes null and void if any of the above conditions are
not met.
.
DISCLAIMER
.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
-24
View File
@@ -1,24 +0,0 @@
# Platform selection only; decoder sources, flags and targets belong to avif.
include_guard(GLOBAL)
include("${CMAKE_CURRENT_LIST_DIR}/ImagePackages.cmake")
# dav1d is the default AV1 decoder and libaom the explicit oracle. DAV1D_DIR
# or KRYON_DAV1D_DIR select the pinned dav1d source; otherwise it comes from
# the same locked package graph as avif.
function(kryon_avif_decoder avif_dir aom_dir)
kryon_image_package(package avif)
include("${package}/native/ZiranAvif.cmake")
if(DEFINED DAV1D_DIR AND NOT DAV1D_DIR STREQUAL "")
set(dav1d_dir "${DAV1D_DIR}")
elseif(NOT "$ENV{KRYON_DAV1D_DIR}" STREQUAL "")
set(dav1d_dir "$ENV{KRYON_DAV1D_DIR}")
else()
kryon_ziran_package_path(dav1d_dir dav1d)
endif()
set(shared)
if(ARGV2 STREQUAL "BUILD_SHARED_BRIDGE" OR (NOT ANDROID AND NOT WIN32 AND NOT APPLE))
# Cairo lazily opens the same self-contained library as before.
set(shared BUILD_SHARED_BRIDGE SHARED_TARGET_NAME kryonavif)
endif()
ziran_avif_add_native(AVIF_SOURCE "${avif_dir}" AOM_SOURCE "${aom_dir}" DAV1D_SOURCE "${dav1d_dir}" ${shared})
endfunction()
-52
View File
@@ -1,52 +0,0 @@
# Resolve codec-owned build entry points through the ordinary package graph.
# Callers can pass KRYON_AVIF_PACKAGE_DIR / KRYON_WEBP_PACKAGE_DIR when building
# a renderer artifact from a consumer's locked dependency graph.
include_guard(GLOBAL)
# Locked checkout of any package or pinned source dependency in Kryon's graph.
function(kryon_ziran_package_path output name)
if(DEFINED ZIRAN_BIN AND NOT ZIRAN_BIN STREQUAL "")
set(ziran "${ZIRAN_BIN}")
elseif(NOT "$ENV{ZIRAN_BIN}" STREQUAL "")
set(ziran "$ENV{ZIRAN_BIN}")
elseif(DEFINED ZIRAN_DIR AND NOT ZIRAN_DIR STREQUAL "")
set(ziran "${ZIRAN_DIR}/build/bin/ziran")
elseif(NOT "$ENV{ZIRAN_TOOLCHAIN_ROOT}" STREQUAL "")
set(ziran "$ENV{ZIRAN_TOOLCHAIN_ROOT}/build/bin/ziran")
elseif(NOT "$ENV{ZIRAN_DIR}" STREQUAL "")
set(ziran "$ENV{ZIRAN_DIR}/build/bin/ziran")
elseif(NOT "$ENV{ZIRAN}" STREQUAL "")
set(ziran "$ENV{ZIRAN}")
else()
set(ziran ziran)
endif()
get_filename_component(project "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/.." ABSOLUTE)
set(locked --locked)
if(EXISTS "${project}/ziran.local.toml")
set(locked)
endif()
execute_process(COMMAND "${ziran}" pkg path "${name}" ${locked}
WORKING_DIRECTORY "${project}"
RESULT_VARIABLE status OUTPUT_VARIABLE directory
ERROR_VARIABLE diagnostic OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT status EQUAL 0)
message(FATAL_ERROR "Cannot resolve ${name} package: ${diagnostic}")
endif()
set(${output} "${directory}" PARENT_SCOPE)
endfunction()
function(kryon_image_package output name)
string(TOUPPER "${name}" upper)
set(selection "KRYON_${upper}_PACKAGE_DIR")
if(DEFINED ${selection} AND NOT "${${selection}}" STREQUAL "")
set(directory "${${selection}}")
elseif(NOT "$ENV{${selection}}" STREQUAL "")
set(directory "$ENV{${selection}}")
else()
kryon_ziran_package_path(directory "${name}")
endif()
if(NOT EXISTS "${directory}/ziran.toml")
message(FATAL_ERROR "No ${name} package at ${directory}; run ziran fetch")
endif()
set(${output} "${directory}" PARENT_SCOPE)
endfunction()
-144
View File
@@ -1,144 +0,0 @@
# Android NDK build helpers for Kryon apps.
#
# An app's droid/app/src/main/cpp/CMakeLists.txt generates its Ziran C sources
# and then uses these helpers for the parts every Kryon Android app shares:
#
# include("${KRYON_DIR}/cmake/KryonAndroid.cmake")
# kryon_android_reproducible_paths("${REPO_ROOT}") # before dependency targets
# kryon_android_codecs("${WEBP_DIR}" "${AVIF_DIR}" "${AOM_DIR}")
# add_library(main SHARED ${APP_SOURCES})
# kryon_android_app(main) # glue, size flags, system libs
#
# The helpers only set what is common; apps add their own definitions,
# include directories, and libraries to `main` as usual.
include_guard(GLOBAL)
include("${CMAKE_CURRENT_LIST_DIR}/WebP.cmake")
include("${CMAKE_CURRENT_LIST_DIR}/AVIF.cmake")
set(KRYON_ANDROID_NATIVE_APP_GLUE_DIR
"${ANDROID_NDK}/sources/android/native_app_glue")
# Apply to every target in this directory and its children, including native
# dependencies. Debug paths enter the linker's build ID before Gradle strips
# the APK library; normalizing only the final app target is insufficient.
# Keep debug information and build IDs so retained crash symbols still match.
function(kryon_android_reproducible_paths source_root)
get_filename_component(source_root "${source_root}" ABSOLUTE)
# NDK clang accepts these flags for C/C++ and preprocessed assembly.
# NASM/Yasm use -f for their object format and cannot receive them.
add_compile_options(
"$<$<COMPILE_LANGUAGE:C,CXX,ASM>:-fdebug-compilation-dir=.>"
"$<$<COMPILE_LANGUAGE:C,CXX,ASM>:-ffile-prefix-map=${source_root}=.>"
"$<$<COMPILE_LANGUAGE:C,CXX,ASM>:-ffile-prefix-map=${ANDROID_NDK}=./ndk>"
"$<$<COMPILE_LANGUAGE:C,CXX,ASM>:-ffile-prefix-map=${CMAKE_BINARY_DIR}=./build/android>")
endfunction()
# Build the image codecs Kryon's platform-native Android host uses. Software
# presentation needs no graphics, audio, or renderer dependency.
function(kryon_android_codecs webp_dir)
if(NOT EXISTS "${webp_dir}/CMakeLists.txt")
message(FATAL_ERROR "No libwebp source at ${webp_dir}")
endif()
kryon_webp_decoder("${webp_dir}")
set(avif_dir "${ARGV1}")
set(aom_dir "${ARGV2}")
if(avif_dir STREQUAL "")
set(avif_dir "$ENV{KRYON_ANDROID_AVIF_DIR}")
endif()
if(aom_dir STREQUAL "")
set(aom_dir "$ENV{KRYON_ANDROID_AOM_DIR}")
endif()
kryon_avif_decoder("${avif_dir}" "${aom_dir}")
add_library(kryon_android_codecs INTERFACE)
target_link_libraries(kryon_android_codecs INTERFACE
kryonwebp ziran_avif::static)
endfunction()
# Turn a shared library into a Kryon NativeActivity payload: add the NDK's
# native_app_glue, optimize for speed, keep symbols hidden, garbage-collect unused
# sections, align for 16 KB page devices, route fopen() through Kryon's APK
# asset reader, retain native crash symbols, and link Android's system APIs.
function(kryon_android_app target)
set_target_properties(${target} PROPERTIES SKIP_BUILD_RPATH TRUE)
if(NOT ZI2C_BIN)
find_program(ZI2C_BIN NAMES zi2c REQUIRED)
endif()
set(thread_source "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../src/backend/android_thread.zi")
set(thread_generated "${CMAKE_CURRENT_BINARY_DIR}/kryon-android-thread")
add_custom_command(
OUTPUT "${thread_generated}/android_thread.c" "${thread_generated}/android_thread.h"
COMMAND "${ZI2C_BIN}" --no-main
--root "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../src/backend"
-o "${thread_generated}" "${thread_source}"
DEPENDS "${thread_source}" "${ZI2C_BIN}"
VERBATIM)
# The NDK's glue is compiled from a copy in the build tree. Its own path
# carries the NDK's install location into the object and module names,
# which ThinLTO hashes into symbols, so builds on other machines differ.
set(glue_source "${CMAKE_CURRENT_BINARY_DIR}/kryon-native-app-glue/android_native_app_glue.c")
configure_file("${KRYON_ANDROID_NATIVE_APP_GLUE_DIR}/android_native_app_glue.c"
"${glue_source}" COPYONLY)
target_sources(${target} PRIVATE
"${thread_generated}/android_thread.c"
"${glue_source}")
# Only the NativeActivity-owned app thread receives this stack policy.
# The generated configurator calls libc normally; other thread creators retain
# their own attributes and defaults.
set_property(SOURCE "${glue_source}"
APPEND PROPERTY COMPILE_DEFINITIONS pthread_attr_setdetachstate=ConfigureNativeThread)
target_include_directories(${target} PRIVATE
"${KRYON_ANDROID_NATIVE_APP_GLUE_DIR}")
target_compile_definitions(${target} PRIVATE
PLATFORM_ANDROID ANDROID_BUILD=1 _DEFAULT_SOURCE _GNU_SOURCE
_FILE_OFFSET_BITS=64)
target_compile_options(${target} PRIVATE
-O2 -ffunction-sections -fdata-sections -fvisibility=hidden
-fno-omit-frame-pointer $<$<NOT:$<CONFIG:Debug>>:-g1>)
target_link_options(${target} PRIVATE
-Wl,--gc-sections
-Wl,--as-needed
-Wl,-z,max-page-size=16384
-Wl,-z,common-page-size=16384
# Kryon serves fopen() from APK assets through __wrap_fopen.
-Wl,--wrap=fopen
-Wl,--wrap=fopen64)
# Gradle strips the packaged library. Keep this original, with line
# information, so native startup failures can be symbolicated.
# Imported scene shaders use EGL and GLES directly, including when the
# Android host itself presents through a software surface.
target_link_libraries(${target} PUBLIC android log atomic dl m EGL GLESv3)
endfunction()
# Adopt Kryon's canonical Android host for a shared-library target whose
# generated sources include the application's main and android_glue modules
# (created by scripts/android_scaffold.py). KRYON_ANDROID_HOST selects
# Kryon's own platform keyboard implementation; an application that supplies
# its own JNI glue, like one with a custom SetPlatformTextKeyboardVisible,
# must not call this. The library exposes Android's entry points and the
# notification JNI callbacks that Android resolves on receiver/service startup.
function(kryon_android_host target)
target_compile_definitions(${target} PRIVATE KRYON_ANDROID_HOST=1)
foreach(source IN LISTS ARGN)
get_filename_component(source_name "${source}" NAME)
if(source_name STREQUAL "main.c")
# Kryon's NativeActivity glue calls android_main directly. The
# scaffold's argv-style main remains the stable application ABI.
set_source_files_properties("${source}"
PROPERTIES COMPILE_OPTIONS "-ffreestanding")
elseif(source_name STREQUAL "android_glue.c" OR
source_name MATCHES "(^|_)(android_notifications|notification_push)\\.c$")
# The VM locates this exported entry before native methods are
# registered through it. Notification receivers and push services
# also locate their JNI callbacks after a cold process start.
# Package-generated sources carry an identity prefix.
set_source_files_properties("${source}"
PROPERTIES COMPILE_OPTIONS "-fvisibility=default")
endif()
endforeach()
target_link_options(${target} PRIVATE
"-Wl,--version-script,${CMAKE_CURRENT_FUNCTION_LIST_DIR}/libmain.map.txt"
"-Wl,--no-undefined-version")
set_property(TARGET ${target} APPEND PROPERTY LINK_DEPENDS
"${CMAKE_CURRENT_FUNCTION_LIST_DIR}/libmain.map.txt")
endfunction()
-9
View File
@@ -1,9 +0,0 @@
# Keep the renderer's archive name while consuming the package-owned recipe.
include_guard(GLOBAL)
include("${CMAKE_CURRENT_LIST_DIR}/ImagePackages.cmake")
function(kryon_webp_decoder webp_dir)
kryon_image_package(package webp)
include("${package}/native/WebP.cmake")
ziran_webp_decoder(kryonwebp "${webp_dir}")
endfunction()
-4
View File
@@ -1,4 +0,0 @@
cmake_minimum_required(VERSION 3.22)
project(KryonAVIF C CXX)
include(${CMAKE_CURRENT_LIST_DIR}/../AVIF.cmake)
kryon_avif_decoder("${AVIF_DIR}" "${AOM_DIR}")
-9
View File
@@ -1,9 +0,0 @@
cmake_minimum_required(VERSION 3.22)
project(KryonDesktopCodecs C CXX)
# Codecs only: platform-native Android presentation links no renderer.
include("${CMAKE_CURRENT_LIST_DIR}/../WebP.cmake")
include("${CMAKE_CURRENT_LIST_DIR}/../AVIF.cmake")
kryon_webp_decoder("${WEBP_DIR}")
kryon_avif_decoder("${AVIF_DIR}" "${AOM_DIR}" BUILD_SHARED_BRIDGE)
include("${AUDIO_DIR}/native/AudioCodecs.cmake")
ziran_audio_codecs("${OPUS_DIR}" "${SAMPLERATE_DIR}")
-12
View File
@@ -1,12 +0,0 @@
{
global:
# Android loads the NativeActivity entry and registers JNI methods.
ANativeActivity_onCreate;
android_main;
JNI_OnLoad;
# Receivers and optional push services can start without an Activity.
Java_org_kryonlabs_notifications_NotificationReceiver_*;
Java_org_kryonlabs_notifications_push_*;
local:
*;
};
-6
View File
@@ -1,6 +0,0 @@
# Standalone build of Kryon's WebP codec archive for native desktop hosts and
# renderer artifacts: cmake -S cmake/webp -B BUILD -DWEBP_DIR=LIBWEBP_SOURCE
cmake_minimum_required(VERSION 3.22)
project(KryonWebP C)
include(${CMAKE_CURRENT_LIST_DIR}/../WebP.cmake)
kryon_webp_decoder("${WEBP_DIR}")
+4540
View File
File diff suppressed because it is too large. Load diff
+105
View File
@@ -0,0 +1,105 @@
#ifndef KRYON_KC_INTERNAL_H
#define KRYON_KC_INTERNAL_H
#include <stddef.h>
enum {
KC_PATH_MAX = 1024,
KC_TEXT_MAX = 1024 * 1024,
KC_NAME_MAX = 128,
KC_INCLUDE_MAX = 64,
KC_USE_MAX = 32,
KC_CALL_MAX = 64,
KC_CONST_MAX = 64,
KC_DEFINE_MAX = 64,
KC_TYPE_MAX = 256,
KC_RAW_MAX = 1024,
KC_STATE_MAX = 128,
KC_BODY_MAX = 512,
KC_BODY_LINE_MAX = 1024,
};
typedef struct KryFunction {
char screen[KC_NAME_MAX];
char args[512];
char return_type[KC_NAME_MAX];
char guard[KC_BODY_LINE_MAX];
int exact_name;
int is_public;
int global_name;
char calls[KC_CALL_MAX][512];
char body[KC_BODY_MAX][KC_BODY_LINE_MAX];
int body_line[KC_BODY_MAX];
int call_count;
int body_count;
} KryFunction;
typedef struct KryFile {
char *path;
const char *root;
char *text;
char app_title[256];
int app_width;
int app_height;
int app_fps;
int app_font_examples;
char app_theme[KC_NAME_MAX];
int app_dark_mode;
int no_main;
char raw[KC_RAW_MAX][KC_BODY_LINE_MAX];
char public_types[KC_TYPE_MAX][KC_BODY_LINE_MAX];
char private_types[KC_TYPE_MAX][KC_BODY_LINE_MAX];
char state[KC_STATE_MAX][KC_BODY_LINE_MAX];
char public_globals[KC_STATE_MAX][KC_BODY_LINE_MAX];
char globals[KC_STATE_MAX][KC_BODY_LINE_MAX];
char includes[KC_INCLUDE_MAX][KC_PATH_MAX];
char include_guards[KC_INCLUDE_MAX][KC_BODY_LINE_MAX];
char const_names[KC_CONST_MAX][KC_NAME_MAX];
char const_exprs[KC_CONST_MAX][KC_BODY_LINE_MAX];
char define_names[KC_DEFINE_MAX][KC_NAME_MAX];
char define_values[KC_DEFINE_MAX][KC_BODY_LINE_MAX];
char define_guards[KC_DEFINE_MAX][KC_BODY_LINE_MAX];
char module[KC_NAME_MAX];
char module_file[KC_NAME_MAX];
char use_aliases[KC_USE_MAX][KC_NAME_MAX];
char use_modules[KC_USE_MAX][KC_NAME_MAX];
KryFunction *functions;
int raw_count;
int public_type_count;
int private_type_count;
int state_count;
int public_global_count;
int global_count;
int include_count;
int const_count;
int define_count;
int use_count;
int function_count;
int function_cap;
int current_line;
KryFunction *current;
} KryFile;
typedef struct KryMacroFrame {
char condition[KC_BODY_LINE_MAX];
char excluded[KC_BODY_LINE_MAX];
} KryMacroFrame;
void add_raw_line(KryFile *file, const char *line);
void add_type_line(KryFile *file, int is_public, const char *fmt, ...);
void add_state_line(KryFile *file, const char *line);
void expand_compile_expr(char *dst, size_t dst_size, const KryFile *file,
const char *src);
void add_guard_line(KryFile *file, const char *guard, int is_public_type,
int is_type, int is_state);
void add_guard_end(KryFile *file, int is_public_type, int is_type,
int is_state);
void combine_compile_guards(char *dst, size_t dst_size, const char *left,
const char *right);
void current_macro_guard(char *dst, size_t dst_size,
const KryMacroFrame *macros, int macro_count);
void append_macro_excluded(char *dst, size_t dst_size, const char *current,
const char *next);
#endif
+74
View File
@@ -0,0 +1,74 @@
#include "kc_internal.h"
#include <stdio.h>
#include <string.h>
void
add_guard_line(KryFile *file, const char *guard, int is_public_type,
int is_type, int is_state)
{
char line[KC_BODY_LINE_MAX];
if(guard == NULL || guard[0] == '\0')
return;
snprintf(line, sizeof(line), "#if %s", guard);
if(is_type)
add_type_line(file, is_public_type, "%s", line);
else if(is_state)
add_state_line(file, line);
else
add_raw_line(file, line);
}
void
add_guard_end(KryFile *file, int is_public_type, int is_type, int is_state)
{
if(is_type)
add_type_line(file, is_public_type, "#endif");
else if(is_state)
add_state_line(file, "#endif");
else
add_raw_line(file, "#endif");
}
void
combine_compile_guards(char *dst, size_t dst_size, const char *left,
const char *right)
{
const char *a = left != NULL ? left : "";
const char *b = right != NULL ? right : "";
if(a[0] == '\0') {
snprintf(dst, dst_size, "%s", b);
} else if(b[0] == '\0') {
snprintf(dst, dst_size, "%s", a);
} else {
snprintf(dst, dst_size, "(%s) && (%s)", a, b);
}
}
void
current_macro_guard(char *dst, size_t dst_size, const KryMacroFrame *macros,
int macro_count)
{
char guard[KC_BODY_LINE_MAX] = "";
for(int i = 0; i < macro_count; i++) {
char next[KC_BODY_LINE_MAX];
combine_compile_guards(next, sizeof(next), guard,
macros[i].condition);
snprintf(guard, sizeof(guard), "%s", next);
}
snprintf(dst, dst_size, "%s", guard);
}
void
append_macro_excluded(char *dst, size_t dst_size, const char *current,
const char *next)
{
if(current == NULL || current[0] == '\0')
snprintf(dst, dst_size, "%s", next);
else
snprintf(dst, dst_size, "(%s) || (%s)", current, next);
}
+5429
View File
File diff suppressed because it is too large. Load diff
-41
View File
@@ -1,41 +0,0 @@
# Accessibility
Kryon's retained tree owns semantic labels, kinds, hierarchy, identity,
selection, editable values and focus. Platform actions return through the
same session and widget behavior used by pointer and keyboard input. Tab and
Shift+Tab traverse eligible controls; Enter and Space activate focused
controls while editors keep their normal key handling. Modal scopes reject
outside focus, activation and edit requests.
The Linux desktop host exposes an optional AT-SPI bridge through GIO.
It registers the application with the accessibility bus, uses retained
generations for object paths, reconciles reordered and removed objects, and
provides Accessible, Application, Component, Action, Text and EditableText
interfaces where applicable. State/name/text changes refresh the AT-SPI
cache. Callbacks run on the UI thread between frames. An unavailable bus does
not prevent an ordinary desktop app from opening.
Text offsets use Unicode scalar counts in AT-SPI and UTF-8 bytes in Kryon.
Requests that would split a grapheme cluster are rejected. Read-only editors
omit EditableText. Passwords expose neither plaintext nor text length or
selection. Edit requests are queued; the widget applies its existing limits
and returns a caller-owned edit for the application to accept. A successful
platform request acknowledges the queue rather than promising application
acceptance. Each request and text read is limited to 64 KiB.
Custom Linux hosts can import `kryon/AccessibilityLinux`, call
`AccessibilityOpen`, poll between frames, synchronize after successful
commits and close before disposing the session. Supply the window's
client-area screen position with `AccessibilityOrigin`; the desktop host
updates it from its own SDL window. The default origin is (0, 0).
`sh tests/native_accessibility_test.sh` builds source and saved-IR fixtures
and drives them through real libatspi on private Xvfb and DBus sessions. It
checks discovery, identity after reorder, focus, Unicode text/selection,
readonly and disabled controls, modal blocking and password redaction.
These checks establish the implemented protocol paths, not complete Orca or
other screen-reader usability. Text boundary/extents methods, list Selection,
table interfaces, and Windows/macOS/mobile accessibility remain unverified
or unsupported. Canvas2D and terminal hosts do not currently
provide the Linux bridge automatically.
+162
View File
@@ -0,0 +1,162 @@
# Kryon Agent Guide
This document is for agents and maintainers using Kryon inside applications such as
Inbe. It describes the behavior Kryon owns, what application code should keep, and
how to update downstream projects without editing vendored copies by hand.
## Role
Kryon is a small immediate-mode UI layer on top of raylib. Applications should use
Kryon for shared UI behavior instead of duplicating pointer capture, modal backdrop,
button, tab, scroll, text input, theme, and DPI logic in each project.
Keep application code focused on product state and domain behavior. Move repeated UI
interaction rules into Kryon when more than one screen or project needs them.
## Frame Lifecycle
Call `BeginUIFrame(width, height, dpi)` once at the start of a normal
screen-space UI frame. If the application uses a transformed UI camera, call
`InitUI(width, height, dpi)` and then `SetUIFrame(camera)` instead. Kryon sanitizes
invalid cameras before using them; a zero-initialized `Camera2D` is treated as
`GetUIDefaultCamera()` so pointer input does not silently break.
Beginning a frame resets per-frame interaction state:
- input blocking
- modal capture state from the previous frame
- input clip stack
- focus registrations
- pointer gesture state
- clip state
Do not persist `ui_set_input_blocked` or input clips across frames. Register them again
while rendering the UI that needs them. Modal capture is registered while drawing the
modal and Kryon carries it into the next frame. Until the current frame registers the
modal bounds again, Kryon captures all pointer input so controls underneath the modal
cannot receive clicks before the modal is drawn.
## Input Capture
Every clickable Kryon control should gate pointer interaction through
`UIInputCapturesClick(point)` or the lower-level helpers already used inside Kryon.
That keeps scroll drags, dropdowns, modal backdrops, and explicit input blockers from
leaking clicks to the screen underneath.
Use these APIs by responsibility:
- `UIInputCapturesClick(point)`: normal public check for app or component code.
- `ui_base_input_captures_click(point, include_pointer_drag)`: internal/specialized
components that need to decide whether pointer dragging should count as capture.
- `ui_set_input_blocked(blocked)`: full-frame blocking for overlays that should stop
all controls for the rest of the frame.
- `SetUIModalCapture(bounds)`: modal-specific capture that blocks background
clicks, then allows controls inside the active modal rectangle after the modal
registers its bounds. It applies immediately and to the next frame.
## Modal Rules
Kryon modal helpers own backdrop capture:
- `DrawUIActionModal`
- `DrawUIModal`
- `DrawUIModal3Button`
- `DrawUIModalFrame`
When an application uses one of those helpers, it should not add separate outside-click
guards or duplicate backdrop blocking. The helper registers the modal bounds for the
current frame and the next frame.
Prefer `DrawUIActionModal` for title, message, and action-button dialogs. It measures
button labels, fits text inside buttons, and wraps actions into multiple rows when
localized labels do not fit. Prefer `DrawUIModalFrame` for custom modal content.
Use manual
`SetUIModalCapture` only for specialized overlays that cannot use the shared modal
frame.
When an application draws a custom modal manually, it must call
`SetUIModalCapture((Rectangle){x, y, w, h})` immediately after calculating the modal
rectangle and before drawing modal controls. This prevents clicks outside the modal from
activating the underlying screen, prevents controls underneath the modal from receiving
clicks before the modal is drawn, and keeps buttons, sliders, dropdowns, and text fields
inside the modal usable.
Do not manage modal click blocking in application-level route code. The application
should decide whether a modal is open and what state changes happen after a modal
button is clicked; Kryon should decide whether pointer input is captured.
## Custom Modal Pattern
```c
int modal_w = ScaleUIPx(320);
int modal_h = ScaleUIPx(240);
int modal_x = (view_width - modal_w) / 2;
int modal_y = (view_height - modal_h) / 2;
SetUIModalCapture((Rectangle){
(float)modal_x, (float)modal_y, (float)modal_w, (float)modal_h
});
DrawRectangle(0, 0, view_width, view_height, (Color){0, 0, 0, 180});
DrawRectangle(modal_x, modal_y, modal_w, modal_h, GetThemeSurface());
```
Before this call on a frame following an active modal, Kryon captures all pointer input.
After this call, normal Kryon controls inside the rectangle remain clickable because
their hit tests are inside the active modal bounds. Controls outside the rectangle see
the click as captured in the current frame and the next frame.
## What To Move Into Kryon
Move behavior into Kryon when it is general UI behavior rather than product behavior:
- repeated modal shell drawing or backdrop capture
- repeated button hit testing, hover, disabled, and focus handling
- repeated scroll clipping or scrollbar handling
- repeated dropdown open/capture behavior
- repeated text input editing and platform text input activation
- repeated theme color derivation or DPI scaling helpers
Keep behavior in the app when it is domain-specific:
- navigation route selection
- practice/session state machines
- settings persistence
- app-specific copy and locale keys
- app-specific icons and assets
- business rules for confirmation or cancellation
## File Dialog Backends
Kryon owns desktop file dialog backend selection. Applications should call
`LoadFileDialog`, `SaveFileDialog`, or `SelectFileDialogFolder` instead of invoking
desktop-specific picker commands directly.
The default backend order is `zenity`, then `kdialog`, then `yad`. For local
diagnostics and packaging checks, `KRYON_FILE_DIALOG_BACKEND` can be set to `auto`,
`zenity`, `kdialog`, `yad`, or `none`.
Do not add permanent app dependencies on an XFCE-specific picker. If a downstream app
needs different desktop behavior, add the backend support in Kryon first, then update
the downstream submodule pointer.
## Downstream Submodule Workflow
Applications should vendor Kryon as a git submodule. Do not edit
`vendor/kryon` directly for permanent changes.
Use this flow:
1. Edit the real Kryon repository.
2. Commit and push Kryon.
3. In the downstream app, update the `vendor/kryon` submodule to the pushed commit.
4. Commit the downstream app's submodule pointer and any app code needed to use the new
Kryon API.
This keeps Kryon reusable and prevents project-local vendor edits from diverging.
## Documentation Rules
Keep `docs/API.md` as the public API reference. Keep this guide as the operational
guidance for agents and maintainers. Documentation in Kryon should describe current
APIs, current behavior, and the expected downstream workflow.
+1485 -58
View File
File diff suppressed because it is too large. Load diff
-148
View File
@@ -1,148 +0,0 @@
# Applications and window hosts
How a Kryon application starts, which host draws it on each platform, and how
input reaches the session. Read this when creating an app entry, embedding a
bundle, or wiring custom input.
The smallest executable application imports `kryon/app` and the widgets it
draws:
```zi
App :: #import "kryon/app";
Text :: #import "kryon/text";
main :: () -> s32 {
window := App.Window.{ .title = "Hello", .width = 320, .height = 160 }
return App.Run(window, Draw)
}
Draw :: (frame: App.Frame) {
Text.Draw(frame, Text.Props.{ .text = "Hello, world!", .size = 32 })
}
```
Such a file is a *program*: it owns `main`, and `kryon/app` selects the desktop
host for a Linux C build and the Canvas host for a web build. In this
checkout, `ziran build --project --target=c --exe --entry hello:main hello.zi`
builds it directly: Kryon's `[package] links` names the desktop host's system
libraries, so no caller `LDLIBS` is needed. Ziran applies those links to the
root manifest only; an application that depends on Kryon builds through the
project tool, which supplies them.
A program carries only what it uses. `kryon/app` imports each platform's
window (`desktop_window`, `page_window`) and frame loop (`frames_desktop`,
`frames_web`) as separate modules, so `App.Show(window)` reaches only the
window: on Linux the checked program of `examples/window.zi` is the window,
`kryon/app`, `app_types`, `desktop_window`, `desktop_process_linux`,
`sdl_event`, `pixmap_sdl` and C strings. In a portable bundle the window is `zx_window`: the checked program is
the window, `kryon/app`, `app_types` and `zx_window`, and the bundle asks its
host only for the window, its events, clearing and presenting
(`ZxWindowOpenHost`, `ZxWindowEventHost`, `ZxWindowClearHost`,
`ZxWindowPresentHost`, `ZxWindowCloseHost`). Kryon's desktop zx player binds
them to the same SDL window and runs the bundle's `main` as native code, so
with the player installed (`make install-user`) `ziran run --backend native
window.zx` opens the window. The same capabilities are a host library,
`libkryon-desktop.so` from `zx_window_host.zi` (`make zx-window-host`), which
`make install-user` registers as `kryon-desktop.library`, so `zx2native
window.zx` writes a Linux executable that links them and opens the window
itself. `make zx-window-test` checks both on a private Xvfb, and that with no
library registered `zx2native` stops at the gap naming `ZxWindowOpenHost`. In
the browser, a project profile with `backend = "canvas"` and `codegen = "zx"`
takes a program entry too: its bundle is the program's own `main`, and the ZX
canvas player binds the window to the page's canvas (`window_page_player`),
lowers the bundle to Wasm in the page and runs it, each wait for an event
yielding to the page. `App.Run(window, Draw)` brings the frame loop, the widget tree's frame
driver (`TreeFrameUse`) and, on Linux, the accessibility tree
(`DesktopAccessibilityUse`). The desktop raster loads pictures, smooth copies and
fonts when a frame first draws them, video when it opens, and the test driver
only with `KRYON_TEST_DRIVER`. `make pay-per-import-test` checks the examples'
generated C, the window's checked programs and its bundle's modules and host
capabilities.
The project tool accepts a program as a project's entry. When the entry module
declares `main`, `kryon build --profile NAME` generates a host that only calls
that `main`, for a `desktop` profile and for a `canvas` page alike. A program
entry uses `codegen = "c99"` for native source builds. Desktop and Canvas
`codegen = "zx"` profiles also accept a program with its own `main`; the
player binds its window capabilities. `Frame` entries use the frame host.
The selected host owns the process entry point, calls `BeginFrame` and
`EndFrame`, supplies input to the session, and presents paint operations.
Every host reports the same key codes through `KeyboardTake`: letters as
uppercase ASCII and named keys as `KeyEnter`, `KeyBackspace`, `KeyLeft`, and
the other `Key` constants. A letter is the one the active keyboard layout types,
not its physical position. `TypedTextTake` collects pending text into the caller's byte
buffer, and `TextFieldInputFor(key, modifiers, text)` turns both into a
focused `TextField`'s input.
An entire Unicode scalar must fit before it is consumed; a buffer of at least
four bytes guarantees progress. `tree_input.TypedCodepointPeek(session)` reads
the next scalar without consuming it, and `TypedCodepointCapacity(session)`
reports free slots in the bounded 32-scalar session queue.
Every graphical host owns an ordered key/text queue and exposes one session
delivery call: `DesktopInputTake(session)` or `CanvasInputTake(session)`. Poll the host every frame, including while session
text remains unread, then call its take once before composition. The take
transfers one editing action or a printable-key/text run into that session and
returns `(key, modifiers)` using portable key and modifier codes. Unread text
delays later editing actions; Return can commit a text run delivered in the
same call. Focus loss cancels queued keys so a queued shortcut cannot fire after
focus returns, while text already committed by the platform remains ordered.
Desktop's bounded 256-record delivery queue backpressures SDL key and text
events without blocking window lifecycle events. Run
`build-queue -- make test-focus TEST=desktop_input_backpressure` for the native
SDL source and saved-IR regression.
The Canvas app host retains unread key presses, repeats, IME commits and
gamepad navigation across drawing frames. Pressed/released snapshot flags still
expire at the frame boundary; delivery does not replay them. Each queued press
or repeat retains its browser event's Shift, Control/Meta and Alt modifiers.
Custom loops call `CanvasInputTake(session)`; an empty take reports current held
modifiers. `CanvasModifiers()` and `CaptureFrameInput(session).modifiers` report held
state at their own sampling time, so consuming a shortcut never changes held
keys or snapshot flags.
Application code owns its product state and calls widgets within `Frame`.
The complete manifest and build commands are in [PROJECTS.md](PROJECTS.md).
Individual `.zi` modules under [`src/ui`](../src/ui) can also be imported by
non-graphical Ziran programs. A program that does not import Kryon uses no
Kryon code. A portable `.zx` links only imported modules and needs a host
binding for any platform effect they call.
To run a portable `.zx` as a windowed app in a host such as TaijiOS, use
[`kryon/host/surface`](BACKENDS.md#hosted-zx-software-surface). The bundle runs
ordinary Kryon widgets with its own session and software raster. The host
supplies the window, pixel presentation and ordered input events.
Call `Surface.Run(window, Draw, 250)` to compose on input and every 250 ms
when idle. Apps that draw through Kryon's paint queue can call
`Surface.RunRetained(window, Draw, 250)` with the same window and callback.
It keeps the last RGBA frame, repaints damage in bounded strips, and presents
on damage or a host redraw request. Custom paint emitters use a full replay.
Use `wake = Wake` with `idle_ms = 0` to schedule state checks independently
of composition. `Wake(now_ms: s64) -> Surface.SurfaceSchedule` returns the
next `wait_ms` and whether an idle event needs a `redraw`. Pass a clock to
receive its sample; otherwise `now_ms` is -1. Nonzero waits are bounded to
1–60000 ms; zero uses the default wait.
Unchanged timeout checks skip composition; input and host redraws still draw.
Surface wheel events reach Kryon scroll widgets and `CaptureFrameInput` for
the current callback. Pass `clock = Clock.Milliseconds` to either entry point
to sample the monotonic `kryon/clock` service on each callback. This fills
`elapsed_ms` and `delta_ms` and lets scroll widgets animate wheel motion.
With the default clock, wheel motion is immediate and the four Surface host
bindings suffice.
Import `kryon/gtk_style_types` for GTK style nodes, state flags, metrics and
bitmap records in portable code. The records are shared with `GtkStyleLinux`.
An empty metrics record has `available = false` so portable callers can use
their own palette and layout when native GTK measurement is unavailable.
Import `kryon/window_chrome` to draw a themed caption and window controls.
Pass the current `Session` and `Chrome.Props` to `Chrome.Draw`, with a stable
key, bounds, title, focus flag, and a bit mask of enabled controls. The host
can use `Chrome.PointerPress` with a per-window `Chrome.State`, position,
and millisecond timestamp. Call `Chrome.CancelClick` when a press becomes a
drag or pointer capture ends. `Chrome.KeyPress` maps unhandled keys for the
focused window. The caller dispatches the returned `Chrome.Action`.
+91
View File
@@ -0,0 +1,91 @@
# Kryon App Build Plan
Goal: Kryon owns the repeatable build and packaging flow for every Kryon app.
App repositories should provide app metadata, native sources, `.kry` sources, and
assets. Kryon should provide the compiler, runtime, dependency builds, packaging
helpers, IDE preview hooks, and diagnostics.
## App Contract
Each app should define one project file, `project.kryon`, with the portable
metadata Kryon needs:
- app id, name, title, version, license, maintainer, website, categories
- source roots for C and `.kry`
- asset roots for images, sounds, fonts, locales, and generated embedded assets
- platform knobs such as Android id/activity, Linux desktop metadata, package
names, and signing-key variables
- build feature flags such as file dialog, tray, sync, audio, and web runtime
The app repo may keep small glue files for platform entry points, but target
selection, dependency build rules, generated Kryon C output, and package layout
should come from Kryon.
## Unified Commands
Kryon should expose one command surface for all apps:
- `kryon build native`
- `kryon build web`
- `kryon build android-debug`
- `kryon build android-release`
- `kryon package linux`
- `kryon package appimage`
- `kryon package deb`
- `kryon package rpm`
- `kryon package flatpak`
- `kryon package snap`
- `kryon package click`
- `kryon package windows`
- `kryon preview`
- `kryon test`
Makefiles in app repos should become thin wrappers that call these commands.
## Build Ownership
Kryon owns:
- strict `.kry` parsing and file:line:column diagnostics
- generated C and headers under the app build directory
- runtime source selection for native, web, Windows, Click, and Android
- Raylib, curl, liboqs, and other shared vendor build rules
- embedded asset generation
- Linux desktop files, icons, metainfo, AppImage, deb, rpm, Flatpak, Snap, and
Click packaging helpers
- Android CMake, Gradle property generation, APK/AAB assembly hooks, and asset
copy helpers
- web/WASM HTML, JS, data-file generation, cache busting, and smoke-test hooks
- Podman-backed Linux packaging where host tools are missing or platform
isolation is needed
Apps own:
- product code and app-specific C modules
- `.kry` pages, widgets, and screens
- translations and media assets
- app metadata values in `project.kryon`
- optional platform-specific shims that cannot be generalized cleanly
## Migration Phases
1. Rename old build variables and paths from Flint to Kryon in every app.
`vendor/kryon` is the only runtime submodule path.
2. Keep app Makefiles working, but make them use `KRYON_DIR` and Kryon-owned
`mk/*.mk` includes exclusively.
3. Move repeated Makefile logic from Inbe into Kryon `mk/app.mk`,
`mk/android.mk`, `mk/web.mk`, and `mk/package-linux.mk`.
4. Add a Kryon CLI wrapper that reads `project.kryon` and invokes the shared
make fragments with normalized variables.
5. Convert app Makefiles to compatibility shims, then remove duplicated app-side
package/build rules.
6. Make the IDE use the same build graph for preview/run so errors from manual
build, auto preview, and package targets use one diagnostic format.
7. Add template checks so new Kryon apps start with the unified layout.
## Vendor Rule
Vendored Kryon directories are pinned dependencies. App builds must not modify
files under `vendor/kryon`. Regenerated Kryon runtime assets, generated icon
tables, and shared packaging helpers must be changed in the root Kryon
repository, committed there, and consumed by updating the app submodule pointer.
-134
View File
@@ -1,134 +0,0 @@
# Application hosts and embedding
The desktop ZX player launcher API, the SDL2/Cairo desktop host's optional
parts, Canvas host extensions and Android frame ownership. Read this when you
embed or launch Kryon bundles, or need host-level window and platform control.
## Linked desktop ZX player
Native launchers import `kryon/desktop_zx` and call
`RunWithBindings(path: string, options: PlayerOptions, bindings: []HostBinding) -> s32`
to play a desktop frame bundle or hosted app. Supply the exact bundle module
and function name in each `std/bundle_host.HostBinding`. Kryon binds its window, frame,
drawing and input capabilities first. The player rejects missing or ambiguous
capabilities before initializing the guest.
`PlayerOptions.{.check = true}` checks bindings without starting the guest or
opening a window. The launcher owns its callback contexts and binding storage
until the call returns. Callbacks receive typed `HostValue` values and their
own context. Use typed values or opaque application handles as the guest
interface. Run on the desktop thread, one instance at a time.
Build the launcher for C with `PLATFORM_DESKTOP` defined. Link the runtime
archives and desktop libraries specified in [`mk/zx-player.mk`](../mk/zx-player.mk)
along with the launcher's own native libraries. Grant each application's
native capabilities only to the bundle the launcher was designed to run.
For a hosted shell that runs other apps, `kryon/nested_app_host` provides a
`NestedAppHost` table owned by the linked launcher. Set its `ChildAppPolicy`
to approve child bytes and supply that child's services and asset resolver.
Use `CollectNestedAppBindings` with the inspected outer bundle. Keep that bundle
and the table alive until playback returns, then call `CloseNestedApps` even
if the outer guest traps. The shell uses `std/bundle_guest` for lifecycle and
packed asset reads and `kryon/nested_app` for frame, command, save and reply.
`Frame` draws into a bounded child scope inside the shell's current widget
frame. It receives the key and modifiers the shell passes, and its input
snapshot exposes pointer data within those bounds. Each child has its own
runtime state and the launcher grants its native services explicitly.
## Desktop host parts
The SDL2/Cairo desktop host (`desktop_runtime`) carries optional parts that
only programs importing them link. Key codes are Kryon's: letters as
uppercase ASCII, named keys from 256 (Escape), as `desktop_keys` maps SDL's.
| Module | Surface |
| --- | --- |
| `desktop_runtime` | Routes each SDL event to the window it names; `DesktopWheelMoveX()` gives the poll's sideways wheel steps (positive to the right) beside `DesktopWheelMove()`. Over another window of the program the main window's pointer is at -1, -1 and presses nothing. On X11 a button held by another client's grab, such as a window-manager move, produces no application press or release. `OpenDesktopWindow(width, height, title, options)` opens the window with any of `DesktopWindowResizable`, `DesktopWindowUndecorated`, `DesktopWindowTopmost` and `DesktopWindowAlwaysRun` (keep the frame cadence while hidden or minimized); `OpenDesktopTitled` is the resizable window. `DesktopFrameRate(fps)` caps drawing at `fps` frames a second, or draws without waiting with 0 (the default is 60, settling to 15 while nothing changes). `DesktopExitKey(key)` makes a key end the loop as closing the window does (0 turns that off). `PollMiddlePointer()` reports the middle button like `PollSecondaryPointer()` the right one. `DesktopPrepareGlyphs(text)` loads the fallback faces non-ASCII text needs before a frame draws it |
| `kryon/desktop_activity` | `DesktopWaitForActivity(descriptors, milliseconds)` sleeps until one of the program's own descriptors (such as a terminal's PTY) is readable, window input is queued, or the time ends, and returns `DesktopActivityDescriptor`, `DesktopActivityInput` or `DesktopActivityNone`. Queued input stays for the next `PollDesktop`. Windows and Android return `DesktopActivityUnsupported`; keep drawing there |
| `kryon/desktop_keyboard` | `DesktopKeyDown(key)`, `DesktopKeyPressed(key)` (the first press), `DesktopKeyRepeated(key)` (keyboard auto-repeat) and `DesktopKeyReleased(key)`, for the last `PollDesktop` |
| `kryon/desktop_window_state` | `DesktopMinimize`, `DesktopMaximize`, `DesktopRestore`, `DesktopRaise` and `DesktopSetAlwaysOnTop(enabled)` ask the window manager; `DesktopMinimized`, `DesktopMaximized` and `DesktopAlwaysOnTop` report what it did. `DesktopSetFullscreen(enabled)` and `DesktopToggleFullscreen()` fill the monitor at the desktop's own resolution and `DesktopFullscreen()` reports it. `DesktopMonitorBounds()` and `DesktopMonitorUsable()` give the window's monitor in desktop pixels, and `DesktopDisplayScale()` its density over 96 dpi (X11's `Xft.dpi` when set) |
| `kryon/desktop_secondary_window` | Up to three more windows, each with its own Cairo surface, presenter and events: `OpenSecondaryWindow(title, x, y, width, height, flags, background, scale)`, `CloseSecondaryWindow`, `BeginSecondaryWindow`/`EndSecondaryWindow` around `BeginSecondaryFrame`/`EndSecondaryFrame`, `SecondaryWindowInput`, `PumpSecondaryWindows`, `IsSecondaryWindowClicked`, `RightClicked`, `Dragged`, `TakeSecondaryWindowClose`, `GetSecondaryWindowSize`, `Position`, `ClickPosition`, `SetSecondaryWindowKeyboardGrab` and `CloseSecondarySession`, plus each window's own keys (`IsSecondaryWindowKeyDown`, `KeyPressed`, `KeyRepeated`, `KeyReleased`), `IsSecondaryWindowFocused` and `SecondaryDesktopWindow` (its SDL window) |
| `kryon/cairo_assets` | `RasterUseAssets(read)` gives the raster the program's own assets, such as files embedded in its executable: a picture whose bytes `read(path)` returns decodes from memory in any format the raster decodes. `RasterAssetsClose()` forgets them. Each asset the decoders read, and each face `kryon/cairo_typefaces` is given as bytes, is a file of its own: an in-memory file on Linux, and on Windows a file in the user's temporary folder, removed when it is closed or when the program exits |
| `kryon/cairo_typefaces` | `kryon/typeface_source`'s `RegisterTypefaceData`, `RegisterTypefaceFile`, `RegisterSystemTypeface`, `UseTypeface` and `ClearTypefaces` on Pango and fontconfig. Registered faces also serve scripts the selected face lacks |
| `kryon/cairo_render_scale` | `RasterSetTransform(scale, offset_x, offset_y)` maps layout points to pixels as `point * scale + offset`. It rejects scales outside `(0, 16]` and nonfinite offsets. The transform survives window resize; `RasterScale()` reads its scale. Custom hosts map their raw pointer with `RasterPointFromPixels(point)` before routing input to the widget tree |
`make desktop-windows-test` checks these on a private Xvfb with XTest input.
## Compiled canvas host extensions
`canvas_app_run.CanvasAppMainLoop(false)` runs an AppContext app compiled into
its page. Bind `canvas_app_run:CanvasAppMain=app:Main`. Private documents retain
`/kryon-apps/<app id>` on IndexedDB. The bare runner supports mini mode only.
A host may install `canvas_app_hooks.CanvasAppHooks` with `CanvasAppUseHooks`
before entering the loop. Every callback is optional: `start(mini) -> bool`
runs once after persistent storage and the app's documents are open; `pump()`
runs before input each frame; `stop() -> bool` runs after a successful start, before
storage flush and teardown. A false stop result makes the loop fail after cleanup.
A failed start must clean up its own partial work.
`supports(capability)` and `service(name, request)` provide host-owned optional
services. An absent service returns the usual unavailable JSON response.
`frame(session, bounds, key, modifiers, input) -> s32` runs inside the runner's
frame. Return 0 to run the app, 1 to replace its entire frame, or -1 to fail the
loop. Replacement frames exclusively receive input; the app callback is skipped,
including on the frame that closes an overlay. The host draws widgets but never
calls BeginFrame/EndFrame. Callbacks run on the frame thread. Account, payment,
authentication and application navigation policies belong to the embedding
package. A host decides which services it offers in mini mode.
### Android frames owned by the application
Android applications can import `kryon/android_egl` and call
`EnableAndroidGlesComposition()` before starting the first frame. A managed
`Frame` entry can call it on its first invocation. Kryon composes Pixmap paint
into a retained GLES 3 framebuffer and swaps the EGL window surface. It
falls back to CPU Pixmap if GLES setup or presentation fails. Explicit frame
snapshots still return ordinary owned textures and may read back GPU pixels.
The `Kryon GL_RENDERER` log names the driver. The `Kryon` log records the
first successful EGL swap and any software fallback.
`kryon/android_runtime` hosts applications with their own main loop. Select it
as the Android host when generating native sources. `PollAndroidHost(timeout_ms)`
drains lifecycle and input events and returns false only on destruction;
a missing window, pause or lost focus does not end the loop. Query
`AndroidHostPaused()`, `AndroidHostFocused()` and `AndroidHostViewport()` before
composing. `BeginAndroidFrame()` borrows the NativeActivity surface for Pixmap;
`EndAndroidFrame()` presents its device-pixel damage. The app owns its widgets,
state and pacing. Resizing, density, insets, redraw and surface replacement
invalidate retained pixels; an unchanged frame skips presentation.
After polling, call `SetAndroidPausedSurfaceVisible(visible)` if the operating
system reports that a floating window such as picture-in-picture is visible.
This permits drawing on a live surface during an activity pause while
preserving the usual pause and focus reports.
Pixmap's `RasterSetTransform(scale, offset_x, offset_y)` and
`RasterPointFromPixels(point)` use the same camera for painting and input.
The inverse takes physical pixels, including a negative logical origin. The
held camera survives frame borrows and surface resize. Device damage is
already scaled and must not be scaled again by the presenter.
`kryon/pixmap_assets_android` adds owned decoded pictures. A picture the
application ships decodes from its APK assets the first time Pixmap measures
or draws its path; a missing asset is looked up once, until invalidation or
host cleanup. The Android Frame host imports it, and an application that owns
its loop imports it to show pictures.
`PixmapLoadImageBytes(path, data, file_type)` replaces a registered Pixmap
picture only after a successful bounded decode. Preview decoding returns owned,
upright straight RGBA through the ordinary image-preview capabilities.
Path, folder and full image invalidation share the raster-cache API; replacing
or closing owned entries releases their pixels and sampling cache. A borrowed
picture installed with `PixmapSetImage` remains borrowed.
`kryon/pixmap_typefaces_android` provides the ordinary `typeface_source`
capabilities: register a font file, borrowed font bytes or the system face,
then select its registered name. Bind those capabilities to this provider.
Selection installs Pixmap's optional text rasterizer; the default Pixmap font
needs no Android font service. Android Paint shapes and measures the same run
that Canvas rasterizes into coverage for Pixmap's camera, clipping, rotation
and alpha composition. The line box is the requested font size, matching the
desktop layout contract. System font lookup uses `system_typeface_android`,
and Android supplies script fallback for the selected face. Clearing faces
restores the built-in Pixmap font. CPU discard clears raster masks while
retaining registered faces; host teardown releases owned references and masks.
-51
View File
@@ -1,51 +0,0 @@
# Kryon architecture
Kryon supplies reusable UI behavior as Ziran modules. Ziran owns the source
language, checker, standard library, `.zir`, `.zx`, code generation, and
portable execution. Applications import Kryon only when they need its UI
library. The compiler and bundle loader have no Kryon-specific branches.
## Source ownership
| Location | Responsibility |
| --- | --- |
| `src/ui/*.zi` | Widget APIs, retained tree, layout, input decisions, styling, text, accessibility policy, and paint commands |
| `src/backend/*.zi` | Terminal and window hosts: platform observations, native bindings, rasterization, and presentation |
| `src/project/*.zi` | Kryon project tool that builds an app through Ziran |
| `tests/*_host.zi` | Ziran behavior-test hosts; not part of the library or application hosts |
| Application repositories | Screens, assets, translations, product data, and workflows |
All maintained implementation files under `src/` are `.zi`. The core module
inventory is [`src/ui/modules.txt`](../src/ui/modules.txt). Applications import
each widget package by name, such as `Text :: #import "kryon/text";`, and the
shared core modules they use. Optional packages
have separate imports and build targets; the core UI does not import them.
## Widget and host boundary
The host observes input and submits it to a `Session`. Kryon widget modules
decide focus, hit testing, layout, semantics, styling, and paint commands.
The host supplies system effects such as windows, terminal output, font and
image loading, rasterization, and storage. A host should not implement a
second set of widget decisions.
An application owns `main` and calls `App.Show` or `App.Run`, or exports
`Frame(session: Session, viewport: Rectangle) -> s32` for a profile host.
A frame host calls it between `BeginFrame` and `EndFrame`. Package
profiles choose the terminal, desktop, Android or Canvas2D host;
see [BACKENDS.md](BACKENDS.md). A non-graphical Ziran program can
import a Kryon policy module without selecting any of these hosts.
## Build and verification
`make` checks the Ziran modules, writes `.zir`, generates C and Go,
compiles native objects, and creates a C archive from generated source.
`make test` exercises the checked library through source, saved `.zir`, and
portable `.zx` behavior, Canvas2D Wasm effects, and packaged Canvas2D
browser applications in private headless Chromium. Desktop package tests run on private Xvfb displays;
CI runs them too. `make sanitize-test` repeats the behavior tests with AddressSanitizer and UndefinedBehaviorSanitizer.
[FEATURE_MATRIX.md](FEATURE_MATRIX.md) states exactly what those checks cover.
Ziran's generic capabilities should be added to Ziran and imported here.
Kryon-specific compiler cases, compatibility runtimes, and app-specific
screens do not belong in this repository.
-171
View File
@@ -1,171 +0,0 @@
# Asset audio
Sound effects, music and PCM streams through one hosted-capable call.
Read this when an application plays audio.
`kryon/Media` retains `MediaOpen`, pause/stop/state/message and text fetching.
It also exports `MediaAudio(session, command: MediaAudioCommand) ->
MediaAudioResult`. A hosted bundle uses `KRYON_HOSTED_UI` and requests only
`media_audio.MediaAudioHost` for this function. The same types/function are
available directly from `kryon/media_audio`.
| `MediaAudioCommand` field | Meaning |
| --- | --- |
| `operation: MediaAudioOperation` | `Capabilities`, `Load`, `Play`, `Gain`, `Stop`, `Unload`, `Status`, `CreateStream`, `SubmitStream`, `Pause` or `Resume` |
| `voice: s32` | Caller-selected `1..16`, local to one actual app instance. Each loaded voice has an independent decoder and gain, so several effects and music voices play together |
| `asset: string`, `music: bool`, `gain: float32` | `Load` uses these; unload an occupied ID before reloading it |
| `looping: bool` | `Play` starts from the beginning; `looping` is accepted only on a voice loaded with `music = true` |
| `gain: float32` | `Gain` changes only that voice. Gain must be finite and in `0..1`; out-of-range, NaN and infinite values are rejected, without clamping or changing playback. Zero-initialized gain means silence |
| PCM fields | `format`, `sample_rate`, `channels`, `frames_per_block` and `pcm` for streams (below) |
`Stop` retains a decoded voice for replay; `Unload` stops and frees it.
`Status` updates the stream and reports actual completion. `Capabilities`
does not need a voice ID. There is no queued playback or automatic transition.
`MediaAudioResult` owns `message: string` across the hosted boundary, with
`code: MediaAudioCode`, `state: MediaAudioState`, `capabilities: u32`, and
`writable: bool` for PCM streams, `has_position: bool`, and `position_seconds: float64`.
| `MediaAudioCode` | Meaning |
| --- | --- |
| `Ok` | Success |
| `Unsupported` | No provider |
| `Unavailable` | No device/reader or an operation already in flight |
| `Suspended` | Browser context cannot play, including before an autoplay-unlocking gesture |
| `Invalid`, `Denied`, `Missing`, `Limit` | Bad request, refused, unknown voice/resource, or a limit reached |
| `Failed` | Provider/decode failure |
| `Backpressure` | A full PCM stream |
States are `Unloaded`, `Ready`, `Playing`, `Stopped`, `Finished`, and `Paused`.
A failed command does not imply playing; inspect `code` first.
| Capability bit | Meaning |
| --- | --- |
| 1, 2, 4 | Asset effects, asset music and gain; providers keep these bits when the device is unavailable or suspended |
| 8 | Bounded PCM streams |
| 16, 32, 64 | Asset pause/resume, asset-music position, PCM pause/resume |
A partial provider need not implement these features; check its bits and
result code. Operation and state wire values stay stable; `Pause`, `Resume`
and `Paused` extend the lists.
`Pause` changes Playing to Paused, preserving the individual voice's offset,
loop, gain and queued PCM copies. Repeating Pause on Paused succeeds. `Resume`
changes Paused to Playing; repeating it on Playing succeeds only when the
device/context is available. Both operations reject Ready, Stopped and Finished
with Invalid, and unloaded IDs with Missing. Resume never starts a new voice or
replays a stopped one. Play remains an explicit restart from the beginning.
Neither operation suspends the shared device/context or another owner.
Asset-music Status sets `has_position` only when `position_seconds` contains a
finite, nonnegative provider playhead in seconds, within the current loop
iteration (it wraps at the loop boundary). Paused time freezes. Browser time
also freezes during external context suspension, using AudioContext.currentTime;
Status then reports Suspended with its available frozen position. Resume while
suspended returns Suspended and queues nothing; retry explicitly after unlocking.
PCM and effects have `has_position = false`; zero seconds alone never indicates
support. PCM exposes neither a drained counter nor an estimated elapsed duration.
Paused PCM is not writable and rejects submission with Invalid, preserving the
same bounded queued copies until Resume; Stop and Unload clear those copies.
```zi
using Media :: #import "kryon/Media";
// Once, after verifying the capability/result:
loaded := MediaAudio(session, MediaAudioCommand.{.operation = .Load,
.voice = 1, .asset = "assets/my-game/chime.wav", .gain = .6})
if loaded.code == .Ok {
played := MediaAudio(session, MediaAudioCommand.{.operation = .Play, .voice = 1})
// Consume played.code in the application's audio policy.
}
```
`CreateStream` occupies one of the same 16 voices. Set `format: MediaAudioFormat`
to `S16LE` (signed little-endian 16-bit interleaved samples), `sample_rate` to
8000–48000 Hz, `channels` to 1 or 2, `frames_per_block` to 2048–8192, and
`gain` to a finite value in `0..1`. These are the provider's supported bounds;
no other PCM formats are advertised. Creation accepts no samples. `Play`
starts an empty stream; repeating it clears pending samples. `SubmitStream`
uses `pcm: string` as binary bytes, including NULs, and requires exactly
`frames_per_block * channels * 2` bytes (at most 32768). Samples are copied
before return; the guest retains no host pointer. Format/rate/channels are
fixed until `Unload`; submission uses the voice's creation settings.
`Status` returns `writable: bool`, true only for a running stream with room
for a complete block. `SubmitStream` returns `Backpressure` without accepting
any bytes when full; retry the same block later. `Ok` means the entire block
was copied. The provider holds at most two blocks in its own stream
buffers; no application command queue is added. `Stop` clears queued samples,
`Gain` changes only that voice, and `Unload` frees the stream. Streams remain
`Playing` across frames and underruns, emitting silence while empty: they are
open-ended and do not claim `Finished` or a precise drained count. Asset voices
keep their completion semantics. Suspended/unavailable providers
reject creation, play and submission without queuing them for later autoplay;
after a trusted browser gesture the app must retry explicitly. Owner reset,
revocation, close and successful restart dispose streams with asset voices.
Wurm's synthesis, phrase scheduling, crossfades and game policy stay in Wurm;
its mono 22050 Hz / 2048-frame transport fits these bounds.
Only packed paths under `assets/` pass: absolute paths, empty path components,
traversal, backslashes and schemes are refused before the host's
allowed-asset callback and packed reader. An asset is at most 8 MiB; there
are at most 16 loaded voices per owner and no command queue. Resource bytes
are copied/decoded into provider-owned storage; no native pointer or decoder
handle crosses the VM. The host reply codec uses named fields, and the VM
copies its strings before the host reuses the reply buffers.
`HostedApp.audio` stores the owner for the actual VM instance. `AppContextCall` dispatches audio only in an identified app's active widget
frame, validates its session and the widget asset policy, and reads
only that runtime's packed resources. `AppContextRun` / `AppContextRunFrame`
service streams; audio commands disable quiet-frame replay so effects cannot
repeat as cached UI. `HostedAppClose` and successful `HostedAppRestart`
release all voices. Failed restart preserves the previous instance's audio.
Before changing a context's account/resource ownership, the host
must call `AppContextAudioReset(app)`; it revokes in-flight decoding too.
Never use the outer Session alone as the resource owner.
A custom hosted widget host can supply its own instance's `MediaAudioOwner`
and packed reader as the final optional arguments to
`WidgetHostBegin(session, allowed, resolve, audio, audio_read, audio_context)`.
The original arguments remain sufficient. Without an owner, audio returns
`Unsupported`. `WidgetHostEnd` clears dispatch only; music survives frames.
The custom host must call `MediaAudioOwnerClose(owner)` on actual disposal,
account/resource context changes and instance close. Keep the owner storage
alive until an in-flight synchronous host call returns; a browser decode may
yield. A revoked decode discards its temporary resource before returning.
Native app hosts can use `MediaAudioBegin(owner, session, allowed, read,
context)` / `MediaAudioEnd()` around each callback, and
`MediaAudioOwnerTick(owner)` once per host frame while voices continue.
Binding a changed session or resource context closes previous voices;
close explicitly before replacing a reader or changing its policy in place.
closing an invalid session is also detected by the next tick. Owner close
is explicit and idempotent. Closing one owner never closes the shared device
or another owner's voices. Hosts can register a different actual provider
with `MediaAudioUseProvider`; current owners keep their provider until
closed. The caller retains cue selection, score/synthesis, volume UI, mute,
phrase scheduling and any single-in-flight music transition policy.
`kryon/media_audio_desktop`'s `MediaAudioUseDesktop()` installs the UI
provider over `std/audio` and `std/audio_sink`. The same provider works on
Android: the selected sink uses AAudio from API 26 and OpenSL ES for the
minSdk-21 scaffold. Device opening is asynchronous; voices and PCM blocks can
be queued during opening. A confirmed device failure returns `Unavailable`.
Kryon owns the UI commands and resource lifetime; audio works without a UI:
- `std/audio` mixes voices into 48 kHz float32 stereo. It provides decoded
clips, streaming music, signed PCM16 blocks, gain, pitch, looping,
pause/resume, position, length, seeking and a mixed-output tap.
- `std/audio_sink` selects SDL, Android or WebAudio. `AudioSinkOpen()` starts
opening; `AudioSinkPending()`, `AudioSinkReady()` and
`AudioSinkUnavailable()` report progress. `AudioSinkClose()` explicitly
joins device teardown. SDL's disk driver supports deterministic tests.
- Decoders register by import: `std/audio_decode_wav` (PCM16, float32 and
IMA/MS ADPCM), `std/audio_decode_mp3` and `std/audio_decode_vorbis`.
MP3 uses the core `ziran_mp3` archive; Vorbis links the core recipe's
`vorbisfile`, `vorbis` and `ogg` archives. `audio/decode_opus` optionally
registers Ogg Opus decoding and links libopus. A custom decoder registers
`AudioUseDecoder(probe, open)` with an `AudioSource`.
`make desktop-audio-test` exercises the mixer and UI provider through SDL's
disk driver. `make android-audio-test ANDROID_SERIAL=ZE2223BQZT` exercises
the same UI PCM provider, source and saved IR, on the USB Moto.
-734
View File
@@ -1,734 +0,0 @@
# Kryon hosts
Kryon's reusable widget, layout, input, and composition code is written in
Ziran under `src/ui/`. An application imports the widget packages it uses,
such as `Text :: #import "kryon/text";`, and exports `Frame(session: Session, viewport: Rectangle) ->
s32`. A selected host under `src/backend/` owns the process entry point,
window or terminal, platform input, rasterization, and presentation. Ziran has
no special knowledge of Kryon widgets.
Select a host with a profile in the application's `ziran.toml`:
```toml
[tool.kryon]
default_profile = "desktop"
[tool.kryon.profiles.desktop]
backend = "desktop"
```
Run `ziran tool kryon build` or `ziran tool kryon run` from the application.
See [Ziran projects](PROJECTS.md) for the complete package manifest.
## Renderer artifacts in build scripts
The package exports `renderer-desktop`, `renderer-desktop-windows` and `renderer-web`
artifacts for the supported native and browser targets. Request them through
`ziran pkg artifact kryon:NAME --platform OS-ARCH-ABI`, using the application's
package wrapper and locked graph. Ziran's `scripts/ziran_artifacts.py` verifies
the descriptor and its declared outputs; see its package guide for the Python
`Artifact` and `request` API.
Kryon's `scripts/renderer_artifact.py` provides the renderer-specific consumer
functions alongside its provider. Load it from the resolved `pkg path kryon`
directory and call `renderer_metadata(artifact)` with that verified artifact.
It validates the renderer/platform combination, compile/link argument types,
resources, include directories and virtual preload mounts, then returns
metadata with absolute paths. Every archive, resource, JavaScript library and
preload must be a declared artifact output. Paths resolve beside that
artifact, regardless of the build script's working directory.
`renderer_link(metadata, preloads=True)` returns ordered linker arguments,
including JavaScript libraries and browser preloads. Set `preloads=False`
when a host supplies those files separately. `compile_flags`, `defines` and
`include_directories` remain separate metadata fields for the host compiler
or CMake invocation. Application editions, asset lists and output names stay
in the application.
## Available hosts
| Profile backend | Ziran entry | Presentation |
| --- | --- | --- |
| `terminal` | `src/backend/terminal_run.zi` | 80 × 24 terminal cells via `terminal.zi` |
| `desktop` | `src/backend/desktop_run.zi` | SDL2 window with Cairo raster |
| `canvas` | `src/backend/canvas_run.zi` | Canvas2D page with Emscripten and Asyncify |
| `dom` | `src/backend/dom_run.zi` | HTML elements with browser layout and CSS |
| `android` | app `src/main.zi` → `android_run.zi` | Android NativeActivity package with direct `ANativeWindow` pixel presentation |
The small application surface selects the host from the compile-time target.
Import `kryon/app` and call `App.Run(window, draw)`: C/Linux uses
`kryon/host/desktop`, while C/Web uses `kryon/host/web`. Advanced hosts can
import those named host packages directly. The desktop implementation uses
`cairo_raster.zi` and `desktop_loop.zi`.
After `PollDesktop()`, custom loops call `DesktopInputTake(session)` to transfer
the next ordered editing action or printable-key/text run into that session.
The returned key uses shared codes, including 320–329 for numeric-keypad
digits, and carries the modifiers held when that key arrived.
Standalone `AppContext` applications use the compiled host
`canvas_app_run.zi`.
Polygon-clipped images use native Cairo/Canvas path clips. Complex polygons and pixel hosts use
clipped spans while preserving the original source mapping.
SDL pixel hosts use software presentation by default. `SDL_RENDER_DRIVER`
retains explicit driver selection; `KRYON_PIXMAP_GPU=1` requests accelerated
presentation. Pixel rasterization remains on CPU workers unless the host
explicitly enables a GPU painter.
Desktop windows become visible only after their first complete frame has
been uploaded and presented. A failed initial upload or copy leaves the
window hidden until presentation succeeds.
The `image_preview` module also supplies `ImageCompress` for smaller upright
JPEG copies. It keeps transparent and animated originals intact and returns
no replacement when encoding would increase file size.
## HTML DOM profile
```toml
[tool.kryon.profiles.web]
backend = "dom"
```
Run `ziran tool kryon build --profile web`. The C99 profile produces a
self-contained `build/<package>-web.html`. It calls the app's exported
`Frame(session: Session, viewport: Rectangle) -> s32` with the viewport in
CSS pixels. Submit the retained widgets with their ordinary package APIs.
Give widgets stable `key` values to retain their HTML elements as labels and
sibling order change. Changing a node's parent, widget kind or tag creates a
new element. Close widget scopes with `kryon/tree`'s `End(session)`.
| Ziran API | HTML |
| --- | --- |
| `kryon/page` `Draw` and `Section` | `main` and `section` with the supplied accessible name |
| `kryon/page` `Heading` or `kryon/text` `Draw` with heading semantics | `h1`–`h6` |
| `kryon/text` `Draw` | `span`, or `p` with paragraph semantics |
| `kryon/button` `Draw` | `button type="button"`, with browser tab focus and click, Enter and Space activation delivered through the shared widget result |
| Retained row, column, grid, stack and scroll scopes | `div` with basic flex, grid or overflow rules |
| Retained separator | `hr` |
The root is `#kryon-dom-root`. `data-kryon-widget` holds the committed widget
kind. `data-kryon-id` and `data-kryon-class` hold nonzero decimal style tokens
when the widget publishes them. `data-kryon-selected="true"` marks selected
nodes for CSS. Selected buttons expose `aria-pressed="true"`. Disabled and
loading buttons are disabled in the browser and publish `aria-disabled` or
`aria-busy` respectively.
Import `Dom :: #import "kryon/dom";` in a DOM frame app and call
`Dom.SetStyleSheet(css)` to replace the author stylesheet with CSS text.
An app with multiple host profiles can guard DOM imports and setup with
`#if #defined(KRYON_DOM)` while sharing its widget submissions.
Passing an empty string clears the sheet. Scope rules to `#kryon-dom-root` as
needed. The browser handles selectors, document flow, variables,
`prefers-color-scheme`, and `prefers-reduced-motion`. Native style sheets
continue to drive shared widget calculations and other hosts. Supply browser
CSS separately, for example with the CSS package's `ExportCSS`.
`Dom.RequestClose()` stops frame delivery after the current frame and leaves
the final document visible.
CSS controls the browser's geometry. The DOM profile uses the retained
hierarchy and semantics and discards the raster paint queue. Other retained
node kinds appear as generic containers. Use the Canvas profile for pixel
painting, image rendering, and widgets requiring editing, dragging or custom
pointer coordinates. `make dom-profile-test` builds the normal consumer
profile and exercises it in private headless Chromium.
## Hosted ZX software surface
Import `kryon/host/surface` in a portable app and call `Run(window, draw)`
with the same `Window` and `Draw` types as `kryon/app`. A `Frame` identifies
the current session by slot and epoch. The bundle runs the widget tree,
layout, hit testing, paint queue and pixmap raster, including text measurement
and rasterization with Kryon's bundled fonts. Compile ordinary widget imports
and bind their raster calls to `pixmap` inside the bundle.
`RunRetainedRows(window, draw, present, idle_ms, clock)` lets the host retain
pixels while the app keeps only one strip of output. The `SurfaceRowsPresenter`
callback takes `(width: s32, height: s32, first: s32, rgba: string) -> bool`.
Each call supplies up to 32 complete opaque RGBA8 rows beginning at zero-based
`first`. Consume or copy those bytes before returning. Initial draw, resize
and expose deliver every row in order. Ordinary updates deliver affected rows
and unchanged frames deliver none. Use built-in queued paint with this entry
point. A presenter that returns `false` ends the loop with an error.
`RunRetainedPixels(window, draw, present, idle_ms, clock)` uses the same strip
renderer and damage tracking, but its `SurfacePixelsPresenter` receives
`(width: s32, height: s32, first: s32, pixels: []u32) -> bool`. Each pixel is
packed `0xRRGGBB`; ignore its high byte. Consume these borrowed words before
returning. This avoids the RGBA conversion loop and output buffer when a host
can upload the raster's packed pixels directly. Input, resize, expose and
failure behavior match `RunRetainedRows`.
The `hosted_surface` example's packed and scheduled packed smoke variants
match the full renderer's frame hashes and input results with 32-row batches.
All surface loops accept an optional `wake: SurfaceWake` callback.
It receives the host clock sample (or -1 without a clock) before each event
is handled and returns `SurfaceSchedule { wait_ms, redraw }`. An idle timeout
only composes when `redraw` is true or `idle_ms` is positive. This allows a
cheap state poll to run without rebuilding the widget tree. The next wait is
bounded to 1–60000 ms; zero uses the default wait, and a positive `idle_ms`
also bounds that wait to its existing interval of at most one second. Input,
expose, resize and queued text continue to compose immediately.
Define `KRYON_PIXMAP_EXTERNAL_BUFFER` when the portable app always uses
caller-supplied pixmap storage. This also omits the static fallback framebuffer.
From the Kryon checkout, using canonical Ziran:
```sh
mkdir -p build/scratch/zx-surface
ziran bundle --project --bind-host pixmap --entry hosted_surface:main \
-o build/scratch/zx-surface/hosted_surface.zx examples/hosted_surface.zi
```
A host supplies typed `HostBinding` callbacks for the four capabilities in
[`zx_surface.zi`](../src/backend/zx_surface.zi). Bind the exact module name
from the bundle's capability metadata. The module is `zx_surface` in the
in-tree build and may be package-qualified in a consumer build.
For a consumer project, use `--bind-host <kryon-package-id>_pixmap`, where
`<kryon-package-id>` is the Kryon package's `id` in the project's `ziran.lock`.
| Function | Signature | Host behavior |
| --- | --- | --- |
| `Open` | `(title: string, width: s32, height: s32) -> bool` | Create one hidden window per instance. The dimensions establish the initial pixel viewport. |
| `Event` | `(wait_ms: s32) -> SurfaceEvent` | Return one event in FIFO order. Wait at most `wait_ms` when the queue is empty. Zero polls immediately. |
| `Present` | `(width: s32, height: s32, rgba: string) -> bool` | Consume or copy exactly `width * height * 4` bytes during the call. A successful first frame shows the window. |
| `Close` | `()` | Release the window and its input queue. Closing is idempotent. The host also releases them when the instance exits or traps. |
`Present` uses tightly packed top-down RGBA8 with alpha 255. Its `string`
is a byte span and can contain zeros. If a resize arrives during painting, the
host can discard the stale frame and return success while delivering the resize
event for the next frame. The app exits with status 1 if `Open` or `Present`
fails or a resize provides unsupported dimensions. A close request exits
with status 0. The bundle accepts up to 4,194,304 pixels per surface and up to
16,384 pixels per dimension.
`SurfaceEvent` has signed 32-bit fields `kind`, `x`, `y`, `button`, `key`,
`modifiers`, `width` and `height`, plus `text: string`. Set unused fields to
zero or the empty string. Return the event's declared record type from the
capability metadata.
| `kind` | Meaning | Payload |
| --- | --- | --- |
| 0 | Idle or timeout | |
| 1 | Close requested or window lost | |
| 2 | Redraw | |
| 3 | Resize | Positive `width`, `height` in pixels |
| 4 | Pointer move | Window-local `x`, `y` in pixels |
| 5, 6 | Button down, up | `x`, `y`, `button` (1 left, 2 middle, 3 right) |
| 7, 8 | Key down or repeat, up | `key`, `modifiers` |
| 9 | Committed text | UTF-8 `text` |
| 10 | Reserved for Taiji visibility | |
| 11 | Vertical wheel | Window-local `x`, `y` and signed milli-detents in `button` |
Use the portable [key codes](../src/ui/input_protocol.zi), including uppercase
ASCII for letters and modifier bits 1 Shift, 2 Control and 4 Alt. Deliver text
as a commit independently of the key press. Kryon routes left and right
buttons through its primary and secondary widget input. Frames run on input,
expose and resize. Pass a positive `idle_ms` to also redraw on timeouts at an
interval of up to one second. For example, a stopwatch can redraw every 250 ms
and read elapsed time from its host clock. Platform services such as clocks,
clipboard and live IME composition require additional capabilities.
Send one kind-11 event per vertical wheel sample. Positive `button` values
scroll up and negative values scroll down. Use `1000` units per detent and
leave the other payload fields zero. The wheel sample keeps held buttons and
keys in their current state and clears before the next callback.
`make zx-surface-test` builds and runs the example in the Ziran instruction
engine with a typed host. It verifies the RGBA bytes, rendered count changing
after a click, UTF-8 editing, resize, close and opt-in timeout redraw. An
emulator can launch the same bundle by registering the four capabilities.
## Experimental SDL3 GPU renderer
Custom Linux x86_64 GNU hosts can import `kryon/pixmap_sdl3` and
`kryon/pixmap_sdl3_gpu`. This is an opt-in rendering prototype, rather than a
new project profile: the host supplies an SDL3 window, input loop and
presentation. Desktop profiles keep their behavior.
The handwritten renderer is Ziran; SDL3 supplies the GPU API and shaders.
Kryon's `native-sdl3` artifact builds static SDL 3.4.18 from its pinned official
source package. No Git submodule or global SDL3 installation is needed. Build
prerequisites are a GNU C toolchain, CMake, pkg-config, Python 3.11+, X11
development headers and Vulkan headers/loader. Running requires an SDL3 GPU
device, which may be software. On Debian/Ubuntu the additional test packages
are `libvulkan-dev mesa-vulkan-drivers libx11-dev libxext-dev libxtst-dev xvfb xauth`.
From the Kryon checkout, with Ziran available:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY \
-u DBUS_SESSION_BUS_ADDRESS make sdl3-test
```
This resolves and builds the locked SDK through Ziran, verifies its declared
outputs, and runs shared scene, geometry adapter and real private-Xvfb renderer
tests. Package metadata and the generated import smoke test stay under ignored
`work/sdl3-integration`; there is
no copied source checkout or hard-coded SDK cache key. The Linux CI hosts job
runs the same target with Mesa's software Vulkan device. Missing GPU support
fails the test instead of skipping it.
A host's minimal rendering sequence uses the ordinary package exports:
```zi
Sdl3 :: #import "kryon/pixmap_sdl3";
Sink :: #import "kryon/pixmap_sdl3_gpu";
// After SDL3 initialization and window creation, on the window's thread:
renderer := Sdl3.CreatePixmapSdl3Renderer(window)
// Check renderer != null, then Sink.PixmapSdl3Open(renderer).
// Create and retain a target with Sink.PixmapSdl3CreateTarget(width, height).
// Record normal pixmap painting, then check Sink.PixmapSdl3Draw().
// Copy the target to the window with SDL_RenderTexture and SDL_RenderPresent.
// Close the sink before destroying host-owned targets, renderer and window.
```
`CreatePixmapSdl3Renderer` explicitly requests SDL's `gpu` renderer and returns
null on failure, without trying another renderer. Inspect
`PixmapSdl3DescribeRenderer(renderer)` for the renderer name, API, device name
and driver information; its strings are borrowed until renderer destruction.
A `gpu` renderer using `vulkan` does not establish hardware acceleration.
These tests establish rendering behavior, not hardware performance.
The sink shares `pixmap_gpu`'s clipped geometry, glyph atlas, paint order and
single active recorder. Image publications and sink calls must use the renderer
thread. After a failed draw, close/open and repaint fully; after an SDL render
device reset, call `PixmapSdl3DeviceLost`, recreate the host-owned target and
repaint fully. The sink does not destroy host-owned render targets.
The CPU parity tests cover five scenes and three frames each. Blending has small
rounding differences (observed maximum channel difference 3). Exact nearest
texel ties in the 1.25× zoom scene can choose the adjacent texel, as in the SDL2
reference; the test accepts only analytically identified checker boundaries
within the image and clip. The shared sampler is therefore not byte-exact at
those ties. SDL3 also converts byte colors to float colors in 1536-vertex chunks,
which can add draw calls; this does not establish a speedup over SDL2.
See the executable lifecycle example in
[`tests/sdl3_renderer_host_test.zi`](../tests/sdl3_renderer_host_test.zi).
For SDL2 versus SDL3 on a physical AMD GPU under Linux, use the explicit
hardware mode (choose the render node from `/sys/class/drm/renderD*/device`):
```sh
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY \
-u DBUS_SESSION_BUS_ADDRESS -u SESSION_MANAGER YUE_DESKTOP_RECOVERY=0 \
python3 tests/backend_render_benchmark.py --mode hardware \
--device /dev/dri/renderD129 --trials 5 --frames 1200 --warmup 240 \
--output work/backend-render-benchmark/hardware.json
```
Hardware mode uses SDL2 offscreen EGL/OpenGL and SDL3 offscreen Vulkan with
a headless surface, without the desktop compositor. It removes inherited
software-driver overrides and selects Mesa's Vulkan device by vendor/device
ID. Selection is only a request: both hosts must report a physical renderer
and nonzero Linux DRM graphics-engine execution on the requested PCI device.
The report records that device's render node, PCI address, vendor/device IDs,
kernel driver, renderer/API and Mesa versions. A mismatched device, software
renderer, missing execution evidence or failed pixel oracle blocks hardware
timing. This qualification currently requires AMD's Linux DRM counters; it
does not infer acceleration from the Vulkan API name. The default software mode still forces
llvmpipe on private Xvfb; `--backends sdl2 sdl3` restricts its smoke test.
Every selected backend must pass all 120 frames of all five 480×320 scenes
before hardware timing starts, using the same channel tolerance and narrow
checker-boundary rule described above. Parity exercises presentation as well
as target readback. Repeated trials randomize backend order per scene and
record CPU compose/submit/present p50/p95, individual frame samples, per-trial
drained wall throughput and load averages. Drained wall throughput includes
the final synchronous readback and CPU conversion; it is not a GPU timestamp
measurement. Offscreen results do not measure visible-window/compositor
performance, and other running workloads and GPU clock changes remain
uncontrolled. No backend default or SDL2 software fallback is changed.
## AVIF images
Native AVIF and WebP decoding is supplied by the standalone Ziran `avif`,
`webp` and `image_codec` packages. Kryon selects the platform engine and adapts
caller-owned straight RGBA8 into host pixels, surfaces and textures. Codec
parsing, native ABI and frame composition belong to those packages. The current
native engines explicitly bridge pinned external libraries; this integration
makes no authored AV1 decoder or performance claim.
Content routing uses the packages' bounded prefix predicates; their decoders
perform complete container validation. Kryon's CMake entry points consume the
packages' shared native build recipes and retain the existing target names and
archive locations. Package directories come from `ziran pkg path`; renderer
artifacts pass their resolved dependency paths explicitly. Custom CMake hosts
can set `KRYON_AVIF_PACKAGE_DIR` and `KRYON_WEBP_PACKAGE_DIR` to those paths.
The adapters allocate the final host buffer once. AVIF probes metadata, then
revalidates and decodes the same immutable encoded buffer into that storage;
this repeats bounded metadata parsing without copying a full owned output.
Failed decode, cancellation and changed output dimensions release the buffer
before publishing any pixels. Browser codecs and pixel-renderer inputs retain
their existing paths.
`Image.Draw(Image.Props)` accepts AVIF assets through the same path as PNG/JPEG/WebP,
including extensionless names and packaged bundle/APK assets. Native hosts
decode with the locked libavif 1.3 and dav1d, its assembly selected at run time
for the CPU (x86 SSE2 to AVX-512, ARMv7 and AArch64 NEON); Android 9 requires
no OS AVIF support. libaom is linked as the explicit comparison oracle, never
as a fallback. The still-image API shows the first complete frame of a
sequence. The ARMv7 oracle keeps libaom's portable kernels, because the locked
AOM/NDK combination emits unaligned NEON loads which fault on real Android
hardware; dav1d's own NEON runs there.
Desktop hosts load the AVIF bridge (`libkryonavif.so`, `kryonavif.dll`) on
first use, from `KRYON_AVIF_LIBRARY`, the library search path or beside the
executable, and WebP from the system libwebp. A program that links the codecs
itself builds with `--define KRYON_AVIF_LINKED` (libavif and its AV1 codec)
and `--define KRYON_WEBP_LINKED` (libwebp and libwebpdemux), and loads
neither; `make avif-decode-test` runs such a build, linked with the static
archives, where no `libkryonavif` exists.
8/10/12-bit color and monochrome decode to straight 8-bit RGBA; alpha and
container clean aperture, rotation and mirroring are preserved. The renderer
then premultiplies for Cairo. HDR tone mapping
and ICC display color management are outside the existing 8-bit image surface.
Encoded files are limited to 256 MiB, dimensions to 32768 per axis and pixel
count to 67,108,864 (a 256 MiB RGBA buffer). These are independent axis/count
limits, permitting wide images below the pixel budget. Invalid/truncated
containers, invalid crops and oversized images return no image. 4:2:0 frames
of at least 8 MiP and other frames of at least 2 MiP decode on the process's
usable cores, capped at 4 threads; smaller frames use one, because extra
threads slowed them in measurements. Thread count never changes output
bytes. Only the first decoded frame is retained.
| target | engine | proof |
|---|---|---|
| Linux x86-64 | dav1d, SSE2..AVX-512 | executed: strict parity, benchmark |
| Android armeabi-v7a | dav1d NEON | executed on the USB Moto (MT6765, Android 9): parity, benchmark |
| Android arm64-v8a | dav1d NEON, dotprod, i8mm | static build under qemu-user: strict parity |
| Android x86, x86_64 | dav1d SSSE3..AVX-512 | static build on the x86-64 host: strict parity |
| Linux AArch64 | dav1d NEON, dotprod, i8mm | qemu-user: strict parity |
| Windows, macOS | dav1d via the same recipe | unverified here |
Canvas uses the browser AVIF decoder through `PageImageDecode`; supported
browsers (Firefox 93+, Chromium 85+, Safari 16.4+) supply their native AVIF
implementation. In a browser without AVIF, every AVIF decode fails cleanly:
no pixels and zero size, so the image is treated like any undecodable file,
while PNG, JPEG and WebP keep working. Ship a fallback format for such
browsers. The pure pixel renderer accepts decoded pixel buffers through
`PixmapSetImage`, as for other formats.
`make avif-decode-test` runs independent RGBA goldens from source and saved IR,
and checks dav1d (automatic, 1 and 8 threads) and the libaom oracle against the
strict libavif digests in `tests/avif_strict_digests.zi`, tolerance 0. The
independent goldens keep small documented tolerances: ±1 for 10/12-bit and
grayscale (8-bit rounding of the source pattern), ±4 premultiplied (unpremultiply
rounding) and ±3 for Jungle title samples (YUV420 conversion versus Pillow).
`make avif-render-test` checks native rendering,
including a portable bundle using the public Image widget. `make android-avif-test
ANDROID_NDK=... ANDROID_SERIAL=ZE2223BQZT` builds all four ABIs and runs the
ARMv7 strict-parity/golden-pixel tests on the Android 9 USB Moto, asserting each
ABI's dav1d assembly. `make avif-cross-test [AVIF_CROSS_ROOT=...] [ANDROID_NDK=...]`
runs the strict parity test for Linux AArch64 and static Android arm64-v8a
under qemu-user (Cortex-A53 and every emulated feature) and Android x86/x86_64
on the host; `AVIF_CROSS_ROOT` is a prefix holding the AArch64 GCC and
qemu-aarch64. `make avif-browser-test` exercises the Canvas image
boundary in private headless Firefox, reporting the AVIF capability, and repeats
it as a browser without AVIF. `make avif-benchmark [ANDROID_SERIAL=ZE2223BQZT]
[AVIF_BENCHMARK_BROWSER=1]` records ms/image, MP/s and peak RSS for libaom,
dav1d threads and SIMD tiers, and Firefox, in `build/scratch/avif-benchmark`.
The headless package suite, `sh tests/image_integration.sh`,
resolves real native artifacts and tests source and saved IR under ASan, UBSan
and leak detection, including adapter failure cleanup. With development-only
package overrides, set `ZIRAN_ROOT` and `ZIRAN_BIN` to the rebuilt toolchain.
## AVIF compression and RGBA previews
The native `image_preview` module provides
`ImageCompressAVIF(data: string, file_type: string, orientation: s32,
quality: s32 = 35) -> ImageAVIFResult`. On success, `data` owns actual AVIF
bytes and `source_bytes`/`encoded_bytes` support a real size comparison.
`width`/`height` are the full stored dimensions. Call `ImageAVIFFree(*result)`
when finished. Encoding does not resize or discard a larger result.
`ImageAVIFEncodingAvailable()` reports whether this host supports encoding.
Browser hosts return false, and compression returns `UnsupportedCapability`
without linking native codec archives. Browser RGBA previews remain available.
Accepted still 8-bit JPEG, PNG and WebP sources retain ICC, Exif and XMP when
the container metadata is supported; AVIF uses the headless package's direct
re-encode path. Alpha stays lossless. Animated, high-depth, gain-map and
unsupported color/metadata cases return an explicit shared `DecodeError`.
PNG compressed ICC and compressed text profiles currently return
`UnsupportedCapability`. A host that already baked a nonidentity orientation
must provide raw pixels before compression can preserve the stored orientation.
`ImagePreviewRGBA(data, file_type, max_edge, orientation)` returns owned upright
straight RGBA8 with `pixels`, `width`, `height` and `stride`. It uses Lanczos-3
and retains transparency. `ImagePreviewRGBAPixels` accepts already decoded
pixels with 1..4 channels. Call `ImagePreviewRGBAFree(*result)` to release the
output. These RGBA previews avoid temporary JPEG files and preserve transparent
edges for before/after comparison. Existing JPEG preview callers retain their
existing API.
## WebP images
Images, image previews and app media files accept WebP wherever they accept
PNG or JPEG, recognized by the file's `RIFF`/`WEBP` signature rather than
its name. Lossy, lossless and alpha pictures decode to straight RGBA. An
animated WebP decodes to its first complete frame, since Kryon images are
still; `ImageCompress` keeps animated originals unchanged.
- The desktop (Cairo) host loads the system libwebp demuxer
(`libwebpdemux.so.2`) on first use, like its other optional codecs.
- The canvas host uses the browser's own WebP decoder.
`make test-focus TEST=ziran_image_decode_linux_test` decode the
`tests/fixtures/webp` pictures natively, `tests/webp_browser_test.py` does the
same in headless Chromium, and `make android-webp-link-test` links the
decoder for every Android ABI.
The PNG byte and pixel rules are Ziran in `png.zi`. PNG supports all standard
color types and depths, transparency, all five filters, and Adam7 interlace.
Sixteen-bit samples use their high byte; ancillary color profiles and gamma
are ignored. `tests/ziran_png_test.sh` compares independent reference pixels
for 33 fixtures through source and saved IR in bundles, C and Go, including
malformed streams and bounded decoder output.
Browser projects save the selected `_run` host and `canvas_raster.zi` as
generation roots without entry pruning. This keeps both the host `main` and
the raster adapters available to the paint queue. Native projects continue
through the ordinary package entry route.
## Smooth images (Lanczos)
A smooth picture (`.smooth = true`) is shown at the device pixels it
covers through one shared cache, `src/backend/lanczos_cache.zi`. The copy is
std/resample's Lanczos-3, which gives the same bytes as Pillow's
`Image.resize(size, LANCZOS, box)`. It is computed over premultiplied
pixels and drawn pixel for pixel. The key is the picture's content, its
revision, the source rectangle, the device-pixel size and the session.
Until a copy is ready, the backend draws the previous copy of the same
picture stretched, or uses its own filter if there is none. The finished
copy replaces it in one step. A changed or released picture forgets its
copies. Distinct sizes of the same source and revision coexist within the
LRU budgets, so a large cover and its small marker do not evict each other.
- Only axis-aligned draws under a plain translation are cached. Rotation,
scaled transforms, meshes, polygon strips and render targets keep the
backend's own filter. A whole-pixel draw at the source's own size needs no
copy.
- Limits: a copy is at most 4096 pixels per side and 4,194,304 pixels; all
copies together take at most 64 MiB, and one session at most 32 MiB.
- Like Pillow, filtering works on the stored sRGB bytes, not in linear
light.
- Copies are made on a worker thread with a std/parallel pool in builds
with `POSIX_THREADS`, `ANDROID_BUILD` or `KRYON_FRAME_THREADS`. A browser
build without threads makes a slice of rows each frame instead (about two
million filter taps). Other builds keep the backend's filter.
| Backend | Lanczos copy |
| --- | --- |
| Desktop/Cairo | Cached surface, drawn 1:1 |
| pixmap and SDL3 GPU | A copy slot drawn 1:1 (threaded builds only, `PIXMAP_LANCZOS`), so the CPU rows and GPU hosts show the same bytes |
| Canvas | Ziran resampler in slices, from the texture's pixels read back, then uploaded |
Firefox has no `imageSmoothingQuality`. Canvas therefore does not rely on
it, and still sets it to `high` for upright smooth draws that it does not
cache; meshes and images that the draw or a camera turns keep the browser's
default.
The cached Canvas copy matches Pillow for opaque pictures. Translucent
pictures differ by the browser's 8-bit premultiplied blend, up to about
3.5 levels on average.
A web profile's page carries two builds of the program: one compiled with
`-msimd128` and a baseline one. A small script in the page starts the
SIMD128 build where `WebAssembly.validate` accepts a SIMD probe module, so
Canvas copies use std/resample's SIMD128 kernels, and the baseline build
elsewhere. Both builds give the same bytes. The page stays one file, and the
font is carried once for both builds (`mk/web-page.sh`).
`tests/web_simd_page_test.py`, part of `make canvas-project-test`, checks
this in headless Firefox and Chromium.
A host that sleeps between events calls `PixmapLanczosPending` or
`LanczosSetWake` so it draws again when a copy finishes. The desktop loop
already does this by pushing a wake event. `PixmapLanczosWait` and
`LanczosWait` finish the current copy; captures use them so every
smooth picture is final.
`make lanczos-goldens-test` (part of `make test`) compares Cairo, pixmap,
Canvas in a private headless browser against
Pillow goldens. `make lanczos-benchmark` times Kryon against Pillow,
Pillow-SIMD, libvips and stb_image_resize2. It reports ms per output
megapixel, extra peak memory and PSNR against a float64 reference, on
x86-64 and over ADB on an ARMv7 phone. It writes
`build/scratch/lanczos-bench/receipt.md`. The comparison libraries are
test-only oracles.
## Android host
`backend = "android"` builds an installable APK instead of a native binary.
Add the profile and the application id to `ziran.toml`:
```toml
[tool.kryon.profiles.android]
backend = "android"
[tool.kryon.android]
package = "com.example.app"
min_sdk = "21" # optional, 21 by default
abis = "arm64-v8a" # optional, arm64-v8a by default
```
`kryon build --profile android` generates a `droid/` Gradle project beside
the application sources on the first build (never overwriting existing
files), then assembles a debug APK through the Android Gradle plugin, the
NDK, and CMake. `kryon run --profile android` additionally installs and
launches it on a connected device through adb, and `kryon check --profile
android` checks the whole Zi graph with the Android defines. The build needs
a JDK, the Android SDK with NDK `28.2.13676358` and CMake `3.22.1`
(`ANDROID_HOME`, default `$HOME/Android/Sdk`), and the locked `libwebp`,
`libavif` and `libaom` source packages. Scaffolds pass their source roots to
`kryon_android_codecs`; the packaged host links no renderer or audio library.
At runtime a `NativeActivity` subclass owns the Java side: it reports window
insets, display cutouts, IME state, density, dark mode and orientation
through JNI natives registered by the generated `src/android_glue.zi`, and
forwards soft-keyboard text as codepoint, backspace and enter events. The
generated `src/main.zi` delegates to `AndroidRunMain`, which owns Android's
looper and lifecycle, drives the session with the current Ziran VM and Pixmap
runtime, and applies Kryon's Android viewport policies to the session-owned
text input queue. `Frame` always receives the safe area, clear
of the system bars and cutouts; a backdrop meant to run behind them draws into
`AndroidWindowBounds()`. Applications with their own JNI surface
keep their own `JNI_OnLoad` and call `AndroidJniOnLoad` with their activity
class to add the canonical natives. An application without Java code, a plain
`NativeActivity`, calls `PollAndroidWindowInsets` once per frame instead: it
reads the system bar, keyboard and cutout insets from the window through JNI
a few times a second, and stops once Java reports them.
The generation runs `ziran ir --project` for the whole graph, so application
module names may repeat Kryon module names; every package is prefixed in the
emitted C. `tests/ziran_android_device_test.sh` checks the device protocol
headlessly with the Java side stubbed.
`android_device.AndroidRequestOrientation(policy)` queues an ActivityInfo
screen-orientation policy through `requestOrientation(int)` in the scaffold
activity, which calls `setRequestedOrientation` on the UI thread. Custom
activities must provide that method. `AndroidOrientationSensor` (4) permits
sensor portrait and landscape; `AndroidOrientationSensorLandscape` (6) keeps
landscape. The caller owns route policy and deduplication. A true result means
the Java call succeeded, not that the OS has applied a rotation. Configuration
observations still use `AndroidOrientation()` and are independent of requests.
Android runs the native host loop on NativeActivity's app thread. Each poll
drains lifecycle and input events, snapshots the current touch/key state,
runs one VM frame through Pixmap, and presents the damaged viewport by locking
and unlocking `ANativeWindow`; there is no EGL, OpenGL ES or second render
thread. Rotation, surface destruction and redraw requests invalidate the
retained bitmap, while consecutive quiet frames can pace at 100 ms instead of
16 ms until the next event. Pausing stops presentation and platform media;
resuming restores the existing guest state.
Touch, pointer, soft-keyboard and hardware-key events are consumed only inside
that frame boundary, so guest code receives a stable input snapshot and no
platform callback reenters the VM. The same viewport transform maps single
and secondary pointers into guest coordinates.
Portable ZX images are decoded before a guest is activated and retained in two
bounded host slots. PNG, WebP and AVIF use native codecs; JPEG can use the
platform decoder and all camera images apply EXIF orientation. A valid
replacement promotes candidate pixels only after its services and images load;
an invalid document leaves the previous guest, pixels and private data intact.
MediaPlayer reads a private file written from bundle bytes and supports the
portable play, pause, resume, stop, gain and completion surface.
## Frame and input ownership
A host polls platform input and submits it to the session before calling the
application's `Frame`. The application and widgets consume generic session
input such as `KeyboardTake`, `TypedCodepointTake`,
`PointerWheelTake`, and pointer state. `KeyboardModifiers` reports
Shift, Control, and Alt keys as `KeyModifierShift`, `KeyModifierControl`, and
`KeyModifierAlt` bits, so a shortcut such as Ctrl+S is a key press read with
the modifiers that were down. Desktop and Canvas custom loops call
`DesktopInputTake(session)` or `CanvasInputTake(session)` before each frame. Each take transfers ordered text
to that session and returns the next key with the modifiers retained when the
press or repeat arrived, so shortcuts remain intact even when every physical
key is released before a frame. `CanvasModifiers()` and the immutable frame
snapshot keep their held-state semantics. Other hosts report none.
The host calls `BeginFrame` and
`EndFrame` around application composition, then presents the resulting
paint operations. Widget behavior stays in `src/ui/`.
The terminal host renders one frame when input or output is redirected. With
a TTY, it submits ASCII and UTF-8 text to the same session input API as the
window hosts and ignores terminal escape sequences. The project test drives
this through a private PTY. The other hosts can capture a frame with
`KRYON_CAPTURE_PATH`; the graphical integration tests run on private Xvfb
displays. Run `make test` for the library, browser, and typeface gates, plus
`make desktop-project-test` for graphical
capture and input.
Never run graphical tests against the developer's live display.
The SDL/Cairo desktop host also exposes `DesktopSetTitle(title)` and
`DesktopTakeDroppedFile(output)` through `Desktop`. A file-manager drop queues
up to sixteen complete UTF-8 paths (4095 bytes each), only for the host's own
window. The application consumes and opens them during `Frame`; an output
buffer that is too small leaves the next path queued. Text drops are ignored.
## Portable programmable scene rendering
`scene_render` executes `shader` material programs in Ziran on CPU before
presentation. Cairo and Android's
ANativeWindow/Pixmap host consume the resulting managed bitmap through the
standard Image surface. These hosts do not need a shader-language bridge.
This interface does not claim GPU execution, GLSL compilation, vertex-shader
execution or GPU performance. See [programmable scene materials](SCENE_RENDERING.md#programmable-scene-materials)
for binding ownership, colour space, clipping, alpha and explicit scratch release.
Programs and pictures contain no context-bound handles. Recreate the host
presentation context as usual; keep or re-upload the owned bitmap and render
again as needed. Shader discard affects colour rendering, not depth-map shadows.
Host lifecycle tests must verify bitmap re-upload after teardown; checking a
shader declaration alone does not establish host execution.
The physical-device regression `make shader-android-test` executes Ziran shader
materials and the Pixmap-to-ANativeWindow presentation path on the USB Moto. It
uses a private offscreen AImageReader window, verifies posted RGBA pixels,
clipping, alpha and binding changes, and destroys/recreates that window while
keeping the CPU program and bitmap alive. It does not launch or alter an owner
app. These targets also load a real PNG through
`kryon/image_pixels`; activity-bound Android asset/JNI decoding is a separate
application integration responsibility.
Native scene frames can render on the shared Ziran range-worker capability
when source generation enables `POSIX_THREADS`. Immutable transformed geometry
and ordered triangle commands are prepared once; each lane clears, draws and
resolves disjoint rows, joining once per frame. The scene owns its pool
separately from the presentation raster; `RenderSceneRelease` joins and
closes it. This is CPU row parallelism and does not change texture resolution,
four-sample coverage, shader operations or draw ordering. WebAssembly without
pthread support retains the same serial implementation. Application code must
keep all borrowed material inputs unchanged through the render call.
## Optional native GPU scene rendering
`kryon/scene_gpu` is an explicit native EGL/GLES3 host for the same Scene and
material APIs. It renders offscreen with four MSAA samples, depth-map shadows,
retained geometry/programs/textures and an Image readback bridge. It creates no
window and preserves the caller's current graphics context. Link only consumers
of this module with `-lEGL -lGLESv2 -lGLX -lm`; core UI and `scene_render` imports retain
their existing portable and WebAssembly dependencies.
`kryon/shader_glsl` supplies portable material translation used by this host.
The translator alone has no EGL dependency. GPU execution uses highp floats
and hardware coverage, so it has pixel tolerances relative to the binary64 CPU
oracle. Capability failures are explicit; the separate `SceneGpuRenderOrCPU`
call permits a full-quality CPU frame and reports `accelerated=false`.
Probe/render/resource counters must establish acceleration and retained upload
behavior before reporting GPU timing. A module export or successful link alone
does not establish application integration or deployment.
See [GPU scene APIs](SCENE_RENDERING.md#portable-glsl-translation-and-optional-native-gpu-rendering)
for ownership, lifecycle, capability requirements and local test targets.
## Custom application entry
Applications that own their frame lifecycle import `kryon/application_entry`
and export `KryonApplicationMain(argc: s32, argv: **u8) -> s32` with
`#program_export "KryonApplicationMain"`. The adapter owns `main`: native
hosts forward their exact command line and browser hosts pass `(0, null)`.
The callback retains initialization, frame scheduling and shutdown policy;
Android's NativeActivity host can call the same native entry. Do not define
an additional application `main` when importing this adapter.
-22
View File
@@ -1,22 +0,0 @@
# Repository boundaries
| Owner | Code and data |
| --- | --- |
| Ziran | Language, compiler, standard library, `.zir`, `.zx`, and generic host capabilities |
| Kryon | Reusable Ziran UI modules, widget decisions, and UI hosts |
| Applications | Screens, copy, translations, assets, data storage, migrations, and product workflows |
Kryon is imported by applications. It is not linked into programs that never
import it, and the Ziran compiler does not special case widgets. A generic
capability missing from the language belongs in Ziran. A reusable UI choice
belongs in Kryon. A product-specific behavior belongs in the application.
Kryon's graphical host owns platform windows, input events, and presentation.
Its widget modules own focus, pointer capture, layout, semantics, and paint
decisions. The host may call native libraries through declared Ziran foreign
bindings, but must not duplicate widget policy.
Make upstream Kryon changes on `master` and commit them there. A downstream
app picks them up by updating its `ziran.lock`. Never edit
Kryon's source inside an application. See [ARCHITECTURE.md](ARCHITECTURE.md)
for source modules and [PROJECTS.md](PROJECTS.md) for package use.
-300
View File
@@ -1,300 +0,0 @@
# Kryon cheat sheet
Kryon is a Ziran UI library: Kryon calls the app's `Frame` every frame, which
declares every widget from the app's state; widgets report what the user did.
`make cheatsheet-test` builds, shoots and drives every `// file:` block below.
## Start and see
```sh
kryon new notes && cd notes # app starter: app bar, cards, dark mode; locks itself
kryon run --watch # the window; rebuilds and relaunches on every save
kryon run shot --png build/shot.png --width 390 --height 844 --theme dark
```
No display needed; `build/shot.json` lists each node's kind, role, label and bounds.
## Rules
- Declare every widget every frame; keep state at file scope (`x: s32;`) in a Kryon-free module.
- Containers (Layout, Grid, Flow, Modal) place children: never compute `x` or `y`;
a child declares its size, and zero width fills a column. If `opened`, draw the
children, then `End(session)`: a missing `End` fails the whole frame. Composite
widgets (Card, TitleBar) draw into a `Layout.Stack` slot: pass `slot.bounds`.
- Size and space come from theme tokens. Act on a result in the same frame.
- Typed text lives in `TextField.State` bytes; zero `length cursor anchor scroll_x` to clear.
- A returned `string` must view file-scope bytes (as `NoteAt` does), never a local buffer.
- `ziran lock` refused "checked package metadata": `[toolchain]` must be the
exact Ziran that Kryon pins (`kryon init` sets it). No window under the
driver: build with `KRYON_TEST_DRIVER=1`. Never start Xvfb yourself.
## The project
```toml
# file: ziran.toml
[package]
name = "notes"
entry = "src/app.zi"
module_roots = ["src"]
bridge_modules = ["app"]
links = ["X11"] # private_display in the driver test uses Xlib
tool = "kryon"
[toolchain]
git = "https://git.waozi.xyz/ziranlang/ziran.git"
ref = "5db3d3c39425d5dfe4bfe4a84e6f6e2e5a810ad0"
[dependencies.kryon]
git = "https://git.waozi.xyz/kryonlabs/kryon.git"
ref = "fd3bc9982b45bd02e076445262cda93e7398ad9d"
[tool.kryon]
default_profile = "desktop"
entry = "src/app.zi"
[tool.kryon.profiles.desktop]
backend = "desktop"
```
```zi
// file: src/notes.zi
#import "std/text_tools" // state and text; no Kryon import
note_bytes: [8][64]u8;
note_lengths: [8]s32;
note_count: s32;
AddNote :: (text: string) -> bool {
trimmed := TextTrim(text)
if trimmed.count == 0 || note_count >= 8 { return false }
length := ifx trimmed.count > 64 then 64 else trimmed.count
for i: 0..length - 1 { note_bytes[note_count][i] = trimmed[i] }
note_lengths[note_count] = cast(s32)length
note_count += 1
return true
}
NoteAt :: (index: s32) -> string { return TextView(note_bytes[index][0:note_lengths[index]]) }
NoteCountText :: () -> string { return ifx note_count == 0 then "No notes yet" else "Some notes" }
```
```zi
// file: src/app.zi
Button :: #import "kryon/button";
Card :: #import "kryon/card";
Dropdown :: #import "kryon/dropdown";
Layout :: #import "kryon/layout";
Text :: #import "kryon/text";
TextField :: #import "kryon/text_field";
Theme :: #import "kryon/theme";
TitleBar :: #import "kryon/title_bar";
Toggle :: #import "kryon/toggle";
#import "kryon/control_props"
#import "kryon/geometry"
#import "kryon/session"
#import "kryon/tree"
#import "notes"
#import "widgets"
started: bool;
dark: bool;
showcase: bool;
draft_bytes: [64]u8;
draft: TextField.State;
no_menu: []Dropdown.Option;
#program_export
Frame :: (session: Session, viewport: Rectangle) -> s32 {
if !started { draft.bytes = draft_bytes[:]; dark = Theme.CurrentTheme().dark; started = true }
screen := Layout.Draw(session, Layout.Props.{.bounds = viewport})
if !screen.opened { return 0 }
AppBar(session)
body := Layout.Draw(session, Layout.Props.{.gap = Layout.Gap(.ThemeMetricSpace3),
.gap_override = true, .padding = Layout.Gap(.ThemeMetricSpace4), .padding_override = true})
if body.opened {
if showcase { Widgets(session) } else { NotesScreen(session) }
unused End(session)
}
unused End(session)
return 0
}
AppBar :: (session: Session) {
height := Theme.CurrentThemeMetric(.ThemeMetricControlHeightLarge) + Theme.CurrentThemeMetric(.ThemeMetricSpace3)
slot := Layout.Stack(session, Layout.Props.{.bounds = .{height = height}})
if !slot.opened { return }
bar := TitleBar.Draw(session, TitleBar.Props.{.bounds = slot.bounds, .title = "Notes", .strong_title = true, .trailing_width = 120}, no_menu)
switch := Toggle.Draw(session, Toggle.Props.{.bounds = bar.trailing_bounds, .label = "Dark", .value = dark})
if switch.changed { dark = switch.value; unused Theme.SetThemeMode(dark) }
unused End(session)
}
NotesScreen :: (session: Session) {
control := Theme.CurrentThemeMetric(.ThemeMetricControlHeightMedium)
row := Layout.Row(session, Layout.Props.{.bounds = .{height = control},
.gap = Layout.Gap(.ThemeMetricSpace2), .gap_override = true})
if row.opened {
add := Button.Props.{.label = "Add", .tone = .ButtonToneAccent, .emphasis = .ButtonEmphasisFilled}
add.bounds.width = Button.ButtonMeasure(add).width
field := TextField.Bind(session, *draft, TextField.Props.{.placeholder = "Write a note",
.label = "Note", .bounds = .{width = row.content.width - add.bounds.width - cast(float32)row.gap}})
if Button.Draw(session, add) == 1 || field.committed {
if AddNote(TextView(draft_bytes[0:draft.length])) {
draft.length = 0; draft.cursor = 0; draft.anchor = 0; draft.scroll_x = 0
}
}
unused End(session)
}
Text.Draw(session, Text.Props.{.bounds = .{height = control}, .text = NoteCountText()})
for i: 0..note_count - 1 {
slot := Layout.Stack(session, Layout.Props.{.bounds = .{height = control + 2.0 * Theme.CurrentThemeMetric(.ThemeMetricSpace3)}})
if slot.opened {
card := Card.Draw(session, Card.Props.{.bounds = slot.bounds, .variant = .CardOutlined})
Text.Draw(session, Text.Props.{.bounds = card.content, .text = NoteAt(i)})
unused End(session)
}
}
if Button.Draw(session, Button.Props.{.label = "All widgets", .bounds = .{height = control}}) == 1 { showcase = true }
}
```
## One line per widget
`Button.Draw` returns 1 on a click; value widgets return `.changed` and the value.
```zi
// file: src/widgets.zi
Button :: #import "kryon/button"; // .label .tone .emphasis .size .disabled
Checkbox :: #import "kryon/checkbox"; // .label .checked -> .changed .checked
Chip :: #import "kryon/chip"; // .label .selectable .dismissible -> .changed .dismissed
Layout :: #import "kryon/layout";
ListItem :: #import "kryon/list_item"; // .title .subtitle .leading_name .trailing -> .clicked
Progress :: #import "kryon/progress"; // .min .max .value .label
Radio :: #import "kryon/radio"; // .label .checked -> 1 when picked
Skeleton :: #import "kryon/skeleton"; // .shape .now: a pulsing placeholder
Slider :: #import "kryon/slider"; // DiscreteSlider: .value .min .max -> .changed .value
Text :: #import "kryon/text"; // .text .size .wrap .align .strong
Theme :: #import "kryon/theme";
Toggle :: #import "kryon/toggle"; // .label .value -> .changed .value
#import "kryon/control_props"
#import "kryon/geometry"
#import "kryon/session"
#import "kryon/tree"
#import "layouts"
checked: bool;
choice: s32;
level: s32 = 3;
on: bool = true;
Slot :: (session: Session, height: float32) -> Layout.LayoutContainer {
return Layout.Stack(session, Layout.Props.{.bounds = .{height = height}}) // draw into it, then End
}
Widgets :: (session: Session) {
h := Theme.CurrentThemeMetric(.ThemeMetricControlHeightMedium)
unused Button.Draw(session, Button.Props.{.label = "Save", .bounds = .{height = h}, .tone = .ButtonToneAccent, .emphasis = .ButtonEmphasisFilled})
box := Checkbox.Draw(session, Checkbox.Props.{.label = "Remember me", .checked = checked, .bounds = .{height = h}})
if box.changed { checked = box.checked }
switch := Toggle.Draw(session, Toggle.Props.{.label = "Sync", .value = on, .bounds = .{height = h}})
if switch.changed { on = switch.value }
if Radio.Draw(session, Radio.Props.{.label = "Weekly", .checked = choice == 1, .bounds = .{height = h}}) == 1 { choice = 1 }
slider := Slot(session, h)
if slider.opened {
moved := Slider.DiscreteSlider(session, Slider.DiscreteSliderProps.{.semantic_label = "Level", .value = level, .min = 1, .max = 5, .bounds = slider.bounds})
if moved.changed { level = moved.value }
unused End(session)
}
bar := Slot(session, 8)
if bar.opened { Progress.Draw(session, Progress.Props.{.max = 5, .value = level, .bounds = bar.bounds}); unused End(session) }
unused Chip.Draw(session, Chip.Props.{.label = "Design", .selectable = true, .selected = on})
unused ListItem.Draw(session, ListItem.Props.{.title = "Ada", .subtitle = "Profile", .leading_name = "Ada Lovelace", .trailing = .ListTrailingChevron})
Skeleton.Draw(session, Skeleton.Props.{.shape = .SkeletonLine})
Layouts(session)
}
```
Also: `kryon/text_field` (`Bind(session, *state, props)`), `kryon/card`
(`.variant` -> `.content`), `kryon/title_bar` (`.trailing_width` ->
`.trailing_bounds`), `kryon/box` (`.fill .border .radius`), `kryon/dropdown`
(`Draw(session, props, options)`), `kryon/modal` (`opened` -> `End`,
`.dismissed`), `kryon/avatar` (`.name`), `kryon/image` (`.asset_path .fit`),
`kryon/badge`, `kryon/toast`, `kryon/scroll`; `ziran api kryon/<path>` prints an API.
## Layout recipe
```zi
// file: src/layouts.zi
Button :: #import "kryon/button";
Flow :: #import "kryon/flow";
Grid :: #import "kryon/grid";
Layout :: #import "kryon/layout";
#import "kryon/geometry"
#import "kryon/grid_props"
#import "kryon/session"
#import "kryon/tree"
Layouts :: (session: Session) {
gap := Layout.Gap(.ThemeMetricSpace2)
size := Button.ButtonMeasure(Button.Props.{.label = "OK"}) // a child's natural size
row := Layout.Row(session, Layout.Props.{.bounds = .{height = size.height}, .gap = gap, .gap_override = true})
if row.opened { // row children: width set, height fills
unused Button.Draw(session, Button.Props.{.label = "OK", .bounds = .{width = size.width}})
unused Button.Draw(session, Button.Props.{.label = "Cancel", .bounds = .{width = size.width}})
unused End(session)
}
sizes: [2]Rectangle = .[size, size]; measured := Layout.LayoutContentBounds(Rectangle.{}, .FlexColumn, sizes[:], gap)
column := Layout.Draw(session, Layout.Props.{.bounds = .{height = measured.height}, .gap = gap, .gap_override = true})
if column.opened {
for i: 0..1 { unused Button.Draw(session, Button.Props.{.label = "Item", .bounds = .{height = size.height}}) }
unused End(session)
}
items: [4]GridItem = .[.{height = 40}, .{height = 40}, .{height = 40}, .{height = 40}]
grid := Layout.Grid(session, GridProps.{.columns = 2, .gap = gap}, items[:])
if grid.container.opened { // GridStep hands out each cell; spans via .column_span
cursor := grid.cursor
for i: 0..3 { cursor = Grid.GridStep(cursor, items[i].height, items[i].column_span); unused Button.Draw(session, Button.Props.{.label = "Cell", .bounds = cursor.item}) }
unused End(session)
}
flow := Flow.Draw(session, Flow.Props.{.bounds = .{height = 2.0 * size.height}, .gap = gap})
if flow.opened { // wraps measured children into rows
for i: 0..5 { unused Button.Draw(session, Button.Props.{.label = "Chip", .bounds = size}) }
unused End(session)
}
}
```
## Theme tokens
| Token | Use |
| --- | --- |
| `Layout.Gap(.ThemeMetricSpace1)` … `Space6` | 4, 8, 12, 16, 20, 24 px of gap or padding |
| `Theme.CurrentThemeMetric(.ThemeMetricControlHeightMedium)` | control height; also `Small`, `Large` |
| `.ThemeMetricTextXS` `TextSM` `TextBody` `TextLG` `Heading1`…`Heading4` | font sizes for `Text.Props.size` |
| `StyleTokenColor("canvas" \| "surface" \| "border" \| "text")` | palette colors (`kryon/drawing_props`) |
| `CssSheetLoad(*sheet, StylePackMaterial())`, `CssSheetInstall` | a look preset from `css/style_pack_material` (also `classic`, `lightfield`); see the starter's `src/look.zi` |
## Drive it in a test
`env KRYON_TEST_DRIVER=1 ziran build && ziran run --project --target=c tests/notes_test.zi`:
```zi
// file: tests/notes_test.zi
#import "notes"
#import "kryon/private_display"
#import "kryon/test_driver_client"
#import "std/file"
failures: s32;
Expect :: (ok: bool, what: string) {
if !ok { failures += 1; print("FAIL: %\n", what) }
}
main :: () -> s32 {
Expect(NoteCountText() == "No notes yet", "starts empty") // the model, directly
display := OpenPrivateDisplay(800, 600, "build/xvfb.log")
if !display.valid { print("FAIL: %\n", display.error); return 1 }
defer ClosePrivateDisplay(*display)
driver := DriverOpen("build/driver")
arguments: [1]string = .["./build/notes-desktop"]
extra: [1]string = .[DriverEnvironment(*driver)]
app := StartOnDisplay(*display, arguments[:], extra[:], "", "build/app.log")
if !app.started { print("FAIL: the app did not start\n"); return 1 }
defer { unused StopOwnedProcess(*app, 5000) }
DriverWatch(*driver, app.pid, "build/app.log")
if FindOwnedWindow(*display, app.pid, 15000) == 0 { print("FAIL: no window\n"); return 1 }
Expect(DriverWait(*driver, .{label = "No notes yet"}, 10000), "empty list")
Expect(DriverPress(*driver, .{role = "text_field"}), "focus the field")
Expect(DriverType(*driver, "Buy milk"), "type a note")
Expect(DriverPress(*driver, .{label = "Add", role = "button"}), "press Add")
Expect(DriverWait(*driver, .{label = "Buy milk"}, 5000), "the note shows")
Expect(DriverPress(*driver, .{label = "All widgets", role = "button"}), "open all widgets")
Expect(DriverWait(*driver, .{label = "Remember me"}, 5000), "the widgets screen shows")
return ifx failures == 0 then 0 else 1
}
```
Selectors: `.{label = "...", role = "button" | "checkbox" | "text_field" | "text",
index = n}`. `DriverWait` polls until its timeout; a failure prints the labels.
-18
View File
@@ -1,18 +0,0 @@
# Clipboard state
`src/ui/clipboard.zi` is a checked, portable UI value module. Applications
keep a `ClipboardState` and own the bytes referenced by its strings. A platform
host supplies system clipboard observations with `ClipboardObserve` and reads
`ClipboardPendingWrite` to apply requested OS writes. After a successful OS
write, it calls `ClipboardWriteCompleted`. Pending writes take precedence over
older host observations.
`ClipboardCopySelection` updates the primary selection and requests a system
write for nonempty text. Copying an empty selection clears the primary value
without erasing the current system value. `ClipboardRead` selects system,
primary, or primary with system fallback. The checked text widgets return
copy, cut, and paste intents; the application handles those intents using this
state and its platform host.
OSC 52 and bracketed paste are terminal protocols. The Terminal application
implements them; Kryon does not.
-105
View File
@@ -1,105 +0,0 @@
# Kryon portable components
A Kryon component is a separately bundled Ziran entry plus its declared host
capabilities. `ComponentHost` owns stable namespace/name identities and up to
sixteen live components. All components share the host's retained tree, input
session, style state, paint queue and renderer. Their owned widget state stays
inside each ZX instance.
## Lifecycle
Open a component with `ComponentHostOpen`, run slots together with
`ComponentHostFrame`, and replace one with:
```ziran
ComponentHostReplace :: (host: *ComponentHost, id: u64, zx: []u8) -> bool
```
`ComponentHostAcquire`, `ComponentHostHandleValid`,
`ComponentHostCloseHandle`, `ComponentHostLiveBytes` and `ComponentHostClose`
complete the public lifecycle. Ziran's bundle-component ABI checks code and
capability identity. Kryon additionally records each admitted capability's
typed ABI descriptor per slot.
Replacement opens the candidate outside the live registry, checks its typed
ABI, and migrates its owned state. Verification composes the migrated candidate
on a private session and commits its tree/paint queue without flushing any
raster effects. Staged text editors return clipboard intents without reading or
writing the system clipboard, and staging does not bind audio services. The
active tree, focus, input and framebuffer stay untouched.
The validation frame's state changes are discarded before Ziran atomically
commits replacement. Each component has a stable retained-tree scope, so local
widget keys may repeat in different components. All sixteen slots may be live
while a replacement is staged. A failed ABI, initialization, schema, resource or
verification candidate is closed and the old component remains runnable.
Unrelated slots keep their state and handles. A successful replacement
invalidates old handles.
`COMPONENT_CAPABILITY_HOST`, `COMPONENT_CAPABILITY_INPUT`,
`COMPONENT_CAPABILITY_WIDGET` and `COMPONENT_CAPABILITY_TREE` are independent
grants. A component that imports only text therefore does not carry button or
renderer code merely because another slot uses them.
State migration matches portable global values by module and name. Scalars
move directly; the recursive matcher also supports matching owned strings,
fixed arrays and nested records by field name and type. Borrowed pointers and
slices are rejected. The replacement's `component_schema_version` in its entry module is retained
and must meet the slot's minimum version. Other matching globals migrate. New globals keep their initialized values.
The counter test fixtures preserve a nested record, an owned string and a fixed
array as well as scalar state; the replacement keeps its new initialized
suffix field.
`ComponentHostLiveBytes` returns Ziran's owned portable-value payload bytes.
It is not immutable code bytes, bundle bytes, renderer memory or process RSS.
## Local integration test
Replacement versions, status guests, and deliberate failures live under
`tests/fixtures/component_*`. They are test inputs, separate from the public
component usage examples.
Run `env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS sh tests/ziran_component_host_test.sh`.
The test builds each selective guest from both source and saved IR and compares
ZX bytes. A native Ziran host runs two live components into the retained tree
and CPU pixmap renderer. It checks interaction, nested-state migration,
ABI/init/schema/resource and migrated-frame rejection, unchanged pixels/focus/
queued input on rollback, staged clipboard isolation with a live-copy positive
control, independent local keys, stale handles and replacement
with every registry slot occupied. It reports bundle/gzip size, swap/frame time,
owned-value bytes and process peak RSS. These are local native/portable-VM
results; they do not establish Android device integration.
## Browser integration test
Run `env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS YUE_DESKTOP_RECOVERY=0 PYTHONDONTWRITEBYTECODE=1 python3 tests/component_browser_test.py`.
The dedicated Zi/Wasm host uses the production `ComponentHost`, `WidgetHost`,
Canvas2D renderer and canonical Ziran browser runtime. A disposable headless
Chromium profile receives actual pointer and key events. WebGL is disabled and
all WebGL context requests are counted. Source and saved-IR guest bundles must
match byte for byte.
The test proves migrated state, old-handle invalidation, independent B text
input after swapping A, focus and queued-input continuity, and unchanged live
pixel hashes through ABI/schema/resource/initialization/truncation and migrated
render rejection. The same clipboard-copy candidate is accepted with initial
state and rejected with changed state, proving the render verifier executed.
Staging performs zero clipboard calls; a normal editor copy reaches the real
browser clipboard API as a positive control. It reports measured browser swap
time and owned-value bytes. No visible desktop or Browser MCP is used.
## Caller-owned widget state
TagInput, OneTimeCode, InlineEdit, ScrubField, MoneyField and ShortcutRecorder,
and Tooltip, Sheet, CommandPalette, HoverCard, ConfirmPopover and GuidedTour
share their canonical native composition with hosted guests. The boundary
passes typed props and owned state values and returns both updated state and
the widget result. No caller pointer crosses the boundary. Command, tour and
initial-tag slices are decoded into bounded host storage. SheetBegin/SheetEnd
also preserve the host scope stack for caller-composed content.
The component tests edit all six input states, exercise all six overlays, then
reject a clipboard-producing candidate and migrate those records to a second
ZX version. The native CPU renderer and actual Canvas2D browser host both use
this fixture. State storage bounds are validated before composition; hosted
TagInput currently permits 32 tags, matching its 2048-byte storage at 64 bytes
per tag.
-46
View File
@@ -1,46 +0,0 @@
# Composition input
Kryon's checked `TextField` and `TextArea` accept raw composition events in
`props.input.composition_event`. They return the next `CompositionState` and,
for a commit, a normal byte-range edit. The caller owns the committed text and
applies that edit before the next frame.
`composition_input.zi` exposes `SampleComposition()` as an ordinary Ziran
library function. It calls the platform's `PollComposition` capability and
returns a `CompositionSample`. Convert an available sample with
`CompositionEventForSample(sample)` and pass it to the focused text widget.
An unavailable sample converts to a no-op event. Events have the same phase
numbers as the platform input phases: start 1, update 2, commit 3, cancel 4.
`src/backend/composition_queue.zi` implements a single-threaded queue for up
to 16 pending events. `BeginCompositionFrame`, `SubmitComposition`, and
`TakeComposition` manage ordering, owned byte copies, and UTF-8 truncation.
The queue is tested from source and saved `.zir` on C and Go targets.
Portable applications bind `composition_input:PollComposition` to an ordinary
Ziran provider with `ziran bundle --bind`; the checked test uses this route for
source and saved `.zx` execution. A native platform host may implement the
same `PollComposition() -> CompositionSample` function directly. The returned
text must stay alive while the caller uses it. A caller that retains
`CompositionState.text` must copy the bytes into its own storage before the
provider releases them. Kryon owns composition decisions, preedit paint, and
commit ranges; platform adapters own event delivery.
## Graphemes and native shaping
TextField and TextArea cursor movement, deletion, selection boundaries and
wrapping use the standard library's Unicode 17 grapheme segmentation. This
keeps combining accents, family emoji, modifiers, regional-indicator flags
and Indic joins intact, including joins across preedit segments. Existing
`max_codepoints` limits continue to count Unicode scalars.
The native Cairo host uses Pango for shaping, bidirectional placement and
font fallback. Caret measurement uses the full shaped line rather than a
separately shaped prefix. `tests/native_text_test.sh` checks combining marks,
Arabic joining, Hebrew caret/hit positions and long text through source/saved IR and C.
Logical Left/Right movement is still by grapheme order. Mixed bidirectional
selection uses a single highlight rectangle, and separately styled preedit
runs are not shaped as one joined run. Pixmap and other hosts retain
their own font/rendering capabilities; Cairo shaping does not imply all-host
bidirectional support.
-17
View File
@@ -1,17 +0,0 @@
# Cursor input
`src/ui/cursor.zi` owns cursor shape choice and priority. An application keeps
one `CursorFrame` per window. At the start of a frame, call
`CursorBeginFrame(state)`. For hovered widgets, call `CursorRequest(state,
shape)`, optionally using `CursorShapeForWidget(kind, disabled)` to choose the
shape. The latest request at the highest priority wins; resize shapes outrank
clickable, text, and disabled shapes. At the end, call `CursorEndFrame(state)`
and retain `decision.state`. When `decision.apply` is true, the application
applies `decision.state.applied` to its own cursor API.
No Kryon host callback is required. The platform maps the requested shape to
its own cursor API; it does not decide which widget gets which shape. The
default, text, clickable, resize, and disabled shape numbers are 0, 2, 4,
5–9, and 10.
This checked path is ordinary Ziran and returns only values.
-36
View File
@@ -1,36 +0,0 @@
<!DOCTYPE html>
<!-- Generated by scripts/feature-matrix-html.py. DO NOT EDIT MANUALLY. -->
<html><head><meta charset="utf-8">
<title>Kryon Feature Matrix</title>
<style>
body{font-family:system-ui,sans-serif;max-width:1100px;margin:2rem auto;padding:0 1rem;color:#1a1a1a;background:#fafafa}
h1{border-bottom:3px solid #333;padding-bottom:.4rem} h2{margin-top:2.2rem;border-bottom:1px solid #ccc;padding-bottom:.25rem}
h3{margin-top:1.6rem;color:#333}
table{border-collapse:collapse;margin:1rem 0;font-size:.92rem;width:100%}
th,td{border:1px solid #bbb;padding:.42rem .6rem;text-align:left;vertical-align:top}
th{background:#2b2b2b;color:#fff;position:sticky;top:0}
tr:nth-child(even) td{background:#f2f2f2}
td.ok{background:#d9f2dd !important} td.part{background:#fdeebc !important}
td.no{background:#fbd5d2 !important} td.na{background:#e8e8e8 !important;color:#888}
code{background:#eee;padding:.08rem .3rem;border-radius:3px;font-size:.85em}
pre{background:#222;color:#ddd;padding:1rem;border-radius:6px;overflow-x:auto}
li{margin:.25rem 0}
</style></head><body>
<h1>Kryon feature matrix</h1>
<p>This table describes the maintained Ziran library and hosts. Kryon is imported by a Ziran application; it is not a language or a built-in Ziran runtime. Ziran owns compilation and portable <code>.zx</code> execution. See <a href="ARCHITECTURE.md">ARCHITECTURE.md</a> and <a href="BACKENDS.md">BACKENDS.md</a> for the module and host boundaries.</p>
<h2>Library packages</h2>
<table>
<tr><th>Package</th><th>Ziran source</th><th>Native code generation</th><th>Package verification</th></tr>
<tr><td class="">Core UI (<code>src/ui</code>)</td><td class="ok">✅ <code>.zi</code> modules listed in <code>modules.txt</code> and named package exports</td><td class="ok">✅ C and Go generation in <code>make</code></td><td class="ok">✅ <code>make test</code> builds the library and runs source, saved <code>.zir</code>, and <code>.zx</code> behavior tests</td></tr>
</table>
<p>The generated C archive is a build output of Ziran source. Behavior tests use Ziran hosts in <code>tests/*_host.zi</code>. Code generation verifies that a module lowers for a target; it does not prove that every native host runs on that target.</p>
<h2>Application hosts</h2>
<table>
<tr><th>Backend</th><th>Implementation</th><th>Input and presentation verification</th><th>Current status</th></tr>
<tr><td class="">Terminal</td><td class=""><code>src/backend/terminal_run.zi</code></td><td class="">Private PTY project test covers ASCII, UTF-8, invalid input, and escape sequences</td><td class="ok">✅ supported</td></tr>
<tr><td class="">Desktop</td><td class=""><code>src/backend/desktop_run.zi</code></td><td class="">Private Xvfb project test covers image capture, keyboard, UTF-8 text, and wheel input</td><td class="ok">✅ supported on the tested Linux host</td></tr>
<tr><td class="">Web Canvas</td><td class=""><code>src/backend/canvas_run.zi</code></td><td class="">Headless Chromium checks Canvas2D pixels, clips, input, textures, fonts, lifecycle, WebAudio, and file behavior</td><td class="ok">✅ supported through Emscripten on the tested browser</td></tr>
<tr><td class="">Android</td><td class="">app <code>src/main.zi</code> + <code>src/backend/android_run.zi</code></td><td class=""><code>tests/ziran_android_device_test.sh</code> checks the device text, lifecycle, and inset protocol with the Java side stubbed; a manual emulator run verifies install, rendering, touch, and back</td><td class="ok">✅ supported through NativeActivity with direct ANativeWindow pixel presentation</td></tr>
</table>
<p>The desktop project test (<code>make desktop-project-test</code>) uses a private Xvfb display. The Canvas2D project test runs in <code>make test</code> and launches only private headless Chromium. <code>make zx-window-test</code> covers bare-window bundles through the native desktop player and host library. Code generation alone does not establish platform execution.</p>
</body></html>
-32
View File
@@ -1,32 +0,0 @@
# Kryon feature matrix
This table describes the maintained Ziran library and hosts. Kryon is
imported by a Ziran application; it is not a language or a built-in Ziran
runtime. Ziran owns compilation and portable `.zx` execution. See
[ARCHITECTURE.md](ARCHITECTURE.md) and [BACKENDS.md](BACKENDS.md) for the
module and host boundaries.
## Library packages
| Package | Ziran source | Native code generation | Package verification |
| --- | --- | --- | --- |
| Core UI (`src/ui`) | ✅ `.zi` modules listed in `modules.txt` and named package exports | ✅ C and Go generation in `make` | ✅ `make test` builds the library and runs source, saved `.zir`, and `.zx` behavior tests |
The generated C archive is a build output of Ziran source. Behavior tests use
Ziran hosts in `tests/*_host.zi`. Code generation verifies that a module lowers
for a target; it does not prove that every native host runs on that target.
## Application hosts
| Backend | Implementation | Input and presentation verification | Current status |
| --- | --- | --- | --- |
| Terminal | `src/backend/terminal_run.zi` | Private PTY project test covers ASCII, UTF-8, invalid input, and escape sequences | ✅ supported |
| Desktop | `src/backend/desktop_run.zi` | Private Xvfb project test covers image capture, keyboard, UTF-8 text, and wheel input | ✅ supported on the tested Linux host |
| Web Canvas | `src/backend/canvas_run.zi` | Headless Chromium checks Canvas2D pixels, clips, input, textures, fonts, lifecycle, WebAudio, and file behavior | ✅ supported through Emscripten on the tested browser |
| Android | app `src/main.zi` + `src/backend/android_run.zi` | `tests/ziran_android_device_test.sh` checks the device text, lifecycle, and inset protocol with the Java side stubbed; a manual emulator run verifies install, rendering, touch, and back | ✅ supported through NativeActivity with direct ANativeWindow pixel presentation |
The desktop project test (`make desktop-project-test`) uses a private Xvfb
display. The Canvas2D project test runs in `make test` and launches only private
headless Chromium. `make zx-window-test` covers bare-window bundles through
the native desktop player and host library. Code generation alone does not
establish platform execution.
-117
View File
@@ -1,117 +0,0 @@
# Frame capture, replay and inspection
## Native fixture preview
To capture the whole app instead, without a fixture, run
`kryon run shot --png FILE.png --width PX --height PX --theme light|dark`
([Projects](PROJECTS.md)); it writes the same PNG and JSON.
From a Linux project with a desktop C99 profile, run:
```sh
kryon preview controls --theme light --width 800 --height 480 --output build/controls.png
ziran tool kryon preview controls --theme dark --width 360 --height 640 --output build/controls-dark
```
`--output` accepts a PNG path or a prefix, relative to the project root or
absolute. Its parent directory must exist. Both forms write `<prefix>.png`
and `<prefix>.json`. Each dimension accepts 1–4096 pixels. The project default
profile is used unless `--profile NAME` selects another desktop C99 profile.
Register `previews` in `[package] module_roots`, for example
`module_roots = ["src", "previews"]`. Each fixture is a uniquely named module
at `previews/<fixture>.zi`. Its entry is the same frame export used by the
default desktop host:
```zi
Button :: #import "kryon/button";
#import "kryon/geometry"
#import "kryon/session"
#program_export
Frame :: (session: Session, viewport: Rectangle) -> s32 {
unused Button.Draw(session, .{.key = cast(u64)7,
.bounds = .{16.0, 16.0, viewport.width - 32.0, 36.0}, .label = "Save"})
return 0
}
```
Return zero after composing the frame. Fixture code can import the project's
ordinary view modules and assets. Use explicit sample data and the supplied
viewport. The preview runs offscreen with the native Cairo renderer, neutral
input, zero frame time and a fixed light or dark palette with reduced motion.
A frame can be recomposed while smooth image copies finish, so keep fixture
state stable across calls. Repeat runs with the same fixture, assets and
renderer/font versions produce the same output when the fixture uses fixed
data and host-supplied time. The command exits after capturing the artifacts.
The JSON contains `version`, `width`, `height` and `nodes` in retained-tree
order. Each node has `index` and `parent` (`-1` at the root), `kind`, `label`
where available, `x`, `y`, `width`, `height`, and clipped `visible_*` bounds.
`role` uses the semantic role when available and the widget kind otherwise.
`key` is an unsigned 64-bit widget key, which a consumer
should parse without losing integer precision. Where supplied, `focus_id`
identifies a focus target. Bounds are viewport pixels reported to one decimal
place. Secure field values are redacted as in test-driver inspection.
## Portable frame replay
`EndFrameCapture(session)` commits a frame and records its retained nodes and
resolved paint commands before emitting raster effects. It replaces
`EndFrame(session)` in a capture-enabled application. Bind all five capture
capabilities declared in `frame_capture.zi`: `RecordFrameStart`, `RecordNode`,
`RecordPaint`, `RecordFrameEnd` and `RecordFrameFailure`. A host that binds
only some fails with `missing host capability: frame_capture:RecordFrameFailure`;
`tools/frame-replay.sh` builds `tools/frame_replay_cli.zi`, which binds all five.
A rejected frame reports its status, message, widget key and kind and emits no
raster effects. Ordinary `EndFrame()` needs no capture bindings.
Run a portable bundle with:
```sh
tools/frame-replay.sh app.zx app trace.txt capture.json
tools/frame-inspect.sh capture.json 3 1
tools/frame-inspect.sh --diff baseline.json candidate.json
```
The inspector prints a frame's inputs and nodes, or a selected node with its
paint commands, colors, font sizes and clips. Comparison reports the first
changed JSON field, ignores object key order and preserves exact integer
identities. Exit codes are 0 for matching/valid frames, 1 for differences or
rejected frames, and 2 for invalid arguments or files. Files are limited to
64 MiB each.
The entry takes no arguments, returns an integer, and samples exactly one
input record per frame. Declare a module-local `PollFrameInput() -> FrameInput` and use the
twenty-column format:
```
x y down pressed released secondary_down secondary_pressed secondary_released key modifiers wheel width height elapsed_ms text_hex ime_phase ime_cursor ime_selection ime_hex clipboard_hex
```
Boolean fields are 0 or 1. Modifiers use Shift=1, Control/Command=2, Alt=4.
Key codes are the same codes accepted by `KeyboardSend`. Composition phases
are none=0, start=1, update=2, commit=3, cancel=4. Composition cursor and
selection lengths count UTF-8 bytes. Text, composition and clipboard payloads
are hexadecimal UTF-8 bytes, with `-` for empty; each payload is bounded to
256 bytes. Coordinates and wheel values must be finite; the viewport is
positive and elapsed milliseconds nonnegative. Blank lines and `#` comments
are accepted. A trace holds at most 1,024 samples within 1 MiB.
`FrameInputApply` supplies session pointer, key, modifier and wheel inputs;
`FrameInputField` converts text and composition into a `TextField.Input`.
Applications explicitly use the recorded viewport and elapsed time rather
than reading wall time. Clipboard reads use the recorded input and clipboard
writes appear in the JSON. Captures use format version 2.
Capture includes focus, read-only state, selection and committed editor text.
Secure editor values, lengths and selections are redacted. A document larger
than 64 KiB retains its length but omits its full value from the capture.
The application still owns state and applies the edits returned by widgets.
Replay uses fixed font measurements and a headless raster sink, so it checks
UI decisions rather than platform-specific pixels or font fallback.
`tests/ziran_frame_capture_test.sh` and `tests/ziran_frame_input_test.sh`
compare source and saved-IR bundles and exercise edits, IME, clipboard,
resizing, rejection diagnostics and inspection. The runners use locked,
stable build directories and scrub the desktop environment.
-141
View File
@@ -1,141 +0,0 @@
# Game touch controls
Picture cursors, the test driver, on-screen joystick, direction pad and swipe
feedback for touch-first applications. Read this when building a game UI or a
driven test.
Import `kryon/cursor`:
| Call | Effect |
| --- | --- |
| `CursorSet(session, CursorProps) -> bool` | A session's own request; it wins over the application cursors |
| `CursorSetDefault(CursorProps) -> bool` | The application cursor every session inherits; replaces the default, arrow, clickable and disabled widget shapes, while text, crosshair and resize shapes still show through |
| `CursorSetPointing(CursorProps) -> bool` | The application's pointing cursor, shown only where a click does something: over clickable widgets and over targets the app marks with `CursorHover`. Without one, clickable shows the application cursor |
| `CursorHover(session, shape) -> bool` | Marks the shape under the pointer for a target the app hit-tests itself |
A request persists until the next deliberate change: repeating it every frame
changes nothing, frames never clear it, and the empty request `.{}` withdraws
it. Requests copy their asset path; disposing or closing a session drops its
request.
A target the app draws and hit-tests itself (a painted hotspot, a field)
reports the shape under the pointer with `CursorHover(session, shape)` while it
builds the frame, from the same test that decides its clicks. A frame keeps its
highest-priority mark, and its commit replaces the previous frame's, so the
cursor changes only when the hovered target does; a retained, cancelled or
failed frame keeps the committed mark, and a frame without one shows the
default. A widget with its own shape under the pointer wins over the mark,
except a disabled one the app's mark covers. A `Press` the app refines with its
own hit test, such as a painted shape inside its bounds, sets
`Press.Props.cursor` to `CursorArrow` while the pointer is off that shape; only
the cursor changes, never presses, touch or keys. Invalid shapes and inactive
sessions return false.
```zi
#import "kryon/cursor"
// Once at startup: a calm arrow everywhere, a hand only where a click works.
unused CursorSetDefault(CursorProps.{.asset_path = "assets/arrow.webp",
.width = 32, .height = 32, .hotspot_x = 6, .hotspot_y = 2})
unused CursorSetPointing(CursorProps.{.asset_path = "assets/hand.webp",
.width = 32, .height = 32, .hotspot_x = 8, .hotspot_y = 1})
// Each frame, from the hit test that opens the painted door.
if DoorAt(pointer.x, pointer.y) { unused CursorHover(session, cast(s32)CursorShape.CursorClickable) }
// A deliberate tool state; .{} returns to the application cursors.
unused CursorSet(session, CursorProps.{.asset_path = "assets/can.webp",
.width = 32, .height = 32, .hotspot_x = 4, .hotspot_y = 6})
```
`width`, `height` and the integer hotspot are logical units, each size 1–128,
independent of the source image size and UI zoom; the hotspot is measured from
the top left and must be inside. Hosts rasterize at their own pixel density
(desktop `XCURSOR_SIZE`/24, web `devicePixelRatio`), so give a source at least
two to four times the logical size. `asset_path` is at most 4095 bytes with no
NUL. With no asset, use `shape` (the `CursorShape` values 0–10) or `hidden`;
size and hotspot must then be zero. An asset and `hidden` together are invalid.
Invalid requests return false and keep the last valid request. A missing or
undecodable image falls back to the requested system shape; only an explicit
hidden request hides the pointer. `CursorResolve(session, widget_shape)` returns
what a host shows.
The SDL/Cairo desktop host applies a real bitmap cursor scoped to its own
windows, caches decoded cursors, and calls the system only when the resolved
cursor changes, so switching between requests never flickers. X11 receives
premultiplied pixels and other drivers straight alpha, so soft edges show no
light fringe. It restores the system cursor on close. Canvas draws the
image into a CSS cursor (a 1x image plus an `image-set` density entry) with the
same hotspot on the canvas. Other hosts
retain their system pointer; touch feedback is drawn by the application. These
requests never move, lock, grab or warp a pointer.
A picture cursor needs the host's image decoder. Importing `kryon/cursor`, as
an application does to request a cursor, registers the decoder through the
`CursorPictureHost(asset_path, width, height, pixels, premultiplied) -> bool`
host capability; the cursor module the hosts themselves import does not, so a
program that requests no cursor links no image decoder. A host that shows no
picture cursors exports the capability and returns false, as the terminal and pixmap hosts do, and a custom host linked with a program
that imports `kryon/cursor` exports it too. An application that hosts widget
bundles imports `kryon/cursor` for its guests' picture cursors.
The test driver (`kryon/test_driver`) is test code and an ordinary build
leaves it out: its procedures then pass the platform's input through
unchanged. A build that a test drives defines `KRYON_TEST_DRIVER`, either with
`--define KRYON_TEST_DRIVER` on a direct `ziran` build or by setting the
variable in the environment of `kryon build`. The program then obeys the
directory the same variable names when it runs. A program built without the
driver and started with the variable set stops at once and says how to build
it, so a test fails with the reason instead of waiting for a reply.
On Android, the private `kryon-test-driver` folder activates a compiled test
driver. Normal builds ignore a folder left by an earlier UI test.
A test captures what the app draws with `DriverCapture(driver, path)` (the
`capture path=` command): the desktop host writes its next finished frame to
that file as a PNG, the same raster it shows. Hosts without a raster to read
reply "this host does not capture frames". A custom host captures by writing
its next finished frame to `TestDriverCapturePath()` when that is not "" and
reporting with `TestDriverCaptured(written)`.
Portable hosted apps use `CursorSet` and `CursorHover` with `KRYON_HOSTED_UI`
(the application cursors belong to their host). Their only effects are
`cursor.CursorSetHostedHost` and `cursor.CursorHoverHostedHost`, which marks
only the active session's building frame; `WidgetHostCall` requires the active
`WidgetHostBegin` session. Asset requests must name a normalized packed path
under `assets/`, pass that instance's asset policy and resolve through
its asset resolver. The host copies the resolved path before returning;
no guest image bytes, pointer or native cursor handle crosses this boundary.
An unavailable resolution returns false. Hosts apply the resolved cursor after
committing the frame with `DesktopCursor(session)` or `CanvasCursor(session)`;
the standard loops already do this. Custom hosts must restore cursors before
teardown.
The desktop host selects the native arrow when its window opens, before the
first frame. `DesktopSetIcon(width, height, rgba)` copies straight RGBA into
that host's window icon. Dimensions must be 1–512 and the slice must contain
exactly `width * height * 4` bytes. The caller retains its pixels; theme-aware
applications can pass `GtkIconRaster` output and release it immediately.
The generic desktop player extracts packed assets into a private directory under
`TMPDIR` (an absolute directory that already exists), or the system default when unset,
and removes that directory on normal exit.
`kryon/joystick` provides `SwipeArea` (swipes and taps over a board) and
its `secondary_tap` option reports a right click as a tap at that position.
It is off by default. The same module provides
`Joystick` (a stick to lean). `kryon/direction_pad` provides
`DirectionPad(session, DirectionPadProps)`, a four-way pad like a game
controller's D-pad, drawn in the largest square of its bounds. Directions are
0 left, 1 up, 2 right and 3 down. It returns the arm held (`direction`) and
`step`: true when an arm is pressed or the thumb slides onto another arm,
then while held after twice `repeat_seconds` and at each repeat, like a held
arrow key. The hub stops, and a quick tap steps once. `floating` lays it
over a board: lighter arms and outlined arrows let the pieces under it show
through, and drawn after the board it takes the presses there. It is composed
from `Press`, `Box` and `SvgIcon`, so hosted games can use it.
`DirectionPadBounds(usable_viewport)` places a floating pad at the bottom left
with 24–32 logical units of edge padding and a 168–216 unit side on normal
phone screens, in either orientation. Pass the area inside system insets and
app bars; very small embedded areas shrink the pad to fit.
`joystick.SwipeFeedback(session, SwipeFeedbackProps.{key, gesture, size})`
draws a faint base at a `SwipeAreaResult`'s contact start and a glowing ball
following the finger, clamped to that base. It disappears on release and
does not take input. Draw it after the board; `size` is the base diameter
in logical units (56 by default). The app keeps its movement rules.
-247
View File
@@ -1,247 +0,0 @@
# GTK3 theme rendering on Linux
Native GTK3 theming for a Linux application: query styles, raster CSS
backgrounds, icons, text and native widgets, and manage providers and
invalidation. Read this when your app should look like the desktop GTK theme.
Import `kryon/GtkStyleLinux` only in a Linux native application that links GTK3.
This module reads the current GTK settings, screen CSS providers, icon theme and
Pango fonts. It renders offscreen; the application supplies its selectors, layout,
input and accessibility. Call its functions on the GTK owning thread, and call
`GtkStylePoll()` from a non-GTK event loop to deliver up to 32 pending GLib events.
Pass an ancestor-to-leaf slice of `GtkStyleNode` values.
| `GtkStyleNode` field | Meaning |
| --- | --- |
| `widget_type` | For example `"GtkButton"` |
| `element`, `name` | CSS element and CSS ID |
| `classes: []string` | CSS classes |
| `state: u32` | `GtkStyleNormal`, `GtkStyleActive`, `GtkStylePrelight`, `GtkStyleSelected`, `GtkStyleDisabled`, `GtkStyleFocused` or `GtkStyleChecked`; combine flags for compound states |
| `providers: []GtkStyleProviderAttachment` | Optional. Each attachment carries a live `provider: u64` handle and native `priority: u32`, and applies only to that node's GTK context, including ancestor contexts. At equal priority, GTK gives context providers precedence over screen providers, using its own selector rules |
| `sibling_count`, `sibling_index` | Optional homogeneous sibling group (1–64) and zero-based index for native child selectors; zero count leaves position unspecified. Header measurement builds the same column group, so first/middle/last CSS borders affect its real child allocations |
### Style query and raster calls
| Call | Behavior |
| --- | --- |
| `GtkStyleQuery(nodes, scale)` | Returns `GtkStyleMetrics`: `available`, `foreground` and `background` as RRGGBBAA, `border`, `padding` and CSS `margin` in logical pixels, a copied NUL-terminated `font_family: [256]u8`, logical-pixel `font_size: float64`, Pango `font_weight` and `font_style`, and screen `dpi`. GtkTreeView selectors also expose native `vertical_separator` and `horizontal_separator` style properties. |
| `GtkStyleRaster(nodes, width, height, scale)` | Paints the CSS background and frame. Its bounds are the CSS border box; callers lay out CSS margins separately. |
| `GtkStyleIndicatorRaster(nodes, width, height, scale, indicator)` | Asks GTK to draw the last node's check box (0), radio option (1) or submenu arrow (2, pointing right, or left in a right-to-left context) with `gtk_render_check`, `gtk_render_option` or `gtk_render_arrow`. |
| `GtkStyleRasterRegion(nodes, width, height, scale, x, y, crop_width, crop_height)` | Renders a crop of the original logical CSS box, preserving gradients and borders. Logical boxes can reach 8192 pixels per axis; the allocated crop retains the ordinary 4096-axis and 4,194,304-pixel bitmap limits. |
| `GtkIconRaster(name, size, scale, nodes, force_size = true, styled = false)` | Resolves a named icon using the current GTK icon search path and theme inheritance. PNG, SVG and symbolic icons use GTK's loader; symbolic colors come from the supplied style context. Clear `force_size` to retain the theme's natural artwork, as GtkImage does. Set `styled` with the image's full CSS ancestry to render through GTK's icon surface painter, including native transforms, shadows, direction and state. `GtkIconSize(category)` resolves GTK's menu/toolbar/button size categories. `GtkUserDirectory(index)` returns GLib's borrowed XDG user-directory path. |
### Text, cells and native widgets
| Call | Behavior |
| --- | --- |
| `GtkWidgetMeasure(nodes, text = "", sort_arrow = false, allocation_width = 0, allocation_height = 0, options = .{})` | Returns `available` and minimum/natural width and height for GtkButton, GtkEntry, GtkMenuBar, GtkMenuItem, GtkToolbar, GtkToolButton, GtkStatusbar or a horizontal GtkPaned. It constructs an offscreen hierarchy with the supplied classes, names and providers. Tree-view header selectors use a real GtkTreeViewColumn, including its label and native sort arrow. Menu bars include one item with the supplied label; icon toolbars include one item with the supplied icon name at GTK's large toolbar size. For these containers, `item_x/y/width/height` report GTK's representative child allocation. Zero allocation dimensions use the natural size. Header `item_*` fields describe its label, and `arrow_*` describe its visible sort image. For entries, `text` optionally names the primary icon; `item_x/y` are native layout offsets, `item_width` is the remaining text-area width, `item_height` is the layout height, and `arrow_*` is the icon area. Status bars use `text` as their message and return the label allocation, which follows the actual supplied message, native alignment and ellipsis, so cache it with the message text. The offscreen root is never shown. Entry allocation realizes an offscreen backing surface so GTK can supply its text-area bounds; it creates no visible window. `GtkWidgetMeasureOptions.margin` overrides the final widget's template margins on edges selected by `margin_edges`; the default zero mask preserves all native margins. Combine `GtkWidgetMarginLeft/Right/Top/Bottom`, or use `GtkWidgetMarginVertical` or `GtkWidgetMarginAll`; values use logical pixels. A paned widget includes two empty visible children, so its preferred width measures the native separator without adding application content widths. |
| `GtkCellTextMeasure(nodes, text)`, `GtkCellTextMeasureMany(nodes, texts, width_chars = -1, ellipsize = false)` | Measure actual GtkCellRendererText requisitions in a native GtkTreeView hierarchy. The batch reuses one renderer and reports component-wise maximum minimum/natural dimensions; renderer padding, Pango metrics and optional end ellipsis are included. |
| `GtkTextMeasure(nodes, text, width, scale, font = "", markup = false)` | Returns `available`, logical-pixel `width`, `height` and `baseline`. A zero width measures natural size; a positive width wraps by word or character. |
| `GtkTextRaster(nodes, text, width, height, scale, align, font = "", markup = false, ellipsize = false, snap_y = false)` | Paints Pango text and GTK text shadows onto transparency, vertically centered and clipped to the box. Alignment is 0 left, 1 center or 2 right. An empty `font` uses the computed CSS font; a Pango description overrides it for application settings such as a clock font. Set `ellipsize` for a single line with native Pango end ellipsis instead of wrapping. Set `snap_y` for integer vertical positioning, matching GTK's widget and cell allocations. |
Text layouts use GTK's widget Pango context, including explicit GTK font
settings. Unresolved Cairo font options inherit the native display backend's
defaults, queried from an empty compatible surface, before rasterization.
This preserves the glyphs used by realized GTK widgets when drawing to RGBA.
Native GTK backend adapters can use `GtkNativeReady()` and
`GtkNativeWidgetNodeApply(widget, node)` on the GTK owning thread. The latter
validates selectors/providers and applies them to a borrowed live GTK widget;
the adapter owns its widget lifecycle. `GtkNativeSurfaceBitmap(surface, width,
height)` copies a borrowed Cairo ARGB32 image surface into an owning bitmap.
It checks status, type, format, exact dimensions, stride and allocation bounds;
release the returned buffer with `GtkStyleBitmapRelease`.
### Native scrolled windows
`kryon/GtkScrollLinux` owns offscreen GTK scrolled windows for native scrollbar
layout, adjustments and drawing. `GtkScrollCreate(nodes)` accepts a `GtkWindow`
root, optional `GtkBox`/`GtkGrid` ancestors and a final `GtkScrolledWindow`;
it returns a bounded owning handle, or zero. Release it with
`GtkScrollRelease(handle)`. `GtkScrollCancel(handle)` cancels an owned drag
on focus loss or hiding; valid handles are idempotent. All calls stay on GTK's
owning thread.
`GtkScrollUpdate(handle, props)` takes viewport/content dimensions, offsets,
enabled axes, overlay policy and optional pointer state. Its metrics expose the
actual viewport, bar allocations, opacity, adjustment ranges and slider limits.
Use those allocations for content layout rather than reserving a fixed gutter.
`GtkScrollWheel(handle, delta, horizontal = false)` applies the native discrete
wheel distance immediately. Positive deltas move toward the start. Its page-based
unit follows GTK and its adjustment keeps fractional offsets across notches;
the returned metrics expose the updated values in the same call.
`GtkScrollRaster(handle, horizontal = false, scale = 1)` returns an owning
straight RGBA bitmap for the allocated native bar, at scale 1–4; release it with
`GtkStyleBitmapRelease`. Draw it over content at its reported bar allocation.
`GtkScrollRasterOver(handle, backdrop, horizontal = false, scale = 1)` accepts
a borrowed RGBA backdrop matching the scaled allocation. GTK draws
directly over it on an owned native compatible surface, preserving window
curve coverage and per-layer alpha rounding. The result replaces that backdrop.
`GtkPainterScrollOver(painter, handle, bounds, horizontal = false)` supplies the
painter's current backdrop and clips that replacement to its visible area.
`GtkNativeWidgetRaster(widget, width, height, scale, backdrop)` provides
the same bounded raster operation for a borrowed allocated GTK widget. The
caller retains widget ownership; only newly allocated surfaces are read.
`Scroll.Props.external_scrollbar` and `GridMulti.Props.external_scrollbar` let a
caller supply native scrollbar visuals and input. They preserve the complete
supplied viewport while retaining wheel, keyboard reveal, content dragging and
momentum; the caller synchronizes the resulting offset with its native bars.
`Scroll.Props.immediate_wheel` and `GridMulti.Props.immediate_wheel` opt out of
wheel gliding while retaining drag behavior. The default retains wheel gliding.
`ScrollWheelTake(session, key, bounds, scrolls, horizontal = false)` consumes
the targeted wheel once; horizontal mode includes the sideways wheel.
`GridMulti.Props.preserve_scroll_on_focus` retains a native view's manual offset
when focus returns. Its default keeps the focus reveal; cursor,
navigation, initial-open, layout and viewport changes still reveal the item.
An explicit valid `TreeSetCursor` shape also applies to disabled controls;
loading controls retain their loading cursor policy. Without an override,
disabled controls continue using `CursorDisabled`.
Desktop `PollPointer` and `PollSecondaryPointer` expose the gathered frame
sample, including focus-loss release and cleared held state. Raw SDL collection
stays separate from this published view. On X11, physical button sampling also
recovers transitions missed while another window owns focus; queued event edges
still preserve taps completed between polls. Other SDL drivers keep their
event sampling.
### Composited raster regions
`GtkStyleRasterRegionOver` takes the same box/crop coordinates as
`GtkStyleRasterRegion`, followed by a borrowed straight-alpha RGBA backdrop
matching the scaled crop. CSS background and frame layers draw directly over
that backdrop with Cairo's native rounding. Rendering uses a newly allocated
surface compatible with the GDK window backend, with an image-surface fallback.
The backdrop uploads with Cairo SOURCE; readback maps only that owned surface.
Device scale is normalized before allocation so the supplied CSS scale is
applied once, independently of `GDK_SCALE`. The returned bitmap is owned;
release it with `GtkStyleBitmapRelease`. An empty backdrop means transparent.
`GtkPainterStyleOver(painter, nodes, bounds)` draws those layers on the current
painter pixels and replaces the clipped crop without applying alpha twice.
Toolbar `GtkWidgetMeasure` results include the actual child button rectangle
in `control_*` and image rectangle in `arrow_*`, relative to the toolbar.
### File icons, sizes and dates
`GtkFileIconRaster(path, size, scale, nodes)` resolves a local file's GIO icon
through the active GTK theme, including MIME inheritance, special user folders
and the filesystem root. `GtkFileDescription(path, output)` returns the native
localized content description. `GtkFileLinkTarget(path, output)` queries the
link itself and returns its raw target without following it. These byte-path
APIs accept up to 4095 bytes without NUL; text helpers write NUL-terminated
output and return its byte length, or -1 on failure. The caller must escape
raw filenames and link targets before displaying them. `GtkImageRaster(path,
width, height)` uses installed GdkPixbuf loaders and preserves aspect ratio.
`GtkFormatFileSize(size, output)` uses GLib IEC units. `GtkFormatFileDate(unix_time,
output, style = .LocaleDate, now = -1, domain = "")` uses the local timezone and
locale date format. Its `GtkFileDateStyle.RelativeDate` option uses local calendar
days: Today, Yesterday, weekday names for two through six days ago, and the locale
date otherwise. Zero or invalid timestamps use Unknown in relative mode.
Relative labels use the native gettext catalog named by `domain`, or the
application's default catalog when empty. A negative `now` uses the current time;
an explicit timestamp permits deterministic comparisons and midnight refreshes.
The same formatter is available without GTK initialization as
`kryon/FileDateLinux.FormatFileDate`, with its `DateStyle` enum.
`GtkFileSystemFree(path)`
returns available bytes from GIO, or -1 when unavailable.
`GtkSerializedIconRaster(value, size, scale, nodes)` resolves a serialized GIcon
without discarding its native identity or fallback names. `GtkContentDescription`
accepts a GIO content type and the same output-buffer contract as file descriptions.
### The painter composer
`kryon/GtkPainterLinux` composes these rasters into one managed `Image` per
surface. Own one `GtkPainter`; call `GtkPainterBegin(*painter, session, bounds)`,
`GtkPainterPaint(*painter, nodes, bounds, text = "", kind = 0, align = 0, revision = 0)` and
`GtkPainterEnd(*painter, key)` inside a retained frame; it returns upload success.
`GtkPainterBitmap(*painter, bounds, bitmap)` composites a borrowed native bitmap
at its exact pixel dimensions, with the current clip and draw order. It copies
no ownership into the tile cache; the caller can release or reuse the bitmap
immediately. Invalid dimensions/buffer lengths return false without painting.
Kinds are CSS surface (0),
ellipsized text (1), themed icon (2), local file icon (3), image thumbnail (4),
Pango markup (5), serialized GIcon (6), styled naturally sized themed icon (7),
wrapped text (8), and the theme's own check box (9), radio option (10) and
submenu arrow (11) for the last node, such as `menuitem > check:checked`.
Text snaps to integer positions; thumbnails and natural icons center their
actual bitmap within the allocation. Cached RGBA layers follow Cairo's 8-bit
premultiplied OVER rounding. `revision` invalidates cached file pixels
when caller metadata changes. `clip` is a logical rectangle within the surface. The
painter caches at most 256 CPU tiles and 32 MiB, invalidating them when GTK
settings/providers change. It uploads only changed pixels. Call
`GtkPainterRelease(*painter)` before closing its session; release is idempotent.
Input, semantic labels, layout and file actions remain the application's
responsibility. This module requires an ordinary Kryon raster host.
Large surfaces use an exact, shared 64-pixel region atlas while retaining the
managed image limits. The CPU canvas is bounded to 16,777,216 pixels and 8192
pixels per axis; the atlas holds at most 1024 unique regions (4,194,304 pixels).
`GtkPainterEnd` returns false if allocation or the bounded unique-region budget
cannot represent the surface. Callers must handle that result.
Set `markup = true` to validate and render Pango markup, including styled spans,
bold text and escaped characters. Malformed markup fails without painting.
`GtkMarkupPlain(markup: string, output: []u8) -> s32` uses the same parser to
decode a plain label for accessibility. It returns the UTF-8 byte count excluding
the terminating NUL, or -1 for invalid input or insufficient space. Failure
leaves the output unchanged; success writes a terminating NUL. This helper
requires no display. Parsing performs no file, network or application actions.
Raster calls return an owning `GtkStyleBitmap` with physical `width`, `height`
and straight RGBA8 `rgba` bytes. Upload using `BitmapImageCreate`, then release
the CPU buffer with `GtkStyleBitmapRelease(*bitmap)`. Do not copy owning values.
Release is safe on an empty bitmap and resets its fields. Failure returns an
empty bitmap or metrics with `available = false`, including when no display is
available. Background color metrics alone cannot represent a CSS gradient;
use the raster call for its actual appearance.
Scale is 1–4. Style paths have 1–32 nodes and up to 32 classes per node;
selector strings and font descriptions are at most 255 bytes with no NUL.
Text must be valid UTF-8 without NUL and at most 65,536 bytes. Raster axes are
at most 4096 physical pixels with a 4,194,304-pixel total limit; icon edges are
at most 2048 physical pixels. Icon names cannot be paths.
### CSS providers, dark preference and invalidation
`GtkStyleProviderCreate(css: string) -> u64` parses CSS with GTK's native parser,
without installing it. Zero means failure. `GtkStyleProviderInstall(handle,
priority: u32) -> bool` installs that provider on this process's default GTK
screen. Repeating the same installation is a no-op. A provider can also be
attached to several node contexts at different priorities without screen
installation. `GtkStyleProviderReplace(handle, css) -> bool` parses a fresh
provider before replacing the active one. Parser errors, invalid lengths,
embedded NUL, input above 1,048,576 bytes, and recoverable allocation failures
leave the previous provider and generation unchanged. Empty CSS is valid. GTK/GLib's
own fatal allocation policy remains in effect. CSS may reference resources;
applications choose which CSS they trust.
`GtkStyleProviderRelease(handle) -> bool` removes its screen installation and
releases owned refs. Remove attachments using that handle before the next query;
a stale attachment rejects the whole path. Zero, stale and double release return
false. There are at most 64 live providers and 32 attachments per node. Handles
are process-local, never reused, and must not be persisted. Release works after
display environment variables change, without reinitializing GTK.
`GtkStyleDarkPreferencePush(value: bool) -> u64` temporarily sets this process's
`gtk-application-prefer-dark-theme`. `GtkStyleDarkPreferenceRestore(token) ->
bool` removes that scope. The newest live scope wins, even when older scopes
are restored out of order. The last restore reinstates the original value and
releases the settings reference; the next push captures a fresh original.
There are at most 64 live scopes. Zero/stale tokens fail without changing the
setting. These calls do not modify desktop configuration files or other
processes. Coordinate writes to this same property while scopes are active.
`GtkStyleGeneration() -> u64` changes immediately on successful provider
installation, replacement or release and effective preference changes. Creating
an unattached provider and failed calls do not change it. Cache query, raster,
text and icon results with this generation and the complete path (including
attachments, priorities and states). The bridge itself retains no result cache.
Native GTK settings notifications invalidate generation synchronously, without
retaining a settings owner. A default-settings identity change invalidates
on the next bridge call. Default icon-theme `changed` notifications also
invalidate generation. Unrelated GLib callbacks leave caches valid.
`GtkStylePoll()` returns nonzero once after API invalidation
as well as for delivered events. Call it before checking cached styles. All
provider/settings APIs share the GTK owning thread rule and fail safely without
a display. This opt-in Linux module adds no GTK dependency to portable, WASM,
Windows or Go application imports.
-163
View File
@@ -1,163 +0,0 @@
# Hosted widgets
Running another `.zx` bundle inside your application's window, the widgets a
bundle may draw, and the platform services a hosted or portable app can
import. Read this when embedding a bundle or reaching a platform capability.
An application runs another `.zx` inside its own window with
[`hosted_app`](../src/backend/hosted_app.zi): `HostedAppOpen` takes the
bundle's bytes, `HostedAppStart` asks the host about every capability the
bundle requests and binds them to one `HostCall`, and `HostedAppRun` runs it
under a step limit. `HostedAppRestart` keeps the working instance until the
new one passes the host's handshake. It draws that
bundle's widgets with [`widget_host`](../src/backend/widget_host.zi). The
bundle calls each widget's `HostedHost` function; the host binds
`WidgetHostCall` for the functions `WidgetHostSupports` lists, and wraps each
bundle frame in `WidgetHostBegin(session, asset_allowed)` and
`WidgetHostEnd()`. The callback decides which asset paths the bundle may
draw; texture handles never cross. Records match fields by name, so a bundle
and its host may be built against different Kryon layouts.
Hosted `image_raster.ImageWidth(path)` and `ImageHeight(path)` return typed
dimensions for assets approved by the same callback. Paths resolve through
the active bundle owner; denied paths and calls outside a frame are rejected.
An unresolved approved image returns `-1`, and an empty path returns `0`.
Host replies copy returned strings into the bundle's memory, including text
inside records and collections. A host may reuse its reply buffers on its
next call; the bundle can retain those strings across calls and instance runs.
[`scripts/generate-widget-codecs.py`](../scripts/generate-widget-codecs.py)
generates the codecs for Kryon's widget records and, with `--uses`, for an
application's own records.
A bundle measures text with its host's fonts through
[`text_measure`](../src/ui/text/text_measure.zi): `TextWidth(session, props)` is
the width a line takes and `TextHeight(session, props)` the height Text
takes to draw a paragraph wrapped in `props.bounds.width`.
A vector icon that is not a button, such as a symbol beside a name or a coin
beside an amount, is `SvgIcon(session, SvgIconProps.{bounds, shape, color})`
from [`svg_icon_widget`](../src/ui/svgicon/svgicon.zi); a bundle submits it
to its host like the other widgets. An icon is rasterized once at the
screen's pixels and kept, with the 255 others painted most recently, as the
rectangles it paints, so a screen with many icons does not rasterize them
again every frame. A host that draws textures registers
`SvgIconUseTextures(make, free)` and then paints each icon as one image of
the same pixels.
A bundle draws a row of choices, such as a week or calendar view, with
`SegmentedControl.Draw(session, props, options)` from
[`segmented_control_widget`](../src/ui/segmented/segmented.zi); its host
draws it as it draws its own, with up to 32 options. It frames a form's
sections with `Fieldset.Draw(session, props)` from
[`fieldset_widget`](../src/ui/fieldset/fieldset.zi), and places a toggle at a
row's end; `ToggleSize(session, props)` from
[`toggle_measure`](../src/ui/toggle/toggle_measure.zi) measures it, kept apart
from the toggle widget as `text_measure` is apart from Text. Lines, circles,
rings and triangles from [`shape_widget`](../src/ui/shape/shape.zi) are
hosted too, so a bundle can draw a chart's lines and dots; their host fills
them with the renderer's `RasterTriangles`. `Slider` and `DiscreteSlider`
from [`slider_widget`](../src/ui/slider/slider.zi) and `Progress` from
[`progress_widget`](../src/ui/progress/progress.zi) are hosted as well: the
host drags the slider with its own pointer and answers the value, and paints
the progress bar.
[`open_uri`](../src/backend/open_uri.zi) opens a link with the platform's
handler: `OpenUri(uri)` passes it unchanged to the desktop opener, Windows'
shell, an Android `ACTION_VIEW` intent or a new browser tab,
and `CanOpenUri(uri)` says whether that platform can open it. Android code
reaches the activity through [`android_jni`](../src/backend/android_jni.zi).
The generated Android activity also exposes `public static synchronized String
takeLaunchUri()` (JNI static signature `()Ljava/lang/String;`). It consumes the
latest nonempty intent data string of at most 4,096 UTF-16 units and returns
`""` when none is pending. Capture occurs before native startup and on
`onNewIntent`; recreation with saved state does not replay the original launch.
The single slot is process memory only; a newer bounded value replaces it.
Null, empty, oversized or unreadable data leaves the slot unchanged. Values
are preserved without decoding or truncation. The application owns URL
allowlisting, UTF-8 copy bounds, user confirmation and any resulting action.
The bridge does not open URLs or validate their origin. Applications own
their manifest intent filters and custom-activity integration.
`kryon/play_billing` exposes `PlayBillingBuy(id, accountID, output)` for
Google Play editions. Pass the signed-in account's stable ID. The bridge sends
`buy:product|account` and sets Play's obfuscated account ID to the lowercase
64-character SHA-256 digest of the account ID's UTF-8 bytes. Empty IDs,
embedded NULs, delimiters and oversized requests are rejected without opening
a purchase sheet. Each queued sheet retains the account from its request.
The application server must verify the paid purchase and its account binding
before crediting it; this client binding alone grants no balance or referral
reward. Other editions/platforms return an empty answer.
Other platform services an application may import:
| Module | Surface |
| --- | --- |
| [`file_export`](../src/backend/file_export.zi) | `ExportBytes` and `ExportFile`: hand a finished file to the user as a browser download or through Android's share sheet |
| [`pdf_export`](../src/backend/pdf_export.zi) | `PdfOpen`, `PdfImage`, `PdfImagePixels`, `PdfText`, `PdfTextHeight`, `PdfPage` and `PdfClose`: compose Linux-native PDF pages from full-resolution images and searchable UTF-8 text |
| [`file_picker`](../src/backend/file_picker.zi) | `PickFile(FilePickerProps, output)`: zenity on Linux and BSD, Windows' common dialog, and the browser's chooser, which copies the file into the page's file system |
| [`window_close`](../src/backend/window_close.zi) | `WindowCloseWatch(window)` and `WindowCloseTake()`: close requests for the application's own SDL or Win32 window, so it can ask first or hide to a tray |
| [`idle_time`](../src/backend/idle_time.zi) | `IdleMilliseconds()` from the session's idle service over D-Bus, and `IsWaylandSession()` |
| [`notification_desktop`](../src/backend/notification_desktop.zi) | The `notification` host for Linux and BSD desktops, through notify-send |
| [`android_picker`](../src/backend/android_picker.zi) | `AndroidPickerOpen`, `AndroidScannerOpen` and `AndroidPickerPoll`: asynchronous document and QR selection. Import accepts one MIME type or a comma-separated allowlist; custom activities use the scaffold's `org.kryonlabs.platform.DocumentTypes.apply` to set Android's primary type and `EXTRA_MIME_TYPES`. Android filters by MIME type rather than filename extension. `AndroidSavePickerOpen` returns a private staging path through the same poll; write it, then `AndroidSavePickerCommit` confirms the selected document was written and closed. The activity implements `openImportPicker`, `openQrScanner`, `openSavePicker` and `savePickedFile`. |
| [`android_text_editor`](../src/backend/android_text_editor.zi) | Input method editing on Android: the activity's input connection sends snapshots of the focused field, so composition, autocorrect and suggestions work; android_device's text input uses it when the activity implements `setTextInputState` and `nativeTextInputState` |
| [`file_download`](../src/backend/file_download.zi) | `FileDownloadStart`, `FileDownloadPoll` and `FileDownloadRelease`: a large file downloaded to a path, appearing only when complete, through curl, the browser's streaming `fetch` into the page's file system, or the Android activity |
| [`http_transfer`](../src/backend/http_transfer.zi) | `HttpTransferStart`, `HttpTransferPoll` and `HttpTransferCancel`: HTTP requests that run while the application draws, through curl on a worker thread, the Android activity's transport, or the browser's `fetch` |
| [`page_socket`](../src/backend/page_socket.zi) | `PageSocketOpen`, `PageSocketPoll` and `PageSocketClose`: a browser WebSocket for text events, polled each frame, with bounded messages and a token carried as a subprotocol |
| [`browser_viewport`](../src/backend/browser_viewport.zi) | `BrowserViewportMeasure` and `BrowserResizeSettled`: the room a canvas application has in the browser, and when a new size has settled enough to resize to, for applications that size their own canvas |
`PdfImagePixels(document, pixels, width, height, bounds)` draws tightly packed
straight RGBA bytes, contained and centered in `PdfBounds` without changing their
aspect ratio. It preserves alpha, does not modify or retain the caller's bytes,
and returns false for invalid dimensions, byte count or a closed document.
`PdfImage` loads a file and uses the same renderer.
`PdfTextHeight(document, text, width, size, bold=false)` returns the full wrapped
height in PDF points, using the same Noto Sans font, fallback fonts and word wrap
as `PdfText`, without drawing or limiting the number of lines. It returns zero
for empty or invalid UTF-8, nonpositive width/size, dimensions exceeding Pango's
fixed-point range, or a closed document. Measure each paragraph before placing
it; add a page when its measured height exceeds the remaining space.
After a completed HTTP poll, `transfer.failure` distinguishes a response that
exceeded the caller's buffer (`HTTP_TRANSFER_FAILURE_CAPACITY`) from a transport
failure. Failed responses never publish partial bytes. A new start or cancel
clears the failure. Large logical transfers can use this result to switch to
the service's paged API and preserve progress without enlarging frame memory.
[`src/ui/modules.txt`](../src/ui/modules.txt) is the core build inventory.
`make test` checks source, saved `.zir`, `.zx`, and generated C/Go behavior.
See [FEATURE_MATRIX.md](FEATURE_MATRIX.md) for package and host verification.
Portable apps can import `kryon/input_protocol` for pointer observations,
key codes, modifier bits and `PointInBounds` without loading the native tree
implementation. `tree_input` keeps that surface.
`kryon/file_picker` exposes the native file chooser; `kryon/app_theme` reads
optional host theme colours from a portable app.
An app embedded by a supervising host, such as Harmony's app host, draws in
the host's theme by default on Linux. The host names its process and the
window it embeds the app in (`HARMONY_APP_HOST_PID`, `HARMONY_APP_CONTAINER`)
and keeps its palette on that window (`_HARMONY_APP_THEME`).
`SystemThemeLinux.SystemPaletteRead()` returns that palette after checking
that the host is the app's parent and owns the window; started on its own, an
app gets the desktop's GTK palette. Each call reads the host's
current palette, so an app that reads it again follows a theme change.
`ParentThemeLinux.ParentThemeActive()` says whether a host supplies the theme,
and `ParentPaletteRead(*palette)` reads only the host's palette. libX11 is
loaded at run time and only when a host is named.
`SystemThemeHostLinux.SystemPaletteFollow()`, called once per frame, applies
that palette (the desktop's when not embedded) the first time and again
whenever the host changes it, and returns true when it applied, so an app
follows its host's theme change with one call; portable apps call
`SystemThemeHost.SystemPaletteFollow()`. Applying installs the palette's style
rules and sets the active theme's colours (`SystemPaletteApply`), so code
that draws from `CurrentPalette()` follows too.
`SystemTheme.SystemPaletteColors(palette)` expands a system palette into a full
theme `Palette` (surfaces, text levels, borders, accent, controls) for an app
that draws from one.
`Theme.SweetDarkPalette()` provides the dark Sweet surfaces, text and accent
colors. `Theme.CompactDarkPanel()` returns a `CompactPanelStyle` with a near-black
palette, 32-pixel height and item width, 20-pixel icons, workspace and clock widths,
and compact corner, padding and font sizes. Apply these tokens within the panel's
palette scope; application compositions retain their own saved layout and state.
-138
View File
@@ -1,138 +0,0 @@
# Runnable example: searchable card with real CSS
This complete `.zi` program translates a common HTML pattern (`<section class="card">` + `<input type="search">` + `<button class="primary">` + status text) into native Kryon + `css/Css`:
```zi
App :: #import "kryon/app";
Button :: #import "kryon/button";
Card :: #import "kryon/card";
Text :: #import "kryon/text";
TextField :: #import "kryon/text_field";
Theme :: #import "kryon/theme";
CSS :: #import "css/Css";
#import "kryon/control_props"
#import "kryon/geometry"
#import "kryon/session"
#import "kryon/tree"
APP_CSS :: #string CSS
:root {
--card-bg: #ffffff;
--border: #cbd5e1;
--accent: hwb(160deg 2% 41%);
--focus: hwb(199deg 5% 8% / 95%);
}
@media (prefers-color-scheme: dark) {
:root {
--card-bg: #181d25;
--border: #334155;
--accent: #34d399;
--focus: #38bdf8;
}
}
Card.panel {
background: var(--card-bg);
border: 1px solid var(--border);
border-radius: 12px;
-kryon-elevation: rest;
}
TextField.query-box {
border: 1px solid var(--border);
border-radius: 8px;
padding: 0px 12px;
outline-color: var(--focus);
}
TextField.query-box:focus {
border-color: var(--accent);
}
Button.primary {
background: var(--accent);
color: #ffffff;
border-radius: 8px;
min-block-size: 36px;
}
Button.primary:hover {
opacity: 92%;
}
CSS;
sheet: CSS.CssSheet;
started: bool;
dark: bool;
query_bytes: [64]u8;
query: TextField.State;
submitted: bool;
main :: () -> s32 {
return App.Run(App.Window.{.title = "Search Card", .width = 520, .height = 240}, Draw)
}
InstallTheme :: () {
unused Theme.InstallDefaultTheme(dark)
CSS.CssSheetReset(*sheet)
if CSS.CssSheetParse(*sheet, APP_CSS, "app.css", CSS.CssNoImports) {
env := CSS.CssEnvironmentWithNames(
CSS.CssDefaultEnvironment(), ifx dark then "dark" else "light",
"normal", "comfortable", "mouse", "desktop")
unused CSS.CssSheetInstall(*sheet, env, null)
}
}
Draw :: (frame: App.Frame) {
session := Session.{.slot = frame.slot, .epoch = frame.epoch}
viewport := TreeRootBounds(session)
if !started {
query.bytes = query_bytes[:]
query.focused = true
InstallTheme()
started = true
}
card := Card.Draw(session, Card.Props.{
.key = 1, .class_name = CSS.StyleClass("panel"),
.bounds = Rectangle.{20.0, 20.0, viewport.width - 40.0, viewport.height - 40.0},
.variant = .CardOutlined
})
c := card.content
Text.Draw(session, Text.Props.{
.key = 2, .bounds = Rectangle.{c.x, c.y, c.width, 24.0},
.text = "Filter cluster nodes", .size = 18
})
edited := TextField.Bind(session, *query, TextField.Props.{
.key = 3, .id = 3, .focus_id = 3, .class_name = CSS.StyleClass("query-box"),
.bounds = Rectangle.{c.x, c.y + 34.0, c.width - 110.0, 38.0},
.label = "Filter", .placeholder = "Type host or region..."
})
if Button.Draw(session, Button.Props.{
.key = 4, .id = 4, .class_name = CSS.StyleClass("primary"),
.bounds = Rectangle.{c.x + c.width - 98.0, c.y + 34.0, 98.0, 38.0},
.label = "Apply", .tone = .ButtonToneAccent, .emphasis = .ButtonEmphasisFilled
}) != 0 || edited.committed {
submitted = true
}
if Button.Draw(session, Button.Props.{
.key = 5, .id = 5, .bounds = Rectangle.{c.x, c.y + 84.0, 120.0, 32.0},
.label = ifx dark then "Light mode" else "Dark mode",
.emphasis = .ButtonEmphasisOutline
}) != 0 {
dark = !dark
InstallTheme()
}
status := ifx submitted && query.length > 0 then TextView(query_bytes[0:query.length]) else "All nodes active"
Text.Draw(session, Text.Props.{
.key = 6, .bounds = Rectangle.{c.x, c.y + 128.0, c.width, 22.0},
.text = status, .size = 14
})
}
```
For a complete multi-view example with sidebar navigation, KPI cards, scrollable results, loading/empty/error states, responsive wide/narrow breakpoints, and a keyboard-operable settings modal, see [`examples/dashboard/`](../examples/dashboard/README.md).
-297
View File
@@ -1,297 +0,0 @@
# HTML & CSS to Kryon / Ziran Mapping
Use this guide to port a dashboard into native Kryon. Write the view in `.zi`,
keep the supported CSS declarations, and build the same frame into `.zx` with a
portable Kryon profile. The [responsive dashboard fixture](../examples/dashboard/previews/responsive.zi)
shows the composition and [its README](../examples/dashboard/README.md) has
build and verification commands.
---
## 1. Mental Model: DOM to Retained Frame
| Web / HTML Concept | Kryon / Ziran Equivalent | Notes |
| --- | --- | --- |
| DOM tree mutated by callbacks | Immediate declaration per frame inside `Frame(session, viewport) -> s32` | Kryon retains node identities across frames by `(parent, key, kind)`. |
| Component / element state | Caller-owned structs or file-scope variables (`bool`, `s32`, `TextField.State`, `[N]u8`) | Widgets never own application state; read `Result` structs each frame. |
| `key` / `id` attribute | `.key = cast(u64)N`, `.id = CSS.StyleId("...")`, `.class_name = CSS.StyleClass("...")` | Every sibling widget in a frame needs a unique nonzero `key`. |
| Parent/child nesting | Container returns `.opened: bool`; submit children, then call `End(session)` | Applies to `Page.Draw`, `Page.Section`, `Layout.*`, `Scroll.Draw`, `Modal.Draw`, `Collapsible.Draw`. |
| `window.innerWidth` / `@media` | Pass `viewport.width` to `CSS.CssEnvironmentWithViewportWidth(env, viewport.width)` | Native width, min-width and max-width accept literal `px`, `rem` or unitless zero. Use `CssSheetSameMedia` to avoid reinstalling while the matching rules stay the same. |
---
## 2. Semantic HTML Element -> Kryon Widget Table
Agents and editor tools can load [ui-map.json](ui-map.json) for the native
imports and callable symbols. Match the most specific HTML selector first.
The `css` value gives the Kryon stylesheet selector. When `scope` is present,
draw the children and call `End(session)` only if that result field is true.
`lists` gives the ordered slice arguments after props as `[name, item type]`
pairs. Item types without a package path are exported by the widget module or
are built-in Ziran types.
| HTML Element / Pattern | Kryon Package & Call | Key Props / Notes |
| --- | --- | --- |
| `<html>`, `<body>` | `Page :: #import "kryon/page";` -> `Page.Draw(session, Page.Props.{...})` or `Layout.Screen` | Call `End(session)` if `result.opened`. Also fill root background with `Box.Draw`. |
| `<main>`, `<section>` | `Page.Section(session, Page.SectionProps.{.bounds, .label, .key})` | Sets `SemanticSection`; close with `End(session)` when `opened`. |
| `<article>`, `.card` | `Card :: #import "kryon/card";` -> `Card.Draw(session, Card.Props.{.bounds, .variant})` | Variants: `.CardFilled`, `.CardElevated`, `.CardOutlined`. CSS padding sets `result.content`. Draw children inside that rectangle. |
| `<div>` (styled box) | `Box :: #import "kryon/box";` -> `Box.Draw(session, Box.Props.{.bounds, .fill, .border, .radius})` | Decorative only; captures no input. |
| `<header>` / toolbar | `Toolbar :: #import "kryon/toolbar";` or `TitleBar :: #import "kryon/title_bar";` | Or `Layout.Row` + `Button` / `Text`. |
| `<nav>` (rail / bar) | `Navigation :: #import "kryon/navigation";` -> `Navigation.Draw(session, props, items)` | Use `.compact = true, .fit_items = true` for embedded panels/rails, or vertical `Button` list. |
| `[role="tablist"]` | `TabBar :: #import "kryon/tab_bar";` -> `TabBar.Draw(session, props, tabs)` | Supports `.TabBarTop`, `.TabBarBottom`, `.TabBarLeft`, `.TabBarRight`. |
| `<h1>`..`<h6>` | `Page.Heading(session, .{.bounds, .text, .level = 1})` or `Text.Draw` with `.semantic_kind = .SemanticHeading, .heading_level = N` | Exposes heading semantics to test driver and accessibility tree. |
| `<p>`, `<span>`, `<label>` | `Page.ParagraphText(...)` or `Text :: #import "kryon/text";` -> `Text.Draw(session, Text.Props.{...})` | Supports `.wrap = .TextWrapAuto \| .TextWrapNone \| .TextWrapEllipsis \| .TextWrapAnywhere`, `.align`, `.strong`, `.links`. |
| `<a href="...">` | `Link :: #import "kryon/link";` -> `Link.Draw(session, Link.Props.{.text, .link, .bounds})` | Caller handles navigation when `result.open_url` is true. |
| `<button>` | `Button :: #import "kryon/button";` -> `Button.Draw(session, Button.Props.{...}) != 0` | `.tone` (`Neutral`, `Accent`, `Danger`, `Success`, `Warning`), `.emphasis` (`Filled`, `Soft`, `Outline`, `Ghost`, `Link`), `.detail`, `.icon_shape`, `.selected`. |
| `<input type="text\|search\|password\|number">` | `TextField :: #import "kryon/text_field";` -> `TextField.Bind(session, *state, props)` | Binds caller-owned `TextField.State` directly to session input (`session_input = true` default) and returns `BindingResult` (`node`, `focused`, `changed`, `committed`, `escaped`). Use `TextField.Draw(session, TextField.StateProps(state, props))` + `StateApplyResult` when supplying custom `props.input`. Set `.secure = true` for password, `.numeric = true` for digits. |
| `<textarea>` | `TextArea :: #import "kryon/text_area";` -> `TextArea.Draw(...)` | Multiline editor using `TextAreaInputFor(...)`. |
| `<input type="checkbox">` | `Checkbox :: #import "kryon/checkbox";` -> `Checkbox.Draw(session, Checkbox.Props.{.checked, .label})` | Read `result.changed` and `result.checked`. |
| `<input type="checkbox" role="switch">` | `Toggle :: #import "kryon/toggle";` -> `Toggle.Draw(session, Toggle.Props.{.value, .label})` | Read `result.changed` and `result.value`. |
| `<input type="radio">` | `Radio :: #import "kryon/radio";` -> `Radio.Draw(...)` | Caller tracks selected group index. |
| `<select>` | `Dropdown :: #import "kryon/dropdown";` -> `Dropdown.Draw(session, props, options)` | Manages its own popup menu & scroll; read `result.selected_index`. |
| `<input type="range">` | `Slider :: #import "kryon/slider";` -> `Slider.Draw(...)` / `Slider.DiscreteSlider(...)` | Continuous float or discrete integer steps. |
| `<progress>` | `Progress :: #import "kryon/progress";` -> `Progress.Draw(session, .{.bounds, .min, .max, .value})` | Linear progress bar. |
| `<fieldset>` | `Fieldset :: #import "kryon/fieldset";` -> `Fieldset.Draw(...)` | Grouped form section. |
| `<ul>` / `<select multiple>` | `ListBox :: #import "kryon/list_box";` -> `ListBox.Draw(...)` / `ListBox.ListBoxMulti(...)` | Built-in scroll + keyboard Up/Down/Home/End, or use `Scroll` + `Button` rows for rich rows. |
| `<table>`, `<th>`, `<td>` | `Scroll.Draw` + `Layout.Grid` + `Text.Draw` | Give all rows the same explicit tracks. Use `.horizontal = true` and `.content_width` to preserve the columns on narrow viewports. Label headers and cells in reading order. |
| `<details>` / accordion | `Collapsible :: #import "kryon/collapsible";` -> `Collapsible.Draw(...)` | Animated reveal; draw body inside `result.content` when open. |
| `<dialog>` | `Modal :: #import "kryon/modal";` -> `Modal.Draw(session, props)` or `Dialog.Dialog(...)` | Scoped container (`if modal.opened { ... End(session) }`); `modal.dismissed` fires on Escape/scrim. |
| `<hr>` | `Separator :: #import "kryon/separator";` -> `Separator.Draw(session, .{.bounds, .vertical})` | Horizontal or vertical divider, optional centered `.label`. |
| `<img>` | `Image :: #import "kryon/image";` -> `Image.Draw(session, Image.Props.{.asset_path, .bounds})` | Supports PNG/WebP/AVIF or `texture`. |
| `<svg>` (icon) | `SvgIcon :: #import "kryon/svg_icon";` -> `SvgIcon.Draw(session, .{.shape, .bounds, .color})` | Uses Kryon `Shape` path strings (e.g. `"S1.8rr:M..."`). |
| Status pill / tag | `Badge :: #import "kryon/badge";` -> `Badge.Draw(session, .{.text, .tone, .dot, .solid})` | Tones: `Neutral`, `Info`, `Success`, `Warning`, `Danger`, `Violet`, `Teal`, `Rose`, `Accent`. |
| Spinner / skeleton | `Loading :: #import "kryon/loading_indicator";` -> `Loading.Draw(session, .{.bounds, .now})` | Pass seconds clock (`CaptureFrameInput(session).elapsed_ms / 1000.0`). |
| Empty search/list state | `EmptyState :: #import "kryon/empty_state";` -> `EmptyState.Draw(session, .{.title, .description, .action})` | Read `result.action` to recover/reset filters. |
| Error / notice banner | `Alert :: #import "kryon/alert";` -> `Alert.Draw(session, props, *state)` or `Banner.Draw(...)` | Tones: `AlertToneNeutral`, `Info`, `Success`, `Warning`, `Danger`. |
---
## 3. Native Layout Equivalents (CSS Flex / Grid -> Kryon Layout)
Kryon separates **retained layout containers** (`kryon/layout`, `kryon/scroll`, `kryon/paned_view`) from **pure geometry cursors** (`layout_behavior`, `grid`, `kryon/PageLayout`).
### A. Container Scopes (`kryon/layout`, `kryon/scroll`, `kryon/flow`)
```zi
Layout :: #import "kryon/layout";
Scroll :: #import "kryon/scroll";
TextField :: #import "kryon/text_field";
Theme :: #import "kryon/theme";
// display: flex; flex-direction: column; gap: 12px; padding: 16px;
gap := Layout.Gap(.ThemeMetricSpace3)
card_size := TextField.Measure(TextField.Props.{.placeholder = "Search..."})
items: [2]Rectangle = .{card_size, card_size}
col := Layout.Draw(session, Layout.Props.{
.key = 10,
.bounds = Layout.LayoutContentBounds(viewport, .FlexColumn, items[:], gap, 16),
.gap = gap, .gap_override = true,
.padding = 16, .padding_override = true
})
if col.opened {
// Children with unset width/x/y (or .bounds.width = Layout.ColumnWidth(session)) auto-stack cleanly
End(session)
}
// overflow-y: auto;
sc := Scroll.Draw(session, Scroll.Props.{
.key = 20, .bounds = list_rect, .content_height = total_h, .scroll_offset = scroll_y
})
scroll_y = sc.scroll_offset
if sc.opened {
// Position items at sc.content.y + offset
End(session)
}
```
> [!TIP]
> `Layout.Props.gap` and `Layout.Props.padding` only override the theme/CSS values `0` or nonzero when `.gap_override = true` / `.padding_override = true` (useful when forcing zero gap/padding against a non-zero theme default). Use `Layout.ColumnWidth(session)` inside a container to size children to the current content width, and `Layout.LayoutContentBounds(bounds, direction, child_rects, gap, padding)` to size a container around its children.
### B. Flex & Grid Geometry Cursors (Zero-Allocation `Rectangle` Math)
- **CSS Flexbox (`justify-content`, `align-items`, `gap`, `padding`)** -> `BeginFlexCursor` + `FlexStep` (in `kryon/layout_behavior` / `kryon/layout`):
- `FlexDirection`: `.FlexRow`, `.FlexColumn`
- `JustifyContent`: `.JustifyStart`, `.JustifyCenter`, `.JustifyEnd`, `.JustifySpaceBetween`, `.JustifySpaceAround`, `.JustifySpaceEvenly`
- `AlignItems`: `.AlignStart`, `.AlignCenter`, `.AlignEnd`, `.AlignStretch`
- **CSS Grid** uses `Layout.Grid(session, Grid.GridProps.{.key, .class_name}, items[:])`.
Provide each item's height and optional span. The grid measures the rows, fills its parent column or section's inner width by default, and gives back a `GridCursor` for drawing. Two-argument calls retain automatic placement for unpositioned single-track children.
- **CSS `grid-column: 1/-1`** maps to `Grid.GridItem.{.column_span = -1}`. Positive spans occupy that many tracks. Use `Grid.GridStep(cursor, item.height, item.column_span)` for the returned `cursor.item` bounds.
- **Breakpoint layout** uses the same stylesheet and frame code at every width. Set the viewport in the CSS environment before submitting widgets. `PageLayout.PageFor` remains available for manually centered or capped page geometry.
- **Split Pane** -> `PanedView.Draw(session, PanedView.Props.{.bounds, .split, .has_split = true, .vertical = true})` -> read `panes.first`, `panes.second`, `panes.split`.
---
## Author a responsive dashboard
```css
Grid.metrics {
grid-template-columns: repeat(auto-fit, minmax(min(165px, 100%), 1fr));
gap: 14px;
}
Grid.charts {
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
}
Card.panel { background: #151f30; border: 1px solid #29384f; border-radius: 16px; padding: 20px; }
@media (max-width: 820px) {
Grid.charts { grid-template-columns: minmax(0, 1fr); }
Card.panel { padding: 12px; }
}
```
```zi
CSS :: #import "css/Css";
Grid :: #import "kryon/grid";
Layout :: #import "kryon/layout";
// Inside a Column or Section scope, after installing the viewport styles:
items: [3]Grid.GridItem = .[.{.height = 340, .column_span = -1}, .{.height = 240}, .{.height = 240}]
charts := Layout.Grid(session, Grid.GridProps.{.key = 30, .class_name = CSS.StyleClass("charts")}, items[:])
if charts.container.opened {
cursor := charts.cursor
for i: 0..2 {
cursor = Grid.GridStep(cursor, items[i].height, items[i].column_span)
// Draw each keyed Card/Plot in cursor.item.
}
unused End(session)
}
```
| Dashboard HTML/CSS | Native authoring |
| --- | --- |
| `main { max-width: 1480px; margin: auto }` | Cap and center the outer rectangle once, then use a `Column` or `Page` with CSS padding and gap. |
| `display: grid`, equal `1fr` tracks | Select `Layout.Grid` in `.zi`. Use `1fr`, `minmax(0, 1fr)`, or `repeat(N, ...)` in CSS. `N` is 1–1024. |
| `repeat(auto-fit, minmax(min(165px, 100%), 1fr))` | Use the same declaration on `Grid`. Measured grids collapse unused tracks. A single track can shrink below the minimum. Literal minimums also work without the `min(...)` wrapper. |
| `grid-column: 1/-1` | Set `.column_span = -1` on the corresponding `GridItem`. Arbitrary line numbers, named areas, unequal tracks, dense packing and explicit row templates stay in the browser layout. |
| `@media (max-width: 820px)` | Keep the declaration and supply logical viewport width to the native CSS environment. Orientation, height, print and range-operator queries stay browser-side. |
| `gap: 12px 14px`, `padding: 8px 12px` | Use the same CSS on `Grid`. Grid interprets row and column gap independently and follows the native axis-pair padding model. Card uses axis padding for its content rectangle. |
| `font-size: clamp(...)`, `padding: clamp(...)` | Use literal sizes in width media rules, or calculate the clamp from the viewport in `.zi` and pass an explicit size or padding prop. `vw`, `em`, `calc()` and `clamp()` do not resolve as native lengths. |
| `font-weight`, `line-height`, `letter-spacing` | Keep native-supported literal properties on `Heading` and `Text`. Use a typeface with fixed-width digits or a mono face for numeric columns. CSS `font-variant-numeric` and `text-transform` do not apply to native text. |
| `background: radial-gradient(...)` | Use the base `background-color`, or a supported two-stop `linear-gradient` on a surface that draws gradients. The native CSS parser does not accept radial gradients. |
| Wrapped navigation, `a[href="#section"]` | Use native `Link`/`Button` controls and a `Row` or measured grid. Handle navigation and scrolling in the frame. The native runtime has no DOM fragment links or CSS flex wrap. |
| `.table-scroll`, `white-space: nowrap`, border-collapse | Use `Scroll.Draw` with `.horizontal = true` and a shared `Grid` for row/cell slots. Use `.wrap = .TextWrapNone` and separators for row lines. Browser table layout and border collapse have no native counterpart. |
| `details > summary`, `pre`, `code` | `Collapsible.Draw` with caller-owned open state, and `Text.Draw` with a code typeface and explicit wrap or scroll policy. |
| Plotly line/step, bars, heatmaps, waterfalls and candles | Import `plot/Plot`. Use `XYChart` for named shared-axis line, point or step series, `BarChart` for signed categories, `HeatmapChart` for a row-major matrix, `WaterfallChart` for deltas and totals, and `TimeCandleChart` for OHLC. Give `ChartProps.bounds` the native panel content rectangle and pass typed data. |
## 4. Kryon CSS Support (`kryonlabs/css`)
Import `CSS :: #import "css/Css";` and install a stylesheet over `Theme.InstallDefaultTheme`:
```zi
CSS :: #import "css/Css";
Theme :: #import "kryon/theme";
sheet: CSS.CssSheet;
ApplyStyles :: (dark: bool, compact: bool, viewport_width: float32) -> bool {
unused Theme.InstallDefaultTheme(dark)
CSS.CssSheetReset(*sheet)
if !CSS.CssSheetParse(*sheet, app_css, "app.css", CSS.CssNoImports) {
return false // inspect CSS.CssSheetDiagnostic(*sheet, buf[:])
}
env := CSS.CssEnvironmentWithNames(
CSS.CssDefaultEnvironment(),
ifx dark then "dark" else "light",
"normal",
ifx compact then "compact" else "comfortable",
"mouse",
"desktop")
return CSS.CssSheetInstall(*sheet, CSS.CssEnvironmentWithViewportWidth(env, viewport_width), null)
}
```
Bind selectors on widgets via `props.class_name = CSS.StyleClass("primary")` and `props.id = CSS.StyleId("save")`.
Parse once per stylesheet in a running app. The example reparses to show the complete setup.
### Supported Selectors
- **Widget types**: `*`, `Any`, `App`, `Button`, `Text`, `TextField`, `TextArea`, `Surface`, `Dropdown`, `Card`, `Slider`, `SliderThumb`, `Toggle`, `ToggleThumb`, `Scroll`, `ScrollThumb`, `Checkbox`, `Radio`, `Progress`, `Separator`, `NavigationBar`, `NavigationBarItem`, `Selectable`, `Fieldset`, `Link`, `TabBar`, `Tab`, `TabClose`, `SegmentedControl`, `Segment`, `Menu`, `MenuItem`, `MenuSeparator`, `ListBox`, `ListBoxItem`, `ListBoxMulti`, `ListBoxMultiItem`, `TreeView`, `TreeViewItem`, `TableView`, `Collapsible`, `Modal`, `Toast`, `Toolbar`, `TitleBar`, `Image`, `Heading`, `ParagraphText`, `Page`, `Section`, `Popup`, `Row`, `Column`, `Grid`.
- **Classes & IDs**: at most one `.class` and one `#id` per compound selector (e.g. `Button.primary#save:hover`).
- **Kryon attributes**: `[tone=Neutral|Accent|Danger|Success|Warning]`, `[emphasis=Filled|Soft|Outline|Ghost|Link]`, `[size=Small|Medium|Large]`, `[role=Label|Panel|Track|Fill|Header|Close|...]`, `[state=any|normal|hover|pressed|focus|disabled|loading|selected]`.
- **State pseudo-classes** (max 1 per selector): `:hover`, `:active`, `:focus`, `:focus-visible`, `:disabled`, `:selected`, `:checked`, `:loading`.
- **Not supported** (parse error): descendant/child/sibling combinators (` `, `>`, `+`, `~`), pseudo-elements (`::before`), `!important`, `//` comments, selector functions (`:not()`).
### Supported Properties & Values
- **Native StyleData properties**:
- Colors: `color`, `background` (color or two-stop vertical `linear-gradient([to bottom | 180deg,] top, bottom)`), `background-color`, `border-color`, `outline-color` (focus ring).
- Borders & shape: `border` (`width`, `solid` or `none`, `color`), `border-width`, `border-style` (`solid` | `none`), `border-radius`, `opacity` (unitless number or clamped `0%`–`100%`).
- Spacing & sizing: `padding` (1–4 values; top/bottom and left/right must be equal), `padding-inline`, `padding-block`, `gap` (one value for both axes or two values in `row column` order), `row-gap`, `column-gap` (`Row` reads `column-gap`, `Column` reads `row-gap`, uniform-gap controls read the first `gap` value; accepts `normal` = 0 or nonnegative `px`/`rem`), `min-height`, `min-block-size` (logical alias for `min-height`), `translate` (`x [y]`).
- Retained `Row`, `Column` and `Grid` also accept `width` and `height` as positive `px` or `rem` lengths or `auto`. Other size expressions pass through to the browser.
- Use `border-color: var(--line)` and `border-width` for typed border variables.
- Typography: `font-size`, `font-family`; native `Text`, `Heading`, and `ParagraphText` read `font-weight` (`normal` = 400, `bold` = 700, or `1`–`1000`), `font-style` (`normal` | `italic` | `oblique` without angle), and `letter-spacing` (`normal` or signed `px` / `rem`); `Text` and `Button` accept `line-height` (`normal`, nonnegative unitless factor, `%` of font size, or nonnegative `px` / `rem`).
- Kryon extensions: `-kryon-material` (`lightfield` | `flat` | `glass`), `-kryon-icon-size`, `-kryon-font-role` (`inherit` | `control` | `body` | `heading` | `code`), `-kryon-elevation` (`none` | `rest` | `raised` | `floating`), `-kryon-motion-duration`, `-kryon-motion-multiplier`, `-kryon-motion-easing` (`inherit` | `standard` | `linear` | `instant`), `-kryon-motion-reduced` (`reduce` | `no-preference`).
- **Units & values**: hex (`#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`), CSS named colors, `rgb()`, `rgba()`, `hsl()`, `hsla()`, `hwb(hue white% black% [/ alpha])`, hue angle units (`deg`, `rad`, `grad`, `turn`), `px`, `rem` (`16px`), `s`, `ms`, `:root` custom properties (`--token: ...;`) with `var(--token, fallback)`. `em` and `%` lengths are rejected (use `px` or `rem`).
- **At-rules**: `@import` (before rules), `@layer`, `@keyframes`, `@media` (`prefers-color-scheme`, `prefers-contrast`, `prefers-reduced-motion`, `pointer`, `width`, `min-width`, `max-width`, `-kryon-theme`, `-kryon-density`, `-kryon-pointer`, `-kryon-platform`).
- **Web-only pass-through properties** (accepted by parser for `kryon/Dom`, ignored by native widgets): `min-width`, `max-width`, `max-height`, `margin*`, `display`, `flex*`, `justify-content`, `align-items`, `align-self`, grid declarations outside the native track subset, `text-align`, `text-decoration`, `text-transform`, `white-space`, `cursor`, `box-shadow`, `overflow`, `z-index`, `visibility`.
Use `color-mix(in srgb, #2076c0 35%, transparent)` in a native color
declaration or custom property to derive a tint from two literal colors.
For native `@media (prefers-reduced-motion: reduce)` rules, set
`env.reduced_motion` from `Theme.CurrentTheme().motion.reduced_motion` and
reinstall the parsed sheet when that preference changes. DOM output uses
the browser's live preference.
### CSS and layout motion
Install motion styles with `css/motion`. Supported native styles animate
through `transition` and `@keyframes`, including duration, delays, easing,
direction, fill modes and repeat counts. For example, a native Button with
`class_name = CSS.StyleClass("save")` uses these rules.
```css
button.save {
background-color: #365bd6;
transition: background-color 180ms ease-out;
}
button.save:hover { background-color: #2443ac; }
```
| UI effect | Kryon API |
| --- | --- |
| Move keyed items when a row, column or grid reflows | `LayoutMotion.Children(session)` from `kryon/layout_motion` in the open layout scope |
| Grow an entering item or ease a size change | `LayoutMotion.Children` with `.enter` or `.resize` |
| Keep drawing an exiting item until it settles | `LayoutMotion.Presence` with caller-owned state |
| Animate a custom shape, number, angle or graph value | `Motion.TweenTo` or `Motion.Sample` from `kryon/motion` |
| Animate a changing line chart | `Plot.AnimatedLineChart` with reusable chart state from `plot/Plot` |
See the [retained motion API](MOTION.md#retained-style-and-layout-motion) for
supported native widget properties and the [scalar motion API](MOTION.md#timed-motion-and-keyframes)
for application-owned tracks. The DOM backend applies motion directly through
browser CSS.
---
A complete runnable example with real CSS lives in [HTML_EXAMPLES.md](HTML_EXAMPLES.md).
## 5. Focus, Keyboard & Accessibility Checklist
1. **Keyboard `Tab` / `Shift+Tab` focus traversal**: `TreeKeyboardRoute` moves focus across `Button`, `Checkbox`, `Toggle`, `Radio`, `Slider`, `Selectable`, `Link`, `Collapsible`, `Dropdown`, `TextField`, `TextArea` (and `Card` / `Text` when `.focus_id > 0`). Leave `TextField.Props.capture_tab = false` so `Tab` leaves inputs cleanly.
2. **Focus rings**: Widgets draw focus outlines when `TreeFocusVisibleAt` is true (after keyboard navigation). Customize ring color in CSS via `outline-color: var(--focus-ring);`.
3. **Text editing**: Prefer `TextField.Bind(session, *state, props)` (`session_input = true` default) which manages keyboard/clipboard/composition updates against caller-owned `TextField.State`. Use `TextField.Draw(session, TextField.StateProps(state, props))` + `TextField.StateApplyResult(*state, result)` only when feeding synthetic `props.input` (`session_input = false`).
4. **Modals & Escape**: `Modal.Draw` submits an `Overlay` with `TreeSetPopup`, blocking background input and automatically dismissing on `Escape` (`modal.dismissed == true`). Always pair `if modal.opened { ... End(session) }`.
5. **Test driver & one-shot previews**: Keep `.label` meaningful on interactive widgets so `kryon/test_driver_client` (`DriverPress`, `DriverWait`, `DriverType`, `DriverKey`) and `kryon preview` tree JSON can inspect every control.
---
## 6. Live Signature & Checked Example Discovery (`ziran api`)
Do not duplicate parameter lists by hand. From a project with pinned `kryon` dependencies (such as `examples/dashboard/`), inspect imports first to resolve the local package module alias (`"Layout"` -> `#import "kryon/layout"`, etc.), then query bounded symbol metadata, stable symbol IDs (`"id": "zi:..."`), and checked `.zi.examples` entries dynamically:
```sh
# 1. Inspect resolved imports (`name` -> `resolved_module`) from your entry file
ziran api --project --json --imports-only src/dashboard.zi
# 2. Look up a resolved module dynamically and query a symbol + checked example `entry`
mod=$(ziran api --project --json --imports-only ../../src/ui/layout/layout_api_example.zi | \
python3 -c 'import json,sys; d=json.load(sys.stdin); print(next(i["resolved_module"] for m in d["modules"] for i in m["imports"] if i["name"]=="Layout"))')
ziran api --project --json --module "$mod" --symbol Draw ../../src/ui/layout/layout_api_example.zi
# 3. Execute the returned example `entry` directly (never hardcode package hashes)
ziran run --project --target=c --entry <entry_from_json> <sibling_example.zi>
```
Each discovered symbol exposes a stable `"id": "zi:..."` identifier you can pass back via `--symbol <id>` to select a single overload deterministically.
Curated `.zi.examples` sidecars and hostless sibling fixtures ship alongside representative public modules (`layout.zi`, `layout_behavior.zi`, `button_props.zi`, `card_behavior.zi`, `text_input.zi`, `modal_behavior.zi`). Full-widget `Draw` modules (`button.zi`, `card.zi`, `textfield.zi`) require native raster/glyph host symbols (`RasterRoundedRectangle`, `MeasureGlyphWidth`, etc.), so headless standalone API examples target the pure layout/props/behavior layers while end-to-end widget frames are exercised via `kryon preview` and `examples/dashboard/tests/dashboard_test.zi`.
-52
View File
@@ -1,52 +0,0 @@
# Image, tile and shape rendering
Advanced `Image` rendering options, tile maps, palettes and decorative shapes.
Read this when an image needs clipping, warping or a loading preview, or when
you draw shapes directly.
| `Image.Props` option | Meaning |
| --- | --- |
| `clip_polygon` | Clips the image without stretching it. Supply 3–4096 points in normalized destination coordinates (0–1); the path closes automatically. Empty leaves the image unchanged. Invalid coordinates, too few points, or combining a polygon with a mesh draw nothing. Native, hosted and browser images each keep their own copy of the supplied points. |
| `mesh` | Warps the image over a grid of `columns` × `rows` screen points, row by row from the source's top left, each cell drawn as two textured triangles — a cut-out puppet's painted arm can bend at its elbow, or a picture can follow a curve. The bounds still clip it; fit, origin, rotation and the style radius do not apply, and a grid with too few points draws nothing. Points are copied when the image is queued, at most 4096 per image (256 through a portable bundle's hosted `Image`). |
| `preview_path` | Names a small copy of the same picture that draws in its place, with the image's own bounds, fit, mesh and clip, while the picture loads or when it is unavailable, so something shows at once and the picture replaces it when ready. A preview of part of a picture (a nonempty `source`, such as a jigsaw piece) needs `Image.Props.full_size`, the picture's size in pixels, to map that rectangle onto the preview; without it the image waits for the picture. Hosted previews pass the same asset policy as their picture. |
`image_showing.ImageShowingOf(session, image)` reports `ImageShowingNone`
(loading), `ImageShowingPreview`, `ImageShowingFull` or
`ImageShowingUnavailable`, natively and through a portable bundle's host, so
an app can wait for a picture before what belongs with it. Asking starts the
host loading the picture, which also fetches pictures shown soon.
`image_mesh.ImageMeshQuad(bounds, camera, points)` constructs a four-corner
mesh for the standard `Image.Props.mesh`. It uses the same 2D `Camera` as
`WorldToScreen`, with caller-owned space for four points; too little space
produces an empty mesh. Rotation and scale stay on the standard image surface.
`TileMapProps.pixel_snap` fits and positions whole-pixel cells. `nearest` selects
nearest-neighbour sampling for the whole map; `nearest_tiles` selects individual
tile indices while the rest remain smooth. Sampling survives the hosted codec.
A hosted map uses batched sampling only when its host advertises
`tile_map.sampling`; hosts without mesh support draw the same standard Images individually.
Pixel snapping uses bounds fitted by the bundle.
`WidgetPaletteUse` scopes semantic colors along with widget rules. Hosted
`AppThemeColor` calls and compositions using canvas, surface, text, border and
accent see the same palette. `WidgetPaletteRestore` restores the surrounding palette when calls nest,
including its text style and semantic tokens. The host frame unwinds palettes
a guest leaves open. Sixteen nested parents are retained; scopes beyond that
restore to the deepest retained palette, then unwind to the original host.
The outermost restore preserves the complete prior token set, including
host-specific colors and the absence of unset tokens.
Hosts call `PaintResourcesChanged()` when replacing raster resources without
changing widget props. Retained frames then compose and paint again, including
when a browser graphics context resets or an app updates its image assets.
`Shape.Draw(Shape.Props)`, `Circle(Shape.CircleProps)`, `Shape.Ring(Shape.RingProps)` and
`Shape.Triangle(Shape.TriangleProps)` draw lines, circles, radial gradients,
rings and triangles. Like `Box`, each
is decorative: it submits a node covering what it draws and queues one paint
command. Kryon cuts the shape into triangles, clips them to its parent's clip
and sends each colour's triangles to the host in one `RasterTriangles` call;
a radial fade is drawn as rings of one colour each. `Box.Props.fill_bottom`
with `has_fill_bottom` fades a box's fill from top to bottom.
Import `kryon/shape` to use these shapes, including in a portable hosted
bundle.
-147
View File
@@ -1,147 +0,0 @@
# Input components
These six Ziran components cover the selected modern input families without an
external compatibility layer. Each render entry is `(Session, Props, *State) -> Result`;
each `Apply` function has the same behavior without requiring a building frame.
Caller-owned state is plain fixed-size data, including text bytes, so it can be
copied or serialized. No component owns global text, focus, clipboard, or
shortcut state.
All compositions submit real retained-tree nodes, resolve the installed theme
and stylesheet through the current style facts, and use the existing field, box,
text, paint, and session primitives. IDs, style classes, disabled state, focus,
bounds, and supported font/geometry/motion metrics remain customizable. A
disabled component neither accepts text nor keeps focus.
## Tag input
```zi
TagInput :: #import "kryon/tag_input";
TagInput.Draw :: (session: Session, props: TagInput.Props,
state: *TagInput.TagInputState) -> TagInput.TagInputResult
TagInput.TagInputApply :: (state: *TagInput.TagInputState,
props: TagInput.Props) -> TagInput.TagInputResult
```
`TagInputState` owns up to 64 tags and their stable caller IDs, the editable
text, selection, scroll, and focus. Initial IDs can be supplied through
`TagInputStateInit`; newly entered tags receive stable generated IDs.
Commit text on Enter or `TextField.Input.commit`. A nonempty separator also
splits committed and pasted text. Spaces can be trimmed, duplicates rejected,
and a positive `max_tags` enforced. Backspace on an empty field requests removal
of the final tag through `field.backspace_on_empty`; explicit removal is by
`remove_index` or stable `remove_id`. Results distinguish add, remove, duplicate
rejection, maximum count, removed ID, and number added. The group, chips, remove
buttons, and nested field all honor disabled state and stylesheet cascade.
## One-time code
```zi
OneTimeCode :: #import "kryon/one_time_code";
OneTimeCode.Draw :: (session: Session, props: OneTimeCode.Props,
state: *OneTimeCode.OneTimeCodeState) -> OneTimeCode.OneTimeCodeResult
OneTimeCode.OneTimeCodeApply :: (state: *OneTimeCode.OneTimeCodeState,
props: OneTimeCode.Props) -> OneTimeCode.OneTimeCodeResult
```
The state owns 1–12 alphanumeric slots, the cursor, focus, and prior completion.
Typed characters insert at the cursor and advance it. Left/right move, Backspace
deletes backward, and paste replaces all slots after filtering invalid bytes.
Escape blurs and reports cancellation. Completion is emitted only when the code
becomes full after a real change; it is not repeated by later frames or input.
Masked rendering shows `*`. This is only an input component and performs no
authentication or delivery.
Slots use the canonical 44×52 default, optional six-digit grouping, current
control radius, and display font. Width, height, radius, both gaps, and font
size are explicit style metrics. The group, every slot, and every character are
real retained nodes.
## Inline edit
```zi
InlineEdit :: #import "kryon/inline_edit";
InlineEdit.Draw :: (session: Session, props: InlineEdit.Props,
state: *InlineEdit.InlineEditState) -> InlineEdit.InlineEditResult
InlineEdit.InlineEditApply :: (state: *InlineEdit.InlineEditState,
props: InlineEdit.Props) -> InlineEdit.InlineEditResult
```
Activation selects the current value for replacement. Normal text and paste
edits update state directly; IME composition is forwarded to the nested field.
Enter or blur commits the edited bytes. Escape cancels by restoring the backup
taken at activation and leaves editing mode. Disabled props close editing and
reject input. Results expose the nested field result, editing, commit, cancel,
and whether the committed value changed.
## Scrub field
```zi
ScrubField :: #import "kryon/scrub_field";
ScrubField.Draw :: (session: Session, props: ScrubField.Props,
state: *ScrubField.ScrubFieldState) -> ScrubField.ScrubFieldResult
ScrubField.ScrubFieldApply :: (state: *ScrubField.ScrubFieldState,
props: ScrubField.Props) -> ScrubField.ScrubFieldResult
```
Arrow-left/right, arrow-up/down, and horizontal drag use the same step. Shift
selects fine or coarse behavior: by default the non-shift direction moves ten
steps while Shift moves one tenth. `fine_divisor` and `coarse_multiplier`
replace those ratios when positive. Values round to `precision` and clamp to
the supplied bounds. Activation enters text mode, commit parses/clamps/rounds,
and Escape restores the pre-edit value. Results distinguish ordinary change,
drag start, commit, and cancel.
The label, editable value, and suffix are retained child nodes. Height is an
explicit metric; the remaining visual contract starts at current control
metrics and can be overridden by ID/class stylesheet rules.
## Money field
```zi
MoneyField :: #import "kryon/money_field";
MoneyField.Draw :: (session: Session, props: MoneyField.Props,
state: *MoneyField.MoneyFieldState) -> MoneyField.MoneyFieldResult
MoneyField.MoneyFieldApply :: (state: *MoneyField.MoneyFieldState,
props: MoneyField.Props) -> MoneyField.MoneyFieldResult
```
The state owns a `float64` value and the focused edit bytes. Blurred display
uses the selected decimal separator, optional grouping, optional currency
prefix/suffix, precision, and minus-or-parentheses negative style. Gaining focus
changes to a plain round-trippable edit string; commit parses grouping and
either negative notation, rounds, clamps, and returns to formatted display.
Escape cancels. Results expose validity as well as commit/cancel/change.
Both comma-decimal and period-decimal conventions are supported. The last period
or comma is decimal; earlier punctuation is grouping. No locale service is
hidden in widget state.
## Shortcut recorder
```zi
ShortcutRecorder :: #import "kryon/shortcut_recorder";
ShortcutRecorder.Draw :: (session: Session, props: ShortcutRecorder.Props,
state: *ShortcutRecorder.ShortcutRecorderState) -> ShortcutRecorder.ShortcutRecorderResult
ShortcutRecorder.ShortcutRecorderApply :: (state: *ShortcutRecorder.ShortcutRecorderState,
props: ShortcutRecorder.Props) -> ShortcutRecorder.ShortcutRecorderResult
```
Activation records only while this widget is focused. A supported key plus
modifiers is accepted, including `Ctrl+Enter`; bare Escape cancels recording,
bare Backspace or Delete clears the shortcut, and bare Tab exits recording.
Unknown or out-of-range keys/chords report `unsupported` without changing the
prior shortcut. Blur, outside press, and disabled also stop recording. This
component never installs a global accelerator or consumes another owner's input.
The state owns the key, modifier mask, focus/recording flags, and its fixed
label buffer. Width, height, and font size have explicit metrics; animation
uses the current theme motion duration and installed style cascade.
+116
View File
@@ -0,0 +1,116 @@
# Kry Language
Kry is C-close app code for Kryon. `kc` emits readable `.c` and `.h` files
that are compiled by the normal C toolchain; there is no VM, runtime package
system, or hidden ownership model.
## Style
- Small files, clear names, and plain data flow.
- Explicit module prefixes for generated C symbols.
- Direct C-compatible pointers, field access, labels, and cleanup `goto`.
- Compile-time modules only.
- Raw C escape hatches only for platform or third-party edges.
## Declarations
```kry
#module "practice.session"
#output "session_impl"
#import "app.h"
#import <stddef.h>
#import "private_dep.h" #private
#pragma "GCC diagnostic push"
SessionTimer :: struct {
elapsed: float
running: bool
}
SessionMode :: enum {
SESSION_IDLE,
SESSION_ACTIVE,
}
#enum {
SESSION_FLAG_DIRTY = 1,
}
#enum #private {
SESSION_LOCAL_FLAG = 1,
}
TickCallback :: int (*)(float) #type
LocalSize :: unsigned long #type #private
session_count :: int #global #export
local_counter :: int = 7 #global
platform_ping :: (value: int, tag: const char*) -> int #extern
platform_log :: (level: int, text: const char*, ...) -> void #extern
win_entry :: (hwnd: void*) -> int #extern #storage "__declspec(dllimport)" #abi "__stdcall"
weak_hook :: () -> void #extern #attr "__attribute__((weak))"
session_update :: (app: InbeApp*, dt: float) -> int {
if !app->session.running {
return 0
}
result := breath_step(&app->breath, dt)
if result.done {
goto done
}
done:
return 1
}
session_entry :: (app: InbeApp*) #export {
session_update(app, 0.0f)
}
```
## Rules
- `#module "name"` sets the compile-time module name and generated C symbol
prefix. Dots become underscores.
- `#output "basename"` changes only the generated file basename.
- `#import "path.h"` emits a public include in the generated header.
- `#import <system.h>` and `#import "path.h" #private` emit source-only
includes.
- `alias :: #import "module/path"` imports another Kry module and binds a
compile-time alias for qualified calls.
- `name :: (...) -> Ret { ... }` defines a function. Inside a module, the
generated C symbol is module-prefixed by default.
- `#export` keeps the exact C ABI name and emits the declaration publicly.
- `#private` keeps a function or type alias source-local.
- `#global` creates a file-level variable; add `#export` for a public `extern`.
- `#extern` declares an external C function without defining it.
- External declarations accept precise interop tags when the platform ABI needs
them: `#storage "..."` before the return type, `#abi "..."` before the
function name, and `#attr "..."` after the parameter list.
- `...` is allowed as the final parameter of an external declaration.
- `#intrinsic "web"` emits a Kryon-owned platform wrapper for supported web
operations.
- `#pragma "text"` and `#error "message"` emit guarded C preprocessor
directives for compiler and platform integration.
Kry statements are deliberately minimal — declarations, assignments, calls,
and control flow. There are no widget keywords and no bespoke sugar verbs:
- `name := expr` for inferred locals.
- `name: Type = expr` or `name: Type` for typed locals.
- `name = expr` assignments (including compound `+=`, `%=`, `&=`, ...).
- plain function calls (any call used as a statement is a draw call and is
automatically wrapped with source-inspection metadata for click-to-source).
- `if`, `else if`, `else`, `while`, `for`, `switch`, `case`, `default`,
labels, `goto`, `break`, `continue`, `guard`, and `return`.
- `c line` for raw C glue and `unused expr` to silence unused-value warnings.
Widgets are ordinary library functions (WidgetText, WidgetRect, WidgetLine,
WidgetBackground, WidgetButton) declared in `ui_widgets.h`; the compiler
treats them exactly like any other call. Input handling is plain control
flow: `if (UIKeyPressed(KEY_A)) { ... }`, `if (UIKeyDown(KEY_A)) { ... }`.
Event-style blocks (`button ... {`, `on key ... {`, `event ... {`) and
arithmetic/declaration sugar (`advance x by N`, `clamp_min`, `c_rect`,
`texture`, `set_theme`) were removed in favor of their direct equivalents.
-147
View File
@@ -1,147 +0,0 @@
# 3D models
Reading glTF 2.0 documents and VRM 0.x avatars into Kryon scenes, with
skins, morph targets, animations and spring-bone physics. Read this when
loading a 3D model or avatar.
### glTF 2.0 models
Import `kryon/scene_gltf` to load `.gltf` (JSON with `.bin` or `data:` URI
buffers) and `.glb` files without any platform graphics dependency:
```ziran
#import "kryon/scene"
#import "kryon/scene_gltf"
#import "kryon/scene_skin"
#import "kryon/scene_render"
model := GltfReadFile("models/character.glb")
defer GltfModelRelease(*model)
if !model.valid { return }
scene: Scene
SceneInit(*scene)
instance: GltfSceneInstance
defer { GltfInstanceRelease(*instance); SceneFree(*scene) }
if !GltfSceneCreate(*scene, *model, *instance) { return }
if model.animations.count > 0 {
unused GltfAnimateScene(*model, *instance, *scene, 0, seconds)
}
camera := PerspectiveCamera(0.9, 16.0 / 9.0, 0.1, 100.0)
picture := NewImage(width, height)
defer VecFree(picture.pixels)
unused RenderScene(*scene, camera, *picture)
```
`GltfReadBytes(bytes, base_dir)` reads the same formats from memory;
`base_dir` resolves relative buffer and image URIs, and stays empty for a GLB
whose binary chunk holds everything. A loaded `GltfModel` owns its buffers,
decoded images, materials, meshes, nodes, skins and animation samplers;
`GltfModelRelease` frees them.
The reader covers buffers, bufferViews and accessors for every component type,
normalized integers and sparse overrides. Primitives read `POSITION`, `NORMAL`
(averaged flat normals when absent), `TANGENT`, `TEXCOORD_0`, `TEXCOORD_1`,
`COLOR_0`, `JOINTS_0`, `WEIGHTS_0` and indices; triangle lists, strips and fans
are supported. Meshes read morph targets and default weights. Nodes read TRS or
a column-major matrix, children, meshes, skins and per-node morph weights.
Skins read joints and inverse bind matrices. Animations read translation,
rotation, scale and weights channels with `LINEAR`, `STEP` and `CUBICSPLINE`
interpolation and report their duration. Materials read
metallic-roughness factors, base colour, metallic-roughness, normal, occlusion
and emissive texture info, alpha modes, double-sided, `KHR_materials_unlit`,
samplers, textures and PNG/JPEG images from a URI, a `data:` URI or a
bufferView.
Malformed input never crashes: every accessor and sparse range is
bounds-checked, required arrays are type-checked, node hierarchies reject
cycles and multiple parents, and relative URIs must stay inside the model's
directory. A rejected document leaves `model.valid` false and `GltfError`
describes the first problem. Documents above 256 MiB, accessor counts above
16 million, non-triangle primitive modes, non-finite floats and required
extensions other than `KHR_materials_unlit` are rejected.
`GltfSceneCreate(scene, model, instance, scene_index = -1)` builds one
`SceneIndexedMesh` per primitive under group nodes for the document's node
hierarchy and creates a `SceneSkin` for every skinned primitive; skinned
primitives draw through the same retained indexed path as other scene meshes.
`GltfUpdateScene` recomputes node world transforms, morph blending and skin
poses. `GltfAnimateScene(model, instance, scene, animation, time, loop = true)`
samples an animation and updates the scene in one call; `loop` wraps `time`
modulo the animation duration, and a non-looping sample clamps to the last
keyframe. `GltfSampleAnimation` changes only the instance, `GltfSampleSkinPose`
returns the current bind-to-pose `SkinAffine` array for one skin, and
`GltfSetDualQuaternion` switches skinned primitives to volume-preserving dual
quaternion skinning. `GltfPoseReset` returns to the document's rest pose.
Material conversion maps base colour, metallic, roughness, emissive, alpha
mask/blend, double-sided and unlit into `SceneMaterial`, uploads the base
colour texture with its sampler, and flips V so glTF's top-down UVs match the
scene's bottom-up UVs. Metallic-roughness, normal, occlusion and emissive maps
stay available on `GltfMaterial` for callers that supply a custom shader
material; the standard material uses the base colour map. Use
`GltfMaterialToScene` to convert a material yourself.
`make scene-gltf-test` checks the reader and adapter against small fixtures
(GLTF and GLB, sparse and normalized accessors, morph targets, all
interpolation modes and malformed files), and `make scene-gltf-gpu-test`
renders an animated two-bone skin headless through the GLES scene path and
compares it with `tests/fixtures/gltf/skinned_reference.png`. Both run through
`build-queue --`. The committed Khronos sample models under
`tests/fixtures/gltf/khronos/` are CC-BY-4.0 or CC0-1.0 and keep their
upstream README files; models carrying a non-Khronos trademark are never
committed and run only from a local sample-assets checkout named by
`KRYON_GLTF_SAMPLE_ASSETS`.
### VRM avatars
Import `kryon/scene_vrm` for VRM 0.x avatars (`.vrm` files such as VRoid
exports) loaded through `scene_gltf`: the humanoid bone map, expressions,
eye lookAt and spring-bone physics for hair and clothes.
```ziran
#import "kryon/scene_gltf"
#import "kryon/scene_vrm"
model := GltfReadFile("models/avatar.vrm")
instance: GltfSceneInstance
unused GltfSceneCreate(*scene, *model, *instance)
avatar: VrmAvatar
defer VrmAvatarRelease(*avatar)
if VrmReadFile(*avatar, "models/avatar.vrm") {
unused VrmSpringsReset(*avatar, *model, *instance)
}
// Each frame: pose the bones in instance.rotations, then
VrmSetFrame(*avatar, turn, position, scale)
VrmSpringsUpdate(*avatar, *model, *instance, seconds_since_last_frame)
unused VrmSetExpression(*avatar, *model, *instance, "blink", closed)
VrmLookAtSet(*avatar, *model, *instance, yaw_degrees, pitch_degrees)
unused GltfUpdateScene(*model, *instance, *scene)
```
`VrmReadFile(avatar, path)` and `VrmReadBytes(avatar, bytes)` read the `VRM`
extension of a GLB or glTF JSON document and return false when there is
none. `VrmBoneNode(avatar, "leftUpperArm")` gives the glTF node of a VRM
humanoid bone or -1; `avatar.bones` holds all of them in `VrmBoneName`
order. `VrmSetExpression` sets a blend shape group, found by its preset
(`blink`, `joy`, `a`, ...) or its name, to a weight from 0 to 1 in the
instance's morph weights; binary groups snap at one half.
`VrmLookAtSet` turns the eye bones of a `Bone` lookAt avatar by degrees to
the avatar's left and up, mapped through its lookAt range curves.
Spring bones follow the VRM 0.x reference: each joint's tail moves by Verlet
inertia less drag, a stiffness pull back to its rest direction and gravity,
keeps its length and is pushed out of the sphere colliders of the collider
groups its bone group names. Physics runs at a fixed 60 steps a second in
the world placed by `VrmSetFrame(avatar, turn, at, scale)`, so moving or
turning the whole model swings the hair as well. A step backwards or of more
than a quarter second, as after a seek, puts the springs back at rest, as
`VrmSpringsSettle` does. Node positions come from the instance's
translations, rotations and scales, so one `GltfUpdateScene` after posing
and springs is enough. VRM 1.0 (`VRMC_vrm`) files are not read.
`make scene-gltf-test` also checks the VRM layer against
`tests/fixtures/gltf/vrm_avatar.gltf`: the bone map, expressions, lookAt
curves, gravity, colliders, stability while the body moves at uneven frame
steps, and settling after a seek.
-183
View File
@@ -1,183 +0,0 @@
# Motion
Timed scalar tracks, stylesheet transitions, layout reflow motion, per-widget
springs and page view transforms. Read the section for the kind of movement you
want.
## Timed motion and keyframes
Import `kryon/motion` for a timed scalar transition or keyframe track.
The module takes time and state from the caller and depends only on scalar
math. Apply a sample to opacity, position, size, or several chart points.
- `Motion.TimingFor(.EaseOut)` creates a CSS timing preset. The choices are
`.Linear`, `.Ease`, `.EaseIn`, `.EaseOut`, and `.EaseInOut`.
`Motion.CubicBezier(x1, y1, x2, y2)` accepts CSS control points, including
overshoot. Invalid control points yield linear timing. Use `Motion.Progress`
to ease a unit interval directly.
- `Motion.BuildTrack(frames)` validates a borrowed slice of `Motion.Keyframe`
records. Start at offset `0`, end at `1`, and place any other offsets in
increasing order. A keyframe's timing governs the segment leaving it.
Keep the slice alive and unchanged. `Motion.At(track, progress)` samples
by normalized progress. `Motion.Sample(track, elapsed, duration, iterations,
alternate, reduced_motion)` samples by seconds and reports `.value` and
`.active`. Reduced motion settles at the same endpoint as ordinary playback.
- `Motion.TweenTo(*state, target, now, duration, timing, reduced_motion)`
starts an implicit transition when the target changes. Give each value its
own zero-initialized `Motion.TweenState`. The first call initializes at the
supplied target. Changing targets mid-flight starts at the current value.
Pass monotonic seconds and request motion frames while `.active` is true.
The [checked usage example](../src/ui/motion_api_example.zi) samples a whole
series with one easing calculation per frame and shows an interrupted hover
transition. Keep the chart's scale and the input series stable while they
interpolate. Pass the resulting values to your usual chart drawing code.
## Retained style and layout motion
`kryon/style_motion` installs typed transition rules and keyframes over the
normal widget style cascade. For CSS authoring, use `css/motion` to install
a parsed or packed sheet. Buttons use animated background, text and border
colors, opacity, corner radius, border width and content offset. Text and
links animate their color and opacity. Images animate the surface properties
the image already paints. Give each moving widget a stable key.
`kryon/layout_motion` moves keyed children through a reflow or reorder. Open a
layout scope and call `LayoutMotion.Children(session)` before drawing its
children. Set `.resize = true` to animate width and height changes and
`.enter = true` to grow newly mounted children from zero size at their placed
origin. Each option applies to direct keyed children of that scope.
Set `.seconds`, `.timing` and `.reduced_motion` to control the transition.
The layout reserves each child's target space while its visible size changes.
Paint and hit testing use the sampled bounds, and interrupted transitions
continue from the current sample. Moving a parent also moves its relative
children. Reduced motion and zero duration settle immediately.
```zi
Layout :: #import "kryon/layout";
LayoutMotion :: #import "kryon/layout_motion";
Button :: #import "kryon/button";
#import "kryon/tree"
row := Layout.Row(session, .{.key = 1, .gap = 12})
if row.opened {
unused LayoutMotion.Children(session, .{.seconds = 0.24,
.resize = true, .enter = true})
unused Button.Draw(session, .{.key = 2, .label = "First"})
unused Button.Draw(session, .{.key = 3, .label = "Second"})
unused End(session)
}
```
For exit motion, keep the child’s data and a `LayoutMotion.PresenceState` in
application state. Call `LayoutMotion.Presence` each composed frame, including
while the child is absent. Its first sample is fully visible if present and
fully hidden if absent. Later changes animate from the current sample and
honor reduced motion. The result gives a `fraction` from 0 to 1. Submit the
child while `draw` is true. Use `interactive` to disable input as soon as
exit begins. Optional `PresenceOptions` control `.seconds`, `.timing` and
`.reduced_motion`.
```zi
LayoutMotion :: #import "kryon/layout_motion";
Button :: #import "kryon/button";
#import "kryon/session"
#import "kryon/tree"
#import "kryon/tree_input"
#import "kryon/widget_kind"
PrintAction :: (session: Session, presence: *LayoutMotion.PresenceState,
available: bool) -> bool {
sample := LayoutMotion.Presence(session, presence, available)
if !sample.interactive {
previous := TreePrevious(session, TreeCurrentParent(session), 7,
cast(s32)WidgetKind.WidgetKindButton)
TreeBlurAt(session, previous)
}
if !sample.draw { return false }
// Keep a positive explicit height throughout the transition.
return Button.Draw(session, .{.key = 7, .id = 7, .label = "Print",
.bounds = .{0.0, 0.0, 88.0, 1.0 + 35.0 * sample.fraction},
.fit_content = true, .disabled = !sample.interactive}) != 0
}
```
Hold one state per child and session. If your composition can cancel a frame,
sample into a copy of the state and keep the copy when the frame commits.
A custom retained host can set monotonic seconds with
`kryon/frame_motion.SetFrameMotionTime` before `BeginFrame` and use
`FrameMotionMoving` after commit to keep the frame loop active during motion.
Desktop, Android and Canvas frame hosts supply their own clocks. The web DOM
backend uses CSS motion through the browser.
## Widget motion
`Menu.Props`, `TabBar.Props`, `Navigation.Props`, and `Collapsible.Props`
accept the following motion props. Import each widget from its named package.
Retain one zero-initialized motion state per widget, with a stable widget key.
| Motion prop | Meaning |
| --- | --- |
| `motion: *TransitionMotionState` | Caller-owned spring state; the state must outlive every call and must not be shared between widgets. A null pointer keeps the widget immediate |
| `now: float64` | Monotonic seconds; time zero is valid, equal or backward timestamps do not advance the spring, and a long pause advances at most 0.1 seconds per submission |
| `reduced_motion: bool` | Snaps to the target and clears `animating` |
Motion runs in native widgets and VM-rendered widgets. The portable
`KRYON_HOSTED_UI` TabBar bridge supports immediate rendering with
`motion = null` only. A nonnull pointer payload is rejected before dispatch;
hosted motion needs an explicit state-value and write-back protocol. Guest
addresses are never accepted as native host state pointers.
Each result adds `animating: bool`. Request another application frame while
any submitted widget returns true, supplying the real clock on that frame.
Once every result is false, motion needs no further frames. The first
submission initializes at the current target; subsequent target changes
retain position and velocity, including reversals. Time zero is valid. Equal
or backward timestamps do not advance the spring; a long pause advances at
most 0.1 seconds per submission. Retained session and tree identities reset
state when the widget moves to another parent, remounts, or changes kind.
Spring parameters per widget:
| Widget | Springs |
| --- | --- |
| Menu | Fades, grows from 96 percent and translates six units into place; 0.28-second opening and 0.16-second closing |
| TabBar | Tab indicators stretch toward the selected tab: leading edge 0.26 seconds with no bounce, trailing edge 0.42 seconds with 0.14 bounce |
| Navigation | Selection bounds 0.42 seconds with 0.16 bounce in full and compact layouts |
| Collapsible | 0.40-second spring for the reveal and quarter-turn chevron | Continue submitting the
menu and its current groups during closing. Closing panels keep visual paint
but immediately release their scrim, rows, focus, and activation ownership.
The menu retains indices and a content signature, never borrowed item slices.
Hit targets and returned selection geometry follow the actual controls
independently of the paint.
For Collapsible, `content` is the animated reveal rectangle; the application draws and clips
its body inside that rectangle and owns body interaction while closing.
`open`, focus, keyboard navigation, and close results keep their logical
meaning throughout the transition.
Explicit `reduced_motion`, theme `SetReducedMotion(true)`, or a nonpositive
theme motion multiplier snaps to the target and clears `animating`. A
positive theme multiplier scales spring durations. These controls affect
actual widget paint and reveal geometry.
The four widgets use the shared `TransitionSpringAdvance(spring, target,
delta, duration, bounce, immediate) -> TransitionSpring` integrator.
`TransitionMotionBegin`, `TransitionMotionValue`, and
`TransitionMotionActive` expose its caller-owned, four-channel state for
compositions. `TransitionMotionBegin` takes the clock, reduced-motion flag,
session slot/epoch, parent identity, own identity, and widget kind; callers
using it directly must supply actual retained identities. Treat a widget's
state as opaque while that widget owns it.
## View transforms
`view_transform.ViewFit(viewport, page_width, page_height, maximum)` returns
the state for a page that fills its viewport at zoom 1. The pure mapping and
mutation helpers convert between page and screen coordinates, zoom at a point,
pan, resize while preserving the visible centre, and drive a two-finger pinch.
Every mutation keeps zoom in range and leaves no empty space around the page.
Hosts observe wheel, pointer, and touch input and pass those observations in;
`ViewWheelFactor(notches)` supplies the bounded 1.2-per-notch wheel factor.
-25
View File
@@ -1,25 +0,0 @@
# Overlays
The six overlay families are retained Ziran widgets with caller-owned state and deterministic results. `Apply` functions are pure state transitions suitable to component hosting; widget functions take a `Session`, explicit props and a caller-owned state pointer, then submit popup/modal tree nodes and paint effects. No family owns process-global UI state.
Import `kryon/tooltip`, `kryon/sheet`, `kryon/command_palette`,
`kryon/hover_card`, `kryon/confirm_popover` or `kryon/guided_tour` under the
corresponding widget name. Each module exposes `Props` and `Draw`.
## Composition
- `Tooltip.Draw(session, props, state)` and `Tooltip.TooltipApply(state, props)` implement hover/focus delay, warm replay, touch/press suppression, truncation-only mode, placement fitting, flipping, clamping and ellipsis text.
- `Sheet.Draw(session, props, state)` and `Sheet.SheetApply(state, props)` implement all four sides, clamped min/max size, safe-area insets, scrim/Escape/drag close, deterministic motion and focus wrap/return.
- `CommandPalette.Draw(session, props, state)` and `CommandPalette.CommandPaletteApply(state, props)` implement fuzzy prefix/run/word scoring, stable command order, contiguous group starts, text editing, Up/Down/Enter/Escape, pointer activation and explicit owner takeover.
- `HoverCard.Draw(session, props, state)` and `HoverCard.HoverCardApply(state, props)` implement open delay, movement tolerance, content grace, interactive action dispatch, focus paths and placement fitting.
- `ConfirmPopover.Draw(session, props, state)` and `ConfirmPopover.ConfirmPopoverApply(state, props)` implement danger styling, initial confirm focus, Enter/Space confirm, Escape/cancel, outside close and trigger focus return.
- `GuidedTour.Draw(session, props, state)` and `GuidedTour.GuidedTourApply(state, props)` implement target geometry, padded highlight hole, four-band scrim, card fitting, count formatting, Back/Next/Done/Skip and three-focus wrap.
Each `*StateFor` constructor returns an isolated, serializable state value. Results identify nodes, geometry, interaction outcome and state change; callers supply `now_ms` and retain ownership. Empty `id`, `class_name`, key and action values follow the explicit prop values, while nonpositive geometry/delay fallbacks use the documented defaults in the matching `*_props.zi` module.
## Styles and semantics
Every family has typed `StyleData` props with installed selector facts for kind, ID, class, role, state and popup/modal/guide style kind. Caller styles merge over theme/selector values with `MergeValues`; state overrides resolve through `StyleStates`. Light and dark defaults come from `CurrentTheme`, and motion honors duration, multiplier and reduced-motion fields.
Tree nodes carry style ID/class facts plus interactive, popup, semantic kind, heading and label metadata. Paint uses the real queued raster API; no mock painter or parallel styling protocol exists.
-233
View File
@@ -1,233 +0,0 @@
# Painting and picture effects
This file covers painting primitives outside the widget catalog: vector paths, text as pixels, scene textures, light cookies, grades, daylight, image loading, window frames and window icons.
## Vector path coverage
`vector_path` rasterizes the portable `KVP1` filled-path format and round
polyline strokes into caller-owned 8-bit coverage. `VectorPathFill` accepts an
affine `VectorTransform`, so hosts can render either a complete image or an
integer-translated tile with identical pixels. `VectorPolylineStroke` uses the
same transform, target, and `VectorAdd` / `VectorErase` coverage arithmetic.
File helpers are bounds-checked; callers retain ownership of all bytes and
coverage storage.
Calls share bounded scratch storage and must be serialized. Targets may be up
to 8192 by 16384 pixels; invalid input or exhausted scratch returns `false`.
### Text as pixels
`#import "kryon/text_pixels"` exposes `TextPixels(value, font, color, width,
height, pixels) -> bool`: the host's own text raster letters VALUE at FONT
size in COLOR, centred on a transparent WIDTH by HEIGHT picture of straight
RGBA in PIXELS (at least WIDTH * HEIGHT * 4 bytes), shaped exactly as its text
on screen. Use it where text must become a texture, such as lettering on a 3D
surface. The desktop letters with Cairo and Pango (`RasterTextPixels`), the
web with the page's canvas in its text face; it is false before the desktop
raster exists and on Android.
Use the single public scene-image surface:
```zi
wood := LoadImagePixels("assets/wood.png")
options: SceneTextureOptions = .{
projection=.SceneTextureBox,
filter=.SceneTextureLinear,
wrap=.SceneTextureRepeat,
scale=.{3.0,3.0},
}
material := ImageMaterial(*scene, *wood,
LitMaterial(.{255,255,255,255}, 0.72, 0.0), options)
VecFree(wood.pixels)
unused RoundedBox(*scene, 1.8, 0.08, 0.32, 0.01, material)
```
`ImageMaterial(scene, image, base, options) -> SceneMaterial` validates and
copies a complete `std/image.Image`; the source can be freed immediately.
Equal images, including equal explicitly prepared mip levels, share one owned
scene texture. The scene releases logical storage in `SceneClear`/`SceneFree`.
Native GPU contexts upload the immutable copy once, reuse it without scanning
the image every frame, and release/recreate the upload with context lifecycle.
`SceneTextureOptions` contains `projection`, `filter`, `wrap`, `scale`, `offset`
and `mip_level`. Projection is `SceneTextureUV` or `SceneTextureBox`; box mapping
chooses a face from the dominant object-space normal, so moving, rotating or
scaling a bookshelf part does not make its grain swim. Filtering is
`SceneTextureNearest` or `SceneTextureLinear`, and wrapping is
`SceneTextureClamp` or `SceneTextureRepeat`. A zero scale component defaults to
1. `mip_level` is an explicit nonnegative level prepared once with a box filter;
its fixed selection makes native CPU and GPU results deterministic. Both
renderers filter sRGB texels in linear light and use the same clamp/repeat and
top-row/V-bottom rules. `SceneTextureCoordinate` exposes the exact object-space
coordinate transform for procedural geometry and tests.
`ImageMaterial` attaches scene textures. Shader samplers use programmable
linear-RGBA values; convert sRGB first when using those bindings.
### Light cookies
`LightCookie(scene, light, texture, scale, offset)` projects a scene texture
through a light's beam, like a gobo: dappled sun through leaves, window bars or
stained glass. `texture` is a scene texture index, usually
`ImageMaterial(...).texture`. The texel's linear RGB multiplies the light's
direct irradiance on every lit surface, receiver or not; the hemisphere light,
unlit and exact-colour materials are unaffected. The texture spans the light's
shadow box from `CastLightShadow` `scale` times, shifted by `offset` (in
repetitions), with bilinear filtering and repeat wrapping in linear light, so
the CPU and GPU renderers agree. A light needs a shadow box to carry a cookie;
`shadow_size` may be zero when no depth map is wanted. Only the first light
with a cookie projects one. Change `SceneLight.cookie_offset` between renders
to drift the pattern without rebuilding anything.
### Scene grade: a time-of-day look for pictures
`Scene.grade` (`SceneGrade`) lights scenes made of painted pictures, whose
unlit and exact-colour materials ignore scene lights and cookies. Every
material without `SceneMaterial.ungraded` keeps its colour C as
`(grey + (C - grey) * saturation) * tint`, plus C times the light of up to
four `lamps` (`SceneGradeLamp`: position, radius, sRGB colour, strength,
falling off as `1/(1+(d/radius)²)²`) and one `beam` (`SceneGradeBeam`): light
through an elliptical opening such as a round window. A surface point is in
the beam when the ray from it along `direction` crosses the ellipse `centre`
plus half axes `axis_u` and `axis_v`; `softness` fades the edge over that
fraction of the radius. Lit materials are graded after lighting. The grade
beam can receive real cast shadows: set `beam.shadows = true` and
`beam.shadow_light` to a directional light's index, configure its depth map
with `CastLightShadow`, and align the light's position/target with the beam's
direction. Nodes opt into casting and receiving with `SetShadows`. Only the
direct beam is occluded; ambient tint and local lamp light stay readable.
An absent shadow light leaves the beam unoccluded. This also works on unlit
painted surfaces, in both CPU and GPU rendering. Shadow maps respect material
opacity and texture alpha/cutoff, so foliage cards cast their painted
silhouettes instead of solid rectangles. `SetVisible` only affects the camera;
hidden nodes still cast shadows when enabled with `SetShadows`.
The grade applies before tone mapping. It is disabled by default; `SceneGradeNeutral()`
is enabled with white tint and saturation 1, leaving every colour exactly as
it was, and the renderers skip such a grade entirely, so a neutral hour costs
nothing per pixel. Change it between renders: it never rebuilds geometry and keeps
`FreezeGeometry`'s promise. The CPU and GPU renderers prepare it identically
(`PrepareGrade`) and agree within the GPU tolerance (`make scene-gpu-test`).
Mark skies and lamp glows `ungraded` so they keep their own colours.
### Daylight: sun, sky and grade by the hour
Import `kryon/daylight`. `DaylightAt(hour, latitude = -25.0)` (local solar
hours, wrapped to 0..24) returns `DaylightState`: the sun's direction for a
north-facing view (rising at 06:00 on +x/east, setting at 18:00 on -x/west,
north beyond the scene on -z), its height, day/full/golden weights,
linear sky colours, the sRGB grade `tint` and `saturation`, and 0..1 weights for
`lamps` (dusk to dawn), `beam` (sunlight throughout the day) and `stars`. The
path uses equinox declination and fixed 06:00/18:00 dawn/dusk, rather than
date/location-specific ephemerides. Negative latitude places the noon sun
in the northern sky; positive latitude places it south. `DaylightBeam`
admits light only from the outward side of the opening (the cross product
of its axes faces indoors), fading grazing rays. While
the sun is high (`full == 1`) the tint is exactly white and the saturation
exactly 1, so pictures keep their painted colours. `DaylightGrade(state)`
turns it into a `SceneGrade`; the app adds its lamps and beam, scaled by
`state.lamps` and `state.beam`. The app owns the clock, so it can follow the
local time or let a debug build set, fast-forward or rewind the hour.
`DaylightSky` is a storybook sky drawn by one material shader: a gradient from
horizon to zenith, the sun's glow and disc, two drifting cloud layers and
twinkling stars, from a 256-pixel tileable noise texture made in code at
`DaylightSkyInit` (no image files). Each frame call
`DaylightSkyUpdate(sky, state, seconds, aspect, horizon)` with the plane's
width over height and the horizon's height (0..1) on it; seconds drive the
clouds and stars. Draw it on a plane whose UV runs left to right and bottom to
top with `DaylightSkyMaterial(*sky.program, sky.uniforms[:], sky.samplers[:])`
(unlit, exact colour, ungraded); keep the sky at a stable address while it is
drawn and release it with `DaylightSkyFree`. `tests/daylight_test.zi` covers
the hours, the sky and the grade on native and portable builds (`make
daylight-test`).
Linux uses the system image loader and packaged WebP/AVIF adapters,
copying the original straight pixels before Cairo premultiplies them. Android reads relative APK asset paths
through the current NativeActivity's asset manager, or absolute filesystem
paths. It decodes PNG, WebP and AVIF in process with the linked codecs, on every
supported API level. Other formats, such as JPEG with its orientation, need the
activity's `decodeBundleImage(byte[])` method: it returns width, height and
then ARGB_8888 pixels, or null, and the droid template provides it. Without
it those formats fail empty and Kryon logs once that the method is missing.
Unsupported formats fail empty; this API does not promise WebAssembly AVIF
support.
These are CPU images and survive presentation context teardown.
`make image-pixels-test` verifies exact RGBA/alpha ownership and invalid inputs.
`make shader-host-test` and the explicit hardware target
`make shader-android-test` additionally execute the loader in their real hosts.
The Android console test covers absolute PNG files and the real offscreen native
window. `make android-pictures-device-test` decodes AVIF textures and checks the
missing bridge inside Android's VM on the USB Moto.
Custom native and Canvas hosts can import `kryon/window_runtime` for
`BeginWindowFrame`, `ClearWindowFrame(color)` and `EndWindowFrame`.
`CloseNativeWindow`, `WindowHidden`, `WindowMinimized` and `WindowClosing`
keep the backend's window semantics. These observations do not
poll input, change focus, pause work, or decide whether closing hides or quits.
Applications using retained frames keep their retained presentation lifecycle.
`WindowWidth` and `WindowHeight` report the custom desktop host's drawing
surface or Android's current native pixel extent. Desktop frames use the same
SDL/Cairo window opened by `Desktop.OpenDesktopSized`; resize takes effect at
`BeginWindowFrame`. Clearing replaces the whole Cairo surface, including alpha,
while preserving the caller's clip for subsequent drawing. Android frames lock,
paint and post NativeActivity pixels directly, and pause while the activity is
paused or has no window. `SyncWindowSurface` refreshes Android's shared surface
and touch transform. Closing requests activity shutdown, drains its lifecycle
commands, then frees its native pixels. Canvas keeps its page lifecycle.
Custom hosts import `kryon/window_icon` for
`SetWindowIcon(encoded: string, file_type: string) -> bool`. Encoded bytes
are borrowed for the call; native hosts decode through their shared image
codecs, apply JPEG orientation, and preserve full dimensions and straight
alpha. The native window must already exist. False means invalid or
unsupported data, a missing SDL window, or a browser/Android host where the
application icon belongs to the page or package manifest. Native AVIF uses the shared codec libraries.
Desktop image services include `RasterInvalidateImage(path) -> bool`,
`RasterInvalidateImagesIn(folder) -> s32`, and `RasterInvalidateImages() -> s32`.
They remove cached file pictures and their pending smooth copies; folder matching
respects path boundaries. Counts report entries removed. `ImagePreviewDecode`
uses the desktop image decoder's bounded, oriented RGBA output; release its
pixels with `ImagePreviewRelease`.
`FramePreviousSnapshot() -> FrameSurface` captures an owned copy of the previous
frame on desktop and Android. Call it after composing a new route and before
painting, draw it with `FrameTransition` using the full logical frame bounds
(including a negative camera origin), and call `FrameSurfaceRelease` when the
transition ends or is canceled. `FrameSurfaceCopy` owns an independent copy.
The Web host returns an invalid surface, so callers skip the fade there.
### Indexed animated surfaces and watercolor
Import `kryon/scene_skin` for `SceneIndexedMesh`, `SceneSkinCreate`,
`SceneSkinDeform` and `SceneSkinRelease`. Indexed surfaces copy positions,
normals, UVs and triangle indices into their owning `Scene`. Triangle indices
address the mesh's own vertices, not the scene's vertex list. A `SceneSkin`
retains bind positions and four normalized joint weights per vertex. Supply
final bind-to-pose `SkinAffine` transforms; deformation always starts from
bind data and uses inverse-transpose normal transforms, including nonuniform
scale. Invalid indices, weights and singular transforms are rejected before
changing visible geometry. Release the skin before reusing or freeing its
scene. Bone animation and inverse kinematics belong to the caller.
Import `kryon/watercolor` for `WatercolorMaterialCompile` and
`WatercolorFinish`. The portable material samples real paper and pigment
RGBA bitmaps and supplies soft directional light and a Fresnel rim. Uniform
0 is UV repetition, 1 light direction, 2 view direction, and 3 rim RGB with
zero W; samplers 0 and 1 are repeated linear paper and pigment images. Keep
the program, uniforms and images alive while rendering. Use an unlit scene
material when this program supplies the final lighting. The finishing pass
uses caller-owned retained scratch, brush radius 0–2, and brush, grain,
edge, pooling and contour strengths 0–1. Pooling darkens pigment within two
pixels of the silhouette; contour draws a graphite pencil line on the
silhouette and where neighbouring washes differ. It preserves source alpha
and excludes transparent samples from pigment filtering. CPU and translated GLSL share the material;
no window or platform graphics dependency is required.
Desktop `LoadImagePixels` accepts the host's optional
`ImagePixelsUsePathResolver` callback, so the same loader can read bundled
assets and disk files. A resolver borrows its input path and an output buffer
and returns a retained file path (or empty to keep the original). Loading and
resolver registration belong to one owner thread; the host retains resolved
files until decoding finishes. `ImagePixelsClearPathResolver` restores disk loading.
The image loader does not import a raster backend or open a window.
-173
View File
@@ -1,173 +0,0 @@
# Repeatable performance checks
`python3 tools/performance.py` builds an optimized native, display-free runner
and measures four workloads at 960 × 600 pixels: a scrolling 10,000-item list,
an 8 KiB wrapped Unicode document, 144 images, and 20 idle controls. Each has
10 warmup frames followed by 60 measured frames. Reported values include
submission, combined commit/raster and total median/p95 times, nodes, paint
commands, raster emissions, damage pixels, workers and runner peak RSS.
The idle workload must emit zero unchanged paint commands.
Use a same-machine baseline for a regression gate:
```sh
python3 tools/performance.py --output backup/performance-baseline.json
python3 tools/performance.py --baseline backup/performance-baseline.json --max-regression 0.20
```
Comparison rejects mismatched hardware, compiler command, optimization,
viewport, warmup or requested worker count. A p95 regression fails when it
exceeds the percentage and adds more than 0.2 ms. `--budget-ms 64` provides an
absolute p95 ceiling for every workload; CI uses this generous ceiling to
catch large regressions across shared runners. Local baselines give a tighter
check on fixed hardware. The JSON retains check results and failures.
The build directory is stable and locked for the whole run. Desktop variables
are scrubbed. RSS comes from the native runner's `/proc/self/status` VmHWM
after the measured frames. Unlike a launcher's `wait4` high-water mark, it
excludes the Python process's memory before exec. Schema 2 baselines use this
measurement. The timings
exclude warmup; the runner CPU-seconds counter includes initialization and all
warmup/measured frames, and excludes compilation and the Python launcher. Timings
cover the pixmap pipeline, not native window presentation, asset decoding,
screen-reader overhead, process idle wakeups or GPU/browser rendering.
The widget review harness measures actual public controls, rather than mock
faces. It includes the core gallery scenes plus light and dark system-palette
compositions. Each interactive scene captures resting, disabled, hover, keyboard
focus and held-press states, using the same 480 × 320 viewport.
```sh
taskset -c 2 python3 tools/widget-review.py before --backend pixmap
taskset -c 2 python3 tools/widget-review.py before --backend desktop
# Change the shared library only after both baselines finish.
taskset -c 2 python3 tools/widget-review.py after --backend pixmap
taskset -c 2 python3 tools/widget-review.py after --backend desktop
taskset -c 2 python3 tools/widget-review.py compare --backend pixmap
taskset -c 2 python3 tools/widget-review.py compare --backend desktop
taskset -c 2 python3 tools/widget-review.py recheck --backend pixmap --trials 7
taskset -c 2 python3 tools/widget-review.py recheck --backend desktop --trials 7
```
The stable executables and disposable generated C live under
`build/scratch/widget-review/`. Captures, bounded per-frame CSV, JSON metrics and
comparison PNGs live under ignored `backup/material-widgets/`. Each backend has
its own `comparison-BACKEND/grid-overview.png` and full-size state comparisons.
A second baseline replaces the previous baseline, so preserve any earlier study
before starting another.
Use `--output-dir backup/material-widgets/navbar` or
`--output-dir backup/material-widgets/perf` for an independent study; this also
selects that study's fixture image. `--scenes 20` limits a capture to the
NavigationBar. Keep previous studies in place instead of reusing their output
directory. The normal executable paths stay stable.
Cairo retains up to eight owned Pango layouts for alternating labels and font
sizes; long editor runs share one slot. Layouts are released when the raster
closes or resizes. Retained paint text uses 512-byte snapshot blocks, so a short
frame initially reserves 4 KiB instead of 32 KiB while larger frames still grow
without truncation. Pixmap fills opaque spans in bounded groups of four pixels;
the translucent rounding and coverage remain unchanged. Validate memory with
both peak heap allocation and RSS: small heap savings need not reduce the
process's resident high-water mark on every run.
Both hosts run 10 warmup and 120 measured frames for **each** state and mode.
Retained mode tests that unchanged frames emit no raster commands. Forced repaint
invalidates the paint snapshot before every frame and includes widget composition,
commit, rasterization and, for desktop, SDL texture upload/presentation. Timings
include monotonic wall time and process CPU time. They are CPU-side measurements,
not GPU timestamps or input latency. The desktop uses SDL's software presentation
on private Xvfb; the pixmap uses its actual CPU raster and bundled font outlines.
The fixture image is identical on both hosts.
Runner `/proc/self/status` supplies peak and steady RSS after warmup/measurement;
it excludes the Python launcher. Steady RSS can exceed an earlier high-water
sample by a page when the status reader itself faults a page. Startup is the
in-process interval from runner entry through its first complete frame, including
host setup and font work, but excluding the OS executable loader and compilation.
Binary size and its SHA-256 are recorded with the samples. The text reservation
counter covers reusable frame-owned label/path storage, not total memory.
The comparison JSON gives medians across scene/state cases and the largest
observed process high-water RSS across both modes. It flags per-case timing
increases above both 5% and 0.025 ms for investigation; repeat flagged cases to
distinguish reproducible costs from shared-machine variation. `recheck` runs each
flagged case three more times with the recorded after executable (verified by
SHA-256), preserves the initial samples, and fails for a confirmed increase in
the median of the repeats. Raw repeats and their summary stay beside the captures.
Use `recheck --backend desktop --trials 7` for a longer investigation on a noisy
shared machine; this keeps the same threshold and records all seven trials.
For close comparisons pin both phases to the same single allowed CPU core, as
above, to avoid migrations between differently loaded cores.
Idle CPU covers a 200 ms quiet interval with five 40 ms sleeps and, on desktop,
its ordinary event poll; no frames are submitted in that interval. Together with
zero retained raster emissions this tests the harness's idle behavior, rather
than claiming that every downstream application's event loop sleeps. No renderer
thread, timer or animation is added by the default style. CPU affinity is recorded.
All captures use private Xvfb with inherited display/auth/session variables scrubbed
and desktop recovery disabled. This does not measure Android hardware, a physical
GPU, a desktop compositor, browser behavior or terminal-cell fidelity.
The GPUI reference uses the same five 480 × 320 scene families in a disposable
Cargo project pinned to GPUI 0.2.2 and libc 0.2.186. Its default measurement
covers GPUI `TestAppContext` root render/layout/prepaint/paint only; it does not
execute GPU work, present a frame or include compositor wall time, and therefore
is not interchangeable with Kryon's compose-only or hardware presentation phases.
```sh
python3 tests/gpui_render_benchmark.py \
--trials 3 --warmup 120 --frames 120 \
--output work/backend-render-benchmark/gpui-render-benchmark.json
python3 tests/gpui_render_benchmark.py --gpu-probe \
--device /dev/dri/renderD129 --trials 3 --warmup 120 --frames 120 \
--output work/backend-render-benchmark/gpui-render-benchmark-gpu.json
```
The second command starts a private headless Weston GL instance on the selected
AMD render node. GPUI 0.2.2 currently requires the Wayland `wl_seat` global;
headless Weston has no seat, so the report records the exact client unwrap
limitation instead of presenting an unsupported CPU-to-GPU comparison. Generated
Cargo inputs remain under `build/scratch/gpui-render-benchmark`, while reports and
logs remain under ignored `work/backend-render-benchmark/`.
# Renderer performance benchmark
Run `build-queue -- python3 tests/scene_render_benchmark.py --output PATH`
on Linux. The benchmark enables `POSIX_THREADS`; `ZIRAN_PAR_THREADS=1` selects
the same renderer serially. `CC` can select a compiler wrapper. The benchmark
retains four MSAA samples per pixel and the complete 960x600 and 420x900 output. It measures
clear/resolve, unlit meshes, textured meshes, a 12-instruction programmable
material, and standard lit meshes. The texture is 1024x1024; the scene has a
wall and four rounded boxes. Each workload warms once, then measures three
camera positions. Geometry construction and full-frame hashing are outside
the timed region. Rows contain width, height, workload, frame, wall nanoseconds,
process CPU nanoseconds and an RGBA pixel hash. CPU time separates rendering
work from scheduling delays; it does not predict an application's frame rate.
Use `--compare PATH` with an earlier output to require all 30 pixel hashes to
match and report median speed ratios. Add `--motion` for 120 changing-camera
frames per workload at 960x600, 420x900 and 1280x800. It reports p50/p95/p99,
the count within the 16.67 ms budget, cold render time, retained scratch and
sampled process peak RSS/HWM; it also checks all 1,800 motion hashes when the
comparison contains them. Every sample is retained, including slow frames.
`--shadows` instead adds 120 motion frames at each resolution for a lit
programmable material, a 1024-square shadow map and the unchanged five-tap
soft-shadow disk. Compare against an earlier `--shadows` output to check all
360 shadow hashes. The original 30 reference frames still run in this mode.
`--overdraw` instead adds 16 opaque lit programmable planes, with 12 changing
camera frames at each resolution after warming that camera path's clipping
capacity. Compare against an earlier `--overdraw` output to check all 36 motion
hashes. Statistics rows record the final frame's projected layers, visibility
pass choice and material evaluation counts.
The benchmark checks fixed scratch capacity during these camera motions and
zero scratch after release. It measures rendering only: presentation, image
uploads and application geometry/state updates require application profiling.
These are local tests, not GPU timings or application frame-rate claims.
The renderer reuses sized scratch buffers, converts fragment output once for
its covered samples, and caches the exact byte-to-linear transfer. The output
lookup searches thresholds generated from the original transfer and rounding;
it does not reduce color precision. Shader vector arithmetic dispatches once
per instruction. These changes retain clipping, blending, depth and sampling
behavior; the shader regression renders both sides of every output-byte edge.
-90
View File
@@ -1,90 +0,0 @@
# Persistence and notifications
Durable document storage with acknowledged flushes, and Android OS
notification scheduling. Read this when app data must survive a restart or a
game needs reminders.
## Document persistence
The `kryon/app_context` export provides `DocumentStorageReady() -> bool`
and `DocumentFlush() -> bool`, bound to `app_context:DocumentStorageReadyHost`
and `app_context:DocumentFlushHost` (both zero arguments, bool result).
`AppLocal` and the direct Canvas app host implement them. Other hosts must
explicitly grant and dispatch these capabilities; importing them grants no access.
Readiness is nonblocking: true requires an open private document namespace and,
in a browser, successful initial IndexedDB hydration. Before readiness, reads
report `DOCUMENT_ERROR`, writes and flush return false. The host opens storage
with `AppFilesOpen` after hydration; the guest does not initialize host storage.
`DocumentWrite`/`WriteStore` use queued browser semantics. A true write
result alone does not acknowledge persistence. After successful writes,
`DocumentFlush` returns true only when the backing store has acknowledged a
snapshot including those writes. It waits for any previous snapshot, then
requests and awaits a fresh one. Later writes remain in memory for a subsequent
flush; this operation neither clears a host's pending-write flag nor reloads
files from storage. Failure, unavailable storage, a 15-second browser deadline,
or namespace revocation returns false. False does not roll back queued bytes
or promise that an already running backend transaction has been cancelled.
The native provider syncs file bytes before atomic replacement and syncs parent
directories after rename, including new ancestors. Platforms/filesystems that
cannot sync directories reject that write rather than claim durability. The
browser reuses IDBFS and Asyncify; its acknowledgement is the successful IDBFS
transaction callback, subject to the browser's persistence/eviction policy.
Atomic replacements have distinct mtimes even within one millisecond, as IDBFS
uses mtimes to detect changes.
Hosts use `AppFilesReady(files)` and `AppFilesFlush(files)` for their authorized
`AppFiles`. The no-argument guest operation cannot name or read another node.
The browser backing store is the shared `/kryon-apps` mount: the host's
physical sync can include other queued namespaces, without exposing their paths,
bytes, handles, or authority to the guest. An AppFiles outside this mount can still stage packed assets, but reports
false for durable readiness and flush. Initial hydration is never restarted by flush.
Call on the owning thread. Browser flush yields; keep the owner and its AppFiles
alive until it returns and never reenter its running VM while suspended. Close
with `AppFilesClose` before changing account/resource ownership or rebinding the
namespace; close/open increments a generation, and an in-flight flush then
returns false even when its snapshot write succeeds. Do not overwrite live AppFiles
or mutate its root/lock directly. Readiness is availability, not an account grant.
`make -j1 document-storage-test` exercises native and actual disposable headless
IndexedDB storage, source/saved compilation and portable AppLocal dispatch.
## Local notifications
`kryon/notification_schedule` schedules Android OS reminders independently of
push, network access, and the running app loop. `DailyNotificationsSupported()`
reports scheduler support independently of permission. Other native platforms
return false; portable apps use their authenticated host capability.
| Call | Effect |
| --- | --- |
| `ScheduleDailyNotification(props, hour, minute=0, suppress_on_open=false, not_before_unix_ms=0, weekdays=127, skip_local_date=0)` | Persists one rule. Weekday bits are Sunday=1 through Saturday=64. Times use the device's current timezone; `not_before_unix_ms` is an absolute UTC lower bound. `skip_local_date` excludes one YYYYMMDD date, for example today's completion |
| `ScheduleNotificationAt(props, year, month, day, hour, minute=0)` | Schedules one local date; an elapsed date/time is rejected |
| `ScheduleNotificationDates(props, dates, hour, minute=0)` | Keeps one alarm for a caller-evaluated, finite sequence of at most 3660 strictly increasing valid YYYYMMDD dates. Apps own recurrence and refresh this explicit horizon |
| `CancelDailyNotification(tag, id)` | Cancels any of those rule types and its visible notification. Reusing `(tag,id)` replaces the rule |
| `NotificationAppOpened(tag,id)` | Durably marks that particular rule's local date and cancels its visible notice. Games call it on actual game entry, resume and local date changes while playing. A collection host must never mark its other games opened when the host foregrounds |
Scheduling persists even before permission is granted and never prompts.
Applications request permission through `notification.RequestNotifications`;
Kryon's Android host prompts once and preserves a refusal. System notification
settings remain authoritative. Failed scheduling returns false. Android's
inexact alarms can arrive later during idle; force-stopped applications cannot
receive alarms until relaunched. Reboot, clock, timezone and package-replacement
broadcasts rebuild future alarms from private preferences. Dates already opened
or delivered remain suppressed when the clock moves backward. Android allows at
most 480 active Kryon rules per host package and 64 per authenticated hosted app;
replacements do not consume another slot and cancellation frees it.
The Android scaffold declares the notification receiver, POST_NOTIFICATIONS
and RECEIVE_BOOT_COMPLETED permissions, and receiver actions.
Include `android_notifications` in the native graph so receiver exports survive
linking. `notification_desktop` dispatches immediate notification effects to the
Android implementation when ANDROID_BUILD is defined. Custom activities provide
`requestKryonNotifications()` using the scaffold's UI-thread callback.
In-app `Toast.Props.seconds` is independent: a toast's caller chooses display
length. OS notifications have no app-chosen toast deadline and remain subject
to Android's notification settings and user dismissal.
-564
View File
@@ -1,564 +0,0 @@
# Ziran projects with Kryon
Kryon is a Ziran package. Application source imports its public modules, and
the selected Kryon host links the application's `Frame` function. No UI syntax
or widget handling is built into the Ziran compiler.
## Start a project
Install `ziran` (`make install-user` in the Ziran repository) and the `kryon`
command (`make install-user` here), then:
```sh
kryon new hello # a desktop app; kryon new hello --template tui
cd hello
kryon run # the default profile; kryon run tui picks another
```
| Template | What it starts | Profiles |
| --- | --- | --- |
| `app` (default) | counter with buttons, a step slider, and progress | `desktop`, `tui`, `web` (canvas) |
| `tui` | keyboard-driven task list | `tui`, `desktop` |
| `pages` | Home, Library, and Settings behind a tab row, sharing state | `desktop`, `tui`, `web` (canvas) |
| `web` | page: headings, paragraphs, links, a button | `web` (Canvas2D), `desktop` |
Each template's `src/layout.zi` stacks rows in pixels in a window or browser
and in character cells on the terminal host, so one `Frame` serves every
profile. `kryon init --template tui` adds a template to an existing package:
Ziran merges it into `ziran.toml`, keeps the package's own values, and never
overwrites a file, so a command-line program keeps its `main` and gains a
window.
`kryon` is a front door to `ziran`: `kryon new` and `kryon init` are
`ziran new` and `ziran init` with Kryon's templates (`--template NAME` for
Kryon's, or any `SOURCE[:NAME]`), `kryon run|build|check|profiles` is
`ziran tool kryon …`, and `kryon install` is `ziran install`. Each project
therefore runs the Kryon its `ziran.lock` pins, whatever version of the
`kryon` command is installed. `KRYON_TEMPLATES=DIR` takes the templates from
a local Kryon checkout.
## Package manifest
A Kryon application is a Ziran package whose `ziran.toml` hands its program
to Kryon:
```toml
[package]
name = "Example"
entry = "src/app.zi"
module_roots = ["src"]
tool = "kryon"
[toolchain]
git = "https://github.com/ziranlang/ziran.git"
ref = "master"
[dependencies.kryon]
git = "https://github.com/kryonlabs/kryon.git"
ref = "master"
[tool.kryon]
default_profile = "desktop"
[tool.kryon.profiles.desktop]
backend = "desktop"
```
`tool = "kryon"` makes `ziran run`, `ziran build`, `ziran check`, and
`ziran install` the same as the `kryon` commands. The build binds the host's
frame capability to the selected source's exported `Frame` function. The source
can have any module filename, such as `button.zi`; no `app.zi` alias or reverse
module bridge is needed. `[tool.kryon] entry` selects the source with `Frame`
when it differs from the package entry, as in a command-line package that also
has a window. The app imports the small `kryon/app` runner and only the named
widget packages it uses:
```zi
App :: #import "kryon/app";
Text :: #import "kryon/text";
main :: () -> s32 {
return App.Run(App.Window.{.title="Hello", .width=320, .height=160}, Draw)
}
Draw :: (frame: App.Frame) {
Text.Draw(frame, Text.Props.{.text="Hello, world!", .size=32})
}
```
Style sheets, charts, tables, trees, and source coloring are separate Git
packages: add `https://github.com/kryonlabs/css.git`,
`https://github.com/kryonlabs/plot.git`,
`https://github.com/kryonlabs/data-views.git`, or
`https://github.com/ziranlang/syntax.git` with `ziran add` and import
`css/Css`, `plot/Plot`, `data_views/TableView`, `data_views/TreeView`, or
`syntax/Syntax`. Kryon exports `geometry`, `drawing_props`, and the other
building blocks listed in `ziran.toml` for code that needs those primitives
without importing the widget catalog. Native and browser profiles resolve
imports the same way, so an app's Git dependencies and package-qualified
named imports such as `kryon/text` work in Canvas builds too.
From the app directory, run:
```sh
kryon check
kryon build
kryon run desktop # or: kryon run --profile desktop, ziran run desktop
kryon profiles # the profiles, their hosts, and the default
kryon run shot --png build/shot.png --width 390 --height 844 --theme dark
kryon run --watch # rebuild and relaunch after every saved change
```
`kryon run [PROFILE] --watch` builds a desktop or terminal C99 profile into
`build/watch/PROFILE`, runs it, and polls the project's files (all but
`build/` and hidden entries) four times a second. A change stops the app,
rebuilds and runs it again; a failed build waits for the next change. The
app shares kryon's process group, so Ctrl-C stops both.
`kryon run [PROFILE] --png FILE.png` renders the app's own entry offscreen,
with no display and no preview fixture, and writes `FILE.png` and its widget
tree `FILE.json` (the [preview JSON](FRAME_REPLAY.md#native-fixture-preview)).
`--width` and `--height` take 1–4096 pixels (960 × 600 by default); a comma
list of widths writes `FILE-PX.png` per width. `--theme light|dark` picks the
palette (light by default). The named profile must be a desktop or pixmap C99
profile, and the entry must export `Frame`; the desktop renderer draws the
picture in either case, so it matches the window. The capture build lives in
`build/shot/PROFILE`.
Commit `ziran.lock` to pin exact package and toolchain revisions. `ziran
fetch` fills the shared cache. For local development, `ziran.local.toml` can
override the Kryon and Ziran roots; it is not the published dependency
manifest. See the [Ziran package
guide](https://github.com/ziranlang/ziran/blob/master/docs/PACKAGES.md)
for lock, cache, and override details.
## Profiles and hosts
### Foreign renderer artifacts
Builders can request Kryon's foreign libraries and standard resources through
the generic Ziran artifact API:
```sh
ziran pkg artifact kryon:renderer-desktop --platform linux-x86_64-gnu --locked
ziran pkg artifact kryon:renderer-web --platform emscripten-wasm32-emscripten --locked
```
Omit `--locked` when using `ziran.local.toml` overrides. Success stdout is one
absolute `artifact.tsv` path. Verify its declared SHA-256 output rows and resolve
their paths beside that descriptor. `renderer.json` has schema 1, the artifact
and platform, ordered `archives` and `link_flags`, `compile_flags`, Ziran
`defines`, `include_directories`, and `resources`. Paths in those fields are
relative to the descriptor directory; system flags are argv tokens. Pass archive
paths after application objects, followed by `link_flags`. Pass compile flags
and resolved include directories when compiling native code; pass defines to
Ziran's ordinary compiler invocation. No generated Ziran source tree or object
list is part of this contract.
Every recipe includes `resources/kryon-font.ttf` and its Liberation license.
Linux desktop builds use SDL2, Cairo, FreeType, Pango, Fontconfig and GIO.
`renderer-web` supplies `web/ziran_web.js` from the selected Ziran toolchain,
`js_libraries`, browser link flags and `preload_files` entries (`path`, `mount`)
for the standard font at `/kryon-font.ttf`. Feed these to Emscripten's
`--js-library` and `--preload-file` arguments. Game resources remain separate.
Widget and renderer Ziran code remains ordinary `kryon/...` imports. These
artifacts do not provide a separately compiled Ziran component ABI: the current
generic artifact API stages provider files but does not define such a language
component interface. Builders must not rewrite generated C/H or reconstruct a
private module/object list to manufacture one.
Define each profile under `[tool.kryon.profiles.NAME]`. It requires `backend`;
`codegen` defaults to `c99`. Supported backends are `terminal`, `desktop`,
`canvas`, `pixmap`, and `android`. Set `default_profile` under `[tool.kryon]` when there
are several profiles. `--profile NAME` selects another. `run` asks for a
profile when there are several, none is specified, and it runs in a
terminal; otherwise it uses the default.
| Backend | Host | Requirements |
| --- | --- | --- |
| `terminal` | 80 × 24 terminal cells | TTY for interactive input; redirected output renders once |
| `desktop` | SDL2 window with Cairo raster | SDL2, Cairo, and FreeType development libraries |
| `canvas` | Canvas2D browser page | Emscripten with Asyncify; see [Canvas host](canvas.md) |
| `pixmap` | headless 960 × 600 frame printed as a PPM image; `--png` draws any size instead | nothing; `kryon run shot > frame.ppm` |
| `android` | installable APK through a generated `droid/` Gradle project and direct NativeActivity host | a JDK, the Android SDK with NDK `28.2.13676358` and CMake `3.22.1`, the locked codec source packages, and `[tool.kryon.android] package`; see [Android host](BACKENDS.md#android-host) |
The SDL desktop host presents its already rasterized pixels through the
software renderer and an unaccelerated window surface by default. Custom
SDL pixel hosts can import `kryon/pixmap_sdl` and call
`CreatePixmapRenderer(window)` on the window's owner thread before creating
their texture. The host retains ownership of its window, renderer, texture
and input loop; its raster workers are independent of this presentation choice.
Explicit `SDL_RENDER_DRIVER` and `SDL_FRAMEBUFFER_ACCELERATION` environment
preferences, or normal/override priority SDL hints, take precedence. The
helper leaves other hosts and their graphics APIs untouched.
Such a host can also paint on the GPU by importing `kryon/pixmap_sdl_gpu`.
`PixmapGpuOpen(renderer)` records the same paint commands as textured triangles,
including text and terminal cells through a glyph atlas, and returns false on a software renderer or software GL
driver, where the host keeps uploading pixels. While it is on, create the
presented texture with `PixmapGpuCreateTarget(width, height)` and call
`PixmapGpuDraw()` instead of uploading damage, then copy and present as usual.
`KRYON_PIXMAP_GPU=0` keeps CPU painting; `=1` also uses a software GL driver.
For a custom **SDL3** host, the experimental exports are `kryon/pixmap_sdl3`
and `kryon/pixmap_sdl3_gpu`; they require an SDL3 window and explicit `gpu`
renderer. There is no `backend = "sdl3"` profile. From an application's package
graph, request the pinned SDK with:
```sh
ziran pkg artifact kryon:native-sdl3 --platform linux-x86_64-gnu --locked
```
Use `--locked` when there is no `ziran.local.toml`. With local overrides, run
`ziran lock` after the overridden package advances before requesting artifacts.
The native artifact is
currently Linux x86_64 GNU only. Verify the returned descriptor with Ziran's
`Artifact` API; `Artifact.link_flags()` supplies the ordered static linker
arguments. Verify and extract `Artifact.output("resources/SDL3-headers.tar")`
into the consumer's build area for the complete include directory. The loose
SDK headers are not all declared outputs, so use the verified archive for
compilation. This SDK is native support for custom hosts, not a replacement
renderer selection for an existing desktop profile. See
[experimental SDL3 usage and tests](BACKENDS.md#experimental-sdl3-gpu-renderer).
These settings live only in `ziran.toml`. Kryon declares them under
`[options]` in its own `ziran.toml`. Ziran checks the application's
`[tool.kryon]` tables against that declaration, merges `ziran.local.toml` over
them, and hands the kryon tool the result, so a typo is reported with its file
and line. To try another default profile on one machine, set it in the ignored
`ziran.local.toml`:
Native C profiles also link every system library declared in the root
`[package].links` list, in manifest order. Use system basenames such as
`links = ["gtk-3", "gdk-3", "gio-2.0", "gdk_pixbuf-2.0"]`; the build uses the
system linker's normal search paths. Portable and browser profiles do not
consume this list.
`static_archive` links one project-relative `.a` file directly. The project's
own build prepares the archive, and Kryon adds that exact path as both a build
dependency and linker input. This is for reproducible source-package artifacts;
it performs no `-l` lookup and never selects an operating-system package. The
path cannot be absolute or lexically escape the project directory. Kryon also
resolves the archive and rejects a symlink that leaves the project or a
non-regular file. Browser profiles reject the setting instead of silently
omitting it. `library` remains the existing system-library escape hatch and
should be avoided by reproducible applications.
Native `c99` profiles can instead request dependency-owned foreign support
with `native_artifacts` and an explicit `native_platform`:
```toml
[tool.kryon.profiles.desktop]
backend = "desktop"
native_artifacts = "kryon:renderer-desktop"
native_platform = "linux-x86_64-gnu"
```
This adds the desktop codec support and resources to the SDL/Cairo profile.
Use space-separated `package:artifact` selections for several providers.
Selections come from the application's resolved package graph; no cache
paths or prebuilt archive copies belong in its manifest. The toolchain must
provide Ziran's [shared artifact consumer](https://github.com/ziranlang/ziran/commit/ee86330414a2febb0135d86506b505af5e6a660b).
Each build requests and verifies the artifacts before linking, so changed
provider inputs or local overrides cannot leave an old executable in place.
Kryon's renderer metadata or a provider's ordered `link.txt` supplies its
archives and prerequisite/system link arguments. These appear after the
application objects and before the profile's existing system libraries.
Provider failures, malformed metadata and digest mismatches fail the build;
the existing executable is replaced only after the complete link succeeds.
These options require a native `c99` profile; browser, Android and portable
profiles use their existing target-specific packaging paths. Compile options
and application asset packaging remain the selected profile's responsibility.
```toml
[tool.kryon]
default_profile = "tui"
```
## Zx applications
Desktop, Canvas and Android profiles can package an ordinary `Frame`
application as the same portable program with its resources:
```toml
[tool.kryon.profiles.portable]
backend = "desktop"
codegen = "zx"
assets = "assets"
```
Use `backend = "canvas"` with `codegen = "zx"` for the same portable app
and a browser player. The build writes both `.zx` and `.html` files; serve
the HTML with its generated JavaScript and WebAssembly files. The browser
shell interprets the bundle and uses Canvas2D for rendering. It includes a
file picker for opening another downloaded ZX without recompiling its UI.
Unsupported required services are reported before replacing the running app.
An Android profile with `codegen = "zx"` builds its portable guest first,
then packages `app.zx`, the VM and the NativeActivity host into the APK. Its
`Frame` is not compiled into native application code. The canonical scaffold
handles display density, safe-area insets, touch, hardware/soft-keyboard input
and graphics restoration without resetting bundle state. It also registers a
ZX file opener: Android document URIs are copied into private cache and
validated before replacing the running app. Invalid files retain the current
instance. `make zx-android-test` builds ARM64, ARMv7 and x86-64 shells. Runtime testing
uses `python3 tests/zx_android_test.py --serial emulator-NNNN` and accepts
only an explicitly selected disposable emulator.
`make zx-canvas` builds a generic browser player with no embedded app.
`ZX_CANVAS_BUNDLE=/absolute/path/app.zx` optionally embeds a default app.
A same-origin relative `?bundle=path/app.zx` opens a hosted download.
The browser player supports ordinary `Frame` bundles and standalone
`AppContext` apps, drawing, input, fonts, embedded images and the browser
clipboard. Native, Android and browser players provide packed audio,
asynchronous HTTP audio/text and a monotonic clock. Requests accept only
HTTP/HTTPS; guest paths cannot read host files. Android ZX scaffolds include
a network manifest overlay; ordinary native builds do not use that overlay.
Standalone `AppContext` apps use the existing lifecycle and hosted widget
contracts. They receive a private document directory per declared app ID,
wall time, local time offset, locale, embedded assets and clipboard services.
Native apps save on close; browser apps save periodically to IndexedDB and
restore on reload. Native documents live under `$XDG_DATA_HOME/kryon/apps`
(or `$HOME/.local/share/kryon/apps`), `%LOCALAPPDATA%/kryon/apps` on Windows,
and Android's private application storage. `KRYON_APP_DATA` can select a
different native parent directory. Account/device services that the host
does not provide return the existing explicit unavailable response.
`make gallery-zx` exports every enabled gallery example with its full source
behavior and embedded assets under `build/gallery-zx/`; `index.json` maps
example IDs to their bundle paths. The entire gallery also has a `portable`
profile. Each bundle embeds the gallery's assets, so the website runs the
examples live on its Components page rather than publishing these files.
The exporter and player use the gallery's configured Ziran toolchain, including
its lock or local override. A ZX's embedded IR format must match its player;
the installed compiler on `PATH` can use a different format.
`make gallery-zx-test` validates and renders all exported examples on a
private X server. `make zx-canvas-test` checks that the desktop and browser
bundles are identical and exercises browser startup, images, clicks, Unicode,
resizing, file replacement and rejection of invalid files.
`make zx-services-test` exercises real media and HTTP on native and browser
players. `make zx-hosted-test` checks hosted widgets, packed images and
document persistence. `make zx-headless-test` runs VM drawing, packed PNG,
retained input and Unicode without a display. The Android service and hosted
tests require `--android-serial emulator-NNNN` and `--serial emulator-NNNN`
respectively and verify the disposable `KryonZx` AVD before installing.
Custom native hosts can load `kryon/bundle_player`, prepare embedded assets,
attach `kryon/bundle_raster` callbacks and then start the instance. This lets
initializers use the selected renderer and assets. `PlayerFrameNative` runs
inside the caller's ordinary frame. `PlayerFrame` retains the CPU-surface
route for hosts that supply pixel buffers.
`kryon build portable` writes `build/<package-name>-portable.zx`.
All four project templates include this profile.
`kryon run portable` builds it and launches the reusable desktop player.
After downloading that file, `ziran run app.zx` works without the app's source,
manifest, lock, or compiler-generated native code. Install the player with
`make install-user` in Kryon; this also registers the provider with Ziran.
The player needs SDL2, Cairo and FreeType. `kryon run app.zx` forwards to the
same Ziran runner.
For a custom install prefix, add its `share/ziran/hosts` directory to
`ZIRAN_HOST_PATH` or its `share` directory to `XDG_DATA_DIRS`.
`assets` is an optional project-relative directory or file, embedded under that
same path. Images retain their ordinary `Image.Props.asset_path` values. The
player extracts validated resources into a private temporary directory and
removes it when the app exits. Exports rebuild resource content on every build,
including file removals. A `pixmap` profile also accepts `codegen = "zx"` and
runs through the display-free Ziran interpreter.
The desktop player supplies shapes, text, path-backed PNG images, window
visibility/close handling, clipboard, pointer buttons, wheel, modifiers,
keyboard and Unicode input. App globals and retained sessions persist between
frames. Unsupported capabilities fail before a window opens. Native library
and static archive settings cannot be linked into a portable program.
Applications with custom native storage, audio, pointer casts or C callbacks
must first give those effects portable host interfaces. The desktop player
does not yet replace these application-specific hosts.
`make zx-test` exports a package-qualified app, copies only its Zx file to a
download folder, and checks embedded images, installation, native pixel parity,
persistent click state, keyboard/Unicode input, malformed files and missing
capabilities on private displays. All four starter apps also have their Zx
pixels compared with native output.
`kryon install` also installs a Zx profile: its portable program goes to
`share/kryon/<bin>/app.zx`, and a reusable native player at `bin/<bin>` launches
it. The usual desktop menu and autostart settings apply. Embedded files need
no source checkout after installation.
### Apps shared between harnesses
An app can import `kryon/app_context` and `kryon/app_protocol` instead of a
product's host API. On `APP_IDENTIFY` it calls `AppIdentity(id, minimum_api)`
and `AppDescribe(name, icon)`, then returns `APP_PROTOCOL`. It draws hosted
Kryon widgets on `APP_FRAME`, handles its own state, and saves pending changes
on `APP_SAVE`. A supervising harness supplies `AppContext`, its service
allowlist and callbacks from `kryon/app_context_host`. Identification cannot
read or write user data. A bundle requiring a newer interface is rejected
before its first frame.
`AppSupports(name)` queries optional services; `AppService(name, request)`
returns `{"status":"unavailable"}` when the harness does not grant one.
`AppSupports("kryon.input.desktop")` is true when the device's main input is
a keyboard and mouse: native desktop hosts answer yes, Android and the web
no, and a harness that runs inside another host passes the question on.
An app that imports `kryon/app_theme` follows the host's theme:
`AppThemeColor(token, fallback)` returns the host stylesheet's colour for
`canvas`, `surface`, `border`, `text`, `accent` or `link`, and `fallback` for
a token the host lacks.
An app with a look of its own, such as a game, imports `kryon/widget_palette`
instead: `WidgetPaletteUse(session, palette)` asks the host to draw the
widgets that follow in that palette's colours (as `SystemPalette`), until the
host's frame for the app ends. A host that is itself a bundle passes the
palette on to the host that draws, so it needs a host with the call.
Imports alone do not grant storage, network, clipboard or secret access.
Hosts keep those permissions and account boundaries. `DocumentRead`,
`DocumentStatus` and `DocumentWrite` distinguish missing files from read
errors; an app must preserve a document it cannot read.
The desktop player runs this contract directly. Its local provider uses
private documents under `$XDG_DATA_HOME/kryon/apps/<id>` (or
`~/.local/share/kryon/apps/<id>`), exclusive app-directory locking, atomic
writes, the clipboard, embedded locales and a desktop image picker. Set
`KRYON_APP_DATA` to choose another private app directory. Harnesses can
provide their own account-scoped storage and sync through the same calls.
Local documents do not automatically sync between different harnesses.
For example, Inner Breeze's `diary.zx` runs in its original harness,
Werkzeug's `werk --bundle diary.zx`, or `ziran run diary.zx`; it does not
load `inbe.zx`. Werkzeug's Calculator uses the same interface. Apps that
need device secrets or timed clipboard ownership still require a harness
that supplies those capabilities. The common player currently has a Linux
desktop provider.
## Installing
`kryon install` (or `ziran install`) builds one profile and installs it for
the current user:
```toml
[package]
tool = "kryon"
[install]
bin = "example"
[tool.kryon.install]
profile = "desktop" # default: default_profile
name = "Example" # menu and window name; default: package name
comment = "What it does"
icon = "assets/icon.png"
categories = "Utility;"
working_directory = "." # start in the project directory
autostart = true # also start at login
autostart_env = "EXAMPLE_HIDDEN=1"
```
Every window and browser page is named after the app: this `name`, or else
the package name. A build keeps it beside the program as
`build/NAME-PROFILE.title`, an install as `share/kryon/example/app.title`,
and a page in its HTML `<title>`. A ZX player names a bundle by the `.title`
beside it or by its file name, and a program without a title by its own file
name.
The program is copied to `~/.local/bin/example` (or `--prefix DIR`). The copy
replaces the old file in one step, so a running copy is never touched and
later builds in `build/` do not change the installed program. The icon goes to
`share/pixmaps/`. To use the desktop's icon theme instead, set
`icon_name = "system-file-manager"` and omit `icon`; the launcher stores that
theme name and copies no asset. The two options are mutually exclusive.
The menu entry goes to `share/applications/example.desktop`, and
with `autostart` the login entry to `~/.config/autostart/example.desktop`.
Setting `autostart = false` removes an autostart entry that `ziran install`
wrote earlier. Browser profiles cannot be installed.
The project binary is `build/<package-name>-<profile>`. Checked Ziran modules
are saved in `build/generated/<profile>/ir/` as `.zir`; generated C is in
`build/generated/<profile>/c/`. `ziran inspect FILE.zir` displays a saved
module.
Canvas projects resolve package-qualified hosts and bind the selected
source through the shared frame capability. Their generator also roots
`canvas_raster.zi` and lowers every saved module, preserving raster adapters
and browser callbacks. Native profiles select the package-qualified host
entry as well. The saved IR carries the frame binding into native and portable
builds.
Every host draws text in Kryon's font, Liberation Sans
(`assets/fonts/LiberationSans-Regular.ttf`): a `font`-pixel line box from the
top of the ascent to the bottom of the descent, glyphs at their unhinted
widths. The desktop host loads it from `KRYON_FONT_PATH`, which
`kryon run` sets, else from the system's copy. The `pixmap` host rasterizes
the font's outlines with integer arithmetic, so every Ziran target prints the
same bytes for the same frame, and its text matches the desktop window's. It
renders two frames and prints the second, for screenshots in documentation and
CI without a display. `make pixmap-parity-test` builds every template and
example for C, Go, and the portable runner and checks that
all three images match; `build/pixmap-parity/grid.png` shows them side by side.
`tools/image_tools.zi`, compiled to C, compares two PPM images, converts
them to PNG, and lays out such grids.
Kryon's `make desktop-project-test` exercises the graphical host on private Xvfb
displays, including keyboard and Unicode text input. `make canvas-project-test`
builds a real Canvas2D project and loads it in private headless Chromium. Do
not run graphical tests on the developer's live display.
### Application-owned hosts
A profile can name an application's own Ziran host when it supplies additional
platform capabilities, such as private storage or clipboard handling:
```toml
[tool.kryon.profiles.desktop]
backend = "desktop"
host = "src/desktop.zi"
```
The host exports `main` and imports the application's widgets and platform
modules. Kryon builds and runs that program with the profile's backend libraries.
The host must be a `.zi` file inside the project, including when reached through
a symlink. Profiles without `host` use Kryon's standard host.
## Native asset directories
A native profile's `assets = "assets"` ships that directory's contents beside
its built executable as `PROGRAM.assets/`. `ziran install` copies the contents
to `PREFIX/share/kryon/BIN/assets/`. The install keeps no dependency on the
source checkout or its working directory. Undeclaring assets removes only the
product's managed snapshot on the next build/install.
Packaged asset directories use mode 755 and data files (including the prefix
marker) use 644, even with a private source mode or caller umask. The install
creates missing product directories with mode 755 and executable files with 755;
desktop entries, icons and title metadata use 644. Existing directories are
never made more permissive: callers wanting a shared installation must supply
a prefix whose existing ancestors allow users to traverse it. An existing
private prefix remains private. Custom installers can use
`scripts/make-install-dirs.sh DIR...` and
`scripts/copy-native-assets.sh SOURCE DESTINATION ORIGINAL_PREFIX` for the same
directory-boundary and asset snapshot behavior.
Native Image and ReadAppAsset lookup first preserves an accessible literal
relative file and every absolute path. Packaged lookup then accepts paths
relative to the declared directory (`icons/ui.webp`) and its original project
prefix (`assets/icons/ui.webp`). Missing files keep their original path/error
behavior. Paths containing parent traversal or drive names are never redirected.
Web preloads, ZX bundled assets and Android APK lookup retain their existing routes.
Custom native hosts can import `kryon/app_asset_path` and call
`ResolveAppAsset(path: string, output: []u8) -> string`. Use a separate 4096-byte
buffer: a resolved path borrows it; an unchanged path borrows the original text.
`ResolveAppAssetForExecutable(path, executable, output)` supplies an explicit
executable for hosts/tests. Neither changes the process working directory.
The standard native image loaders use this resolver automatically;
a custom asset-reader callback still has exclusive ownership of its resources.
A host embedding another UI packages that UI's referenced files under its own
declared asset directory, retaining their logical names. For example, an embedded
Shelf's `ImageForIcon` needs `icons/ui.webp` under the Rill host's declared assets;
Rill's executable and install prefix determine the runtime location.
-299
View File
@@ -1,299 +0,0 @@
# Programmable scene rendering
## Programmable scene materials
Import `kryon/scene`, `kryon/scene_render` and `kryon/shader`. `RenderScene`
executes camera-projected, depth-tested 3D meshes into a `std/image.Image`.
`SceneCamera.shift_x` and `shift_y` optionally offset a perspective view in
normalized device coordinates, with zero preserving the symmetric projection.
Positive X moves the scene right; positive Y moves it up. An offset of 1 moves
it by half the viewport width or height. Position, target, field of view and
aspect stay fixed, so this pans a bounded crop without rotating or translating
the camera. The CPU and GPU apply the offset before homogeneous frustum
clipping; render only the requested viewport. Orthographic bounds keep their
meaning and do not use these perspective offsets. Async GPU completion
metadata retains the exact submitted offsets with its camera.
The shader implementation is portable Ziran on CPU, including on Android and
WebAssembly. It does not compile GLSL or require a GPU shader context.
`ShaderCompile(program: *ShaderProgram, code: []ShaderInstruction) ->
ShaderDiagnostic` validates and copies up to 128 instructions into owned,
bounded storage. `ok`, zero-based `instruction` (or -1 for program errors),
and static `message` describe failures. A rejected replacement preserves the
previous executable. Do not modify compiled storage directly.
`ShaderFree(*program)` invalidates it and is idempotent. Programs have no
external handles or allocations and survive presentation-context recreation.
`ShaderProgram.input_mask` records which initial inputs the validated code reads:
`SHADER_INPUT_COLOR`, `SHADER_INPUT_POSITION`, `SHADER_INPUT_NORMAL` and
`SHADER_INPUT_UV`. Reads after overwriting an input register do not require
that initial value. The renderer uses this metadata to avoid normalizing
unused shader normals; UV-only albedo programs retain identical output.
Each instruction has `op`, `dest`, `a`, `b`, `c`, `slot` and `value`.
Registers hold `ShaderValue.{x,y,z,w:float64}`. Registers 0–3 initially contain
linear base RGBA, world XYZ/1, world-normal XYZ/0, and UV/0/0. The renderer
perspective-correctly interpolates these values. Registers 4–31 start undefined;
validation rejects reads before writes and invalid destinations. Operations are
`ShaderLiteral`, `ShaderUniform`, `ShaderSample`, `ShaderMove`, `ShaderAdd`,
`ShaderSubtract`, `ShaderMultiply`, `ShaderDivide`, `ShaderMin`, `ShaderMax`,
`ShaderSin`, `ShaderCos`, `ShaderFract`, `ShaderDot`, `ShaderNormalize`,
`ShaderMix`, `ShaderDiscardLess`, and `ShaderOutput` (members of `ShaderOp`).
Arithmetic is component-wise; dot and normalization use XYZ; dot broadcasts its
result and normalization preserves W for nonzero XYZ (zero XYZ returns zero
RGBA). Mix uses A, B and C per component.
Divide by zero returns zero. DiscardLess discards when A.x < B.x. Output takes
A and must end the program. Nonfinite outputs discard. No unbounded loops.
Set `SceneMaterial.shader` to the program address, `shader_uniforms` to a
borrowed slice of up to 16 vec4 slots, and `shader_samplers` to borrowed slots
(up to 8). Owners must remain alive and unchanged during `RenderScene`;
values and pixel contents can change between renders without recompilation.
`ShaderBindings` reports missing slots, released programs, nonfinite uniforms
and invalid RGBA dimensions. `RenderScene` rejects invalid bindings before
drawing. `SceneFree` never frees borrowed programs, uniforms or sampler pixels.
`ShaderPrepare(*prepared, program, uniforms, samplers)` validates bindings once
and produces a bounded `ShaderPrepared` draw plan with folded constants and
unused instructions removed. Reprepare after changing the program, uniforms,
sampler bindings or sampled pixels. The plan owns its instructions/constants
and borrows sampler storage for the draw. Its `input_mask` describes the initial
inputs still needed after preparation.
`ShaderRunPrepared(*prepared, *scratch, inputs)` executes one pixel with exact
interpreter arithmetic. `ShaderRunBatch(*prepared, *scratch, inputs, outputs)`
executes up to `SHADER_BATCH` (32) pixels per instruction dispatch and returns
false for an unprepared plan, oversized input or insufficient output storage.
Use `ShaderScratch` for scalar execution and `ShaderBatchScratch` for batches;
each concurrent caller owns separate scratch. Programs, bindings and samplers
remain unchanged during execution. `RenderScene` prepares per mesh each frame
and batches its pixel shader calls, preserving changes between frames.
`ShaderSampler.{width,height,pixels,repeat}` samples straight linear RGBA bytes,
top row first. UV V=0 selects the bottom row. Sampling uses nearest-neighbor
clamp-to-edge by default, or repeat including negative coordinates. Supply
linear data when loading an sRGB image for a custom sampler. `ImageMaterial`
is the standard sRGB image path described below.
Shader output replaces base RGBA before standard lighting and tone mapping.
Use `UnlitMaterial` for direct colour, or `LitMaterial` for procedural surfaces
that keep scene lighting. Set `transparent=true` for fractional alpha;
`alpha_test` also applies to shader output. Discarded and zero-alpha fragments
write neither colour nor depth. Shadow maps still use mesh geometry; custom
shader discard does not cut holes in shadow casters.
The renderer clips triangles against all six homogeneous camera planes,
preserving attributes when triangles cross the eye or near plane.
Present its straight sRGB output with `BitmapImageCreate`/`BitmapImageUpdate`
and the standard `Image` widget; widget clipping and alpha remain in effect.
`RenderSceneRelease()` releases shared scratch buffers, recreated on the next
render. Render and release on one owning thread; this renderer is not reentrant.
Native builds with `POSIX_THREADS` prepare immutable mesh states and clipped
triangle commands once per frame, then render through `std/parallel_linux`.
The pool defaults to one lane per online logical processor, up to 64 lanes.
Set `ZIRAN_PAR_THREADS` to select a lane count. A value of `1` runs serially.
Each lane clears, draws and resolves its own full pixel rows in the original
opaque and sorted transparent order. One completion barrier joins the frame.
Conservative row bounds skip empty triangle regions while retaining the
original edge equations at all four sample positions.
Soft-shadow disk radii are initialized once. Each lane memoizes exact disk
rotations in a 512-entry cache for its frame; the light's radius and depth
comparisons are still evaluated per fragment. This uses about 44 KiB of
temporary stack per lane, without a full-frame cache or changed shadow samples.
`RenderSceneWorkerCount()` reports available pool lanes, including the caller;
it returns one before initialization and after `RenderSceneRelease()`, which
also closes the pool. Small draws and thread-creation failure remain serial.
Portable bundles and WebAssembly builds without this capability remain serial.
Borrowed programs, uniform values and sampler pixels must remain immutable
until `RenderScene` returns on the owning thread.
For expensive opaque materials with more than two projected surface layers,
the renderer first tests depth and material discard without lighting. It then
shades only candidates near the final opaque depth, preserving the original
draw order, float32 depth comparisons and four coverage samples. Conservative
depth ceilings temporarily reuse the target's sample color bytes; this adds
no frame-sized buffer. Empty samples regain the scene background before the
original sorted transparent pass. Low-overlap scenes retain the single pass.
Programs and alpha textures still run during visibility testing, so savings
depend on overlap and lighting cost.
`RenderSceneStatistics()` returns the last completed render's
`opaque_projected_layers` (summed clipped opaque triangle area divided by image
area), `depth_prepass`, `depth_fragments` and `shaded_fragments`. Fragment counts
are pixel-center material evaluations after coverage and depth testing, shared
by covered MSAA samples; they include evaluations that discard. The depth count
belongs to the optional visibility pass, and the shaded count includes opaque
and transparent color passes. Lanes accumulate private counts before joining.
Release resets the snapshot.
`RenderSceneMemoryBytes()` reports retained backing-buffer bytes for renderer
scratch, including transformed vertices and prepared draw commands. It excludes
the caller's scene, textures and output image, static color tables, allocator
overhead and worker stacks; it is not process RSS. Color and depth buffers grow
without geometric spare capacity. Sized buffers retain capacity across renders
and all reported scratch is freed by `RenderSceneRelease()`.
`RenderSceneMemoryUsage()` returns the same backing storage split into
`framebuffer_bytes`, `shadow_bytes`, `vertex_bytes`, `triangle_bytes`,
`draw_bytes`, `node_bytes` and `ordering_bytes`. These fields sum to
`RenderSceneMemoryBytes()`. Triangle commands refer to shared draw states and
do not copy material bindings. The four coverage positions are shared constants,
not stored in each command. Geometry reservation allows one eighth of source
size plus 32 records for clipping; additional growth uses the same bounded
headroom. Camera frames within retained capacities allocate no geometry storage.
Transparent depth-sort keys also retain capacity across frames and are included
in `ordering_bytes`.
Render at a bounded resolution and reuse the image while camera, geometry,
lights and material inputs remain unchanged. CPU rendering every UI frame
at full window resolution can be expensive.
`tests/shader_scene_test.zi` demonstrates mutable uniforms, sampling,
diagnostics, clipping, alpha and recreation. Focused targets are
`make shader-scene-test` and `make shader-host-test`, through `build-queue --`.
### Portable GLSL translation and optional native GPU rendering
`kryon/shader_glsl` translates the same `ShaderProgram` into a GLSL ES material
function. `ShaderGLSLTranslate(program)` returns `ShaderGLSLResult` with a
`diagnostic`, owned `source` text, and uniform/sampler counts and input mask.
Check `diagnostic.ok` before composing its `kryonMaterial` function into a host
shader. `ShaderGLSLBindings` validates the borrowed values for GPU execution.
Translation is portable Ziran; it does not create a graphics context. GPU
highp arithmetic has different precision from the CPU's binary64 arithmetic,
so GPU comparisons use documented pixel tolerances rather than exact hashes.
Native desktop applications can explicitly import `kryon/scene_gpu` and link
`-lEGL -lGLESv2 -lGLX -lm`. This optional host is separate from the core UI, portable
CPU renderer and WebAssembly path. It owns a surfaceless EGL/GLES3 context and
renders a `Scene`, materials and `SceneCamera` into a reusable
`std/image.Image` for ordinary Kryon Image presentation. A web build (`OS ==
.WEB`) links none of EGL or GL: `SceneGpuProbe` reports the GPU unavailable,
and `SceneGpuRenderOrCPU` draws with `RenderScene`.
Android code generation defines `ANDROID_BUILD` and uses the default EGL display
through `eglGetDisplay`, including at API 21. `kryon_android_app` supplies the
`EGL` and `GLESv3` system libraries; the Android path has no GLX imports.
Keep one `SceneGpuContext` at a stable address on its owning thread.
`SceneGpuProbe(context)` reports availability, diagnostic, renderer labels,
texture limits and MSAA support. The host requires highp fragment precision,
15 texture units and four MSAA samples; it reports unavailability when those
requirements cannot be met. `pcf_available` reports hardware bilinear depth
comparison. When the probe fails, the GPU fragment shader performs the four
depth comparisons and bilinear interpolation at each of the five shadow taps.
`SceneGpuRender(context, scene, camera, image)` preserves the requested image
dimensions and returns `SceneGpuFrame` with `ok`, `accelerated`, `diagnostic`
and submission/readback/conversion timings. Failure leaves the output untouched.
`SceneGpuRenderOrCPU` explicitly permits the full-quality CPU renderer on
failure, setting `accelerated=false`; inspect that flag when measuring GPU work.
`SceneResizeOpaqueInto(image, width, height, output)` in `kryon/scene_render`
fills an owned RGBA display cache from an opaque scene image. Native builds
use the available Lanczos kernels and can reuse the output allocation. Portable
bundles use `std/image.ResizeLanczos`. An app can opt to render fewer pixels,
resize the result once, then pan a native-size cache using its original crop
coordinates. Pass separate owning Images. Invalid sizes, nonopaque input or
allocation failure return `false` and preserve both images. For translucent
input, use `std/image.ResizeLanczos` for alpha-aware resizing.
`SceneGpuSetProfiling(context, true)` adds stage timings in `frame.profile`.
`shader_setup_ms` covers material program lookup, binding validation and shader
setup. `texture_upload_ms` measures the driver calls that upload scene textures.
For synchronous readback, `gpu_completion_ms` measures the explicit finish
before `pixel_transfer_ms` measures the read. For async readback it measures
the elapsed time from fence submission until a poll first sees it ready, so it
includes polling delay. `image_copy_ms` measures publication to the owning
Image, including any required pixel conversion. Profiling is off by default.
`direct_resolve` identifies a frame that skipped the conversion draw.
`SceneGpuCapabilities.async_available` separately probes pixel pack buffer
readback, fences and read mapping. `async_diagnostic` explains unavailability;
the synchronous GPU API remains available when only async support is missing.
`SceneGpuSubmit(context, scene, camera, width, height, request_id)` draws at
full quality into one of exactly two retained transfer slots. Use positive,
strictly increasing IDs until release. `SceneGpuAsyncResult.ok` means the
operation is valid: `queued` accepts the request, `busy` accepts nothing.
Scene, shader and texture storage is borrowed only during submission and can
be mutated afterward on the owner thread.
`SceneGpuPoll(context, image)` tests the oldest fence with timeout zero.
An empty/unready poll has `ok=true, completed=false` and leaves the image
untouched. A completion returns the exact submitted ID, camera, size, original
draw timings and submission-to-completion `latency_ms`; it never labels pending
work as the latest camera. The image must already have the completed size.
Poll copies only a signaled buffer, validates its read mapping and then updates
the reusable Image. One CPU staging buffer is shared with synchronous readback.
Synchronous render can safely interleave while both transfer slots are pending.
Async queues add at most `2 * width * height * 4` bytes of GPU transfer storage.
On ARMv7 PowerVR Rogue GE8320, each pending opaque frame owns the resolved
framebuffer until its fence signals. The renderer reads it directly and copies
the rows into the Image in top-to-bottom order. Translucent frames still use
straight-alpha conversion. The Android Pixmap presenter takes the same CPU
Image pixels in both cases.
`SceneGpuCancel` discards pending IDs and releases the transfer slots. Resize,
release and context loss also discard them. Cancellation/resize/release may
drain GPU work; poll does not wait for unfinished work. Applications must keep
polling while work is pending, including after input stops, and retain the
completed camera metadata separately from current input. Queueing may add
camera latency, so measure changed presented frames and event-to-pixel latency.
The native Desktop host exposes `DesktopRequestFrame()` for this purpose.
Requests aggregate until the next `BeginDesktopFrame`, keep the active frame
budget while pending, and affect only scheduling. Continue to pass the actual
retained-paint result to `DesktopFrameUnchanged`; scheduling work must never
claim that unchanged image pixels changed.
Geometry, material programs, textures and render targets retain storage across
frames. Each context also keeps up to eight linked material programs from
earlier frames. Scenes with identical shader instructions and material features
reuse the linked program. Scene and binding data are borrowed during the call.
Mutate them only on the owner between calls. When only nodes move, turn or
scale between frames, the renderer sends the affected vertices. Smooth-shaded
indexed meshes keep their element buffers and refresh only changed position, normal and color
streams. Box-projected UVs update with their source positions and normals.
Topology, material and visibility changes rebuild the geometry. `SceneGpuResources.geometry_uploads`
counts uploads and `geometry_vertices` counts the vertices those uploads covered.
`FreezeGeometry(scene)` (in `kryon/scene`) promises that meshes, materials and
vertices stay as they are, so the renderer stops comparing them with its last
upload on every frame and compares only the nodes. Scene calls that add or
change geometry take the promise back; after writing into the scene's vertex
arrays directly, clear `scene.geometry_frozen` yourself. `SceneGpuMemoryUsage` reports retained CPU/GPU
storage estimates, object counts, upload counts and completed GPU frames; this
is separate from process RSS and presentation-host storage.
The resource report includes live fences/pending frames, accepted submissions
and cancelled requests. Deleting a live slot drains it before releasing storage,
so repeated navigation cannot accumulate deferred transfer allocations.
`SceneGpuResize` resizes the retained target. `SceneGpuRelease` releases owned
objects and context and can be called repeatedly; a later probe/render recreates
them. It preserves a foreign host's current graphics context and does not
terminate the process-shared EGL display.
Run the explicit native targets `make shader-glsl-test` and
`make scene-gpu-test` through `build-queue --`. The ordinary public-surface
local tests also compile and execute scene, material and translator imports as
a separate package consumer in native and portable forms without linking EGL.
Run `build-queue -- python3 tests/scene_gpu_test.py --readback-profile` to
compare the two synchronous copy paths on a 2527×1423 opaque frame and verify
their pixel hashes. The reported renderer identifies whether the run used a
hardware or software GLES driver.
### Owned image pixels for scene textures
`#import "kryon/image_pixels"` exposes
`LoadImagePixels(path: string) -> std/image.Image`. Success satisfies
`ImageValid(*image)`; missing, invalid or unsupported files return an empty image.
The caller owns `image.pixels` and releases it with `VecFree(image.pixels)`.
Pixels are tightly packed, top-down, straight RGBA in the source's sRGB encoding.
On the web the page decodes the file's bytes with the browser's own codecs
(photos turned upright by Exif), so a canvas build links no image library.
Headless image-widget tests can use the ordinary `kryon/pixmap` provider for
`image_raster`'s `ImageWidth` and `ImageHeight` capabilities. Import both modules
and bind `image_raster:ImageWidth=pixmap:ImageWidth` and
`image_raster:ImageHeight=pixmap:ImageHeight` with `--bind` when compiling source
or generating saved IR. For a package consumer, prefix **both** module names
with Kryon's package ID from `ziran.lock` and an underscore, for example
`p…_image_raster:ImageWidth=p…_pixmap:ImageWidth`; the ID depends on the locked
revision. Saved IR already contains those bindings. `PixmapSetImage` registers
fixture dimensions; absent paths return `0`. This needs no window or borrowed
framebuffer. A desktop application uses the same capabilities from
`kryon/Cairo`, which loads its picture assets.
-181
View File
@@ -1,181 +0,0 @@
# Style rules
Installable style rules plus the image, bitmap, clipboard and
Linux drag/clipboard integrations that stylesheets and widgets draw with.
Read this when styling widgets, showing pictures or moving data through
system clipboards and drags.
`InstallStyleRules` copies typeface text into Kryon-owned storage and returns
`false` without replacing the active rules when the rule count is outside
`0..320` or the combined typeface text exceeds 65,536 bytes.
`InstallParsedStyleRules` reports the same storage failure.
Use `Image.Draw(Image.Props)` for UI images. Its asset path, bounds, fit, and alt
text describe the image at the widget boundary. Backend texture calls are
renderer primitives, not alternate widget APIs.
Asset paths may name PNG, JPEG, WebP or AVIF files on image-loading hosts. WebP is
recognized by its content: lossy, lossless and transparent pictures load as
RGBA, and an animated WebP shows its first frame (Kryon images are still).
See [WebP images](BACKENDS.md#webp-images) and [AVIF images](BACKENDS.md#avif-images) for each host's decoder.
`Image.Props.radius` gives an image rounded corners in native and hosted UI;
a positive value overrides its style radius.
`kryon/image` brings file pictures, so a program that imports it links a host
that measures them. Code that only needs the image placement rules, such as
`ImageFitBounds` and `ImagePreviewSource`, imports `kryon/image_behavior`,
which needs no host or picture.
Import `kryon/bitmap_image` to create a runtime RGBA image for the same
`Image.Draw(session, Image.Props.{.texture = image, .smooth = true, ...})`.
Bytes are tightly packed, row-major straight RGBA8 and copied/consumed
synchronously; reuse the input buffer after the call.
| Call | Behavior |
| --- | --- |
| `BitmapImageCreate(session, width: s32, height: s32, rgba: []u8) -> Texture2D` | Failure returns a zero texture |
| `BitmapImageUpdate(session, image: Texture2D, rgba: []u8) -> bool` | True for accepted unchanged data; false keeps the current pixels. Only successful
changed data invalidates retained paint. Smooth sampling and alpha use the
ordinary Image renderer on Desktop/Cairo, pixmap and Canvas. Explicit `Image.Props.tint`, including white for original colors,
applies to straight RGBA pixels. GPU reset and native window close/reopen
preserve the session's CPU image; textures are recreated when next painted.
Completed native worker frames own deduplicated copies of the revisions they
draw, so an update or session close cannot change pending pixels. Each frame
retains at most 64 revisions and 32 MiB of straight pixels; pressure fails the
frame explicitly. The native texture cache has the same 64-image/32 MiB bound.
Managed handles belong to the complete Session (slot and epoch) and current
provider. Dimensions must be positive, at most 4096 each and 4,194,304 pixels;
byte count must equal width × height × 4. There are at most 64 images, with a
64 MiB total and 32 MiB per-session budget for straight and premultiplied CPU
copies. Provider copies have the same bounded dimensions/count. Bad, modified,
stale and cross-session handles are rejected; releasing them is harmless.
Closing a Session releases its images. Closing/replacing the Canvas provider
also releases its images. Call on the session/provider's frame thread, outside
an active raster emission. Native renderer texture handles are unchanged.
Standard hosted widget policy rejects all guest runtime texture IDs and does
not advertise bitmap lifecycle capabilities; an embedding must provide a
separate authenticated ownership policy to grant those effects.
In a zx bundle the player owns these pictures: `kryon build` defines
`KRYON_ZX` for zx profiles, and the same three calls become the host calls
`BitmapImageCreateHost`, `BitmapImageUpdateHost` and `BitmapImageReleaseHost`
(pixels cross once as a byte view), so the player's raster draws them. The
desktop zx player provides them for the session it runs; a player without
them refuses the bundle.
### System text clipboard and PRIMARY
Import `kryon/system_clipboard` for the ordinary UTF-8 text clipboard:
| Call | Purpose |
| --- | --- |
| `SystemClipboardText(buffer) -> string` | Whole-UTF-8 prefix borrowed from `buffer` |
| `SystemClipboardAvailable() -> bool` | Whether the clipboard holds text |
| `SystemClipboardHasText() -> bool` | Same question, no buffer |
| `SystemClipboardSet(text) -> bool` | Publish text to CLIPBOARD |
On hosts with a distinct selection clipboard:
| Call | Purpose |
| --- | --- |
| `SystemPrimaryText(buffer) -> string` | Caller-owned whole-UTF-8 prefix |
| `SystemPrimaryAvailable() -> bool` | Distinguishes an empty selection from an unsupported host (an empty `SystemPrimaryText` result can mean either) |
| `SystemPrimarySet(text) -> bool` | Publish text to PRIMARY |
`SystemPrimaryText` returns a borrowed prefix borrowed from `buffer`; an empty result can mean either an
empty selection or an unsupported host, so use `SystemPrimaryAvailable` when
that distinction matters. Linux SDL desktop hosts connect these
calls to the platform PRIMARY selection. Android, Canvas, terminal, pixmap,
bundle and unsupported desktop hosts return unavailable rather than falling
back to CLIPBOARD.
Custom hosts implement the snapshot functions `SystemPrimaryOpenHost() -> s32`
and `SystemPrimaryByteHost(index) -> s32`, plus
`SystemPrimaryWriteHost(text) -> bool`. Open returns the byte count, including
zero for an available empty selection, or -1 when unavailable. The snapshot
remains valid until the next open call; write copies the text during the call.
### Optional native MIME clipboard on Linux
Import `kryon/MimeClipboardLinux` in an X11/XWayland native app and link
`-lxcb` (for example in `LDLIBS`). The text and PNG modules keep their
interfaces. This module owns one dedicated connection and unmapped selection
window, without toolkit callbacks or changes to the toolkit's connection.
It does not implement a Wayland-only data source or clipboard persistence.
Call `MimeClipboardOpen() -> bool` on the application's GTK/X11 owning thread,
then keep every call serialized on that same thread until
`MimeClipboardClose()`. Calls from another thread fail; close there does nothing.
Close is idempotent and destroys only the transport's own connection/windows,
freeing its copied publications and outgoing transfer snapshots. No callbacks
or caller buffers remain registered after any call returns.
| Call | Behavior |
| --- | --- |
| `MimeClipboardPublish(payloads: []MimeClipboardPayload) -> MimeClipboardPublishResult` | Copies every `{mime: string, bytes: []u8}` and publishes the complete target set in one selection ownership change. Reuse/free input storage after return; result fields are `status` and `owner: u64`. Duplicate/empty/NUL names, reserved selection protocol targets and invalid counts fail without replacing the prior publication. Empty byte payloads are supported |
| `MimeClipboardRead(mime: string, buffer: []u8, timeout_ms: s32) -> MimeClipboardReadResult` | Requests exactly that target, including incoming INCR. Returns `status`, `bytes: []u8`, `size: s64`, `owner: u64`. Only `Ok` exposes bytes, borrowed from the supplied buffer; partial buffer data on failure must be ignored. Empty success differs from `Absent`. `size` is the bytes observed, the direct property's exact size, or an INCR lower bound/hint when rejected as too large; INCR hints are untrusted |
| `MimeClipboardPump(max_events: s32) -> s32` | Serves at most 256 events per call (zero for nonpositive budgets). Call regularly from the app frame loop while publishing. Reads also serve queued requests; self-reads copy directly without waiting for a toolkit loop. Retires abandoned/expired transfers |
| `MimeClipboardOwner() -> u64` | Zero for no owner/unavailable transport. Local ownership returns the local generation token; foreign ownership returns an observational XID that cannot identify content changes within that window |
| `MimeClipboardRelease(owner: u64) -> bool` | Clears only the still-current publication created by this transport, comparing server ownership atomically. Every successful local publish has a fresh window and generation token; stale tokens, including across close/reopen, cannot clear newer local data. Foreign tokens always fail, even if a read returned that token: a foreign application may republish different data from the same window |
`MimeClipboardStatus` is `Ok`, `Absent`, `Error`, `TooLarge`, or `Timeout`.
`Absent` means no owner or a refused target. Invalid arguments, malformed
conversion properties, connection errors and owner replacement during a read
return `Error`. Read timeouts are total monotonic deadlines (1–5000 ms),
including trickling INCR chunks; ordinary X-server request round trips assume
a responsive local X server. Only the UI thread may open; concurrent first
calls and reentrant calls are unsupported.
Limits: 32 targets; names 1–255 bytes; 16 MiB aggregate copied publication;
16 MiB per read even with a larger caller buffer; 16 outgoing INCR transfers
with 16 MiB aggregate snapshot bytes and a five-second total serving lifetime.
Transfers use 32 KiB chunks and survive local republish/owner loss using their
own copied snapshots. No MIME conversion, URI validation or file operation
policy occurs here. Clipboard data and remote ownership are observations, not
an authorization or a trustworthy content generation identifier.
Run `make mime-clipboard-linux-test` for source and saved-IR native tests against
independent Xlib fixtures and installed `xclip`, under private HOME/XDG/D-Bus/Xvfb.
### Optional native drag source on Linux
Import `kryon/DragSourceLinux` in an X11/XWayland native app and link `-lxcb`
to drag data out of the app with XDND version 5, for example files onto a web
browser's upload area, a file manager, the desktop or an editor. The module
owns its own connection, an unmapped source window and an optional icon
window; it never grabs the pointer or changes the toolkit's connection.
Call `DragSourceBegin(payloads: []DragSourcePayload, actions: u32, icon: DragSourceIcon) -> bool`
while the primary button is still held, typically once the pointer has moved
past the platform drag threshold from the press. Each payload is a
`{mime: string, bytes: []u8}` pair copied during the call (at most 32 targets
and 4 MiB in total). `actions` combines `DRAG_ACTION_COPY`, `DRAG_ACTION_MOVE`,
`DRAG_ACTION_LINK` and `DRAG_ACTION_ASK`. `icon` is straight RGBA up to
256×256 with a hot spot; pixels at least half opaque are shown in a shaped
override-redirect window that follows the pointer. A zero-sized icon shows none.
While `DragSourceActive()` is true, call `DragSourceUpdate() -> DragSourceState`
once per frame on the same thread and keep frames coming (on the Desktop host,
`DesktopRequestFrame()`). Update follows the pointer, finds the top-level window
under it (honouring `XdndProxy`), sends Enter/Position/Leave/Drop, answers
`XdndStatus`, and serves the `XdndSelection` conversions, including `TARGETS`.
The suggested action follows GTK: Control+Shift links, Control copies, Shift
moves, Alt asks, otherwise the first offered of copy, move and link. The state
reports `status`, the root pointer position, `modifiers` (1 Shift, 2 Control,
4 Alt), the current `action`, whether a foreign target `accepted` it, and
`local` when the pointer is over a window of this process (identified by
`_NET_WM_PID`).
| `DragSourceState.status` | Meaning |
| --- | --- |
| `Dragging` | Button still held |
| `Local` | Release over this process; the module sends no XDND messages over its own windows, so the app performs internal drops itself |
| `Dropped` | Drop sent to an accepting target; lasts until the target's `XdndFinished` (or a 15 second timeout) |
| `Finished` | `performed` and `success` report the target's answer |
| `Cancelled` | Release anywhere else |
`DragSourceCancel()` abandons a drag, for example on Escape. After reading a
final status, call `DragSourceEnd()` to release the selection, icon and copied
data. The application performs no file operation for a foreign drop: the
target does, as with any XDND source.
Run `make drag-source-linux-test` for source and saved-IR tests that drop onto
an independent python-xlib XDND target on a private Xvfb.
-21
View File
@@ -1,21 +0,0 @@
# Theme customization
Linux desktop frame applications follow the system palette by default. The
host reads the palette before the first frame and refreshes it while the app
is open. It uses the containing host's palette when embedded, or the configured
GTK palette on a standalone window. When the palette cannot be read, Kryon
uses its built-in colors for the detected light or dark mode.
Import `kryon/Theme` for theme tokens. `InstallDefaultTheme(dark)` installs
the default palette, metrics, fonts, shadows and motion. `SetThemeMode(dark)`
changes the palette and keeps installed metrics, fonts and motion settings.
Both calls select an explicit mode for the app. `SetThemeMode` resets palette
colors when changing modes, so reapply custom accents afterward.
Use `WithAccent(theme, accent, on_accent, accent_strong, accent_subtle)` and
`InstallTheme(theme)` to install a fixed palette. `ThemePolicy` and `ResolveDark`
support system, light and dark preferences. `SetReducedMotion` controls motion
independently of palette selection.
Typed style rules and optional CSS remain available for application-specific
colors and control styling, using the same components and interaction behavior.
-24
View File
@@ -1,24 +0,0 @@
# Native raster workers
Native C source builds use Ziran's `POSIX_THREADS` capability to
parallelize large pixel clears, rounded fills and decoded images by default.
The renderer reuses `std/parallel_linux` workers; `ZIRAN_PAR_THREADS` selects
1–64 lanes, with four by default. Small damaged regions stay on their owner to
avoid worker wake overhead. Portable bundles and other platforms keep the
same pixel algorithms without requiring pthreads.
The frame owner submits paint in order, prepares glyph caches and keeps the
surface, clipping and image assets immutable during each raster operation.
Workers write disjoint rows and complete before the next paint starts.
Decoded images that overlap the output surface retain serial ordering.
This does not make UI trees or application state safe for concurrent mutation.
`PixmapEndInto` releases the borrowed surface after all work has completed.
Call `PixmapCloseWorkers` before unloading the host or its library; workers
otherwise remain idle between frames. `PixmapWorkerCount` reports the actual
number of lanes, including the frame owner. Thread creation failures reduce
the pool to the lanes available and preserve complete rendering.
Run `sh tests/ziran_pixmap_parallel_test.sh` to compare large native rasters at 1,
4 and 8 lanes, including clipping, transparency, rotation, retained damage,
aliased image storage, guard pixels, pool shutdown and restart.
-18
View File
@@ -1,18 +0,0 @@
# Widget verification
Each widget has a Ziran implementation under `src/ui/` and should have a
focused behavior test for its public values, retained state, and input
decisions. Tests that only verify code generation do not prove behavior.
The current `make test` gate builds the core and optional packages and runs
the `tests/ziran_*` behavior suite through the relevant source, saved `.zir`,
portable `.zx`, and native targets. Package project tests verify imports and
terminal host behavior. `make desktop-project-test` verifies graphical
capture and input on private Xvfb displays.
For an affected widget, check the interaction that changed through the
session and selected host. Input widgets need focus, editing, Unicode, and
selection cases; collection widgets need selection, scrolling, and
activation cases; image and text widgets need paint and clipping cases.
An untested host or platform remains unverified even when another target
passes. [FEATURE_MATRIX.md](FEATURE_MATRIX.md) records supported hosts.
-336
View File
@@ -1,336 +0,0 @@
# Widget controls
Ready-made interactive controls: toasts, bottom navigation, buttons,
breadcrumbs, context menus, cards, swipe rows, the workspace pager, cover
carousels, loading surfaces, rotated text, paged reading and the multi-select
grid. Read the section for the control you are placing or styling.
## Toast actions
`Toast.Draw(session, Toast.Props) -> Toast.ToastResult` accepts an optional
`action_label: string`. A nonempty `message` captures that label in
`Toast.ToastState.action_label`; keep passing `result.state` on later frames.
An empty label gives a passive toast.
The action is a standard Button, with its label exposed to accessibility and
normal pointer, Tab, Enter and Space activation. `Toast.ToastResult.action_clicked`
is true only on the submission that consumes the activation. The caller owns
the action and the dismissal; set `clear = true` when the toast should
disappear. A replacement message replaces the action; expiry and clearing
remove both.
## Bottom navigation
`Navigation.Draw(session, props, items)` defaults to a full-width 80-unit tonal
bottom bar. Reserve `Navigation.NavigationBarHeight(props)` above the bottom of
the view. For an embedded preview or panel, use `compact = true` with `bounds`;
`fit_items = true` fits the shortcuts into that rectangle.
Each `Navigation.NavigationBarItem` accepts an optional `icon_shape` (the
standard Shape format) or `image`; the icon is 24 units inside a 64 by 32
selection pill, with its label below. With neither icon, the label is centered
inside the pill. Item keys, route results, disabled hit testing and custom
style rules keep their contracts. Pointer hover/press and keyboard focus draw
state layers; keyboard focus adds a ring. `compact` keeps the scrolling
dock/rail layout used by Breeze, including its footer and drag/close behavior.
## Buttons
Installed system palettes give buttons the full (capsule) shape. A button
taller than 56 units is a tile, such as a launcher or keypad tile, and takes
20-unit card corners instead of becoming a stadium; `pill` and `circle` still
force a capsule. Neutral soft buttons are tonal: a light tint of the palette's
accent over the background. A labeled `image` in a tile fills the spare
height instead of staying at the styled icon size: up to 64 units above the
label, or up to 40 units beside it. A vector `icon_shape` takes precedence
over an `image` and keeps the styled size.
A button draws only the icons its program imports. A vector `icon_shape` and
pixels handed over as `image.texture` always draw. A file picture in
`image.asset_path` draws once the program imports `kryon/image`, and a
built-in `icon_type` once it also imports `kryon/icon`. A button without an
icon carries no picture decoder, asset path or icon atlas. The same holds for
pictures a toolbar, title bar or modal header hands to its buttons.
## Breadcrumbs
`Breadcrumb.Draw(session: Session, props: Breadcrumb.Props,
items: []Breadcrumb.BreadcrumbItem) -> Breadcrumb.BreadcrumbResult` is exported
by `kryon/breadcrumb`. No labels are interpreted as paths.
| `BreadcrumbItem` field | Meaning |
| --- | --- |
| `label: string` | Borrowed for the frame |
| `key: u64` | Unique, stable and nonzero; keys, not indices or labels, preserve retained item identity and menu highlight across reorder |
| `disabled: bool` | Skips activation |
| `Breadcrumb.Props` field | Meaning |
| --- | --- |
| `key`, `bounds`, `id`, `class_name` | Standard placement, identity and styling |
| `active_index` | Current item, -1 for none |
| `disabled` | Disables the bar |
| `focused`, `focused_index` | Keyboard focus; `focused_index = -1` addresses overflow, where Down also opens the menu |
| `trigger_input` | Enter/Space activates the caller's focused item |
| `open`, `close` | Request overflow transitions; internal open state persists |
| `overflow_label` | Label for the collapsed overflow; defaults to an ellipsis |
| `menu_input: DropdownMenuInput` | Up/Down/Home/End, commit and Escape in the overflow menu |
The result reports `activated_index` (-1 for none), `activated_key` (0 for
none), `changed`, and the menu state `open`, `opened`, `closed`. Repeat
activation still reports the item, with `changed = false`. The widget never
changes the caller's selection or focus. Native retained button focus works
normally. Pointer, native Escape/focus dismissal and scrolling use standard
Popup and Scroll behavior. Submit after earlier page controls.
Widths use resolved Button styles and font advances. The tail and active
ancestor remain visible, compressed when necessary; all other hidden ancestors
remain in original order in a viewport-constrained, virtualized overflow.
Labels are clipped/fitted without slicing UTF-8. Borrowed lists of at least
2,048 items are supported without submitting offscreen rows. Zero, negative,
or fully clipped bounds submit no controls.
## Context menus
`ContextMenu.Draw(session, props: ContextMenu.Props,
items: []ContextMenu.ContextMenuItem) -> ContextMenu.ContextMenuResult` is
exported by `kryon/context_menu`. The caller keeps `open` and the pointer
position (`x`, `y`); the result reports `activated_id` (0 for none) and
`closed`. Submit it after the page's other controls.
| `ContextMenuItem` field | Meaning |
| --- | --- |
| `id: s32` | Positive; reported when chosen |
| `label: string` | Row text |
| `disabled: bool` | Draws and reports as disabled |
| `separator: bool` | Divider row; the other fields are ignored |
| `inline: bool` | Compact cell sharing a row with its inline neighbours |
| `parent: s32` | Id of the row whose submenu holds this one; a row others name shows › and opens the submenu instead of reporting |
| `accelerator: string` | Shortcut label such as `"Ctrl++"`, right-aligned in the muted (disabled rows: disabled) text colour before any ›; the menu only shows it, the caller handles the shortcut |
| `checkable: bool` | Draws a 14-unit check box at the row's left inset |
| `checked: bool` | Check state of a checkable row; the caller flips it after a choice reports the id |
Fields are appended in order, so positional `.{id, label, disabled, separator}`
initializers keep their meaning. The panel widens so each row's label, a
32-unit gap and its accelerator fit. When any row of a panel is checkable,
every label in that panel starts after the box column so labels line up, as in
GTK menus; panels without check rows keep the plain inset. Check rows keep the
option role and expose `checked` as the row's selected state. Menus have no
icons.
## Cards
`Card.Draw(session, Card.Props)` draws a filled, elevated or outlined Material
surface. Import it as `Card :: #import "kryon/card";`. Set `variant` to
`CardFilled` (the default), `CardElevated` or `CardOutlined`, and supply
`bounds` and a stable `key`. The returned `content` rectangle has 16 units of
padding, reduced for small bounds. Draw your content in that rectangle; Card
does not open a scope.
Cards are decorative by default. `clickable` enables the standard Button's
pointer, keyboard, focus and disabled behavior; `activated` reports activation.
An optional `label` is drawn centered and announced by the clickable surface.
Selected and explicit state props keep their usual meaning. Installed Card
style rules apply by id, class and emphasis (soft, filled and outline for the
three variants). Elevated cards and floating menus/dialogs use two fixed,
1-unit contact strips, with no blur, offscreen bitmap or animation timer.
A ListBox with no explicit row height uses 40 units. Its icon size does not
set its row height. Explicit `row_height` and style `offset_y` still win.
## Swipe rows
`SwipeRow.Draw(session, props, state)` follows a horizontal drag, paints the
revealed strip and returns its content `offset` plus state for the next frame.
| `SwipeRow` prop | Meaning |
| --- | --- |
| `start`, `end` | Action shown per direction; an action needs `icon_shape` |
| `threshold` | Completion as a share of row width; zero means 0.35 |
| `end_threshold` | Left-swipe override; zero uses the effective shared threshold |
| `long_start`, `long_end` | Optional second stage per direction |
| `long_threshold` | Width share (zero means 0.5); must exceed that direction's effective short threshold or the stage is ignored |
| `start_width`, `end_width` | Positive value replaces that side's row-width share with a fixed bounds-unit travel span; zero keeps the share. A two-stage strip divides the span into equal containers and clamps the drag at the span |
| `removes` | Per chosen action: whether the row settles back |
| `SwipeRow` result | Meaning |
| --- | --- |
| `offset` | Current content offset |
| `swiped_start`, `swiped_end` | Release past that side's short threshold |
| `swiped_long_start`, `swiped_long_end` | Second-stage release; exclusive with the short results, using the final distance even after crossing and retreating |
| `clicked` | Separate tap or keyboard activation; the app chooses what a tap does |
| `right_clicked`, `pointer_x`, `pointer_y` | Secondary-button release |
Vertical scrolling does not activate swipe actions. For short-swipe completion
and long-swipe editing, set equal `start_width` halves, `threshold = 0.5`,
`end_threshold = 0.35` to keep row-width left deletion, `long_threshold = 1.0`,
put completion in `start` and edit in `long_start`, and handle their separate
results. A tap need not complete the row.
## Workspace pager and centered panel groups
`workspace_pager.Draw(session, props, windows)` draws miniature workspace tiles
from the caller's real count, active workspace and desktop window geometry.
It returns the clicked workspace index, or -1. `Cell`, `WindowBounds` and
`Width` expose the same geometry for sizing and verification. The default is
two rows; window workspace -1 is sticky, and rectangles are clipped to each
tile.
`Layout.CenteredBandsFor(bounds, width)` reserves a geometrically centered band
and returns disjoint leading and trailing rectangles. The center stays fixed
when the surrounding content changes; an oversized center is limited to the
available width and side groups can scroll within their remaining rectangles.
## Cover carousels
`kryon/carousel` provides `Carousel.Draw(session, props, items, state)` for a
full-cover browser. Keep a `Carousel.CarouselState`, pass `Carousel.CarouselItem`
values with portrait and landscape art, an optional source crop, an optional
logo and caption, and an action label. A zero `source` uses the whole selected
image. It returns the activated item index, or -1. Swipe, wheel, arrows and
Enter/Space share one selection; only that selection exposes an action.
The caller keeps game launching and any footer controls. `CarouselArtwork`
paints the same cover composition for a native loading screen and accepts the
same optional source crop, defaulting to the whole image.
## Loading surfaces
`kryon/loading_screen` provides `LoadingScreen.Draw(session,
LoadingScreen.Props)` for app starts and longer operations.
| `LoadingScreen.Props` | Meaning |
| --- | --- |
| title, detail | Title and localized detail; their class IDs allow text styling |
| `icon_shape`, `icon_asset` | App icon |
| `has_progress`, `completed`, `total` | Set only for measured work; shows a slim standard progress bar. The surface never invents a percentage |
| `reduced_motion` | Keeps the quiet arc still |
| `now` | Drives the arc |
The responsive composition uses the current canvas, surface, border and accent
tokens in native and hosted apps. Use `loading_indicator` for small inline
waits, with the same theme accent.
## Rotated text
`Text.Props.rotation` rotates text clockwise in degrees about `bounds` top left
plus `Text.Props.origin` (logical units). Zero keeps horizontal text; `origin =
Vector2.{bounds.width / 2.0, bounds.height / 2.0}` rotates about the box
centre. Layout and font sizes stay unchanged. Native and Canvas rasters
preserve the same pivot; local text clipping rotates with the text, while
ancestor clipping stays in its original coordinate space.
## Reading pages
`text_measure.TextPage(session, props, start)` returns a UTF-8 byte range
(`start`, `end`, `next`) that fits `props.bounds`. Draw `text[start:end]` with
the same Text props and continue at `next`. Only separating whitespace is
skipped; a viewport shorter than a line reports no progress. Apps keep their
own content anchors and page indexes so reflow preserves the reading place.
`Text.Props.line_gap` supplies extra units between lines. `typeface` names a
registered face or a font asset. Hosted fonts pass the same asset policy as
images; absolute host paths are refused. Native and Canvas hosts select the
face for measurement and for queued paint, restoring the interface font
afterward.
### Native Text typography
Stylesheets set typography on `Text` and `Button` through `style.StyleData`. Set the
matching `control_props.StyleField` bit for each value.
| CSS property | StyleData fields | Supported values |
| --- | --- | --- |
| `font-weight` | `StyleFontWeight`, `font_weight: s32` | `normal` (400), `bold` (700), numbers from 1 to 1000. |
| `font-style` | `StyleFontStyle`, `font_style: FontStyle` | `FontStyleNormal`, `FontStyleItalic`, and `FontStyleOblique`. |
| `letter-spacing` | `StyleLetterSpacing`, `letter_spacing: float32` | `normal` (0) or a signed logical pixel length, including fractions, bounded to ±1024 logical pixels. |
| `line-height` | `StyleLineHeight`, `line_height: float32`, `line_height_unit: LineHeightUnit` | `LineHeightNormal` with value 0 uses the natural glyph height. `LineHeightFactor` multiplies the font size by the value (so 125% is 1.25). `LineHeightLength` takes a logical pixel length. Both numeric units accept zero. |
Explicit line height replaces the interline gap and centers the natural glyph
box within each line. Text measures and paints the same rounded line height.
Button measures the label's line box before positioning the glyphs and its
optional detail. A positive `line_height` with no unit is a pixel height:
Text uses `Text.Props.line_gap` and Button the pixel height.
Cairo/Pango and Canvas use their platform's font matching and synthesis when a
family lacks the requested face. Canvas tracking requires
`CanvasRenderingContext2D.letterSpacing`. Pixmap's bundled regular outlines
apply tracking between extended graphemes. Android's selected Pixmap typeface
uses Paint's native shaping and letter spacing. Android API 28 and later use
numeric weights. Earlier versions group them into normal and bold, and Android
maps oblique to italic. CSS relative weights and angle-based oblique are
outside this API.
`Text.Props.wrap = Text.Wrap.TextWrapAnywhere` wraps at extended Unicode
grapheme boundaries, including inside unbroken usernames. Combining marks,
emoji ZWJ sequences and flags stay whole. Spaces are preserved and CR, LF and
CRLF end lines. A single grapheme wider than the bounds stays whole on its own
line; nonpositive widths disable wrapping. The default `TextWrapAuto` still
wraps at word boundaries and keeps oversized Latin words intact. Supply enough
height for the resulting lines.
## Multi-select grid
`GridMulti.Draw(session: Session, props: GridMulti.Props,
items: []GridMulti.GridMultiItem, selected: []bool) -> GridMulti.GridMultiResult`
is exported by `kryon/grid_multi`.
| `GridMultiItem` field | Meaning |
| --- | --- |
| `key: u64` | Unique and nonzero to retain identity across reordering; zero falls back to the current index |
| `label: string` | Row label |
| `image: Image.Props` | Optional image; bounds and child image keys are assigned by the grid |
Build images with `ImageForIcon(icon_type: s32, bounds: Rectangle,
alt_text: string) -> Image.Props` and `IconType` from `kryon/icon` (import
`kryon/image` too); for example `ImageForIcon(cast(s32)IconType.IconHome,
Rectangle.{}, "Home")`. Ship the referenced `icons/` atlases as ordinary
application assets. Images use the ordinary Image renderer, including assets,
previews and session-owned textures.
Keep the mutable selection slice (exactly one bool per item), `cursor`,
`anchor` and `scroll_offset` between calls. Items, labels and image data are
borrowed for the call; normal Image asset/texture lifetimes still apply. The
grid never retains the selection slice. Remap caller state when the
application reorders or replaces items.
| `GridMulti.Props` | Meaning |
| --- | --- |
| `cell_width`, `cell_height` | Logical cell size; defaults 96 by 96 (Icon) and 180 by 32 (Compact) |
| `image_size`, `gap`, `padding`, `scale` | Layout metrics |
| `bounds`, `key`, `class_name`, `id` | Placement, stable session-unique widget key (including across embedded host roots), style class and focus id |
| `invisible` | Retains selection, input, scrolling and accessibility while the host paints natively; use the normal retained frame for image clipping and pointer routing |
| `navigation` | Edge/repeat decisions for keyboard input |
| `GridMulti.GridMultiLayout` | Behavior |
| --- | --- |
| `GridMultiIcon` (default) | Measures columns from available width, places the image above the label, scrolls vertically |
| Compact | Measures rows from height, places a smaller image before the label, scrolls horizontally |
| `GridMultiResult` | Meaning |
| --- | --- |
| `valid` | False on mismatched storage, without changing selection; empty matching slices are valid, with cursor/anchor -1 and zero scroll |
| `changed` | Selection changed |
| `clicked_index` | Every accepted pointer click, even when selection is unchanged; keyboard selection never sets it |
| `activated_index` | Enter activation; ordinary pointer clicks and Space do not activate. Hosts expose no canonical double-click activation, so callers keep their pointer-click action policy |
| `selected_count` | Includes offscreen items |
Missing actions use -1; keep application actions in the caller.
Keyboard input requires `focused` and an enabled grid; modifiers arrive
through `control` and `shift`.
| Input | Effect |
| --- | --- |
| Icon Left/Right, Up/Down | Moves within a row, then by measured columns |
| Compact Left/Right, Up/Down | Moves by measured rows, then within a column |
| Ctrl arrows | Move focus alone |
| Ctrl click, Space | Toggle selection; Space never activates |
| Shift | Extends from the persistent anchor |
| Ctrl+Shift | Adds a range |
| Home/End | Select first/last item with the same modifiers |
| Enter | Selects and activates the cursor |
Incomplete final rows/columns clamp to their last item. Navigation, a newly
focused cursor and viewport resize reveal focus; ordinary frames keep manual
scrolling. `scroll_delta` adds caller movement, while the standard Scroll
handles sampled wheel/drag input. Disabled grids accept no input. Unfocused
grids still accept pointer input.
-270
View File
@@ -1,270 +0,0 @@
# Widget packages
This file covers widgets and input surfaces outside the core catalog: optional widget packages, bound text fields, intrinsic layouts, frame input snapshots and overlay dismissal.
`EmptyState.Props.disabled` and `Banner.Props.disabled` keep configured action and dismiss buttons visible with disabled styling and semantics. They reject pointer and keyboard activation, including input queued before disabling, and become usable again when enabled.
`Carousel.Props.disabled` disables swipe, wheel, keyboard navigation, arrows,
and the selected action together. It defaults to false; item-level `disabled`
disables only that item's action. Disabled controls use their normal
disabled styling and become interactive again when reenabled.
`Carousel.Props.logo_max_width` optionally caps the cover logo's logical width;
`logo_top` optionally positions it below surrounding controls, relative to the
carousel bounds. Zero preserves the default title layout. `CarouselArtwork`
accepts the same optional values after its source rectangle for startup covers.
A widget that is not part of the core catalog lives in its own Git package
and depends on Kryon. [Plot](https://github.com/kryonlabs/plot) and
[DataViews](https://github.com/kryonlabs/data-views) are examples. Import
the building blocks by their package-qualified names, so a reader sees which
package each name comes from:
```zi
#import "kryon/session"
#import "kryon/tree"
#import "kryon/surface"
#import "kryon/paint_queue"
```
Tests that need a host bind Kryon's internal capabilities the same way, for
example `--bind kryon/raster_text:RasterText=my_test_host:RasterText` with
`ziran bundle --project`.
Source coloring is the separate [Syntax](https://github.com/ziranlang/syntax)
package. Its `SyntaxColorSpan` has the same fields as `TextArea.ColorSpan`.
Hosts with stable font measurements call `font_metrics.GlyphMetricsChanged()`
after initializing their font services and whenever fonts or their advances
change. This lets `TextArea` retain wrapped rows in a bounded cache of owned
content. Publish revisions on the UI's owning thread. The pixmap host enables
reuse automatically for its bundled, fixed
font outlines. Hosts that have not published a metrics revision keep measuring
rows on each call; they do not acquire an invalidation requirement implicitly.
Font size, typeface, wrap width and content changes always select a new layout.
`TextArea.Props.manual_scroll` keeps a reader's scroll position independent of
caret and selection changes. Wheel, scrollbar and touch scrolling remain
available. Editors keep the normal caret reveal unless they enable this flag.
`Scroll.Props.manual_scroll` similarly suppresses automatic focused-field
reveal for a reader that owns its viewport.
`TextField.Props.capture_tab` defaults to false. An editable field can opt in
so an unmodified Tab queued before `BeginFrame` remains available through
`KeyboardTake(session)` for application completion. Only the actual retained
focus owner can capture it, using its last committed intent; disabled,
read-only, fully clipped and unfocused fields do not capture. Shift+Tab retains normal focus traversal.
Control-, Alt- and Super-modified Tab stay queued for application input. Intent is scoped to the retained
node and session epoch, including suspended embedded-app input.
`input.focus` also transfers actual focus to a newly submitted TextField in
its first frame, so the next queued key reaches it without an idle render.
### Intrinsic layouts and bound text fields
A retained form can use `Layout.Draw` for a column and `Layout.Row` for a row.
Submit ordinary widgets inside the scope and close it with `End(session)`.
Omit the bounds of an intrinsic button in a row or a bound text field in a
column. The button sizes to its content, and the field fills the column's inner
width and uses the themed control height. `Layout.Gap(.ThemeMetricSpace2)`
resolves a theme spacing token in logical units. `Layout.LayoutContentBounds`
measures unset outer dimensions from child rectangles, direction, main-axis gap
and padding. Its optional `padding_y` sets the vertical inset independently.
Pass a calculated dimension in `Layout.Props.bounds` to fit it to
content, or use an explicit width to compose inside a viewport.
Retained layout rules match `StyleKindRow()` or `StyleKindColumn()` and the
optional `Layout.Props.id` and `class_name`. Styles support `StyleGap` as a
shorthand and `StyleRowGap`, `StyleColumnGap`, `StylePaddingX` and
`StylePaddingY` for independent spacing, rounded to the nearest logical pixel.
A single-line row uses `column_gap` between children and a column uses `row_gap`.
`Layout.Props` accepts uniform `gap` and `padding` over the style and independent
`row_gap`, `column_gap`, `padding_x` and `padding_y` over those shorthands.
Set the corresponding `_override` flag to supply explicit zero. Negative
spacing is clamped to zero.
`Layout.Grid(session, Grid.GridProps, items)` uses CSS `Grid` width, height,
padding, row/column gaps, and equal `grid-template-columns` tracks. Pass
`[]Grid.GridItem` for a measured grid. Each item supplies its height and span.
With unset height, the grid reserves the tallest item's height per row plus
inter-row spacing and block padding. Call `Grid.GridStep` on the returned
cursor for each item and draw using `cursor.item`. A negative span fills a row.
Close `result.container.opened` with `End(session)`. A two-argument `Layout.Grid`
places unpositioned children one track at a time. See the
[HTML/CSS mapping](HTML_TO_KRYON.md#author-a-responsive-dashboard).
For a native bound field, initialize `state.bytes` once from application-owned
storage and set `state.length` to the number of UTF-8 bytes in the initial
value. `TextField.Bind(session, *state, props)` draws and applies edits to that
storage. Give each field a stable `key`. The same field keeps focus, selection,
scroll and IME preedit across frames and resize. It consumes editing input from
the focused session and uses the platform clipboard. Use the returned `changed`,
`committed`, `escaped` and `paste_without_text` flags for application actions.
For deterministic input, pass `false` as the fourth argument to `Bind`
and provide the sample in `props.input`. Custom hosts can pass an IME sample
in `props.input.composition_event`. Native platform text requests use the
same bound widget.
```zi
// name.bytes points to persistent application storage.
form := Layout.Draw(session, Layout.Props.{.key = 11, .bounds = bounds,
.gap = Layout.Gap(.ThemeMetricSpace2)})
if form.opened {
edited := TextField.Bind(session, *name, TextField.Props.{.key = 42, .label = "Name"})
if edited.committed {
SaveName(TextView(name.bytes[:name.length]))
}
unused End(session)
}
```
`TextField.State` keeps a field's value and interaction state in caller-owned
storage. Import it and its helpers as `TextField :: #import "kryon/text_field";`.
Give `bytes` a writable slice and set `length`, `cursor`, `anchor`, `scroll_x`
and `focused` as needed. Every byte of the slice is usable capacity; length
does not include a terminator and the helpers do not write one.
```zi
// Keep the bytes and state alive between frames.
name_bytes: [96]u8;
name: TextField.State;
// Initialize once: name.bytes = name_bytes[:]
// In Frame, use the existing widget and keep the application's commit policy.
edited := TextField.Draw(session, TextField.StateProps(name, TextField.Props.{
.key = cast(u64)42, .bounds = bounds, .label = "Name", .input = input}))
if TextField.StateApplyResult(*name, edited) && edited.committed {
// Save or navigate according to the application's workflow.
}
```
`TextField.StateProps(state: TextField.State, props: TextField.Props) -> TextField.Props`
fills value, selection, scroll and focus, and limits `max_bytes` to storage
capacity while preserving stricter application limits and all other props.
The value borrows the buffer; consume borrowed result text before mutating it.
An invalid length or UTF-8 value disables the field; zero capacity is read-only.
`TextField.StateApplyEdit(state: *TextField.State, edit: TextField.Edit) -> bool`
accepts only ordered ranges within the current value, with both ends at
UTF-8 scalar boundaries, valid UTF-8 replacement text, and a result that fits
the slice. The current value must also be valid UTF-8. Replacement can borrow
any part of the destination: a temporary owned join is freed after the call.
Rejected edits, including allocation failures, preserve every byte and state
field. An accepted changed edit collapses selection after the replacement.
An unchanged edit is accepted without changing state. Application-specific
text limits beyond storage capacity are enforced by the widget's props.
`TextField.StateApplyResult(state: *TextField.State, result: TextField.Result) -> bool`
applies the edit and copies cursor, anchor, scroll and focus together. A rejected
edit preserves all of them. Successful application clamps cursor and anchor
to scalar boundaries in the resulting text and scroll to zero or greater;
the widget still owns grapheme navigation. `true` means accepted, including
navigation with no edit; it does not mean committed. Enter, Escape, clipboard
and IME composition remain available on the original result for the application
to handle, with the borrowed-text lifetime rules above.
Native TextArea and TextField snapshots retain the supplied cursor and anchor
and return only the changed grapheme-aligned span as their edit. An unchanged
snapshot updates selection without a text edit. This keeps a correction near
the beginning of a long note from revealing the document end on its edit frame.
Applications must apply the edit and preserve the result's cursor and anchor.
A `TextArea` can preview a markup language over its value without changing
it. `hidden` bytes take no width or caret stop, `strong` bytes are bold and
`italic` bytes slanted when the host registers a slant raster (otherwise upright), and `colors` tint spans.
`lines` draws a logical line at its own size (`TextArea.Line.scale`), such as
a heading: its rows wrap, take caret stops and take height at that size.
`blocks` adds boxes under a line, one under another in order, the first in
place of its last row with `cover`, each drawing `image` fitted inside it or
a soft frame with `label` while the image is missing; a press inside a box
is the end of its line. Every list is sorted, with starts at line starts and
at most one size per line, or ignored as a whole; without them the layout is
the plain area's. During an IME composition, lines and
boxes after it move with the preedit.
`MarkdownEditor :: #import "kryon/markdown_editor";` shares the inline
Markdown editor used by Inner Breeze Diary. Call
`MarkdownEditor.Draw(session, MarkdownEditor.Props.{.area = area, ...})`
with ordinary `TextArea.Props` and retain its result's edit, cursor, anchor,
scroll and focus. `muted_color` and `link_color` color list/quote markers and
links. Headings, emphasis and links preview while the caret's active lines
show their original syntax. The value and edit offsets always address the
original Markdown; there is no HTML conversion or second document.
The optional `kryon/markdown_preview` module exposes `Scan(preview, text,
cursor, anchor, editing, images)` for hosts that need the formatting ranges.
An app resolves its own media into `ImageSpan` values and corresponding
`area.blocks`; the editor owns only their layout and syntax visibility.
It never reads a file or fetches a URL. `kryon/text_props` exposes the
text/range data types without importing a text renderer.
Import `kryon/pointer_input` for `SamplePointer()`, which also works inside a
hosted widget frame. The host returns the pointer sample for the session passed to `WidgetHostBegin`;
an inactive frame cannot read input, and another session's sample is not exposed.
The pointer value schema lives in `input_protocol`, independently of the native
retained input implementation.
`frame_snapshot.CaptureFrameInput(session: Session) -> FrameInputSnapshot`
returns the host's immutable observations for the current frame. `available`
is false before a host publishes, after it ends the frame, or for an invalid
or different session. The result owns its `keys: [512]u8` array and nested
pointer values: retained copies survive subsequent polls and hosted calls.
Test `snapshot.keys[KeyLeft] & cast(u8)FrameKeyHeld` for sustained movement.
Each entry combines `FrameKeyHeld` (1), `FrameKeyPressed` (2),
`FrameKeyReleased` (4), and `FrameKeyRepeated` (8). A repeat is distinct from
a fresh press; holding a key does not invent repeats. Indices use the
uppercase ASCII and named `Key` codes; index zero is unused.
The snapshot also carries `pointer`, `secondary`, `focused`, `modifiers`,
`wheel`, and `elapsed_ms`, `delta_ms`, `sequence`. Desktop and Canvas
sample a monotonic clock once per successful host poll: first delta is zero,
later deltas are nonnegative, and repeated captures have identical timing.
Sequence starts at one for each opened host. Pointer coordinates use the
host's logical zoom.
On focus loss, held keys become released for one poll, held pointer buttons
are released, and pressed/repeated keys, modifiers and wheel are cleared.
Further unfocused polls have no held keys or repeated releases. The first
focused poll after focus loss may report held keys but suppresses fresh
press and repeat flags, preventing a focus change from activating a shortcut.
Hosts publish on the session's owning thread with `FrameInputBegin(session, snapshot) -> bool` and call
`FrameInputEnd(session)` after the callback, including failure paths. Publishing
copies the value and rejects replacement while that session's frame is open.
Kryon's standard Desktop and Canvas app loops do this automatically.
Desktop freezes raw SDL key events for its own window; Canvas freezes the page's
DOM held state and edge queues before widget reads. Both clear publication on
callback cancellation, terminal polls and host teardown. Custom Desktop or
Canvas loops call `DesktopFrameInputBegin(session)` or
`CanvasFrameInputBegin(session)` after the matching successful poll, and
`FrameInputEnd(session)` when their callback ends (including failure paths).
The host also ends publication before presentation can yield. Other providers must supply
equivalent gathered state; this API does not infer held keys from consumed
keyboard events. A hosted
bundle requests only `frame_snapshot.CaptureFrameInputHost`; `WidgetHostCall`
validates the session against the active `WidgetHostBegin` before returning
that session's published snapshot. No input is queried outside that frame.
Capturing never consumes `KeyboardTake`, `TypedTextTake`, IME, clipboard, or Escape routing. Applications retain movement,
simulation, repeat cadence, and navigation policy. The `FrameInput`
replay record and its apply/field helpers keep their contract.
`Scroll` reveals a newly focused text input and adjusts when the viewport
resizes, such as when a phone keyboard opens. It retains that focus transition
on the scroll node. Keeping an input focused never recenters it after manual
scrolling; applications should not repeat their own focused-field reveal loop.
`BeginFrame` routes Escape to the topmost retained modal or popup, even
while a field has focus. `DismissibleOverlay` and `Popup` report it through
`closed`; a non-dismissible modal consumes Escape without closing. Hosts
send `KeyEscape` with `KeyboardSend`, and application shortcuts check
`TreeEscapeCaptured(session)` before handling that same Escape. `KeyF3` is the
canonical F3 key code (292) for application shortcuts.
`Modal.Props.dismiss_on_outside` defaults to false. Its full-viewport scrim
owns pointer presses that start outside the panel and consumes their releases,
including drags that cross the panel boundary, without reporting `dismissed`.
Set `dismiss_on_outside = true` to opt into outside-release dismissal. Escape
dismisses the modal by default; `dismiss_disabled = true` prevents both Escape
and outside dismissal. `Overlay.Props.outside_dismiss_disabled` blocks outside
releases independently of Escape.
`Overlay.Popup` and context menus keep their separate press-outside dismissal
and click-through behavior.
-64
View File
@@ -1,64 +0,0 @@
# Zoom
`src/ui/zoom.zi` zooms a whole application the way a browser page zoom does.
Ctrl and the mouse wheel step one factor for the session; Ctrl with plus,
minus, or zero steps or resets it. The factor scales the entire application,
not one container, so it is a single number the host or the application
applies once.
Kryon makes the decisions and the host supplies raw observations. Each frame
the host passes the wheel movement and the held modifiers:
```zi
consumed := ZoomWheel(session, platform, wheel, KeyboardModifiers(session))
if consumed { wheel = 0.0 } // Ctrl+wheel is zoom, not scrolling
```
`ZoomWheel` returns true when the wheel belongs to zoom, so the application
must not also scroll with it. Positive movement zooms in. Whole notches step
the factor, and the small movements of a touchpad add up until they reach a
notch. `ZoomKey(session, platform, key, modifiers)` does the same for the
keyboard shortcuts. Read the result with `ZoomFactor(session)` (`1.0` is
100%).
## The prop
`ZoomProps` configures a session with `ZoomConfigure(session, props)`. Its zero
value is the default, so an application that never configures zoom gets it:
| Field | Default | Meaning |
| --- | --- | --- |
| `mode` | `ZoomModeAuto` | `Auto` zooms on desktop windows only. `On` zooms on every platform. `Off` never zooms. |
| `factor` | 1.0 | Starting factor. |
| `minimum` | 0.5 | Lowest factor. |
| `maximum` | 3.0 | Highest factor. |
| `step` | 0.1 | One notch. The factor always lands on a whole number of steps. |
Automatic mode leaves a browser alone, because the page already zooms with the
same keys, and leaves touch screens alone, because they have no wheel. Pass
the platform as the `DPIPlatform` the host already reports for `ResolveDPI`.
`ZoomSet(session, factor)` restores a saved preference and returns the factor
after clamping and snapping; `ZoomReset(session)` returns to the starting
factor.
## Applying the factor
The factor scales the whole application, widget text included, so a host
applies it as a render scale rather than asking each screen to scale itself.
A host that lays out in logical units passes the factor to the DPI state:
`ZoomDPI(state, factor)` makes the render scale the display density times the
zoom, and the layout is the view divided by it. A zoom below 100% lays out a
larger area and a zoom above it a smaller one, and `ResolveDPI` keeps the zoom
across resizes and density changes. Inbe does this: it stores the factor as
its UI scale setting, so the wheel and the Appearance slider drive one value,
and hands that setting to `ZoomDPI` each frame.
A host that draws an application unchanged applies the factor as a render
scale and divides pointer positions and the viewport by it. Layout reflows
to the scaled viewport; text is rasterized at the scaled size.
An application imports the module as `Zoom` (and `DPI` for the platform enum)
from the Kryon package. To opt out, or to force zoom on every platform, call
`ZoomConfigure(session, props)` with `mode` set to `ZoomModeOff` or
`ZoomModeOn`; the default `ZoomProps` is automatic.
-138
View File
@@ -1,138 +0,0 @@
# Canvas2D browser host
A browser integration roots `src/backend/canvas_raster.zi` with the selected
host and defines `PLATFORM_WEB`. Generate native sources with Ziran, then link
them with Emscripten, and Ziran's Web bridge:
```
--js-library $ZIRAN_DIR/web/ziran_web.js
-sEXPORTED_RUNTIME_METHODS=FS
-sASYNCIFY -sSINGLE_FILE=1 -sEXIT_RUNTIME=1 -sENVIRONMENT=web
```
The browser hosts (`page_core.zi`,
`page_paint.zi`, `page_texture.zi`, `page_font.zi`, `page_events.zi`,
`page_files.zi`, `page_input.zi`, `page_mesh.zi`, `canvas_audio_host.zi`, `dom_host.zi`) are
written in Ziran and reach the page through `std/web.zi`; the one JavaScript
file is the generic, Kryon-agnostic bridge in the Ziran repository.
The page uses a Canvas2D context with a drawing preference that survives
occasional pixel reads. When WebGL is available, `Image` meshes share
a private surface around their visible bounds and transfer to the page together.
Indexed grids reuse shared vertices, and small size changes reuse the drawing
buffer. Texture changes retain their painter order within the batch. Other
paint, clipping, target changes, readback and presentation flush that batch
in order. Without WebGL, the same API uses the Canvas2D triangle painter.
Ordinary sprites without local rotation or mirroring draw directly in the
current camera coordinates. They preserve the caller's opacity and sampling
without copying the complete canvas state for each tile. Opacity alone does
not allocate a tinted texture.
The UI host retains its existing back buffer. It compares checked paint plans,
keeps unchanged pixels and clears/replays only the damaged region. Session,
viewport, display-density, background and raster-resource changes repaint as
needed. Ordinary host paint and custom emitters use complete painting. Text
measurement leaves retained pixels intact. This adds no extra full-size surface.
The dedicated `canvas_raster.zi` provider
calls the Canvas modules directly, so retained widgets use the same paint
queue, font selection, and clipping path as the native host. Frame-profile builds retain the selected `_run` host and `canvas_raster.zi`
as generation roots for raster and typeface adapters. A program entry owns
its own `main`.
`RequestWindowClose` is currently a raw browser host capability. An application
may declare it against `host_api`; the host records the request and observes it
on the next poll so the current frame can finish committing.
Ziran owns frame timing, image memory, font atlas packing, text layout, file
callbacks, audio decoding and conversion, resource APIs, and every call into
the browser's events, Canvas2D, FontFace, WebAudio, clipboard, and Emscripten
filesystem. Asynchronous browser calls carry
Emscripten async metadata and require Asyncify.
`EndDrawing` yields to the next browser frame for ordinary canvas loops. An
application using `emscripten_set_main_loop` must call
`SetExternalFramePacing(true)` before starting that loop, so only the callback
scheduler waits for frames. `SetTargetFPS` then adjusts that scheduler's RAF
interval; it does not suspend `EndDrawing`. Opening a window resets this mode.
The host finds `#canvas` and fills its `#canvas-frame` container when one is
present, otherwise the canvas parent. It draws at the canvas's own CSS size, so
a frame padded for safe-area insets still matches where touches land, and maps
pointer positions through the canvas's shown box. Include UTF-8 metadata in
HTML shells, including shells using Emscripten's single-file Wasm output.
Only this host's event listeners and resize observer are removed on close.
A subsequent open creates new input and texture state; cached default font
memory is released before closing the canvas.
A `#canvas` that carries the `data-transparent` attribute has no background:
the host clears the window and each frame to alpha 0 instead of Kryon's frame
colour, so the page behind it shows wherever the program draws nothing, and
widgets draw over it as usual. The editor preview sets it; without it every
pixel is opaque.
Applications that handle Escape as navigation can call `CanvasSetExitKey(0)`
through `kryon/Canvas` to disable the host's default Escape-to-exit behavior.
Ordered keys and text remain available through `CanvasInputTake(session)`.
Custom Canvas hosts can use `BeginRasterClip(bounds)` and
`EndRasterClip(saved)` through `kryon/Canvas` to intersect a rendering scope
with an outer viewport, restoring the previous clip afterward.
Images are RGBA8 (`format = 7`). Individual pixel allocations are limited to
64 MiB and 16384 pixels per dimension. Tint caching retains at most 32 entries
and 16 MiB of pixels; releasing or updating a texture invalidates its cached
copies. Frame input queues hold at most 1024 events. Audio streams enqueue at
most two pending buffers and report their actual readiness.
Mesh acceleration retains at most 32 source textures and 16 MiB of source
pixels; its drawing surface is limited to four million pixels and the device's
own limits. Texture updates refresh cached pixels. A lost context releases
its resources and invalidates retained paint before the next frame.
Browser window position, monitor selection, and native window icons have no
corresponding operation on the embedded canvas. Fullscreen and pointer lock
requests remain subject to browser gesture permissions.
## Focused checks
```
tests/canvas_backend_test.sh
python3 tests/canvas_audio_test.py
sh tests/canvas_text_os_wasm_test.sh
python3 tests/canvas_project_test.py
```
The first command compiles the complete host and checks real pixels in a new
headless Chromium process. It covers camera and nested clipping, UTF-8 input,
texture updates and render targets, asynchronous PNG round trips, a real TTF
font, frame yielding, and close/reopen ownership. Mesh pixels, sampling,
opacity and texture updates run at three display densities with acceleration
both available and unavailable; the accelerated runs also lose and recreate
their graphics context. It scrubs desktop display
variables and controls only its own browser process. The other tests verify
WebAudio and text/file behavior with deterministic browser-effect fixtures. The
project test builds a real application manifest through Ziran, loads the
resulting single-file page in private headless Chromium, and checks its exit.
`EMCC`, `CHROMIUM`, `ZIRAN_DIR`, and `ZIRAN_BUILD_DIR` can select installed
tools. `ZIRAN_RUNNER` optionally wraps focused compiler calls in a caller's
serialization script; do not set it when that script already holds its lock
around the entire test.
## Canvas host performance
Before changing the host or Ziran browser bridge, preserve a compiled baseline:
```sh
python3 tests/canvas_performance.py build/scratch/canvas-performance/before
# Apply the change, then compile the same workload again.
python3 tests/canvas_performance.py build/scratch/canvas-performance/after
node tests/canvas_performance.mjs build/scratch/canvas-performance/before \
build/scratch/canvas-performance/after build/scratch/canvas-performance/result.json
```
The runner uses private headless Chromium profiles and interleaves nine samples
per version after warmup. Each sample draws fifty frames of a 512-sprite tile
board, followed by pixel readback. An independent pixel oracle checks the
ordinary board; rotated sprites must match the baseline. Receipts preserve raw
timings and artifact hashes. This measures warm Canvas host throughput on one
shared machine; it does not establish a whole-game frame rate or a speedup on
other devices. The builder refuses to replace an existing compiled artifact.
-35
View File
@@ -1,35 +0,0 @@
# Compact navigation
`Navigation.Draw` can compose a compact vertical rail or horizontal dock using
the same themed buttons, keyboard activation and retained pointer capture as
other Kryon controls.
```zi
Navigation :: #import "kryon/navigation";
props: Navigation.Props
props.key = KeyHash("navigation")
props.compact = true
props.vertical = true
props.bounds = Rectangle.{0.0, 0.0, 88.0, 720.0}
props.footer_count = 2
props.scroll_offset = navigation_scroll
result := Navigation.Draw(session, props, items[:])
navigation_scroll = result.scroll_offset
```
The last `footer_count` items stay at the bottom of a rail or the trailing
edge of a dock. Other items scroll without covering those actions. Supply
stable item keys when shortcuts can move. Items carry route IDs, labels,
`Image.Props`, optional vector `icon_shape`, selected state and disabled state;
the application applies `result.clicked_route` to its own routing.
Set `draggable` to receive `result.drag`, `drag_route` and `drag_bounds` for
shortcut cards. While dragging a card, supply `dragging` and `drag_position`;
`drop_index` reports the insertion slot among the scrolling shortcuts, or
`-1` outside their viewport. Footer actions are never insertion slots.
The surface resolves `NavigationBar` style rules and buttons resolve
`Navigation.NavigationBarItem` rules. `class_name` and `item_class_name` let applications
customize those faces with their current palette. Compact items use ordinary
button hover, focus, press, selection and accessibility behavior.
-5
View File
@@ -1,5 +0,0 @@
/*
Cache-Control: public, max-age=0, must-revalidate
/showcase-data.json
Cache-Control: public, max-age=0, must-revalidate
+38
View File
@@ -0,0 +1,38 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kryon API Reference</title>
<meta name="description" content="Kryon runtime and UI API reference rendered from the canonical markdown documentation.">
<meta name="theme-color" content="#f3f1ea">
<link rel="icon" type="image/png" sizes="16x16" href="icons/kryon.png">
<link rel="apple-touch-icon" href="icons/kryon.png">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="content">
<header class="hero compact">
<img class="hero-icon" src="icons/kryon.png" width="96" height="96" alt="Kryon">
<h1>API</h1>
<p class="tagline">Runtime and widget reference</p>
</header>
<nav class="site-nav" aria-label="Primary">
<a href="index.html">Home</a>
<a href="index.html#features">Features</a>
<a href="index.html#start">Start</a>
<a href="api.html">API</a>
</nav>
<main class="api-reference">
{{ API_BODY }}
</main>
<footer>
<p>&copy; 2026 Kryon Labs | <a href="https://waozi.xyz" target="_blank" rel="noopener">Made by Waozi</a></p>
</footer>
</div>
<script src="highlight.js"></script>
</body>
</html>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

-2
View File
@@ -1,2 +0,0 @@
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Apps and showcase — Kryon</title><meta name="description" content="Play apps built with Ziran and Kryon in your browser, and find the Kryon Labs desktop apps with their source."><link rel="stylesheet" href="current.css?v=2f7ee344c6192e9c"></head><body><input id="kryon-ime" type="text" tabindex="-1" aria-hidden="true" autocomplete="off" autocapitalize="off" spellcheck="false"><div id="canvas-frame"><canvas id="canvas" tabindex="0" aria-label="Kryon interactive website"></canvas></div><pre id="result" role="status"></pre><noscript>This website runs Ziran through WebAssembly. Enable JavaScript to use the live examples.</noscript><script src="current.js?v=2f7ee344c6192e9c"></script></body></html>
-6
View File
@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512" role="img" aria-label="Kryon Labs mark">
<rect x="32" y="22" width="144" height="134" fill="#a65234"/>
<rect x="32" y="175" width="144" height="314" fill="#24302c"/>
<path d="M192 175 310 22h170L298 256H192Z" fill="#395e48"/>
<path d="M192 274h106l182 215H298L192 382Z" fill="#395e48"/>
</svg>

Before

Width:  |  Height:  |  Size: 389 B

File diff suppressed because it is too large. Load diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Loaded 100 of 2930 files, more files were not shown because too many files have changed in this diff. Show more