Compare commits

...
Author SHA1 Message Date
github-actions[bot] a1281ced3f Update CHANGELOG for v0.1.39 2026-09-03 17:15:44 +00:00
github-actions[bot] 1c4472437f release: bump version to v0.1.39 2026-09-03 17:13:27 +00:00
waozi ac9cc47abd Fix image front-end duplicates and canvas radial gradient shim
The shared image front-end (src/backend/kry_image.c) is linked into
every build, so per-backend copies of LoadImageFromMemory, UnloadImage,
IsImageValid, and ImageFlipVertical collide wherever object files are
linked directly (emcc) or pulled together from the archive. Keep the
shared definitions only: drop the copies from the dom, canvas, termi,
and libdraw backends, which now call the shared ones.

The canvas smoke shim never learned createRadialGradient, so the
circle-gradient draw path crashed the Node harness; shim it alongside
the linear gradient.

The boundary checker now skips the site showcase metadata and the
CHANGELOG history when scanning for downstream app names: the showcase
page legitimately lists public Kryon-based apps and the changelog
records history.
2026-09-03 14:06:06 -03:00
waozi d0ebdc93fb Merge origin/master: v0.1.38 release, themes, platform icons 2026-09-03 13:55:26 -03:00
waozi 5a85d1c75a Make Daochi/ksync optional and refresh the Labs site showcase
Gate the Daochi/ksync sources, liboqs linkage, and static-package
payload behind KRYON_WITH_DAOCHI (derived from KRYON_WITH_KSYNC) so
default builds compile them out. Rework the website navigation and
docs page, and add app showcase banners with generated hashes.
2026-09-03 13:54:32 -03:00
waozi 0410787ee5 Drop --plan9 from k2cpp
Plan 9's native compilers are C compilers; the C++ backend never feeds
them, so the ported 8c rewrite pass was dead code. k2cpp now takes only
--no-main, --root, and -o.
2026-09-03 13:54:27 -03:00
waozi 34d313e526 Ship k2cpp in the tools distribution archive 2026-09-03 13:52:14 -03:00
waozi 8448db3452 Verify k2cpp in the packaged tools bundle 2026-09-03 13:50:36 -03:00
waozi bd05e6b421 Fix k2go syntax test filename in make test recipe
The rename pass missed tests/k2g_syntax_test.sh inside the test recipe
because the sed used word boundaries and k2g_ does not match there.
2026-09-03 13:50:06 -03:00
waozi 80b2cc2919 Finish k2g/k2ir rename in runtime parity doc generator and k2kir test rule
Two spots the rename pass missed: tools/runtime_parity_doc.go still
emitted 'k2g' into docs/RUNTIME_PARITY.md, and the k2kir.ok Makefile
rule still depended on tests/k2ir_test.sh. Regenerated the parity doc.
2026-09-03 13:48:03 -03:00
waozi b24fde792f Add k2cpp backend with full k2c parity
.kry -> C++ compiler sharing the Kir frontend with k2c. Emits .cpp/.hpp
per module calling the C Kryon runtime through extern "C" declarations,
plus kryon_project.h/.c (still plain C) and the --plan9 and --include-dir
options ported from k2c. Inferred declarations emit 'auto' instead of
__auto_type so g++ accepts the output. Wired into the Makefile, tools
package, conformance matrix, feature matrix, and a k2cpp syntax test.
2026-09-03 13:39:37 -03:00
waozi 38eb5ab3a6 Rename k2g to k2go and k2ir to k2kir
The short k2g/k2ir names became confusing as the toolchain grew.
k2go and k2kir name their targets explicitly; k2c, k2js, and k2b
keep their existing names. Hard rename, no compatibility aliases.
2026-09-03 13:34:40 -03:00
waozi 760aa4d48a Decode images in shared front-end for all backends
LoadImageFromMemory, UnloadImage, IsImageValid and ImageFlipVertical are
pure CPU operations over the Image struct. Defining them once in
src/backend/kry_image.c (on top of kry_decode_image_rgba) gives every
backend real image decoding - most importantly the generated null
backend, whose weak stubs previously left headless builds with empty
images. The raylib wrappers stop forwarding these names and both
generated files skip them via shared_symbols, mirroring the
kry_surface_math.c pattern.
2026-09-03 12:50:48 -03:00
waozi e583287dff Implement Canvas texture updates 2026-09-02 18:53:17 -03:00
waozi d51a1acd68 Add Light2D scene nodes 2026-09-02 17:29:57 -03:00
waozi cf1cc01404 Modernize the Kryon platform icons 2026-09-02 17:28:31 -03:00
waozi 596f19078f Add light and dark themes to Kryon Labs 2026-09-02 17:21:13 -03:00
waozi d7c433a827 Give Kryon its crayon color system 2026-09-02 17:06:57 -03:00
waozi be0cb7a96d Give Kryon its crayon color system 2026-09-02 17:06:50 -03:00
waozi 0d169ff610 Redesign the Kryon Labs website 2026-09-02 15:34:18 -03:00
waozi 601f3cee58 Redesign the Kryon Labs website 2026-09-02 15:32:24 -03:00
waozi 55144cb63c Make rejected single-instance launches safe instead of crashing
When a second process with the same title-key launches and the lock
holder survives the steal attempts, InitWindow marks the instance
rejected and skips the backend window - but BeginFrame/EndFrame still
drove into rlgl on the never-created GL context and crashed (null
deref on the first frame). Expose InstanceRejected() and make the
frame APIs no-ops in that state so apps can check and exit cleanly.
Regression-tested with an unkillable lock holder: the second instance
is rejected, wants to close, and never opens the drawing backend.
2026-09-01 23:42:33 -03:00
waozi f3521639f2 Ignore static visitors in Area2D body_enter/body_exit signals
Box2D reports sensor overlaps between static shapes too, so a trigger
volume resting on the level floor fired body_enter from the floor the
moment the scene started. body_enter/body_exit describe moving bodies
arriving and leaving: skip visitors whose Body2D is static.
Regression-tested with static decoration inside a sensor while a dynamic
body falls through it.
2026-09-01 21:29:51 -03:00
waozi 8c43add957 Read back armed shots through glad when glReadPixels is unresolved
The armed capture (KRYON_SHOT_ARM) reads the back buffer through a weak
glReadPixels extern, but apps that link only the raylib backend never
resolve it - raylib loads GL through glad - so the weak symbol stays
NULL, the read is skipped, and LoadImageFromScreen returns the zeroed
buffer (a black frame). Fall back to the glad_glReadPixels pointer the
raylib backend exports.
2026-09-01 21:08:34 -03:00
waozi 52a9931cb0 Fix signal handler dispatch for application-defined kinds
The handler table was sized NODE_CUSTOM + 1, so NodeKindRegisterSignalHandler
silently rejected every kind id from NodeRegisterCustomKind, and SignalEmit
then indexed the table out of bounds when a connection targeted a custom
kind - a garbage function pointer call. Size the table to the same 64-kind
cap scene_tree.c uses. Regression-tested by connecting and emitting a
signal whose target is a custom kind.
2026-09-01 20:57:24 -03:00
waozi 1ab55c854b Add direct Body2D control: transform, velocity set/get
Players and kinematic platforms need to steer bodies directly instead of
fighting the post-step transform sync. KryBody2DSetTransform teleports a
body (node transform follows next tick), KryBody2DSetVelocity and
KryBody2DGetVelocity set and read linear velocity in scene units per
second. Regression-tested by steering the falling test body sideways.
2026-09-01 20:52:23 -03:00
waozi f05b08c895 Emit Area2D body_enter/body_exit signals from Box2D sensor events
Area2D documented body_enter/body_exit signals, but nothing ever drained
Box2D sensor events, so areas never fired. Two fixes in the physics
bridge: tag every created body and shape with its NodeId via Box2D
userData so events map back to scene nodes, and drain
b2World_GetSensorEvents after each step, walking the sensor shape up to
its Area2D and the visitor shape up to its Body2D before emitting.
Sensor shapes also need enableSensorEvents=true - Box2D disables sensor
events on every shape by default, even sensors, so without the flag no
overlap events are ever reported. Regression-tested with a monitoring
area that records the dynamic body falling through it.
2026-09-01 20:45:23 -03:00
github-actions[bot] da1d6b156b Update CHANGELOG for v0.1.38 2026-09-01 23:22:21 +00:00
github-actions[bot] a1bbcc711f release: bump version to v0.1.38 2026-09-01 23:20:06 +00:00
waozi 0f1f044826 Compute world transforms before ready hooks in SceneTick
Body2D creates its Box2D body at n->world during its ready hook, and
Camera2D claims the scene from n->world. SceneTick fired ready before
the world-transform pass, so every body in a freshly built scene was
created at the origin (identity transform) and the post-step sync then
dragged the node back to (0,0). Update world transforms first, fire
ready, then fold in any transforms a ready hook dirtied before process
hooks run. Regression-tested via a custom kind whose ready captures its
composed world position.
2026-09-01 20:16:00 -03:00
waozi 49a4a7bb71 Build KRB mount test before running it 2026-09-01 20:13:32 -03:00
waozi 6d85a41b3e Link app storage test filesystem helper 2026-09-01 20:03:32 -03:00
waozi c6c211fa25 Allow local network sync URLs 2026-09-01 18:36:32 -03:00
waozi 28823cd5f5 Guard file app storage on Android 2026-08-31 23:04:28 -03:00
waozi 6cf90df878 Add responsive score control 2026-08-31 22:38:02 -03:00
waozi 54848faf81 Add responsive segmented control 2026-08-31 20:07:52 -03:00
waozi c5e84b8016 Fallback to fonttools module for subsets 2026-08-31 19:56:27 -03:00
waozi 831ba930d4 Add UI font registration from text corpus 2026-08-31 19:46:44 -03:00
waozi ba96caf923 Deduplicate bubbled web input events 2026-08-31 18:09:44 -03:00
waozi 745c2d307e Add shared native Plan 9 application build rules
The compile/link/install recipe was copy-pasted across the Kryon app
mkfiles; mk/plan9-app.mk now carries it, parameterized by the target,
source lists, extra flags, and libraries.
2026-08-31 17:50:27 -03:00
waozi 3d0aef53ec Add KryAppDataRoot for per-user app data
Applications get a created per-user data directory for their id:
XDG_DATA_HOME or ~/.local/share on the desktops, LOCALAPPDATA on
Windows, $home/.local/share on Plan 9 - one policy instead of each
app hand-rolling the path.
2026-08-31 17:48:44 -03:00
waozi b1cdf92404 Keep the plan9 rewrite result heap owned 2026-08-31 17:20:52 -03:00
waozi 29b188de0f Iterate the plan9 rewrite for nested literals 2026-08-31 17:19:57 -03:00
waozi 3181431822 Flatten cast literals nested in field values 2026-08-31 17:18:32 -03:00
waozi e77413a506 Restrict array literal zeroing to declarations 2026-08-31 17:08:01 -03:00
waozi 3298762ebe Zero arrays declared from matching array literals 2026-08-31 17:07:23 -03:00
waozi d12a2b1378 Accept size expressions in array cast validation 2026-08-31 17:06:23 -03:00
waozi e0fbaf7ef3 Flatten bracketed array compound literals 2026-08-31 17:05:17 -03:00
waozi 2326b498fb Split array cast types and strip inline in plan9 declarations 2026-08-31 17:04:16 -03:00
waozi 73147c698c Fix FreeBSD Android DPI test link 2026-08-31 17:03:08 -03:00
waozi 7774fc083f Remove Inbe from Kryon showcase page 2026-08-31 16:56:42 -03:00
waozi daa819858b Update showcase and Pages deployment 2026-08-31 16:48:31 -03:00
waozi 87276e7202 Make web embeds resize to their host frame 2026-08-31 16:45:56 -03:00
waozi 1fc1f70d59 Refuse member selections on call results in plan9 typing 2026-08-31 16:45:29 -03:00
waozi db52845fd2 Reject statement keywords as plan9 prototype types 2026-08-31 16:36:36 -03:00
waozi ea99f320bf Parse split static headers that open their body inline 2026-08-31 15:47:15 -03:00
waozi eab6700674 Join split static prototype prefixes in the plan9 header scan 2026-08-31 15:46:48 -03:00
waozi d51ad13fd7 Unify void pointers in plan9 expression typing 2026-08-31 15:46:13 -03:00
waozi 25aba1a187 Type array casts with size expressions and libc comparisons in the plan9 pass 2026-08-31 15:45:43 -03:00
waozi a265772485 Finish plan9 initializer typing: floats, ternaries, externs, arrays
Float literal tokens type as float, ternary conditions stop
contributing to the result type, extern variable declarations join the
prototype map, array casts carry bracket expressions, dereference
initializers accept comparisons, and the builtin table covers the libc
calls the scan cannot reach.
2026-08-31 15:44:57 -03:00
waozi 600d3074d1 Type parenthesized and logical initializer expressions in the plan9 pass 2026-08-31 15:43:19 -03:00
waozi d1cf4c4fd4 Drop the struct field table from the plan9 pass
Field names from application struct bodies collide with local variable
names (a padding member typed pad shadows layout locals), so member and
address-of initializers stay unresolved unless the Kry source annotates
them; everything else resolves through the prototype map.
2026-08-31 15:42:40 -03:00
waozi 0fe1ff87d1 Keep the base identifier typing under member chains 2026-08-31 15:41:00 -03:00
waozi 9e96bc26df Restrict struct-body detection in the plan9 field scan 2026-08-31 15:40:03 -03:00
waozi d8333ae125 Type struct fields and member chains in the k2c plan9 pass
Build a field-type table from the struct bodies the generated and
application headers already carry, resolve member chains in arithmetic
initializers, and type address-of member initializers as pointers to
the field's type.
2026-08-31 15:39:30 -03:00
waozi 67383d6c4c Allow pointer stars in plan9 prototype return types 2026-08-31 15:37:54 -03:00
waozi 57419ae783 Reject expression text in the k2c plan9 prototype map
Inline bodies in generated math headers parsed as garbage prototypes
(return types like "result.x = v"), which poisoned bare-identifier
typing. Require the return type to read like a type, and constrain .c
scanning to static definition headers before continuation joining.
2026-08-31 15:37:06 -03:00
waozi f9fe41857f Broaden the k2c plan9 type resolution
Accept one-line inline definitions and array compound literals, warn
instead of failing on declarations left unresolved inside platform
guards, keep comparison expressions classifiable, and fall back to a
small builtin table for libc returns the header scan cannot reach.
2026-08-31 15:34:28 -03:00
waozi a58fcf7928 Type initializer expressions in the k2c plan9 pass 2026-08-31 15:32:15 -03:00
waozi 4fe6f5f7da Resolve more initializer shapes in the k2c plan9 pass
Cast expressions carry their type whether or not they are compound
literals, numeric and arithmetic initializers classify as int or float,
string literals become const char *, numeric #define macros join the
prototype map, and the map now also reads static definition headers
from generated .c files so private Kry functions resolve.
2026-08-31 15:30:52 -03:00
waozi 669df023c5 Add a plan9-safe output mode to k2c
The native Plan 9 compiler has no __auto_type, no compound literals with
designated initializers, and no declarations inside for(), so apps have
been carrying per-project rewriter scripts over the generated C. Move
that rewrite into k2c behind --plan9: cast-literal declarations get the
type from the cast, call initializers resolve their return type from a
prototype map built by scanning --include-dir headers (including
wrapped prototypes), compound literals become zeroed temporaries with
field assignments, for-declarations are hoisted into a block, and the
weak app-lifecycle declarations in the project file lose their
__GNUC__ guard. The default output is unchanged; --plan9 fails loudly
when a declaration cannot be resolved.
2026-08-31 15:25:30 -03:00
waozi daaadf5942 Match Canvas2D random values to raylib 2026-08-31 15:16:42 -03:00
waozi f3e615e5fd Cache web automation query options 2026-08-31 15:11:51 -03:00
waozi cace9b362a Ignore empty automation env options 2026-08-31 15:07:50 -03:00
waozi e323df71d7 Add automation options for test runs 2026-08-31 14:40:36 -03:00
waozi 3ac0174a5f Pace Canvas2D frames with browser vsync 2026-08-31 14:23:18 -03:00
waozi 735835db0c Respect target FPS on Canvas2D 2026-08-31 14:17:35 -03:00
waozi 1016474f40 Render docs IDE previews directly on canvas 2026-08-31 14:09:51 -03:00
waozi cf352dcb2c Build the ksync crypto primitives for Plan 9
Inbe's storage layer encrypts private records with the ksync crypto
surface, which is portable C (the /dev/urandom read falls back to a
seeded PRNG where the device is absent). Add it to the native library;
the sync and transport halves stay excluded.
2026-08-31 14:06:47 -03:00
waozi 31dac7344f Honor Canvas2D texture filters 2026-08-31 13:58:41 -03:00
waozi 16adb53e7c Add web routing stubs to the libdraw backend
The shared page helpers consult the web routing hooks; give the native
libdraw library the same static-root fallbacks the web platform uses
outside the JS bridge.
2026-08-31 13:08:41 -03:00
waozi 7b93c1df58 Add android_host and DOM page stubs to the Plan 9 library
Apps built against the libdraw backend call the AndroidHost reserved-
space and secure-store surface (inert off Android) and the shared page
helpers reference the DOM metadata hooks, which only the web backend
implements. Compile the non-Android android_host stubs into the native
library and give libdraw inert defaults for the DOM page surface.
2026-08-31 12:56:21 -03:00
waozi cb247f629f Add the page, overlay, and spritesheet objects and IsTextureValid to the Plan 9 build
The libdraw library was missing the newer UI toolkit objects (routes,
dismissible overlays, spritesheets), so apps using them failed to link,
and the backend had no IsTextureValid for the raylib surface.
2026-08-31 12:44:48 -03:00
waozi f0a8f3d874 Provide ShowCursor and HideCursor on the native Plan 9 backend
Ktrem hides the pointer while the user types, but the libdraw backend
had no implementation of the raylib cursor calls, so linking the
terminal against the Plan 9 library failed. Back them with the rio
mousectl cursor on/off switches.
2026-08-31 12:18:53 -03:00
waozi 00c50a8d8b Improve Debian platform icon 2026-08-31 12:13:33 -03:00
waozi 84f098f28a Define SIZE_MAX in the Plan 9 libc shim umbrella
kry_alloc.h reaches for SIZE_MAX through <stdint.h>, which hosted
headers define but the stdint shim did not; define it once in the
umbrella header every shim includes.
2026-08-31 12:04:10 -03:00
waozi 61e2cefe8b Define SIZE_MAX in the Plan 9 limits shim 2026-08-31 11:59:31 -03:00
waozi ba240811ce Implement rename for the native Plan 9 runtime
Plan 9 has no rename(2) and no declaration for it, so kry_fs_move broke
the libdraw build with implicit-declaration errors. Add a rename to the
Plan 9 runtime stubs implemented as a same-directory name wstat (the
cross-directory case fails), and declare it in the libc shim.
2026-08-31 11:56:41 -03:00
waozi 9fbeb26e0a Flatten the remaining form section label compound literal for 8c 2026-08-31 11:50:50 -03:00
waozi b44b067703 Avoid multi-field designated compound literals in 8c sources
The native Plan 9 compiler miscompiles compound literals that carry
more than one designated initializer (it garbles the field types), which
broke the libdraw build in the form row helpers, the scaffold scroll
page, and the backend texture draw path. Build those structs through
zeroed locals with plain field assignments; hosted codegen is unchanged.
2026-08-31 11:46:55 -03:00
waozi 26a5ed561d Export immediate button controls 2026-08-31 11:43:38 -03:00
waozi 3efb3a1c4f Flatten nested designated initializers in form row helpers
The UIFormTextField and UIFormSpinbox wrappers built their props with
nested designated compound literals, which the native Plan 9 compiler
cannot parse (it reports incompatible-types errors on the nested brace
initializer). Assign the fields through a zeroed local struct instead;
behavior is unchanged on hosted backends.
2026-08-31 11:42:37 -03:00
waozi 401270f418 Guard GTK tray fallback deprecation 2026-08-31 11:39:20 -03:00
waozi b0938f1c23 Fix KIR parser recursion and tool warnings 2026-08-31 11:37:16 -03:00
waozi 97fe163441 Provide fmaxf/fminf in the Plan 9 math shim
Native Plan 9 libc has no fmax/fmin to map the float spellings onto,
and the generated math3d surface (raymath) clamps with them, breaking
the libdraw build with implicit-declaration errors under 8c. Add inline
implementations with C99 NaN semantics to the shim.
2026-08-31 11:36:38 -03:00
waozi f7b7dcab66 Add native spritesheet helpers 2026-08-31 11:36:18 -03:00
waozi 5a70809374 Fix recursive KIR expression parsing 2026-08-31 11:29:51 -03:00
waozi 3a97f42678 Clean up Kryon build warnings 2026-08-31 11:26:17 -03:00
waozi 0993e60bee Improve Kry language tooling 2026-08-31 10:44:13 -03:00
waozi 8e3dcb4db9 Test dismissible overlay input capture 2026-08-31 10:44:13 -03:00
waozi ad7ff9f3f3 Add dismissible overlay helper 2026-08-31 10:44:13 -03:00
waozi bcf4a04363 Use viewport scale as Android DPI floor 2026-08-31 10:44:13 -03:00
waozi ab071cd892 Stabilize Android viewport scaling 2026-08-31 10:44:13 -03:00
waozi b3a582cce2 Add Android viewport policy resolver 2026-08-31 10:44:13 -03:00
waozi 0ab7a533f4 Fix Android UI density scaling 2026-08-31 10:44:13 -03:00
waozi 73bc83a939 Implement libdraw texture updates 2026-08-31 10:44:13 -03:00
github-actions[bot] 96cceb9c9b Update CHANGELOG for v0.1.37 2026-08-30 22:32:23 +00:00
github-actions[bot] 94510e6be1 release: bump version to v0.1.37 2026-08-30 22:30:12 +00:00
waozi a74ba83708 Keep UI tree API test headless 2026-08-30 19:23:17 -03:00
waozi 074bd94037 Lock the canvas-space input contract with tests
TestCanvasSpaceInputInvariant drives a headless runtime end to end:
taps at drawn bounds consume, taps outside don't, and offset taps
(what a root-position translation would produce) must not hit — the
exact regression that broke every widget click. The X11 decode test
pins pointer coordinates to wire offsets 24/26, untranslated.
setInputFocus no-ops without a connection so decode is testable.
2026-08-30 19:19:59 -03:00
waozi e3ce6599c9 Compress encrypted ksync payload envelopes 2026-08-30 19:08:50 -03:00
waozi 6c06d9a3c9 Revert X11 pointer translation: the canvas is window-sized
The widget canvas is the configured window size, not the screen, so
window-relative pointer events were already in the right space. The
translation broke every widget click by the window's root position
whenever the window sat anywhere but (0,0) — tab bar included.
2026-08-30 17:05:41 -03:00
waozi 4cdf025466 X11: translate pointer events by the window's root position
The widget canvas is laid out in root/screen space while X11 delivers
pointer coordinates relative to the window: with the window anywhere
but (0,0) every tap landed hundreds of pixels away from its widget —
checkboxes, dropdowns and the tab bar were click-dead while the
renderer kept drawing at the right spot. ConfigureNotify's position
now feeds an input translation.
2026-08-30 16:56:33 -03:00
waozi 6a70d6faa7 Runtime: log queued taps under the debug gate 2026-08-30 16:53:16 -03:00
waozi 3131ebdadb Runtime: log tap consumption under the debug gate 2026-08-30 16:52:09 -03:00
waozi 89c4207178 Runtime: env-gated checkbox tap debug line 2026-08-30 16:51:16 -03:00
waozi 3e4facb498 Tray: log registration and (debug-gated) connection death 2026-08-30 16:41:30 -03:00
waozi 247b5cbb03 Tray: path-scoped DBus serving and the dbusmenu property surface
Properties.GetAll answered with the SNI property set regardless of
which object path the host asked about, so the panel's dbusmenu
client got garbage for Version/Status on /MenuBar and silently
dropped the whole item — registration succeeded, no icon appeared.
Handlers are now registered per path, and /MenuBar answers the
com.canonical.dbusmenu properties (Version 3, Status normal). The
SNI set also carries WindowId, IconThemePath and ItemIsMenu that
hosts commonly require.
2026-08-30 16:38:56 -03:00
waozi ef1278d769 Size the web canvas backing store from its CSS layout box
Shells can lay the canvas out inside a framed card instead of
letting it fill the viewport. resizeMainCanvas forced the backing
store to the requested window size and wrote matching inline CSS,
so a card-shaped element displayed a window-shaped bitmap and the
render was stretched. Ask for the requested size, then let the
element's laid-out box win when CSS sizes it; also stop assigning
the width/height attributes on no-op resizes, which cleared the
bitmap every frame.
2026-08-30 15:48:00 -03:00
waozi 228060fbd8 Add reusable app storage API 2026-08-30 14:11:14 -03:00
waozi c438ab4f1f Add reusable Android host services 2026-08-30 13:44:51 -03:00
waozi 2c5c23e053 Include KIR text helpers in CMake codegen 2026-08-30 13:35:52 -03:00
waozi 097573bbef Allocate the canvas font glyph scratch on the heap
canvas_font_build kept a 256 KiB glyph raster buffer as a stack local.
Web builds default to a 64 KiB wasm stack with no guard page below it,
so building any font silently wrapped the stack pointer into static
data and corrupted whatever globals live at the end of BSS.
2026-08-30 12:10:41 -03:00
waozi 924b0355ed Add post-frame callback scheduling 2026-08-30 12:10:06 -03:00
waozi d268a331ff Fix render-target blits and autoplay-blocked audio decode in the canvas backend
js_draw_texture_pro re-anchored negative source extents with sx += sw /
sy += sh, so the raylib render-target idiom {0,0,w,-h} produced an
out-of-bounds source rect that browsers clip to nothing — a full-frame
blit drew nothing and the screen stayed black. Render targets are now
flagged in K.targets: a negative source height on one is the "draw
upright" idiom (canvas targets are stored upright, unlike raylib's
bottom-up FBO textures) and draws an in-bounds rect unmirrored. Regular
textures keep the mirror semantics.

decodeAudioData on an autoplay-suspended AudioContext never settles in
Firefox, parking the whole Asyncify-unwound C stack inside LoadSound.
Decoding now runs on a lazily created OfflineAudioContext at the main
context's sample rate, which is not gesture-gated; playback still goes
through the main context, unlocked by the existing gesture listeners.

The canvas smoke harness now rejects out-of-bounds drawImage source
rects and exercises the negative-height target idiom; the audio harness
shims OfflineAudioContext so the new decode path is covered.
2026-08-30 10:36:06 -03:00
waozi c04abf8f97 Add web app screen routing 2026-08-30 10:33:18 -03:00
waozi 824f34f2a1 Cache bust showcase banner assets 2026-08-30 04:33:34 -03:00
waozi 2a3cd198d5 Go runtime: Primary/OnPrimary/SurfaceVariant theme getters
k2g emits these for .kry screens; the palette's circle color is the
primary per the Material mapping, with its contrast color and a
background tone completing the trio.
2026-08-30 04:12:56 -03:00
waozi ae4e2dada1 Drop unused import 2026-08-30 04:00:43 -03:00
waozi 11bb0ba601 Tray test: expect path-style registration 2026-08-30 04:00:00 -03:00
waozi e9ec7ff715 Fix showcase project directory loading 2026-08-30 03:59:34 -03:00
waozi 1a6b473504 Tray: register with the object path (XFCE host requirement) 2026-08-30 03:59:18 -03:00
waozi ef9d490284 Tray: serve the SNI surface before registering with the watcher 2026-08-30 03:58:07 -03:00
waozi bbb525eafb DBus: fall back to the XDG_RUNTIME_DIR session bus socket 2026-08-30 03:56:55 -03:00
waozi c3104be333 Render context menus in overlay pass 2026-08-30 03:43:11 -03:00
waozi 9656947809 DBus auth: send the hex of the decimal uid string 2026-08-30 03:35:54 -03:00
waozi 73c1f8b68d Pure-Go DBus: session client, action notifications, SNI tray
A minimal D-Bus session-bus client (EXTERNAL auth, method calls,
signal subscriptions, serving incoming calls) plus the two desktop
integrations the Go runtime was missing, mirroring the C API:

- org.freedesktop.Notifications with one action button whose clicks
  arrive via PollNotificationAction (same key and slot semantics as
  the C backends).
- StatusNotifierItem tray icon with a nested com.canonical.dbusmenu
  menu, NameOwnerChanged re-registration for restarting panels, PNG
  pixmaps decoded to ARGB32, and PropertiesChanged broadcasts.

No cgo, no GTK/AppIndicator link deps. Everything is covered by
hermetic tests against an in-process fake bus, including wire-level
frame layout, notify→ActionInvoked→poll, tray registration, GetLayout
serving and menu-click dispatch.
2026-08-30 03:34:30 -03:00
waozi 9636bdddd7 Refactor compiler text helpers 2026-08-30 03:22:57 -03:00
waozi 2de90be774 Fall back to warp-based relative mouse mode when raw mode fails
raylib's SDL DisableCursor ignored the return of
SDL_SetRelativeMouseMode: when the driver refuses raw relative mode the
cursor is only hidden and still clamps at the screen edges, so captured
look control dies there. Detect the failure, retry through SDL's
warp-based relative emulation, and log which mode engaged so field logs
identify the path taken. EnableCursor resets the warp hint.
2026-08-30 03:05:01 -03:00
waozi 1e977180e3 Expand Kryon matrix parity coverage 2026-08-30 03:05:01 -03:00
waozi 68d9a7e578 Add reusable screen and form helpers 2026-08-30 03:05:01 -03:00
github-actions[bot] 54ee12ce93 Update CHANGELOG for v0.1.36 2026-08-30 03:23:53 +00:00
github-actions[bot] b2669614dc release: bump version to v0.1.36 2026-08-30 03:21:43 +00:00
waozi 0cfa58d963 Unify Kryon site playground entry 2026-08-30 00:14:51 -03:00
github-actions[bot] 1cfe3e5382 Update CHANGELOG for v0.1.35 2026-08-30 01:44:05 +00:00
waozi b63d538fb9 Remove README link badges 2026-08-29 22:35:05 -03:00
github-actions[bot] 1d66c5fbb0 release: bump version to v0.1.35 2026-08-30 01:34:34 +00:00
waozi ed624411a8 Refresh Kryon README header 2026-08-29 22:27:57 -03:00
waozi a7de80a93f Harden KRB asset section loading 2026-08-29 22:27:57 -03:00
waozi 77005f2e1d Use host arrow cursor for libdraw windows 2026-08-29 22:27:57 -03:00
waozi f9fc7d94be Add checked JSON allocation helpers 2026-08-29 22:27:57 -03:00
waozi ba050474bc Add libdraw key name lookup 2026-08-29 22:27:57 -03:00
github-actions[bot] b1f8335386 Update CHANGELOG for v0.1.34 2026-08-30 00:57:45 +00:00
github-actions[bot] 4c51d08c42 release: bump version to v0.1.34 2026-08-30 00:55:36 +00:00
waozi 8140255efc Serialize the cmark-gfm vendor rule with a grouped target
The rule building libcmark-gfm.a and libcmark-gfm-extensions.a was a
plain multi-target rule with one recipe, so a parallel fresh build ran
that recipe twice concurrently in the same build directory. The two
racing cmake configure steps corrupt each other, surfacing as a
configure_file "No such file or directory" error and a failed build.
Declare the two archives as a grouped target (&:) so the recipe runs
exactly once for both.
2026-08-29 21:48:43 -03:00
waozi 9e640c7165 Add page semantics and DOM route API 2026-08-29 21:48:43 -03:00
github-actions[bot] 25bb08da85 Update CHANGELOG for v0.1.33 2026-08-29 21:55:38 +00:00
github-actions[bot] 8c8449c9aa release: bump version to v0.1.33 2026-08-29 21:53:33 +00:00
waozi adf232a939 Skip rendering unchanged frames and reuse the present-path buffers
The X11 EndFrame allocated a full RGBA framebuffer and a request
buffer every frame (~8MB/frame churn) and re-rasterized identical
frames. Now the target image is reused across frames (reallocated
only on resize), the PutImage request buffer is grown on demand and
reused, and the op stream is compared against the last presented
frame — unchanged frames skip rasterization and upload entirely
(static content measures ~0.5% CPU at 30fps, down from a full
software-rasterized pass). Exposure and resize events force a
repaint so uncovered regions stay correct.
2026-08-29 18:46:21 -03:00
waozi 822145960a Add rlActiveTextureSlot to the curated rlgl tier
Custom shader pipelines that bind their own textures need to pin the
active texture unit before rlEnableTexture and pair the sampler uniform
to it; without a unit selector on the surface, apps depend on whatever
unit earlier rendering left active, which diverges across GL drivers
(black texels on some hardware). rlActiveTextureSlot selects the unit
and keeps rlgl's tracked state in sync for SetShaderValueTexture.
2026-08-29 18:44:11 -03:00
waozi b61c010e23 Build app sources and vendor deps before the linux arch compile
build-linux-arch only depended on the raylib rename header, so on a
fresh clone the final cc ran before .kry-generated sources existed and
before the vendored curl/liboqs builds produced their headers. The web
target already lists $(SRC); give the native arch build the same
prerequisites plus $(KRYON_NATIVE_DEPS).
2026-08-29 18:44:11 -03:00
github-actions[bot] 318cdb55ee Update CHANGELOG for v0.1.32 2026-08-29 21:43:35 +00:00
github-actions[bot] 25e89a474c release: bump version to v0.1.32 2026-08-29 21:41:29 +00:00
waozi 89df491199 Deliver full clicks from the X11 backend so Button widgets respond
consumeTap reads the tap/click queues that only QueueMouseButton
fills, but the X11 event pump delivered ButtonRelease as a bare
QueueMouseButtonUp — taps never queued, so every tap-driven widget
(Button, TabBar selection) was click-dead under X11 while raw
IsMouseButtonReleased checks kept working. Feed the release through
QueueMouseButton so the widget layer sees a complete click.
2026-08-29 18:34:36 -03:00
github-actions[bot] d161bf2c65 Update CHANGELOG for v0.1.31 2026-08-29 21:32:39 +00:00
github-actions[bot] 7905b391c3 release: bump version to v0.1.31 2026-08-29 21:30:26 +00:00
waozi ba20244444 Implement TabBar in the pure-Go runtime
The Go runtime's TabBar was a stub returning -1, so every Go host
driving the declarative shell (k2g-generated apps like dashboard) got
an empty strip where the tabs should be — stale pixels instead of a
widget. Render equal-width tabs as FrameOpButtons (theme-styled,
selected tab highlighted, hover tracked), fit labels with ellipsis,
select on tap, and return the clicked index. Also gate an ops dump
behind KRYON_OPS_DEBUG in the X11 EndFrame for future diagnosis.
2026-08-29 18:24:29 -03:00
github-actions[bot] 40afa1e46b Update CHANGELOG for v0.1.30 2026-08-29 21:14:28 +00:00
github-actions[bot] f10cafdee5 release: bump version to v0.1.30 2026-08-29 21:12:56 +00:00
waozi 9aedd743d0 Make cursor-locked SDL mouse behave like GLFW disabled-cursor mode
The SDL backend overwrote the mouse position with each motion event
xrel/yrel and zeroed previousPosition while the cursor is locked, so
GetMousePosition returned the last event relative motion instead of an
accumulating virtual position. Apps that difference GetMousePosition
themselves (the common raylib FPS look-control pattern written against
GLFW) got noise instead of camera motion. Accumulate relative motion
into an unclamped virtual position instead: GetMousePosition keeps
moving past window edges and the per-frame previousPosition snapshot
makes GetMouseDelta the sum of the frame motion events, matching GLFW.
2026-08-29 18:06:01 -03:00
github-actions[bot] 275af20599 Update CHANGELOG for v0.1.29 2026-08-29 20:48:32 +00:00
waozi 4a19e89b41 Fix the X11 window runtime dropping all compat input reads
windowRuntime implements MousePosition/MouseButton*/MouseWheelMove/
KeyPressed/CharPressed but not KeyDown, so it never satisfied
compatInputRuntime — every compat-layer input call (GetMousePosition,
IsMouseButtonReleased, IsMouseButtonDown, IsKeyPressed, GetCharPressed)
failed its type assertion and returned zero values. The widget runtime
kept receiving events, but apps reading input through the compat API saw
a dead mouse: no position, no clicks. Add the missing KeyDown forwarding
and a compile-time guard so windowRuntime can never silently fall off
the interface again.
2026-08-29 17:39:24 -03:00
waozi da4ca0f7b5 Keep rlgl wrappers when audio is compiled out
The wrapper pass marks raylib.h's trailing audio section and skips it when
KRYON_COMPAT_AUDIO=0, but the flag leaked into the curated rlgl
declarations processed after raylib.h, so apps building raylib without
audio silently lost every 3D-tier wrapper and failed to link. Reset the
flag at each input file boundary.
2026-08-29 17:33:49 -03:00
waozi a9379427a7 Resolve rlgl and raymath inputs next to raylib.h in the compat generator
App builds invoke the generator with an explicit raylib.h path from their
own working directory, so CWD-relative defaults for the rlgl and raymath
inputs broke downstream makefiles. Derive both from the raylib header
directory instead.
2026-08-29 17:29:37 -03:00
github-actions[bot] 6f2e882f74 release: bump version to v0.1.29 2026-08-29 20:28:44 +00:00
waozi d2647baf47 Add the 3D tier to the kryon surface
Kryon declared raylib's 3D symbols but had no way to run custom 3D
pipelines: the mesh/shader entry points live in rlgl, which the boundary
rules keep out of the surface, and there was no 3D math at all.

The compat generator now also tracks a curated rlgl tier (vertex
array/buffer upload, attributes, element draws, shader and texture binds,
uniforms, matrix state, cull/depth toggles, plus the RL_* constants they
take) extracted from the vendored rlgl.h: declarations join the surface
header, the raylib backend renames and forwards them, and the null
backend stubs them, exactly like the rest of the surface. rlgl itself
stays a raylib-backend implementation detail.

A new include/kry_math3d.generated.h tracks raymath verbatim in
static-inline header-only mode and is included by kryon.h after the
compat surface, so every backend gets identical Vector3/Matrix/Quaternion
math with nothing to link or stub.

Custom shaders on this tier must target GLSL 100 / OpenGL ES 2 because
the desktop raylib backend runs GLES2; documented in BACKENDS.md along
with the per-backend tier status. The raylib compatibility test covers
math3d for real and links the whole camera/mesh/shader/rlgl path; it
passes on the raylib backend and headless on the null backend.
2026-08-29 17:22:01 -03:00
waozi b7d627dd3a Let headless links resolve the instance window hooks
The single-instance front-end declared the backend window hooks as hard
externs, so linking any executable against a KRYON_BACKEND=null archive
failed on KryonRaylibBackend_InitWindow/CloseWindow/WindowShouldClose.
Declare them weak and guard the call sites, matching the weak raylib-only
extern pattern the screenshot front-end already uses. Windowed backends
define the symbols strongly, so their behavior is unchanged.
2026-08-29 17:22:01 -03:00
github-actions[bot] 5938e1ff4d Update CHANGELOG for v0.1.28 2026-08-29 19:24:14 +00:00
github-actions[bot] 5d1f8489c4 release: bump version to v0.1.28 2026-08-29 19:22:01 +00:00
waozi 95f81704a5 Add custom-header variants to kry_http 2026-08-29 16:15:29 -03:00
github-actions[bot] 18eca23084 Update CHANGELOG for v0.1.27 2026-08-29 17:18:57 +00:00
waozi cb28fda2be Document explicit C extern handling 2026-08-29 14:09:17 -03:00
github-actions[bot] d0d1e0c187 release: bump version to v0.1.27 2026-08-29 17:08:54 +00:00
waozi e0c7c2b56f Polish JavaScript lowering integration 2026-08-29 14:01:17 -03:00
waozi 8289a7bcdb Add derived theme color helpers 2026-08-29 13:57:57 -03:00
waozi 2f5fd2f075 Add JavaScript lowering pipeline 2026-08-29 13:56:11 -03:00
waozi 3508d5bac6 Handle unquoted web script cache busting 2026-08-29 13:47:27 -03:00
waozi cf2b8cc7b9 Avoid duplicate Linux directory rules 2026-08-29 13:38:29 -03:00
github-actions[bot] 104217115e Update CHANGELOG for v0.1.26 2026-08-29 16:26:58 +00:00
github-actions[bot] bf0fc128e9 release: bump version to v0.1.26 2026-08-29 16:24:32 +00:00
waozi 88840a9c6f Add DOM web backend smoke coverage 2026-08-29 13:17:43 -03:00
github-actions[bot] 91534d888e Update CHANGELOG for v0.1.25 2026-08-29 15:48:04 +00:00
github-actions[bot] 216a2c8b10 release: bump version to v0.1.25 2026-08-29 15:46:01 +00:00
waozi c8680bc1fc Install ripgrep in release workflow 2026-08-29 12:39:11 -03:00
github-actions[bot] e544b7c198 Update CHANGELOG for v0.1.24 2026-08-29 15:31:25 +00:00
waozi 6cd3089d96 Add Android window inset API 2026-08-29 12:22:20 -03:00
github-actions[bot] f5966b9195 release: bump version to v0.1.24 2026-08-29 15:21:04 +00:00
waozi 627fc78054 Install ripgrep in Linux CI 2026-08-29 12:14:11 -03:00
waozi d512e9c17d Degrade gracefully when instance lock is unavailable 2026-08-29 12:02:49 -03:00
waozi 11a133aa6f Select retained text fields on double click 2026-08-29 11:36:38 -03:00
waozi 37b5ec24be Add release and sanitizer check targets 2026-08-29 11:36:38 -03:00
waozi 28ca38c949 Track backend capabilities in preflight 2026-08-29 11:36:38 -03:00
waozi 3439f5aa9a Harden Kryon boundaries and preflight checks 2026-08-29 11:36:38 -03:00
waozi dbd4e46524 Fix Android surface resize cache 2026-08-29 11:36:38 -03:00
waozi cd5de120f8 Sync frame size for platform UI 2026-08-29 11:36:38 -03:00
github-actions[bot] d705fd8fe4 Update CHANGELOG for v0.1.23 2026-08-28 23:26:46 +00:00
github-actions[bot] 5912b5419d release: bump version to v0.1.23 2026-08-28 23:24:39 +00:00
waozi 65116c8feb Use detected Android UI scale 2026-08-28 20:17:16 -03:00
waozi 29530ec84c Scale default UI fonts 2026-08-28 20:12:32 -03:00
github-actions[bot] 028eb2491f Update CHANGELOG for v0.1.22 2026-08-28 22:12:43 +00:00
github-actions[bot] 154ebf83b7 release: bump version to v0.1.22 2026-08-28 22:09:43 +00:00
waozi c9e5601f77 Improve Canvas2D backend parity 2026-08-28 19:02:42 -03:00
waozi 302051d656 Add Android prelude activity 2026-08-28 19:02:42 -03:00
waozi 9f32703779 Fix Ksync crypto web warnings 2026-08-28 19:02:42 -03:00
waozi 1dbc3edfb6 Fix Android UI DPI scaling 2026-08-28 19:02:42 -03:00
github-actions[bot] 2150fecc5f Update CHANGELOG for v0.1.21 2026-08-28 02:49:13 +00:00
github-actions[bot] 3cccf9e01e release: bump version to v0.1.21 2026-08-28 02:47:33 +00:00
waozi c2cdbf14ac Treat unknown Unix update installs as source 2026-08-27 23:41:47 -03:00
waozi 31e37666f5 Detect BSD home builds as source installs 2026-08-27 23:34:00 -03:00
waozi 00e36f5b8c Make spec test sed portable 2026-08-27 23:27:15 -03:00
waozi 966af47a0a Fix conformance matrix build directory 2026-08-27 23:18:34 -03:00
waozi 14da8ca494 Add layout-key input and terminal UI primitives 2026-08-27 23:10:32 -03:00
waozi 6b77ea43dc Include stdbool in generated compat header 2026-08-27 22:53:47 -03:00
waozi 5d2151846b Add rich text editor control 2026-08-27 22:46:16 -03:00
waozi 584bf1594f Fix native linux raylib backend rename 2026-08-27 22:08:08 -03:00
waozi c56b013815 Add app framework helpers 2026-08-27 19:45:18 -03:00
waozi aeae3d3b20 Expose IsKeyDown in the Go bindings
The compat layer already exposed press/release queries for mouse buttons
but only per-frame presses for keys, so apps checking held modifiers
(Ctrl+X shortcuts) saw constant false. Route it through the runtime's
existing keyDown state.
2026-08-26 16:57:33 -03:00
waozi 22c97e5cc0 Anchor the Go theme enums at their own const blocks
The ThemeId, ThemeStyle, ThemeSource, ThemeMode and PictureFit enums
shared one const block with the flag/key/mouse constants, so every iota
inherited the offset of the specs above it: ThemeSky evaluated to 35,
SideTop to 22, ButtonStylePrimary to 26. The catalog arrays happened to
be keyed by the same inflated constants, so palettes resolved by
accident, but the ThemeSettings picker cycled through dozens of empty
palette slots and the ids matched neither the C THEME_* enum nor the
THEME_* aliases. Give each enum its own block so ids are canonical.
2026-08-26 16:26:58 -03:00
waozi 4c4cd15ef8 Note the Go runtime theme parity in the changelog 2026-08-26 16:22:29 -03:00
waozi 0ac3bc4bcf Assert theme catalog relations instead of absolute iota ids 2026-08-26 16:22:18 -03:00
waozi df041dfe27 Focus Kryon site on runtime 2026-08-26 16:21:10 -03:00
waozi b718ad6d7c Keep theme catalog count assertion relative to Sweet 2026-08-26 16:18:24 -03:00
waozi 3a26b6cbd2 Expose Plan9, Xfce and Sweet themes in the Go runtime
The C core gained THEME_PLAN9, THEME_XFCE and THEME_SWEET but the Go
bindings stopped at Cobalt and clamped everything else to Mono. Add the
three ids and catalog palettes (colors mirrored from theme_meta.c), keep
the previously dropped circle/accent catalog bytes, expose the Material
color roles via GetUIMaterialScheme (mirroring ui_material_scheme from
ui_style.c), and pair styles with palettes through
DefaultThemeForThemeStyle. k2g learns the new constants for .kry code.
2026-08-26 16:17:25 -03:00
waozi 73ae09a559 Hide text input when opening dropdowns 2026-08-26 16:15:39 -03:00
waozi 25d892d915 Fix modal release handling 2026-08-26 16:07:01 -03:00
waozi 9135138da8 Allow scroll viewport visual bleed 2026-08-26 15:58:08 -03:00
waozi 944f951941 Match Sweet theme colors 2026-08-26 15:44:28 -03:00
waozi 3eae5cd313 Add Sweet Material theme palette 2026-08-26 15:37:52 -03:00
waozi 0a81a88d32 Add Android secure store helper 2026-08-26 15:29:03 -03:00
waozi 6a1d70615b Fix termi partial frame writes 2026-08-26 05:15:57 -03:00
waozi 695e41f58a Blend translucent termi cell backgrounds 2026-08-26 04:59:59 -03:00
waozi b72505f5fa Render thick termi lines as cells 2026-08-26 04:38:44 -03:00
waozi eb6b3a5613 Keep termi sixel fallback visible 2026-08-26 04:21:28 -03:00
waozi e462d24b30 Rename terminal showcase to ktrem 2026-08-26 04:00:38 -03:00
waozi b9a79ab2ee Harden termi texture and process defaults 2026-08-26 03:47:17 -03:00
waozi 1a2bcd9730 Reset termi frame clipping 2026-08-26 03:37:48 -03:00
waozi 5a5570822a Remove unused termi env helper 2026-08-26 03:31:14 -03:00
waozi 63fde43f5b Respect terminal viewport in termi backend 2026-08-26 03:28:47 -03:00
waozi df5df97927 Stabilize termi animated image frames 2026-08-26 03:20:09 -03:00
waozi 68e2bc8c2f Batch termi frame output 2026-08-26 03:08:14 -03:00
waozi 5de5e37854 Render termi circles as cell arcs 2026-08-26 02:58:44 -03:00
waozi 49f2387320 Add circle click handling primitive 2026-08-26 02:53:23 -03:00
waozi d62ea8b996 Drain termi mouse events per frame 2026-08-26 00:20:29 -03:00
waozi aebb5d3a75 Add live website examples gallery 2026-08-26 00:17:02 -03:00
waozi ba0f195e7c Default termi sixel to capable terminals 2026-08-26 00:03:56 -03:00
waozi 8c7eae846e Reduce termi frame output 2026-08-25 23:58:44 -03:00
waozi 33188888fb Clarify termi button states 2026-08-25 23:41:25 -03:00
waozi 37864dc67a Cache unchanged termi sixel draws 2026-08-25 23:37:29 -03:00
waozi a4b3fe7e26 Fix termi mouse click delivery 2026-08-25 23:27:41 -03:00
waozi 868aa69d2b Render termi textures with sixel 2026-08-25 23:14:59 -03:00
waozi 81c367528b Add termi terminal backend 2026-08-25 23:01:10 -03:00
waozi feddb86e7b Revert "Add TUI backend"
This reverts commit 219bc6ef5e.
2026-08-25 22:42:17 -03:00
waozi 4a918ba9e1 Revert "Avoid TUI OpenURL ownership conflict"
This reverts commit b792ad3a43.
2026-08-25 22:42:17 -03:00
waozi a293ea2c56 Revert "Make TUI backend terminal-safe"
This reverts commit 5dfc3944ae.
2026-08-25 22:42:17 -03:00
waozi 2110cd69c2 Revert "Scale TUI backend framebuffer"
This reverts commit 647a7cb000.
2026-08-25 22:42:17 -03:00
waozi 647a7cb000 Scale TUI backend framebuffer 2026-08-25 22:37:23 -03:00
waozi 5dfc3944ae Make TUI backend terminal-safe 2026-08-25 22:32:38 -03:00
waozi b792ad3a43 Avoid TUI OpenURL ownership conflict 2026-08-25 22:18:53 -03:00
waozi 219bc6ef5e Add TUI backend 2026-08-25 22:16:51 -03:00
waozi 63d710ff14 Avoid compound literal in icon loader 2026-08-25 18:22:17 -03:00
waozi 3855581d84 Guard Plan 9 math compatibility macros 2026-08-25 18:21:10 -03:00
waozi ce3b6a3a19 Use native Plan 9 default cursor 2026-08-25 18:18:04 -03:00
waozi a7cd265fbe Decode embedded icons as RGBA 2026-08-25 18:11:14 -03:00
waozi 70efe968d2 Use raylib scissor for UI clips 2026-08-25 17:40:25 -03:00
waozi a7388e5acd Preserve BottomNav icon colors 2026-08-25 16:28:40 -03:00
waozi 95c409a426 Add generated progress parity coverage 2026-08-25 16:08:27 -03:00
waozi 136fc2e088 Prepare monochrome UI icons as masks 2026-08-25 16:02:40 -03:00
waozi c85b8053d5 Restore Material bottom nav icon colors 2026-08-25 15:59:10 -03:00
waozi fb9b83ea3c Add generated list box parity coverage 2026-08-25 15:56:24 -03:00
waozi 565a01f1a1 Normalize UI icon textures to RGBA 2026-08-25 15:54:53 -03:00
waozi c819754565 Add generated table parity coverage 2026-08-25 15:45:28 -03:00
waozi a246a5cf0e Preserve bottom nav icon colors 2026-08-25 15:44:27 -03:00
waozi 6e8e8f53c4 Remove native Plan 9 terminal stubs 2026-08-25 15:32:57 -03:00
waozi 28ac59866e Restore Material bottom nav icon tint 2026-08-25 15:26:08 -03:00
waozi 752294700b Add generated controls parity coverage 2026-08-25 15:22:07 -03:00
waozi 41ca336741 Stub legacy terminal helpers on native Plan 9 2026-08-25 15:21:55 -03:00
waozi 0fba52cd16 Fix native Plan 9 terminal pane color resolution 2026-08-25 15:17:09 -03:00
waozi b203378ead Use URI stubs in native Plan 9 archive 2026-08-25 15:15:46 -03:00
waozi 0c759fb3e5 Build terminal pane helpers for native Plan 9 2026-08-25 15:14:19 -03:00
waozi e332f5eb2b Avoid Plan 9 terminal header collisions 2026-08-25 15:07:29 -03:00
waozi f8133309ea Add Xfce theme 2026-08-25 14:57:08 -03:00
waozi 4adfdced80 Add Plan 9 sys types shim 2026-08-25 14:57:01 -03:00
waozi 06dc6a24c7 Add visual comparison matrix 2026-08-25 14:56:55 -03:00
waozi b5e831808f Fix libdraw text and color capture handling 2026-08-25 14:45:02 -03:00
waozi c4d5262ca8 Add web Canvas source capture matrix gate 2026-08-25 14:44:27 -03:00
waozi 8f38c09b2c Improve native Plan 9 libdraw desktop rendering 2026-08-25 14:27:36 -03:00
waozi d1be565333 Track generated C renderer matrix gaps 2026-08-25 12:24:09 -03:00
waozi 08e4f15d32 Rebuild objects when switching backends 2026-08-25 12:13:24 -03:00
waozi a32ec31281 Avoid raylib flush dependency on native Plan 9 2026-08-25 12:06:40 -03:00
waozi 2874d46752 Preserve button paint order in UI tree 2026-08-25 12:00:13 -03:00
waozi b844ac0caa Capture raylib generated C windows 2026-08-25 11:39:41 -03:00
waozi 12724da33d Add raylib generated C matrix gate 2026-08-25 11:35:56 -03:00
waozi 0f2766f986 Expose renderer source matrix on website 2026-08-25 11:31:54 -03:00
waozi 0125a3897b Preserve libdraw text hierarchy 2026-08-25 11:31:13 -03:00
waozi 63139449c6 Use Rect as canonical shape widget
Update matrix examples, generated website data, and feature docs to use Rect rather than RectangleShape.

Keep RectangleShape as a compatibility alias and map Rect to it only for libdraw builds to avoid the plan9port Rect symbol collision.
2026-08-25 11:17:05 -03:00
waozi 627dbcc76f Normalize matrix sources to current UI APIs
Convert Inbe and matrix fixtures to current prop structs, RectangleShape, and UIScrollArea/BeginUIScrollContainer APIs.

Teach KRB lowering the current scroll-container pattern, fix array dropdown option text, and align scroll rendering with the current container behavior.

Update conformance matrix docs/data and recovered libdraw generated-C coverage.
2026-08-25 11:06:00 -03:00
waozi 2db07d8c03 Clip libdraw native text draws 2026-08-25 10:45:44 -03:00
waozi 6ea8f45b23 Isolate hosted app keyboard input 2026-08-25 10:41:04 -03:00
waozi d78fee9e53 Add libdraw generated-C matrix capture
Add a generated-C capture harness and libdraw source matrix gate that lowers each checked-in .kry source, links it through the generated app host, and captures a libdraw frame where the generated C is currently compile-ready.

Track current generated-C lowering gaps explicitly in the website matrix so libdraw coverage reports captured and blocked sources truthfully.
2026-08-25 10:36:47 -03:00
waozi 9f9e51d7a3 Let libdraw follow system themes on Linux 2026-08-25 10:22:55 -03:00
waozi 94304f7b5a Add KRB web source matrix gate
Build the KRB web wasm host in oneshot mode and byte-compare every matrix source against native kry_sw output.

Expose the KRB web per-source gate in the renderer matrix and conformance checks.
2026-08-25 10:19:43 -03:00
waozi 45c66a2efc Extend AppHost lifecycle callbacks 2026-08-25 10:13:17 -03:00
waozi 57716a8b0a Gate widget coverage in conformance matrix
Add a checked-in .kry widget catalog source and fail the matrix when a declared widget has no .kry coverage.

Expose per-widget source coverage and semantic evidence in the website matrix.
2026-08-25 10:09:09 -03:00
waozi c1a8a09c99 Add TableView drag range selection 2026-08-25 10:04:25 -03:00
waozi d4eb9fa19f Avoid libdraw Rect symbol collision 2026-08-25 10:04:15 -03:00
waozi a993e36341 Add runtime and downstream matrix gates
Gate generated Go/C parity and Kapsule downstream tests from the conformance matrix.

Fix retained-tree TextField construction and clean generated C names exposed by the expanded checks.
2026-08-25 10:02:15 -03:00
waozi 203425ff3b Add libdraw compatibility hooks 2026-08-25 09:55:25 -03:00
waozi f2ed281643 Merge remote-tracking branch 'origin/master' 2026-08-25 09:45:27 -03:00
waozi 3e2d01ffb2 Add Go toolbar menu and workbook icons 2026-08-25 09:44:49 -03:00
waozi 406844c9f1 Add Go toolbar menu and workbook icons 2026-08-25 09:43:39 -03:00
waozi fb6d7055a8 Add renderer smoke matrix gate 2026-08-25 09:41:56 -03:00
waozi 3057aea4a9 Add KRB visual conformance checks 2026-08-25 09:38:02 -03:00
waozi 6312fb39f6 Test bottom nav icon color preservation 2026-08-25 09:31:56 -03:00
waozi 6d530f593e Add generated Kry conformance matrix 2026-08-25 09:26:25 -03:00
waozi 2f73accdb8 Resolve Kry host compiler outside Android toolchain 2026-08-24 16:38:57 -03:00
waozi dc93f6a8b3 Use host compiler for Kry generation tools 2026-08-24 16:37:38 -03:00
waozi 229b6f7f3a Add CMake helper for Kry source generation 2026-08-24 16:13:18 -03:00
waozi 04fa4b5108 Remove text input sync diagnostics 2026-08-24 15:25:51 -03:00
waozi 9cffcb00a8 Add eye visibility icons 2026-08-24 15:19:42 -03:00
waozi ca1ffa8abd Coalesce platform text input state per frame 2026-08-24 14:39:24 -03:00
waozi 81a6015163 Keep platform text input active while focused 2026-08-24 14:35:08 -03:00
waozi 7020657590 Honor text input show pulses without active state 2026-08-24 14:32:29 -03:00
waozi a2b3a75647 Log text input platform sync state 2026-08-24 14:29:53 -03:00
waozi 95a24865e4 Request text input platform show on field taps 2026-08-24 14:27:11 -03:00
waozi 1a049ca056 Sync text input platform state at frame end 2026-08-24 14:23:52 -03:00
waozi e9b92ae3f6 Link only showcase author names 2026-08-24 14:22:56 -03:00
waozi 54637b8ab4 Remove showcase ranking note 2026-08-24 14:21:41 -03:00
waozi c8e1baf1a9 Decode X11 spreadsheet navigation keys 2026-08-24 14:20:53 -03:00
waozi 3bb0d89e52 Show showcase authors on site 2026-08-24 14:19:34 -03:00
waozi ee58fc4f48 Decode X11 escape key 2026-08-24 14:17:02 -03:00
waozi 135b8f0106 Test platform text input reactivation 2026-08-24 13:54:51 -03:00
waozi 22a93f2d57 Reset platform text input when deactivated 2026-08-24 13:49:52 -03:00
waozi 0ee2d2798a Support horizontal text field panning 2026-08-24 13:29:45 -03:00
waozi 73c6395541 Normalize fingerprint icon color 2026-08-24 13:20:49 -03:00
waozi 7dcc41fd53 Use themed text input colors without outer focus box 2026-08-24 13:11:22 -03:00
waozi adfaea3480 Keep fallback text field focus per input 2026-08-24 11:04:51 -03:00
waozi cbfea190e5 Add no-cgo mouse drag state 2026-08-24 11:02:10 -03:00
waozi 67631618b0 Render text fields in immediate UI 2026-08-24 10:42:35 -03:00
waozi b17c75d0e6 Improve material text field contrast 2026-08-24 10:40:21 -03:00
waozi 85bc25962b Outline material text fields 2026-08-24 10:38:04 -03:00
waozi 73518771d8 Allow optional text field focus state 2026-08-24 10:35:10 -03:00
waozi ed59e637b9 Fix modal capture and bottom nav icon colors 2026-08-24 10:24:51 -03:00
waozi 105d612797 Use raylib render batch hook for screenshots 2026-08-24 09:31:26 -03:00
waozi c2de409249 k2g pass char buffer args to externs 2026-08-24 09:27:24 -03:00
waozi f50a1d3ba7 k2g fix local helper calls 2026-08-24 09:17:17 -03:00
waozi a87158ba3c k2g resolve cross-file helper calls 2026-08-24 09:00:07 -03:00
waozi cc9cdfe05e k2g support direct Go extern calls 2026-08-24 08:55:33 -03:00
waozi 755cc36a71 Keep Material neutral tones unsaturated 2026-08-23 23:31:52 -03:00
waozi 53f9f427e4 Update generated icon assets 2026-08-23 23:17:20 -03:00
waozi b123d6adbc Revalidate site deploys 2026-08-23 23:10:55 -03:00
waozi 75a8f5877d Expose theme settings in Go runtime 2026-08-23 23:09:03 -03:00
waozi 91814185e5 Lower theme settings for Go runtime 2026-08-23 23:06:56 -03:00
waozi 439d539640 Clean #ui docs site snippets 2026-08-23 23:05:45 -03:00
waozi 1dee381210 Use generated showcase data on homepage 2026-08-23 23:01:27 -03:00
waozi 805ba9c0dd Add clean pane tab wrappers 2026-08-23 22:58:00 -03:00
waozi 32469990a0 Adopt #ui hierarchy syntax 2026-08-23 22:47:03 -03:00
waozi 5523ce128f Update k2 syntax tests for retained UI apps 2026-08-23 22:44:51 -03:00
waozi cffcc3df49 Fix canvas backend smoke source filters 2026-08-23 22:44:45 -03:00
waozi 849b918379 Track retained UI entry functions in Kir 2026-08-23 22:42:32 -03:00
waozi cd02aaf433 Fix k2g generated app entrypoint 2026-08-23 22:41:42 -03:00
waozi a39943f0c0 Use top-origin canvas font metrics 2026-08-23 22:36:27 -03:00
waozi 14761577f5 Generate showcase ranking data 2026-08-23 22:35:27 -03:00
waozi e0b7beac34 Add table clipboard shortcuts 2026-08-23 22:32:17 -03:00
waozi 9103c360bb Fix Android clipped UI after rotation 2026-08-23 22:28:25 -03:00
waozi 32f355a620 Fix canvas guide paragraph clipping 2026-08-23 22:26:11 -03:00
waozi 9bb7ee655a Add Android surface resize sync 2026-08-23 22:20:20 -03:00
waozi a8c1b5eded Restore site icon artifact 2026-08-23 22:17:21 -03:00
waozi d7c7e1bccb Update showcase stars and banners 2026-08-23 22:14:59 -03:00
waozi 99c0f55c6a Support fixed buffers in k2g extern calls 2026-08-23 22:12:23 -03:00
waozi 72e80cd871 Let native Plan 9 follow the system theme 2026-08-23 22:07:36 -03:00
waozi 2d6a497a62 Exclude Plan 9 platform sources from native builds 2026-08-23 22:05:54 -03:00
waozi a5f52a69d7 Make icons tree the shared source root 2026-08-23 17:57:09 -03:00
waozi 6150d13285 Complete native Plan 9 audio streams 2026-08-23 17:56:45 -03:00
waozi e276c088ea Implement native Plan 9 audio mixing 2026-08-23 17:28:21 -03:00
waozi d1e48e2941 Fix native Plan 9 libdraw font scaling
The lucida unicode.N.font buckets render at roughly 2.5x their label (unicode.16.font is 40px tall), so selecting a bucket by filename label drew every native font far larger than the requested size while the UI kept laying out at the requested size. Probe each candidate font once, cache its real Font->height, and serve the bucket whose rendered height is closest to the request, preferring the smaller bucket on ties so text never outgrows its layout box. Also record raster tiers at the size the rasterizer actually produced so nearby plan9 bucket requests share one tier; TTF backends are unchanged because their base size already equals the requested size.
2026-08-23 17:08:14 -03:00
waozi 33c187d4dc Improve native Plan 9 libdraw backend 2026-08-23 15:53:30 -03:00
waozi 02db87e315 Remove the unused Clay layout dependency 2026-08-23 13:41:49 -03:00
waozi 01b9f74180 Skip missing optional compat cleanup helper 2026-08-23 12:02:13 -03:00
waozi 631a84fff5 Add the install target to the plan9 mkfile 2026-08-23 09:42:07 -03:00
waozi d8be16c70d Keep image decoder stb symbols private 2026-08-23 09:41:57 -03:00
waozi 19f6bb77b8 Exclude Plan 9 sources from non-libdraw builds 2026-08-23 09:40:48 -03:00
waozi 23254feef2 Use vendored stb image include 2026-08-23 09:39:38 -03:00
waozi fc73c6239d Untrack native plan9 build objects 2026-08-23 09:37:53 -03:00
waozi 87eac19f06 Ignore plan9 cpp-stage intermediates 2026-08-23 09:37:32 -03:00
waozi 87acb691cf Make the plan9 ui globals inert on hosted builds 2026-08-23 09:37:18 -03:00
waozi fd30ba8c6b Harden the compound literal rewriter against conditional includes 2026-08-23 09:35:04 -03:00
waozi 8874f7138d Keep the zero constants outside preprocessor conditionals 2026-08-23 09:33:59 -03:00
waozi 65be9116c5 Fix the ui internals include depth for hosted builds 2026-08-23 09:31:56 -03:00
waozi bc8a81ec43 Include the ui internals by relative path for hosted builds 2026-08-23 01:43:56 -03:00
waozi 3ae5212b0d Drop line-splicing backslashes left by the comment stripper 2026-08-23 01:41:48 -03:00
waozi 2e4a38ae0f Port ApplyCurrentUITheme for the plan9 theme core 2026-08-23 01:29:07 -03:00
waozi 8486371b54 Search src/ui for internal headers in the plan9 build 2026-08-23 01:27:10 -03:00
waozi ef0c84b956 Add plan9 ui globals and empty asset table for the theme core 2026-08-23 01:25:24 -03:00
waozi 0ea1e60a14 Rename cpp-stage objects to the mkfile object names 2026-08-23 01:04:45 -03:00
waozi 1c0a070b2a Assemble UIStyleTokens field-wise for the plan9 compiler 2026-08-23 01:01:44 -03:00
waozi 7f249a0392 Scope the plan9 library to the theme core for now 2026-08-23 00:58:49 -03:00
waozi 151d4512d8 Drop the Box2D-dependent scene layer from the plan9 build 2026-08-23 00:54:14 -03:00
waozi a6beafa248 Guard the Box2D bridge header behind KRYON_WITH_PHYSICS 2026-08-23 00:51:16 -03:00
waozi d66bc332d3 Skip the fontconfig pipe helpers on plan9 2026-08-23 00:48:34 -03:00
waozi 44207d392c Avoid a scalar compound literal in the sha256 length padding 2026-08-23 00:46:35 -03:00
waozi e8fc57bc75 Drop the shim offsetof in favor of the libc definition 2026-08-23 00:44:45 -03:00
waozi c3fbd8ea1d Shim stdio.h so u.h precedes the pANS varargs declarations 2026-08-23 00:42:36 -03:00
waozi 7737e62955 Provide size_t from the plan9 libc shim 2026-08-23 00:38:53 -03:00
waozi d015bc1e41 Define NULL centrally in the plan9 libc shim 2026-08-23 00:32:44 -03:00
waozi 0685abb6e8 Replace short compound literals with zero constants for the plan9 compiler 2026-08-23 00:28:44 -03:00
waozi 418b1b656f Guard the plan9 assert shim against the libc definition 2026-08-23 00:23:23 -03:00
waozi e53bb198b1 Resolve plan9 shim PI and offsetof redefinitions 2026-08-23 00:22:10 -03:00
waozi 1536383af6 Fix comment apostrophe stripper to keep line-comment newlines 2026-08-23 00:19:43 -03:00
waozi 70f77c08da Enable C++ comments in the plan9 cpp pass 2026-08-23 00:17:42 -03:00
waozi 8d406fdf1a Use absolute include paths in the plan9 mkfile cpp rule 2026-08-23 00:15:15 -03:00
waozi 697128263a Preprocess the plan9 build through the system cpp and strip comment apostrophes 2026-08-23 00:13:59 -03:00
waozi c2116bf2b5 Guard plan9 shim re-includes of the include-once core headers 2026-08-23 00:01:59 -03:00
waozi 464be9f6a9 Keep stdarg include unconditional for the plan9 shim build 2026-08-22 23:59:26 -03:00
waozi d09971726a Fix plan9 mkfile source paths 2026-08-22 23:56:37 -03:00
waozi 39a0db007a Add native Plan 9 libdraw compatibility 2026-08-22 23:44:28 -03:00
waozi 5950a87437 Preserve libdraw UI icon colors 2026-08-22 23:06:14 -03:00
waozi 10db68d7b7 Match libdraw rounded radius semantics 2026-08-22 22:56:06 -03:00
waozi 4bf9a6f7c9 Fix libdraw picture masks and audio 2026-08-22 22:52:02 -03:00
waozi 66e8eaccfc Handle fractional libdraw texture sources 2026-08-22 22:46:30 -03:00
waozi 625056c0fc Complete libdraw image compatibility 2026-08-22 22:27:59 -03:00
waozi ac9116483a Expose toast draw helper 2026-08-22 20:38:42 -03:00
waozi 8044150214 Add libdraw backend and Plan9 theme 2026-08-22 20:36:37 -03:00
waozi 7841c8f65c Use Glenda icon for Plan 9 site card 2026-08-22 19:32:25 -03:00
waozi 13456dbe06 Make table escape clear selection 2026-08-22 19:27:29 -03:00
waozi a1567ca871 Keep system theme fallback selection neutral 2026-08-22 19:03:34 -03:00
waozi a1ac1c36cd Use GTK selected colors in system theme 2026-08-22 18:40:53 -03:00
waozi 17934234eb Add native table row and column selection 2026-08-22 18:28:02 -03:00
waozi 7347b9d6f7 Fix X11 keyboard mapping in Go runtime 2026-08-22 18:15:26 -03:00
waozi fc8811ed9d Add widget conformance for text input focus 2026-08-22 18:04:35 -03:00
waozi f59a6e7d3e Fix Go table double-click selection 2026-08-22 17:25:10 -03:00
waozi 1ade8ec566 Avoid startup X11 focus errors 2026-08-22 17:15:11 -03:00
waozi 454aa4ce27 Request X11 input focus for Go windows 2026-08-22 17:03:03 -03:00
waozi 9fe627c731 Fix native Go text field input 2026-08-22 16:40:40 -03:00
waozi 42668cc826 Bring Go theme handling to C parity 2026-08-22 16:33:37 -03:00
waozi 364d31ad5e Render registered fonts in Go runtime 2026-08-22 16:19:15 -03:00
waozi 48fde38934 Follow system theme in Go tables 2026-08-22 16:11:35 -03:00
waozi 743c1f4f4a Cover portfolio symbols in Go renderer 2026-08-22 15:50:10 -03:00
waozi eda37b3f37 Write screenshots from Go runtime 2026-08-22 15:48:42 -03:00
waozi 7ae570cd4c Add native table cell support to Go runtime 2026-08-22 15:43:51 -03:00
waozi eb96628e4c Complete Go Kryon window compatibility wrappers 2026-08-22 01:59:54 -03:00
waozi 2e82f703a1 Add Go Kryon legacy UI compatibility 2026-08-22 01:59:02 -03:00
waozi b7caa2834b Fix Go X11 setup parsing 2026-08-22 01:53:34 -03:00
waozi eb381d159f Log Go X11 window ids in debug mode 2026-08-22 01:51:18 -03:00
waozi 06e2f70c2d Sync mapped Go X11 windows 2026-08-22 01:48:57 -03:00
waozi a0b8fd3543 Report native Go window fallback errors 2026-08-22 01:46:56 -03:00
waozi 78aede86f8 Support Xauthority in Go X11 window runtime 2026-08-22 01:46:01 -03:00
waozi 62fc9d2d74 Merge remote-tracking branch 'origin/master' 2026-08-22 01:44:53 -03:00
waozi 81ec4efe45 Install FreeBSD CI test tools 2026-08-22 01:42:58 -03:00
waozi 35ac51b3fb Install FreeBSD CI test tools 2026-08-22 01:42:38 -03:00
waozi dd10bf5abd Add native Go X11 window runtime 2026-08-22 01:41:13 -03:00
waozi 62a3bf7f2e Make site navigation page-based 2026-08-22 01:36:34 -03:00
waozi 5219547919 Elide retained UI lifecycle from k2g output 2026-08-22 01:36:14 -03:00
waozi ea52f5fcd9 Rename retained tree keys 2026-08-22 01:28:22 -03:00
waozi 2e8764d30c Rename retained tree node IDs 2026-08-22 01:22:09 -03:00
waozi de2c5b03db Rename navigation and profile API 2026-08-22 01:17:20 -03:00
waozi 5d3a7430ca Add Kryon app showcase 2026-08-22 01:12:37 -03:00
waozi db8a395c42 Rename menu and accelerator API 2026-08-22 01:10:49 -03:00
waozi 79b70a6746 Rename geometry and canvas API 2026-08-22 01:03:18 -03:00
waozi 1664f84bc4 Rename syntax mode API 2026-08-21 23:52:03 -03:00
waozi d2414696bf Rename modal action API 2026-08-21 23:44:31 -03:00
waozi 5d5400191e Rename paragraph spec API 2026-08-21 23:39:42 -03:00
waozi c9e8b28bcc Rename text size API 2026-08-21 23:34:06 -03:00
waozi bf88336b67 Rename button style API 2026-08-21 23:26:48 -03:00
waozi 770bbede67 Rename public button spec API 2026-08-21 23:21:34 -03:00
waozi 9fe94ded24 Rename internal button render path 2026-08-21 23:16:23 -03:00
waozi 75f413ddbd Rename internal text input render path 2026-08-21 23:10:25 -03:00
waozi 65fb87ff27 Check generated feature matrix docs 2026-08-21 23:05:42 -03:00
waozi ba5f65e2d6 Rename public text helper APIs 2026-08-21 23:00:26 -03:00
waozi 6166895cdf Remove legacy KRB widget aliases 2026-08-21 22:54:43 -03:00
waozi eeec8f7b53 Rename public text input APIs 2026-08-21 22:50:43 -03:00
waozi 88e7249cf1 Rename text input platform callback API 2026-08-21 22:46:00 -03:00
waozi c677f75fc7 Rename public text layout API 2026-08-21 22:42:53 -03:00
waozi de8e15f685 Hide retained tree draw internals 2026-08-21 22:39:03 -03:00
waozi 565eee4dcd Hide text draw internals from public header 2026-08-21 22:33:57 -03:00
waozi 435f7dccbd Hide composite DrawUI APIs from public headers 2026-08-21 22:29:23 -03:00
waozi db263890ce Hide legacy control draw APIs from public header 2026-08-21 22:22:31 -03:00
waozi bbfd0af7a5 Rename public text input queue API 2026-08-21 22:14:54 -03:00
waozi 71c9d4456d Assert generated long text runtime stability 2026-08-21 22:11:17 -03:00
waozi 4e6fdbf9c7 Clean legacy widget names from API docs 2026-08-21 22:07:44 -03:00
waozi ac94bed13a Remove legacy Go cgo bridge 2026-08-21 22:04:52 -03:00
waozi b0b31c08bd Remove legacy generated C surface names 2026-08-21 22:01:26 -03:00
waozi 03306c9fa0 Document clean runtime parity surfaces 2026-08-21 21:54:53 -03:00
waozi 0303ef1a56 Remove legacy frame aliases from generated path 2026-08-21 21:49:31 -03:00
waozi 652d31ded7 Remove k2g runtime override 2026-08-21 21:42:15 -03:00
waozi c4b7d05429 Document qualified generated Go runtime 2026-08-21 21:36:20 -03:00
waozi 9c5c167931 Qualify generated Go runtime calls 2026-08-21 21:31:05 -03:00
waozi 1f4421c9b3 Add generated long text parity 2026-08-21 21:21:17 -03:00
waozi a9c5227e7c Stress native host text input 2026-08-21 21:15:12 -03:00
waozi 4f66f32b6d Add native Go host core 2026-08-21 21:08:37 -03:00
waozi f71f1a1cf0 Add fingerprint UI icon 2026-08-21 21:07:58 -03:00
waozi fec5041fc7 Use OpenURI for UI links 2026-08-21 21:06:39 -03:00
waozi 2ce9d891f0 Render generated Go parity frames 2026-08-21 21:03:55 -03:00
waozi f086c00681 Add native Go frame renderer 2026-08-21 21:00:15 -03:00
waozi 5237b1416d Block kryc from public surface 2026-08-21 20:54:27 -03:00
waozi cd0dcc6db0 Fix web URI opener macro 2026-08-21 20:52:26 -03:00
waozi f23330a705 Improve scroll focus and native window behavior 2026-08-21 20:50:16 -03:00
waozi 0f8debf129 Assert generated Go frame operations 2026-08-21 20:49:40 -03:00
waozi 09a15b9fad Record native Go frame operations 2026-08-21 20:43:56 -03:00
waozi 21c0fd00dc Avoid OpenURL duplicate on Android 2026-08-21 20:39:08 -03:00
waozi 9063fefdb9 Add scroll rect visibility helper 2026-08-21 20:37:24 -03:00
waozi 539b415d72 Prune direct Go field state per frame 2026-08-21 20:32:39 -03:00
waozi 9edae9022f Add direct native Go widget helpers 2026-08-21 20:29:05 -03:00
waozi 7b62cb0730 Add native Go generated layout semantics 2026-08-21 20:13:55 -03:00
waozi 4fd9baeb30 Expose native Go runtime input helpers 2026-08-21 20:09:06 -03:00
waozi 25d652bc22 Map native Go text size constants 2026-08-21 20:05:20 -03:00
waozi 0f584051a7 Align generated button click parity 2026-08-21 19:54:41 -03:00
waozi 0d7064fd0c Expand generated runtime parity coverage 2026-08-21 19:48:45 -03:00
waozi 35d5203d12 Disable single-instance lock on Android 2026-08-21 19:44:43 -03:00
waozi 30763d70d5 Fix URI launcher compatibility generation 2026-08-21 19:39:10 -03:00
waozi c7736fd606 Add generated runtime parity test 2026-08-21 19:24:43 -03:00
waozi ede1fb4902 Emit bare clean Go runtime calls 2026-08-21 19:12:34 -03:00
waozi c5bf9d907f Guard clean generated runtime surface 2026-08-21 19:01:59 -03:00
waozi b3d5fa21e2 Emit clean package Go runtime calls 2026-08-21 18:55:45 -03:00
waozi 4bd38d8d41 Add cross-platform URI opener 2026-08-21 18:55:17 -03:00
waozi dc28a4a624 Clean generated frame runtime surface 2026-08-21 18:45:46 -03:00
waozi 9d04f9aef2 Expand native Go text input semantics 2026-08-21 18:39:18 -03:00
waozi 108dbdd8f8 Enforce clean generated runtime output 2026-08-21 18:35:29 -03:00
waozi 7abe4c97ed Add native Go k2g runtime 2026-08-21 18:26:49 -03:00
waozi ba439bb0c6 Expose toast drawing API 2026-08-21 17:48:01 -03:00
waozi b85b33c582 Keep read-only text out of edit mode 2026-08-21 17:09:44 -03:00
waozi 557da45681 Fix Go text field state handling 2026-08-21 16:54:49 -03:00
waozi db655e2029 Add read-only selectable text controls 2026-08-21 16:53:54 -03:00
waozi 6974bb4085 Fix X11 input ungrab status check 2026-08-21 16:01:11 -03:00
waozi eda96fe6a6 Clean picture fit API names 2026-08-21 15:54:18 -03:00
waozi 1ff7e5e53c Rename overlay hook to clean API 2026-08-21 14:38:11 -03:00
waozi 5a7e068aa7 Update picture props lowering 2026-08-21 14:33:48 -03:00
waozi faa7f8a62a Clean picture API styling 2026-08-21 14:30:14 -03:00
waozi b2240b8322 Fix screenshot PNG row buffer size 2026-08-21 11:25:39 -03:00
waozi d350ccc7cd Add system locale detection 2026-08-21 11:25:10 -03:00
waozi 25b07fabfd Use neutral path in session title test fixture 2026-08-21 10:37:32 -03:00
waozi e317079b1c Add terminal input filtering for Kapsule 2026-08-21 09:53:51 -03:00
waozi 80fa33cd12 Simplify window unregister loop exit 2026-08-20 20:53:32 -03:00
waozi 2909dd33b0 Add terminal pane glyph grid rendering 2026-08-20 20:53:32 -03:00
waozi 3c226ea6a6 Add Windows tray menus and registry theme detection 2026-08-20 20:53:32 -03:00
waozi a4cf13b69d Let foreground widgets own the cursor over disabled background
Disabled controls had the highest cursor priority, so background
content marked disabled behind a foreground layer (e.g. a board that
disables its cards while a modal is open) banned the cursor for the
entire frame — the modal's own buttons and text fields could never
show a hand or ibeam. Rank disabled just above default and below every
interactive intent: widgets draw back-to-front, so whatever is drawn
later is on top and wins the cursor. Covered by cursor_intent_test.
2026-08-20 08:37:08 -03:00
waozi 8d4b3de80f Add terminal profile prompt helpers 2026-08-20 08:22:01 -03:00
waozi 97bdee6153 Add terminal search controller 2026-08-20 08:10:57 -03:00
waozi 60cbc5dc5c Add terminal clipboard actions 2026-08-20 08:06:29 -03:00
waozi 3ee08e2687 Add terminal scroll indicator helper 2026-08-20 07:58:20 -03:00
waozi 9049fef5d7 Add terminal row reflow helper 2026-08-20 07:54:26 -03:00
waozi cc28b393de Add terminal profile settings helpers 2026-08-20 07:49:18 -03:00
waozi 3bfba8173a Add terminal session record helpers 2026-08-20 07:43:11 -03:00
waozi 1b43e27ace Add terminal keyboard input runner 2026-08-20 07:38:00 -03:00
waozi d69f38cadd Add terminal DCS buffer helper 2026-08-20 07:31:48 -03:00
waozi 8646f62821 Add terminal sixel decoder 2026-08-20 07:27:09 -03:00
waozi e3eee82ca7 Add simple terminal clipboard runner 2026-08-20 07:20:47 -03:00
waozi 87fe78fd84 Remove legacy terminal prefix aliases 2026-08-20 07:16:11 -03:00
waozi 439d35e623 Add terminal mode state transitions 2026-08-20 07:10:06 -03:00
waozi deda6b8d1c Add terminal OSC command parser 2026-08-20 07:03:35 -03:00
waozi 5da17e0355 Add terminal OSC palette parsers 2026-08-20 06:59:38 -03:00
waozi 778531ef7e Add terminal clipboard controller builder 2026-08-20 06:55:15 -03:00
waozi c857ab8b00 Add terminal OSC color target helpers 2026-08-20 06:50:41 -03:00
waozi 8f00910f2b Add terminal function key mapper 2026-08-20 06:46:11 -03:00
waozi 1f8f297ce0 Add terminal clipboard scroll reset hook 2026-08-20 06:42:04 -03:00
waozi c72a7296f6 Add terminal search navigation helpers 2026-08-20 06:29:37 -03:00
waozi 1213ba4252 Add terminal clipboard command result helper 2026-08-20 06:26:18 -03:00
waozi 9cc8159428 Add terminal pane clipboard and cursor helpers 2026-08-20 06:12:07 -03:00
waozi 1d9a8c83aa Add terminal device status report formatter 2026-08-20 06:06:13 -03:00
waozi 7768b99956 Add terminal mode report formatter 2026-08-20 06:02:37 -03:00
waozi f8ace55d73 Add terminal XTGETTCAP response formatter 2026-08-20 05:58:17 -03:00
waozi c95ba3fdee Add terminal SGR status formatter 2026-08-20 05:53:47 -03:00
waozi ee2d06699a Add terminal cursor style report helper 2026-08-20 05:46:25 -03:00
waozi 89df2795c2 Add terminal pane clipboard command controller 2026-08-20 05:43:49 -03:00
waozi a9a27e6ee9 Add terminal pane view color resolver 2026-08-20 05:36:15 -03:00
waozi 2df536b418 Add terminal pane hyperlink sanitizers 2026-08-20 05:32:56 -03:00
waozi 3013cccb5e Add terminal pane title sanitizer 2026-08-20 05:27:12 -03:00
waozi 68fb25d112 Add terminal pane clipboard selection helpers 2026-08-20 05:16:57 -03:00
waozi e3177f8753 Add terminal pane theme color resolver 2026-08-20 05:12:16 -03:00
waozi f315707d25 Add terminal pane link theme token 2026-08-20 05:08:04 -03:00
waozi 7371e4b3d1 Add terminal clipboard action dispatcher 2026-08-20 04:43:35 -03:00
waozi 140dbc8a02 Add terminal pane color resolver 2026-08-20 04:30:50 -03:00
waozi e8bb9776fc Add terminal pane text escaping helpers 2026-08-20 04:24:15 -03:00
waozi 2d767684c7 Add terminal pane profile color helpers 2026-08-20 04:18:28 -03:00
waozi bf80d45b74 Add terminal pane clipboard and cursor helpers 2026-08-20 04:13:56 -03:00
waozi 36f57fc393 Add terminal pane session title helper 2026-08-20 04:07:11 -03:00
waozi 268e73f3c3 Add terminal pane OSC title helpers 2026-08-20 04:02:28 -03:00
waozi b08f874cac Add terminal pane OSC color helpers 2026-08-20 03:55:25 -03:00
waozi 21e94e2012 Add terminal pane profile color helpers 2026-08-20 03:48:43 -03:00
waozi 71e56bcf0d Add shared terminal mouse and paste helpers 2026-08-20 03:42:31 -03:00
waozi 9098d64528 Add shared terminal key encoding 2026-08-20 03:32:43 -03:00
waozi f3b69d1c38 Add terminal pane clipboard helpers 2026-08-20 03:23:20 -03:00
waozi ada49ab4cb Add shared terminal pane search 2026-08-20 03:16:50 -03:00
waozi 92542185b0 Add shared terminal pane selection clipboard 2026-08-20 03:11:38 -03:00
waozi fb0bc325e3 Add terminal pane content metrics 2026-08-20 02:57:37 -03:00
waozi 82f0cb2583 Add shared clipboard source helpers 2026-08-20 02:52:47 -03:00
waozi 9ab433aee9 Add shared clipboard paste writer 2026-08-20 02:40:12 -03:00
waozi 79b6d27f33 Add terminal pane status theme tokens 2026-08-20 02:12:35 -03:00
waozi 57b147cdcb Add OSC 52 clipboard helper 2026-08-20 01:26:34 -03:00
waozi 19cf5ef230 Add ABI version guard for prebuilt libraries
Apps link prebuilt static archives that are not refreshed when the
kryon sources move; every fix silently stayed out of the binary while
headers and Go bindings compiled fresh. KryonAbiVersion() bakes the
ABI number into libkryon.a, kryui compares it against the current
header value at InitWindow and panics with rebuild instructions on
mismatch.
2026-08-20 01:03:00 -03:00
waozi 140310c87a Resolve trace env flags once per process
The text draw loop read INBE_TEXT_TRACE per glyph and EndDrawing read
KRYON_SHOT_ARM/INBE_SHOT_ARM per frame; getenv scans the whole
environment block each call.
2026-08-20 01:03:00 -03:00
waozi f9a2300a49 Memoize material scheme per theme state
Every themed widget asks for the material scheme each frame (the Go
bindings fetch it per draw call). Recomputing tones and dark-mode
queries per call is wasted work; the scheme is pure given the current
theme colors and dark mode, so cache it on those inputs.
2026-08-20 01:03:00 -03:00
waozi 27f816a610 Rate-limit automatic system theme refresh
Per-frame theme queries re-ran the whole GTK CSS file probe on every
call whenever desktop detection failed — thousands of config reads per
frame, freezing any app whose theme CSS could not be parsed. The
automatic path now attempts detection at most once per 30s retry
window; RefreshSystemTheme() still forces a full re-detection. The
in-process GTK sampler is additionally restricted to startup, before
any app window exists: gtk_init_check realizes X windows and pumps the
GLib loop, which corrupts a live render context. Covered by the new
system_theme_test.
2026-08-20 01:02:49 -03:00
waozi 5e2b37f218 Cover clipboard target helpers 2026-08-20 00:57:55 -03:00
waozi ed2ffa6115 Add clipboard target helpers 2026-08-20 00:55:25 -03:00
waozi 658f0e7721 Move UI clipboard buffer into Kryon source 2026-08-20 00:34:26 -03:00
waozi 6db44471e3 Add terminal pane default palette 2026-08-20 00:24:27 -03:00
waozi 540f3bae2e Add UI clipboard buffer helpers 2026-08-20 00:19:44 -03:00
waozi 05d05f2f61 Expose context menu widget 2026-08-20 00:00:59 -03:00
waozi d476283c13 Add terminal pane selection text color 2026-08-19 23:52:43 -03:00
waozi 28b8fdba76 Add UI primary selection helpers 2026-08-19 23:46:10 -03:00
waozi fabca434a0 Expose vsync window flag in Go 2026-08-19 23:31:23 -03:00
waozi f3d13ac7a7 Enable Go textarea layout caching 2026-08-19 23:25:16 -03:00
waozi 476f874f5f Use system UI font by default 2026-08-19 23:16:06 -03:00
waozi 38d4b07477 Use system style on desktop 2026-08-19 23:08:12 -03:00
waozi 441b31a078 Remove Aero style 2026-08-19 22:14:53 -03:00
waozi e2562560c3 Stop textarea painting past viewport 2026-08-19 22:06:42 -03:00
waozi ff5bac9de7 Cache versioned textarea heights 2026-08-19 21:57:45 -03:00
waozi 656879f011 Make styled pictures respect UI style 2026-08-19 21:51:25 -03:00
waozi 06d8683bd4 Add styled cover picture drawing 2026-08-19 21:38:58 -03:00
waozi e497e42d75 Fix menu bar switching with open popup capture 2026-08-19 21:24:07 -03:00
waozi 63042cfd9f Fix runtime downloads and text decoding
Fix astral UTF-8 encoding in KRB text input and surrogate-pair decoding in ksync JSON string lookup.

Move runtime asset download workers onto owned synchronized state with explicit poll/free lifecycle and add coverage for file-backed downloads.

Avoid unconditional retained UI layout/paint invalidation on stable frames, preserve computed layout bounds, and include the staged Windows notification support.
2026-08-19 21:17:35 -03:00
waozi e66ad681d5 Fix menu close state after popup activation 2026-08-19 21:08:18 -03:00
waozi 4d806387d9 Support sticky UI windows on X11 2026-08-19 20:43:22 -03:00
waozi 5d8bdc307e Fix menu bar switching between open menus 2026-08-19 20:14:28 -03:00
waozi 2ddeeecbdd Allow apps to provide system theme palettes 2026-08-19 20:13:31 -03:00
waozi faa0715f69 Fix Material bottom nav icon contrast 2026-08-19 20:08:55 -03:00
waozi 4e27375161 Apply Canvas cursor to document targets 2026-08-19 20:07:27 -03:00
waozi 8c5ded5844 Fix material tab bar spacing 2026-08-19 18:48:24 -03:00
waozi 5da8134ad0 Consolidate Kry language documentation 2026-08-19 18:31:28 -03:00
waozi 668f4d16f1 Document Kry language and publish benchmarks 2026-08-19 18:21:07 -03:00
waozi 2726d54f72 Advance Kry compile-time checks and expression KIR 2026-08-19 18:12:26 -03:00
waozi 5f04875aea Fix Canvas guide rendering and cursor 2026-08-19 17:45:51 -03:00
waozi 2d641c1137 Draw menu bars as frame overlays 2026-08-19 17:41:19 -03:00
waozi 4b6d9da887 Add reusable app runtime helpers 2026-08-19 17:19:08 -03:00
waozi 22652499d5 Fix Android notification priority signature 2026-08-19 16:55:12 -03:00
waozi a585f1ced5 Implement Canvas WebAudio backend 2026-08-19 16:35:44 -03:00
waozi 594941f421 Add reusable terminal pane widget 2026-08-19 16:19:04 -03:00
waozi 397cd3749c Avoid duplicate badge measurement 2026-08-19 16:04:50 -03:00
waozi 27ce4cbb4a Add website backend and widget matrices 2026-08-19 16:03:56 -03:00
waozi 8f8a2736e6 Align installed desktop metadata names 2026-08-19 15:53:17 -03:00
waozi e0c588cd23 Add Linux desktop integration helpers 2026-08-19 15:47:56 -03:00
waozi 85779958ab Add themed Go surface widgets 2026-08-19 15:46:01 -03:00
waozi b8931be1ae ui_window: baseline the drag at the press position 2026-08-19 15:29:49 -03:00
waozi 7055557bf5 CI: gate on public-HTTPS submodule URLs
A guard job (plain checkout, canonical script) fails the run when any
.gitmodules URL is not https:// — SSH URLs work only for a developer
with the right key and break fresh clones, CI and release builders
instead. make test runs the same check locally.
2026-08-19 15:28:04 -03:00
waozi 94f35f0952 ui_window: follow the global pointer during drags, not motion events
The exact-following drag test showed every drag ending one step short:
SDL3-style pointer batching folds the motion immediately before a
button-up into the button event, so its relative delta never arrives as
a motion event. Diff the global pointer position each frame in the pump
instead - position-derived, immune to event batching - with the release
still delivered reliably through the capture.
2026-08-19 15:26:59 -03:00
waozi a91070ce86 ui_window: flush a released drag's final motion
Button-up clears drag_active in the event watch, so the frame pump
skipped the window and dropped whatever motion was still pending -
every drag ended short of the pointer by the last step. Keep pumping a
window until its pending motion is flushed.
2026-08-19 15:24:03 -03:00
waozi e05a298d4e ui_window: capture the mouse during drags and drop per-frame position reads
Dragging a small borderless overlay visibly trailed the pointer for two
reasons: motion events stopped arriving whenever the pointer outran the
window, and every pump did a synchronous SDL_GetWindowPosition round
trip before moving. Capture the mouse for the drag duration so motion
is delivered regardless of pointer position, read the window position
once at drag start, and move from the tracked coordinates.
2026-08-19 15:21:42 -03:00
waozi aed0aff31b ui_window: expose StealUICoreWindowClose for direct close polling
The bridged SDL_QUIT still has to survive the app's event loop; apps
that prefer determinism (or whose backend never latches pushed quit
events) can instead poll the recorded close request next to their tray
actions and run their own close flow.
2026-08-19 14:57:49 -03:00
waozi 06a32a6ee6 ui_window: bridge core-window close and drag on the SDL path
SDL2 delivers the main window's close request (X button, Alt+F4, WM
delete) as SDL_WINDOWEVENT_CLOSE; the raylib SDL backend only latches
SDL_QUIT, so the close button did nothing. The event watch records
close requests for windows that are not ours, and PumpUIWindows -
called by SetUIFrame once per frame, where calling into SDL is safe -
pushes the bridged SDL_QUIT.

Borderless secondary windows had no drag support on the SDL path at
all (IsUIWindowDragged was a stub): the watch now records press,
relative motion and release, and PumpUIWindows applies the window
move, mirroring the Xlib path. GetUIWindowPosition also stops
reporting a constant 0,0.
2026-08-19 14:51:35 -03:00
waozi 4ad9d1cbdb kry_update: arch-aware AppImage appcast key
AppImages are per-arch, so the download key is now appimage-amd64 /
appimage-arm64 (windows stays bare — the zip bundles every arch exe).
Publishers with a single arch can keep one artifact; multi-arch
publishers list one channel per arch and each machine resolves its
own. Tests and the Go binding updated; nothing has shipped under the
old key yet.
2026-08-19 14:15:24 -03:00
waozi 8b332ab17f kryui: Go bindings for kry_update_flow
StartUpdateFlow/Poll/State/Download/Apply/ExecPending wrap the C
lifecycle for the Go apps (gopass GUI first); ShowToast already covers
the notification side. Links the vendored curl like the rest of the
package's static stack. The binding test drives a file:// appcast
through available -> download -> ready -> apply, including the real
staging rename under a fake $APPIMAGE.
2026-08-19 14:10:40 -03:00
waozi c3f5e6eeef tray: resolve gtk_status_icon_is_embedded through gtk_dl
The activate guard added for XEMBED-handshake activations calls
gtk_status_icon_is_embedded, which was not part of the lazy-load
table - native links failed with an undefined reference.
2026-08-19 14:01:25 -03:00
waozi dd5f9fc356 kry_std: kry_update_flow — the embeddable self-update lifecycle 2026-08-19 14:01:25 -03:00
waozi 22c60ec6d7 tray: ignore XEMBED-handshake activations on the status icon
Some systray hosts emit a stray activate signal while docking the
status icon. Honoring it dispatched the startup activate action -
which toggles the window hidden, since the window is visible at
launch - leaving the app running with no window: nothing to click,
nothing to close. Ignore activates while the icon is unembedded and
for a short window after it becomes ready.
2026-08-19 13:56:22 -03:00
waozi af46dc6109 kry_std: self-update primitives — download, verify, apply
kry_http grows a streaming file sink (kry_http_download) with byte and
fraction progress, sized for artifacts instead of in-memory bodies.
kry_sha256 adds dependency-free FIPS 180-4 hashing (streaming + file +
hex compare). kry_update ties them together: appcast-channel downloads
staged under XDG_DATA_HOME/LOCALAPPDATA with sha256 verification (bad
files are removed), AppImage staging that copies next to the running
image and atomically renames over it (plus re-exec in apply), and a
Windows portable swap script spawned detached from %TEMP%. Tests cover
hash vectors, verified/failed downloads via file://, and AppImage
staging; the exec'ing apply path stays untested by design.
2026-08-19 13:37:20 -03:00
waozi 845f43931e kry_std: add kry_update desktop update-check module
Appcast fetch/parse over kry_http + kry_json, semver compare, and
desktop channel detection (AppImage/Snap/Flatpak env, /usr|/opt
package installs, Windows portable). Poll-based so a frame loop can
watch it; file:// appcasts keep tests offline. Also stub
kry_http_partial in the no-libcurl branch so nothing links unresolved.
2026-08-19 13:08:54 -03:00
waozi 4a865f45fd theme: default to the system theme source on every platform
GetDefaultPlatformThemeSource() no longer falls back to THEME_SOURCE_APP on Android; GetCurrentThemeColor() already falls back to the app palette when no system palette is readable, so SYSTEM is safe everywhere. Also expose SetThemeSource/SetThemeMode (plus ThemeSource/ThemeMode consts) in the go/kryui bindings and the Runtime parity interface.
2026-08-19 12:09:07 -03:00
waozi d6db5a7908 canvas: zero-init LoadFont's failure return
LoadFont returned an uninitialized Font when the file was missing
(clang -Wuninitialized, visible in downstream web builds); callers
check font.glyphs == NULL, so return the zeroed struct instead.
2026-08-18 22:36:33 -03:00
waozi 2fc1318a63 canvas: dedupe the JS glue (ctxNow/col/makeCanvas, rounded radius)
The ctx-resolution prologue, rgba string concat, and offscreen-canvas
allocation were repeated across the EM_JS wrappers; they now live as
helpers on the boot state. js_glyph_metrics keeps its own DOM-canvas
preference on purpose: glyph rasterization must see document.fonts.
The node call-sequence gate still records the identical 413-call trace.
2026-08-18 22:31:54 -03:00
waozi 7b6048a9df canvas: split the backend into per-concern sources
canvas_backend.c (1882 lines) becomes canvas_window/input/draw/texture/
text/os/audio.c plus canvas_internal.h, one file per banner section the
monolith had already grown. Pure code motion: the node call-sequence
gate records an identical 413-call trace before and after.

The canvas branches in Makefile, mk/common.mk, and examples/Makefile no
longer append the backend file on top of the src/ find sweep — that
would have compiled every canvas TU twice. docs: BACKENDS.md path and
empty-TU wording, FEATURE_MATRIX.md stale 'approximated' note.
2026-08-18 22:29:08 -03:00
waozi e0af9509c4 canvas: frame counter and last-op diagnostics in the JS state 2026-08-18 19:56:49 -03:00
waozi c56d3d7232 canvas: null-grade the rest of the audio surface 2026-08-18 19:42:02 -03:00
waozi 63edb0f561 canvas: SaveFileData/Text, ChangeDirectory, GetWorkingDirectory 2026-08-18 19:21:42 -03:00
waozi b15d70ee51 canvas: IsWindowFocused on the surface (dropdown hover uses it) 2026-08-18 18:51:35 -03:00
waozi b969d0f36b locale: detect the system default locale (GetDefaultLocaleCode)
Apps had no way to follow the system locale - inbe hard-defaulted to
English for every fresh profile. GetDefaultLocaleCode resolves
LANGUAGE/LC_ALL/LC_MESSAGES/LANG down to an available catalog
(pt_BR.UTF-8 -> pt) and returns "en" when nothing matches.
2026-08-18 18:47:28 -03:00
waozi 2c604531f3 theme picker: route label fallbacks through the locale catalog
The settings widget fell back to hardcoded English literals whenever an
app passed no label prop, bypassing GetLocaleText entirely - so the
whole theme section stayed English even in fully localized apps, and
the compiled-in theme_* defaults were dead. Props still win, then the
locale catalog (theme_mode_label, theme_light, theme_dark,
theme_follow_device, theme_system, theme_color_label,
theme_style_label, theme_style_system), then the English literal.
Covered by a key-resolution check in the ui_tk test.
2026-08-18 18:46:01 -03:00
waozi 79d4fed6d2 dropdown: wobbled and slow clicks must select, not just pixel-perfect taps
The press-to-release drag threshold armed on any movement past 8px,
even when the popup cannot scroll - so a touchpad click's natural
wobble flipped a click into a 'drag' and silently swallowed the
selection (the 'I press Dark and nothing happens' case on the theme
screen's fixed three-option mode popup).

Arm the drag state only when the list can actually scroll, and on
release still select when a drag never moved the list (wobble there
and back). Covered by two injected-input tests: the layout test now
runs wobbled clicks, slow hold-clicks and scroll-drags from a clean
slate per scenario, and a new theme-screen test drives the stacked
mode/palette/style dropdowns exactly like the settings screen,
including a wobbled Dark press through the two-phase settings API.
2026-08-18 18:35:42 -03:00
waozi 9e157e7b49 canvas: PauseSound and IsMusicStreamPlaying on the surface 2026-08-18 18:22:25 -03:00
waozi dae552ec17 krb-run: remove the Linux framebuffer presentation backend
The fb host (mmap of /dev/fb0 or a raw-file stand-in, xrgb8888/rgb565
dirty-rect conversion) served no user: raylib covers desktop
presentation, the Canvas2D backend covers native web, and TUI is the
remaining terminal story. Drop the --backend fb / --fb-device /
--fb-format surface; krb-run keeps the headless PNG/recording flow the
conformance tests drive.
2026-08-18 18:16:43 -03:00
waozi 6c6cc91c0f canvas: file-name utils and IsMusicValid on the surface 2026-08-18 18:12:17 -03:00
waozi eb9967ce29 theme: drop the dedicated Aero palette, keep the style palette-agnostic
The Aero widget style derives its glass tints from whichever palette is
active, so a 13th palette entry was redundant. Remove THEME_AERO (and
its ini mirrors, locale label and picker slot); the style now defaults
to Sky. Saved theme ids beyond the shrunken count normalize through the
existing out-of-range fallback.
2026-08-18 18:08:54 -03:00
waozi 94079c9f7d canvas: cover the audio-device, wave, and image surface apps drive
inbe's app code calls the audio device lifecycle, wave loading/format,
mixed-processor hooks, GenImageColor, SetShapesTexture, and
SetTraceLogCallback directly. Add null-grade implementations (and a
real GenImageColor fill) so full apps link on the canvas backend.
2026-08-18 18:01:13 -03:00
waozi 0adf507ab0 dropdown: dismiss popups on Escape and window focus loss
Open dropdown popups had no keyboard or focus dismissal - only the
mouse paths (option select, button toggle, outside click) closed them,
so any pointer-state weirdness could leave a popup feeling stuck.

Escape now closes every open popup, and losing the window focus closes
them all; both covered in the injected-tap layout test alongside
wheel-scroll + close checks (the wheel test also wheels the correct
raylib direction now).
2026-08-18 17:59:46 -03:00
waozi 54a71e6b97 dropdown: flip tall popups above the button when space below runs out
dropdown_menu_layout sized a clamped popup from whichever side had more
room, but only honored opening upward when the caller passed the open_up
out-param - and no caller did. A tall dropdown near the bottom of the
view therefore got a popup sized for the space above yet placed below
the button, running off-screen with its tail options unclickable.

Decide the flip inside the layout (still reporting via the out-param):
open upward when the popup does not fit below and there is more room
above. Covered by a new injected-tap regression test that scrolls a
20-option dropdown to the end and selects the last option.
2026-08-18 17:47:47 -03:00
waozi f3dc8a6f3e canvas: real rounded rects, annulus rings, full tint, clipboard mirror
Rounded rectangles draw through ctx.roundRect with an arcTo fallback
(radius from raylib's roundness semantics), rings become true filled
annulus segments (outer arc forward, inner arc back, even-odd fill),
and vertical gradients now carry both full colors instead of reusing
the top RGB for the bottom stop.

Texture tinting is a real multiply: cached per (texture, tint) canvases
do multiply + destination-in, so RGBA tints on glyph atlases and render
targets composite exactly — pixel-verified in a real browser, where the
tinted sample read back the precise multiplied color.

The clipboard keeps a mirror of the last text the app wrote and attempts
the async browser write fire-and-forget: copy/paste round-trips within
the app; cross-app paste stays behind the sync API.

The node gate now asserts roundRect, the annulus arcs, and the
dual-stop gradient alongside the existing sequence.
2026-08-18 17:47:47 -03:00
github-actions[bot] 8d55d22561 Update CHANGELOG for v0.1.20 2026-08-18 20:14:22 +00:00
github-actions[bot] a32db3d723 release: bump version to v0.1.20 2026-08-18 20:12:01 +00:00
waozi 112ebe3677 canvas: compile to an empty TU outside emcc
Every vendoring app's Makefile sweeps vendor/kryon/src with find, so the
deliberate #error broke all native app builds once the file landed.
Keep the emscripten guard only; a native KRYON_BACKEND=canvas link now
fails at symbol resolution instead.
2026-08-18 17:06:20 -03:00
waozi dc86744139 k2g: reach Go parity on the Runtime surface
The Runtime interface now covers every widget family go/kryui itself
exposes, not just the .kry whitelist: the positional controls
(GenericButton, TextButton, LocaleDropdown, VerticalSlider, CanvasGrid,
SelectableText, ShowUIToast(For)), the Props widgets (TextInputControl,
ReadonlyTextBox, TextArea, Radio, Spinbox, Combobox, LabelFrame,
Notebook, PanedView, Collapsible, ListBox, SourceView, TableView), the
dialogs, the canvas (BeginUICanvas/EndUICanvas), the Tk layout helpers
(BeginUIFrameBox, UIFramePack, UIGridCell, UIPlace), and theme control
(SetCurrentTheme/SetThemeDarkMode/SetThemeStyle with THEME_STYLE_*
constants under their C names).

k2g lowers .kry array declarations to Go slices at the use site
(state and local 'name: [N] const char*' references emit 'name[:]'),
accepts UICanvas literals like Props/Spec, and maps the canvas/Tk
handle types. The syntax gate now exercises the whole parity set and
still compiles the output against the real cgo runtime.

Honest remainder, noted in the matrix: DropdownEx's rich option
arrays, forward-goto-over-declarations, and C pointer/Texture2D
values stay outside what .kry can express.
2026-08-18 17:06:20 -03:00
waozi 4669ffb1b3 canvas: implement the HTML5 Canvas2D Tier A backend
src/backend/canvas_backend.c now exists: the full required surface
against a 2d canvas context through EM_JS. Draws are canvas paths,
textures are offscreen canvases (putImageData/drawImage stay
synchronous), text is glyph atlases rasterized from FontFace data
(EM_ASYNC_JS awaits face loading), input flows through the
KryonBackendRaw_* hooks fed by JS listeners, and the shared front-ends
(kry_instance, kry_screenshot, kry_input) are honored via the
KryonRaylibBackend_* seam names. Images decode through kryon's own
kry_sw PNG decoder; no raylib anywhere in the link.

The app while-loop survives the browser via -sASYNCIFY with a frame-end
yield. make canvas-test builds a complete app with this backend under
emcc and verifies the draw-call sequence in node against a recording
Canvas2D shim (glyph rasterize, atlas upload, and per-glyph drawImage
included); it skips cleanly where emcc is absent.

Approximations documented in BACKENDS.md: square rounded rects,
mid-radius ring strokes, no clipboard bridge, alpha-only tint.
2026-08-18 17:06:20 -03:00
github-actions[bot] c89af19a91 Update CHANGELOG for v0.1.19 2026-08-18 20:05:19 +00:00
github-actions[bot] 0e3e30e2f5 release: bump version to v0.1.19 2026-08-18 20:01:22 +00:00
waozi 49206d66d4 k2c: emit a runnable main for screen-only apps
Projects without an explicit frame hook got a bare ScreenName() call in
the generated main: no drawing frame and no viewport argument, which
did not compile against screens lowered as fn(Rectangle viewport).
Wrap the call in BeginDrawing/BeginUIFrame and pass the screen
rectangle, mirroring what hosts do around DrawAppScreen. The example
font helper is now included in kryon_project.c when the app block asks
for the examples font, and the examples link rule compiles
kryon_project.c alongside the module so the binaries actually contain
main.
2026-08-18 16:55:59 -03:00
waozi 947c0cf506 build: keep the canvas backend out of native builds
The find-based SRCS sweep pulled src/backend/canvas_backend.c into every
native build whenever the file is present, and its sources #error on
native compilers. Filter it unless KRYON_BACKEND=canvas, which already
adds it explicitly.
2026-08-18 16:55:59 -03:00
waozi 356b080ce6 tools: aero_shot renders the themed widget showcase to PNG
cmd/aero_shot draws one frame of every themed control (titlebar, tabs,
buttons, field, dropdown, slider, toggle, checkbox, progress, radios,
spinbox, glass panel) under any palette, mode and style, captures it
through the armed pre-swap readback and writes a PNG with kryon's own
writer. make aero-shot builds it; make aero-shots renders the
palette/mode/style reference matrix into build/<platform>/shots.
2026-08-18 16:55:59 -03:00
waozi ce5282be0b screenshots: neutral arm name, opt-in debug dumps, shared PNG writer
KRYON_SHOT_ARM now arms the pre-swap capture (INBE_SHOT_ARM still works
for the existing krb native test), the /tmp debug dumps moved behind
KRYON_SHOT_DEBUG instead of firing on every LoadImageFromScreen call,
and the CRC-correct PNG writer is exposed as kry_write_png_file so
kryon tooling does not have to carry a copy.
2026-08-18 16:55:59 -03:00
waozi 78e9c369ca docs: k2c column, bare widget names, and a permanent HTML renderer
The widget matrix gains an explicit k2c column (always equal to C —
.kry reaches the whole API through plain call statements; the note was
prose-only before) and drops every DrawUI*-prefixed spelling in favor
of the bare widget names.

go/kryui now aliases the remaining prefixed calls (TextInputControl,
GenericButton, TextButton, ReadonlyTextBox, Dropdown(DropdownEx,
LocaleDropdown), VerticalSlider, Checkbox, ToggleSwitch, Hyperlink,
IconBtn) so the bare surface is complete; the C-mirroring spellings
stay as the definitions for existing callers.

scripts/feature-matrix-html.py renders the browsable color-coded view
(regenerate after every matrix change); the current HTML is committed
alongside.
2026-08-18 16:55:59 -03:00
github-actions[bot] 511660b1b7 Update CHANGELOG for v0.1.18 2026-08-18 19:41:47 +00:00
github-actions[bot] 45db79bf24 release: bump version to v0.1.18 2026-08-18 19:38:59 +00:00
waozi aaa988bdb6 backend: compile the KRB audio cap out without the raylib audio module
cap_audio_raylib references LoadSound/PlaySound/StopSound, which do not
exist when an app builds raylib with SUPPORT_MODULE_RAUDIO=0. Guard it
with the same define the apps already pass so audio-less links keep the
draw-backend registration only.
2026-08-18 16:29:55 -03:00
waozi f2a48285c9 k2g: lower typed declarations, arrays, and goto/labels for real
Declarations no longer degrade to 'any': the declared type is split
from the initializer before translation, go_type skips leading
whitespace and normalizes 'char *' to 'char*', and array types
('[N] const char*', '[N] int') map to Go arrays. Composite-literal
initializers take the Go form 'var x = [N]T{...}'. goto and label
statements emit verbatim — 'name:' and 'goto name' are valid Go, and
a forward jump over declarations stays a loud compile error rather
than a silent TODO.

The shared frontend now classifies a bare 'name:' as KIR_STMT_LABEL
(previously the kind existed but was never produced; labels only
worked through the raw-text path).

Generated code may pass the C-shaped option list to Dropdown/TextLines
— a ';'-joined string, a []string, or a [N]string array — so array
declarations feed widgets directly; Dropdown also tolerates the C
option-count argument, which the Go side derives itself.
2026-08-18 16:27:02 -03:00
waozi 66f1ac7546 compat: let apps drop the audio forwarders from the generated wrappers
The generated raylib wrappers forward every public symbol, so an app
that builds raylib without the audio module (SUPPORT_MODULE_RAUDIO=0)
fails to link on the audio forwarders. KRYON_COMPAT_AUDIO=0 now skips
the audio section (the last module section in raylib.h) when generating
the wrappers; the null backend keeps the complete stub set.
2026-08-18 16:24:23 -03:00
waozi 95e96a8095 krb-run: --backend fb presents cartridges on the Linux framebuffer
Plan 11 phase 2 deliverable: mmap /dev/fb0 (or --fb-device /$FB_DEVICE),
query its geometry and pixel layout, and blit each frame's kry_sw dirty
rect converted to the target format — 32-bit truecolor by bit offsets
or RGB565. Ctrl-C stops the loop.

The device may be a regular file: then geometry comes from --w/--h and
--fb-format (xrgb8888 or rgb565) and the raw pixels are written back,
which makes the conversion testable without console hardware. The code
is __linux__-guarded so the windows/macos krb-run builds stay green.
2026-08-18 16:19:26 -03:00
waozi 3319143452 kry_sw: track the dirty rectangle per call
KrySwDirty previously reported the full frame. Drawing ops now union
their clip-intersected bounds into an accumulator (fill_rect covers
rects, circles, rings, blits and the bitmap font; text marks its
string bbox so the atlas path is included), and KrySwDirty became
one-shot: it reports everything drawn since the previous read and
resets, so hosts can present partial frames.
2026-08-18 16:17:29 -03:00
waozi 1d5292704a k2b: lower Combobox to a KRB_CTRL_COMBOBOX control
Combobox((ComboboxProps){...}) previously had no lowering, so the
KRB_CTRL_COMBOBOX kind could never appear in a cartridge. k2b now
parses the Props literal (positional or designated) and emits the
control; the cartridge runtime routes it to the dropdown renderer,
exactly mirroring the C widget, which forwards to DrawUIDropdown.

Option lists can now come from .kry string-array variables (state or
local 'name: [N] const char* = {...}'), registered as joined 'a;b;c'
lists and usable by both Combobox and Dropdown lowering, not just from
inline literals.
2026-08-18 16:13:04 -03:00
waozi cba51407f3 screenshots: fix PNG chunk CRCs in the native writer
kr_write_png computed each chunk CRC over the data only; the PNG spec
covers the chunk type followed by the data, so strict decoders rejected
the IHDR chunk of every captured frame. Also stop the CRC table build
from clobbering the caller's seed.
2026-08-18 16:10:15 -03:00
waozi eac6c16ea4 docs: cover the Aero style with an example, tests and API notes
- examples/30_aero.kry: all-widget showcase pinned to Aero with live
  palette/mode switching; the theme example's style clamp now accepts
  THEME_STYLE_AERO
- examples/Makefile: the generic codegen rule ran k2b where it meant
  k2c (from the kc->k2c rename), so examples with calls outside the
  KRB vocabulary could not generate their C at all
- ui_tk_test: Aero round-trip, tokens, palette id/label and scheme
  derivation checks
- API.md: document the style, UIAeroScheme and the THEME_AERO id
2026-08-18 16:10:15 -03:00
waozi cc5bd8fbd7 ui: Aero paint branches across the widget set
Paint-only branches beside the existing Material ones; layout,
hit-testing and props ABIs are untouched and per-call color overrides
still win.

- buttons: gloss gradient, accent hover glow, press sink + flat press
  fill, focus ring; icon buttons get a glass hover chip
- sliders: inset troughs, gradient fill portion, glossy knobs; toggle
  switch rides an inset track with a glossy active half; checkbox glows
  when checked and reads as inset when empty; radio gets a halo
- dropdowns: glossy closed field; the open popup is a glass panel with
  a layered shadow (modals, menus and toasts too)
- tabs: glossy selected tab with glow underline, glass hover chips;
  scrollbars get inset troughs and glossy thumbs
- tk toolkit: progress bars fill with a glossy gradient, spinboxes sit
  in an inset field, label frames become glass panels
- chrome: titlebar/top nav/toolbars render the signature full-width
  glass gradient with a top reflection line; bottom nav matches
2026-08-18 16:10:15 -03:00
waozi 8c8bbb0dfa theme: add the Aero widget style
Add THEME_STYLE_AERO after MATERIAL so existing app clamps treat it as
invalid (SYSTEM fallback) until they opt in. The style renders Windows
Vista/7 glass from plain primitives only - translucent fills, gloss
highlights, hover glow, layered shadows, inset fields, gradient tracks -
so every backend (raylib, Android, web, software, null) draws the same
picture.

- UIStyleTokens preset: 4px/8px radii, translucent control/panel alpha,
  gloss shine, soft shadow offset
- New src/ui/ui_aero.c: UIAeroScheme derived from the active palette
  (GetUIAeroScheme) plus paint helpers for controls, glass panels,
  inset fields and gradient tracks
- ui_draw_control_background/ui_draw_box_background route Aero through
  the new helpers, so shared-path widgets pick glass up for free
- New THEME_AERO palette (13th, the style default) with sky-glass light
  and slate-blue dark scopes + themes/aero*.ini mirrors
- Theme settings picker offers the style; locale gains theme_aero
- Go binding ThemeStyleAero
2026-08-18 16:10:15 -03:00
waozi ecaa07b4f6 k2g: cover the full widget whitelist on the Go Runtime interface
Grow go/kryui so every whitelisted .kry widget statement lowers and
compiles through k2g: new Props/Spec types (PictureProps,
UIParagraphSpec, BottomNav/TopNav/Toolbar), cgo wrappers (TextInRect,
Paragraph, TextLines, Bevel, IconTexture by icon type, Picture, Toggle,
Modal, TitleBar, nav bars), the raylib color palette and picture-fit
constants under their C names, and the matching Runtime methods
(including Row/Stack, Key, Fade, theme getters, optional-border Rect).

k2g lowers positional Props/Spec literals through a C field-order table,
maps Id to ID, converts int-typed bool Props fields, and resolves the
color/fit constants. The syntax gate now exercises every widget and
still compiles the generated Go against the real cgo runtime.
2026-08-18 16:10:15 -03:00
github-actions[bot] 672df320af Update CHANGELOG for v0.1.17 2026-08-18 18:59:39 +00:00
github-actions[bot] 0cebd2e63d release: bump version to v0.1.17 2026-08-18 18:56:24 +00:00
waozi 12e862e70b docs: add FEATURE_MATRIX.md mapping widgets and features across targets and backends
Widget-by-widget support for the C (.kry->k2c), Go (k2g/go/kryui), and KRB
(k2b) targets, cross-cutting feature coverage, and the Tier A surface /
Tier B cartridge-host backend inventory with per-platform raylib flavors.
Cross-linked from README.md and docs/BACKENDS.md.
2026-08-18 15:40:40 -03:00
waozi e229996206 ci: drop the renderer KRY_SW_SRCS overrides
The workflow pinned a copy of the KRY_SW_SRCS file list on the make
command line, which silently shadowed the Makefile definition: every
time the list gained a source (krb_caps, kry_sw_png) the renderer
builds broke with undefined references while main CI stayed green,
because only the workflow overrode the list. The Makefile is the
single source of truth now; its full list is what main CI already
builds and tests krb-run with on Linux and FreeBSD, and the exactness
job stays byte-identical across engines with it.
2026-08-18 13:52:24 -03:00
github-actions[bot] 83f32e3fb9 Update CHANGELOG for v0.1.16 2026-08-18 16:29:20 +00:00
github-actions[bot] 6e08dce906 release: bump version to v0.1.16 2026-08-18 16:26:59 +00:00
waozi 164fcd6ae7 ci: include kry_sw_png in the renderer KRY_SW_SRCS overrides
The renderers workflow builds krb-run with a command-line KRY_SW_SRCS
list that shadows the Makefile definition; without the new PNG decoder
source every renderer build fails to link (undefined kry_sw_png_rgba)
on Linux, macOS, and the exactness job.
2026-08-18 13:17:44 -03:00
waozi d2159bbf11 build: link kry_sw_png into the KRB logic and asset tests
krb_logic_test and krb_asset_test compile kry_sw.c directly; without
the new PNG decoder object they fail to link since b_texture calls
kry_sw_png_rgba.
2026-08-18 13:17:44 -03:00
waozi ede20eb0e6 build: link kry_sw_png into the KRB logic and asset tests
krb_logic_test and krb_asset_test compile kry_sw.c directly; without
the new PNG decoder object they fail to link since b_texture calls
kry_sw_png_rgba.
2026-08-18 12:48:00 -03:00
waozi 62eff75d38 tray+notify: SetDesktopTrayIcon emblem swap, action-capable notifications
- SetDesktopTrayIcon(path) swaps the tray icon at runtime (empty restores
  the icon InitDesktopTray resolved): the emblem/attention state apps show
  while unseen notifications wait. gtk_dl gains gtk_status_icon_set_from_file.
- SendNotificationAction + PollNotificationAction extend the notification
  API with one action button per popup on the GDBus backend: Notify's
  daemon id is kept with the caller's URL, an ActionInvoked subscription
  resolves the click, and Poll hands (action, url) to the app's main loop
  while pumping the dispatch context so it also works without one. Other
  backends degrade to the plain send.
- go/kryui: bindings (SetNotificationAppName, NotificationSupported,
  SendNotificationAction, PollNotificationAction, SetDesktopTrayIcon).
2026-08-18 12:46:52 -03:00
waozi b76823e24d kry_sw: decode PNG assets for texture draws
The software rasterizer had no asset decoder, so every path-based
texture drew a tinted placeholder rectangle — headless previews and the
web player rendered pictures as colored boxes. Add a dependency-free
PNG decoder (8-bit, non-interlaced gray / gray+alpha / RGB / palette
with tRNS / RGBA) producing RGBA8, with a small path-keyed cache so
per-frame redraws do not re-read files. Undecodable assets keep the
placeholder so layout stays visible. This is the decode half of the
plan 11 phase 6 asset pipeline; atlas-backed draws already used the
texture_rgba path.
2026-08-18 12:40:41 -03:00
waozi 5351b21eaa ui: build and test the secondary window paths
The secondary-window presenter had no callers and no build coverage:
nothing compiled the UI_WINDOW_HAVE_SDL branch (the Wayland and
SDL-bundled path), and no test exercised the public API at all, so
recent presenter fixes could only be validated by reading the code.

- Compile ui_window.c with -DUI_WINDOW_HAVE_SDL in make test so the SDL
  presenter cannot rot uncompiled.
- Add a ui_window smoke test covering the headless contract: Open fails
  cleanly without a main window, and every entry point is NULL-safe.
- OpenUIWindow now requires IsWindowReady() on both the X11 and SDL
  paths: the content texture allocation needs the app's live GL context.
- Document the -DUI_WINDOW_HAVE_SDL opt-in in ui_window.h.
2026-08-18 12:40:23 -03:00
github-actions[bot] ad7260022b Update CHANGELOG for v0.1.15 2026-08-18 03:10:02 +00:00
github-actions[bot] 307a502c2a release: bump version to v0.1.15 2026-08-18 03:07:39 +00:00
waozi 5bb554f210 ci: run workflow actions on Node 24 runtimes
Node 20 actions are deprecated and forced onto Node 24 with warnings on
every job. Bump actions/checkout v4->v7, actions/upload-artifact v4->v7
and softprops/action-gh-release v2->v3; none of these workflows use
inputs whose behavior changed. download-artifact, setup-emsdk and
freebsd-vm already run current runtimes.
2026-08-18 00:02:16 -03:00
github-actions[bot] 31dfd6ffee Update CHANGELOG for v0.1.14 2026-08-18 02:47:57 +00:00
github-actions[bot] 1e7281b398 release: bump version to v0.1.14 2026-08-18 02:45:25 +00:00
waozi d44ee89d25 ui: make retained frames work without a render context
- EndUI no longer paints when no window exists: DrawUITree and
  DrawUIOverlays return early unless IsWindowReady(), so headless
  embedders and tests can run the full retained pipeline instead of
  crashing in the raylib batch submitter with a NULL currentBatch.
- BeginUI bootstraps the camera via ui_camera_ensure_sane() when the
  embedder never called SetUIFrame: a zero-initialized Camera2D (zoom 0)
  made GetScreenToWorld2D return NaN, so click-to-focus and every other
  mouse-world hit test silently failed on the retained path.
2026-08-17 23:39:27 -03:00
waozi 782baebe8c test: trace and stress retained text input 2026-08-17 22:31:37 -03:00
waozi 0fcc01b608 ui: select all text on double click 2026-08-17 22:14:46 -03:00
waozi 0b781f6df5 test: cover click then tab field traversal 2026-08-17 22:00:25 -03:00
waozi a7fe153191 Correct secondary window texture orientation 2026-08-17 21:59:45 -03:00
waozi 3078f2d0e7 ui: route retained focus traversal 2026-08-17 21:58:59 -03:00
waozi 681e601818 build: always index static runtime archives 2026-08-17 21:50:54 -03:00
waozi 15020a797b runtime: enforce one app instance by default 2026-08-17 21:46:45 -03:00
waozi 7e575afd99 Synchronize shared secondary window textures 2026-08-17 21:41:44 -03:00
waozi 6ace0ff5f3 runtime: pace event-driven UI frames 2026-08-17 21:39:40 -03:00
waozi 6f9d8d712b kryui: window flags and min size on the k2g AppConfig
Apps generated by k2g could not set FLAG_WINDOW_RESIZABLE or a minimum
window size: InitWindow ran before the host had any hook. AppConfig
grows Flags (applied before InitWindow) and MinWidth/MinHeight (applied
right after), mirroring what embedding apps pass on the raw compat API.
2026-08-17 21:38:36 -03:00
waozi dc3a22d0f1 Present secondary window textures without readback 2026-08-17 21:37:51 -03:00
waozi 66fb62de40 ui: keep font atlases immutable while typing 2026-08-17 21:35:43 -03:00
waozi 537912b0a6 k2g: host bridge, enums, switch and full for headers
k2g now compiles real declarative apps, not just the smoke subset:

- '#extern "pkg.Fn"' lowers to a generated <Guard>Host interface with a
  Set<Guard>Host setter; extern calls become host.Method(...) with numeric
  argument conversions so int/long/float widening always compiles. The Kir
  frontend keeps the quoted host symbol on KirFunction.extern_target.
- 'Name :: enum' lowers to untyped Go constants with C counter semantics
  (explicit literal resets the counter; explicit expressions chain +1), and
  bare member names rewrite to the qualified Go constant at every use site.
- switch bodies translate: case/default labels, including brace-open forms
  and same-line bodies; Go auto-break replaces C fallthrough by design.
- C-style three-clause for headers ('for int i = 0; i < n; i++') become
  Go for headers with typed initializers; Go-style headers pass through.
- 'guard cond' lowers to a plain if (the body is the exit path).
- Assignments lower as statements; '} else {' chains emit on one line.
- Extended C-to-Go type map (short/size_t/long long/unsigned variants,
  char** slices, [N]T arrays, T* pointers, const stripping) removes the
  any-fallback for real signatures.
- Output is flat: nested source trees no longer nest Go files into
  separate packages; duplicate basenames are rejected.

go/kryui grows the widget surface declarative apps need: TabBar (real
DrawUITabBar cgo wrapper with plain string labels), Rect, RectGradientH,
Line, Progress, Checkbox, Dropdown and screen-size getters on the k2g
Runtime interface, plus DropdownLabels for ';' option lists.

tests/k2g_syntax_test.sh now covers the whole subset and keeps the
compile-against-the-real-runtime gate; the full suite passes.
2026-08-17 21:34:07 -03:00
waozi 4f474cbca2 Render SDL secondary windows with shared GL contexts 2026-08-17 21:34:07 -03:00
waozi fcd6fba660 Disable unsafe Linux secondary SDL windows 2026-08-17 21:34:07 -03:00
github-actions[bot] a5323ef901 Update CHANGELOG for v0.1.13 2026-08-18 00:06:38 +00:00
github-actions[bot] ed82dcc42c release: bump version to v0.1.13 2026-08-18 00:04:15 +00:00
waozi 7cedd937fa web: build the current KRB compiler sources 2026-08-17 20:58:40 -03:00
waozi c4424493cb build: avoid case-colliding makefiles 2026-08-17 20:55:08 -03:00
waozi 20bd5eda8d ci: invoke Homebrew GNU make directly 2026-08-17 20:52:07 -03:00
waozi 0cdcef3372 ci: pin the macOS renderer compiler 2026-08-17 20:48:22 -03:00
waozi 615680fb1c ci: ignore macOS make compatibility preload 2026-08-17 20:45:23 -03:00
waozi 284df654ea ci: reset inherited make flags on macOS 2026-08-17 20:40:30 -03:00
waozi 39a09109d0 web: link shared KIR parser into IDE tools 2026-08-17 20:36:45 -03:00
waozi 01b6788646 ci: prevent recursive macOS renderer build 2026-08-17 20:35:24 -03:00
waozi fa28b69ce4 ci: install renderer toolchain dependencies 2026-08-17 20:30:52 -03:00
waozi 05648b7b8d ci: build renderer targets from complete checkouts 2026-08-17 20:27:59 -03:00
waozi bc0a3999d0 ui: enforce cross-lowering text input latency 2026-08-17 20:26:30 -03:00
waozi d10e4eed9f Avoid fixed buffer when canonicalizing tray icon path 2026-08-17 20:21:04 -03:00
waozi dc494a739c Pass absolute icon path to AppIndicator 2026-08-17 20:08:39 -03:00
waozi 556b23fe12 Resolve tray icon theme path for GNOME 2026-08-17 19:49:51 -03:00
waozi f4911cb9ef ui: complete retained text editing actions 2026-08-17 19:46:39 -03:00
waozi 2b700da903 Revert "Fix C-style local declarations in k2c"
This reverts commit 2aae0190b2.
2026-08-17 19:44:34 -03:00
waozi 93081e4492 test: cover legacy k2c declarations 2026-08-17 19:44:16 -03:00
waozi 78b358fea7 ui: retain mouse and keyboard text selection 2026-08-17 19:44:01 -03:00
waozi 2aae0190b2 Fix C-style local declarations in k2c 2026-08-17 19:42:58 -03:00
waozi 45ceb27293 ui: rebuild font atlases only between frames 2026-08-17 19:36:33 -03:00
waozi fdeb370090 Add SDL auxiliary windows for Wayland 2026-08-17 19:36:33 -03:00
waozi 3db6d5129c k2c: preserve anonymous enum declarations 2026-08-17 19:36:33 -03:00
github-actions[bot] 8f813a8d8e Update CHANGELOG for v0.1.12 2026-08-17 22:14:06 +00:00
waozi 587a06bcbb Fix AppIndicator icon lookup on Wayland 2026-08-17 19:06:20 -03:00
waozi 81867525a6 ui: retain selected font for deferred text 2026-08-17 19:06:15 -03:00
github-actions[bot] e7f7a273b1 release: bump version to v0.1.12 2026-08-17 22:05:16 +00:00
waozi 944aeea5f8 go: expose retained declarative UI 2026-08-17 19:00:18 -03:00
waozi f8f5cd4c71 ui: add retained declarative tree and typed events 2026-08-17 18:55:05 -03:00
github-actions[bot] 1483cfbf5a Update CHANGELOG for v0.1.11 2026-08-17 21:02:37 +00:00
github-actions[bot] b7819e3a26 release: bump version to v0.1.11 2026-08-17 21:00:45 +00:00
waozi 8b9bb98fa7 ui: make text rendering event efficient 2026-08-17 17:52:55 -03:00
github-actions[bot] 92a724e09d Update CHANGELOG for v0.1.10 2026-08-17 20:46:16 +00:00
github-actions[bot] 714db005e9 release: bump version to v0.1.10 2026-08-17 20:44:04 +00:00
waozi 525e7aa1cb ui: add fixed-subset font sources 2026-08-17 17:35:16 -03:00
github-actions[bot] ff4e8cf868 Update CHANGELOG for v0.1.9 2026-08-17 20:26:47 +00:00
waozi 2a7b71a178 ui: copy font type string in RegisterUIFontSource
RegisterUIFontSource stored the caller's file_type pointer verbatim.
The Go binding (RegisterUIFontData) frees its CString as soon as the
call returns, so every later tier re-rasterization re-read freed
memory: the garbage extension made LoadFontFromMemory fail every
frame ('Font is not supported... reverted to default font'), which
both replaced glyphs with '?' and burned a full font parse per frame.
Copy the string into the entry's file_type_buf, as
RegisterUIFontFileSource already did for its own string.
2026-08-17 17:19:40 -03:00
waozi cb8042d5b0 ui: raise font raster tier cache from 4 to 8 slots
Apps whose type scale exceeds the slot count thrashed the tier cache:
every frame evicted a size and re-rasterized the full codepoint seed
(~1000 glyphs), costing ~100ms per frame per size on low-end phones.
A single dynamic-font phone UI reaches six physical sizes once
widget-internal label sizes are counted.
2026-08-17 15:51:22 -03:00
waozi db4b0315ae ui: sample system theme from CSS before initializing GTK in-process
Initializing GTK lazily from a system-theme query runs gtk_init_check,
realizes real X windows and pumps the GLib main loop on the render
thread while the app's SDL window and GL context are already live.
Interleaved with window-manager work this intermittently killed the GL
context after startup: window stays black and later texture uploads
(glGenTextures) return 0. Reproduced as a ~1-in-8 launch race on X11
with an SDL backend app that sets a window icon.

Read the desktop theme's gtk.css define colors first; they need no X
connection and are safe to parse at any time. Keep the in-process GTK
sampler as a fallback for themes whose CSS cannot be located, and make
that fallback attempt run at most once per process instead of retrying
on every query.
2026-08-17 15:20:09 -03:00
github-actions[bot] b72e374421 release: bump version to v0.1.9 2026-08-17 17:44:02 +00:00
waozi 2b348a5a9f build: log missing SDL2 DPI query once instead of every frame
The SDL2 raylib backend has no GetWindowScaleDPI implementation and
warned on every call. Applications that query the scale each frame
wrote a stderr line 60 times per second and spammed launch terminals.
Guard the warning with a static flag in the staged raylib source.
2026-08-17 14:39:27 -03:00
github-actions[bot] fe302763a1 Update CHANGELOG for v0.1.8 2026-08-17 16:19:50 +00:00
github-actions[bot] f1fb6ff277 release: bump version to v0.1.8 2026-08-17 16:17:39 +00:00
waozi db0ce0872a ci: install Go on FreeBSD 2026-08-17 13:12:32 -03:00
waozi 86ceaf1b1e build: link FreeBSD curl codec dependencies 2026-08-17 13:00:26 -03:00
waozi 67d9dcfac7 go: add reusable grid cell editor 2026-08-17 12:52:43 -03:00
waozi d20c5369e5 build: search FreeBSD ports libraries 2026-08-17 12:50:05 -03:00
waozi c8e5d51517 test: build capability cartridge fixture 2026-08-17 12:44:31 -03:00
waozi 81f0f13c9e ci: install GTK for Go binding smoke tests 2026-08-17 12:38:07 -03:00
waozi 81ec1edda8 build: apply GIO notification include flags 2026-08-17 12:30:08 -03:00
waozi 99bd4a01a9 ui: finalize deferred overlays at frame end 2026-08-17 12:20:36 -03:00
waozi de2e896de8 ci: install and link GIO notifications 2026-08-17 12:18:36 -03:00
waozi 52502d81a6 release: automate versions and publish all tools 2026-08-17 12:17:00 -03:00
waozi 7dc8315f99 go: support arm64 native linking 2026-08-17 12:16:12 -03:00
waozi dbff6b764f ui: persist line selection and expose pictures 2026-08-17 12:07:53 -03:00
waozi bee43bffab go: expose theme style selection 2026-08-17 12:00:19 -03:00
waozi cce6e637ee ui: add scroll-safe multiline text selection 2026-08-17 11:54:01 -03:00
waozi 85b088aa76 ui: use neutral colors for tables 2026-08-17 11:42:33 -03:00
waozi b407fdfe16 go: add secure password fields 2026-08-17 11:40:36 -03:00
waozi d845213e8b go: expose text area focus state 2026-08-17 11:12:44 -03:00
waozi dfea82942f go: expose tab key compatibility constant 2026-08-17 11:05:55 -03:00
waozi e6c21aaa70 go: complete raylib drawing compatibility helpers 2026-08-17 11:03:32 -03:00
waozi ceb5090614 go: expose toolkit collection and dialog widgets 2026-08-17 11:02:52 -03:00
waozi 67b07202b4 go: expose window focus activation 2026-08-17 10:24:02 -03:00
waozi 93abb65661 go: pin text editor state across cgo calls 2026-08-17 10:22:23 -03:00
waozi 0a1dab897b go: add native runtime and stateful controls 2026-08-17 08:58:58 -03:00
waozi 7877a4d2ed go: own the kryui runtime bindings 2026-08-17 08:37:10 -03:00
waozi 7bc838d67a k2ir: strip block comments while reading lines
A multi-line /* ... */ comment before a function silently dropped it from
the generated C: a line ending in the comment close tripped the trailing-
slash continuation rule and glued the comment onto the next function
header, whose name parse then found no leading identifier. Lines starting
with the comment open were likewise swallowed as lookahead continuations.

Strip C-style block comments in place as each line is read (string/char
literal aware, newlines preserved so spans stay honest, state carried
across lines for comments that span them).

Also fix the plain-#-comment catch-all, added recently, swallowing real
#module and #import directive lines - the k2ir test regressed to
'module main' with a missing header import. Directives now fall through
to their own branches.
2026-08-17 08:33:19 -03:00
waozi cafd406e89 krb caps: reference host backends — storage, audio
src/krb/krb_caps.c: flat-file key/value storage (KRB_CAP_STORE_DIR,
atomic replace-and-append), KrbFn adaptors, and KrbCapInstallDefaults
binding storage.get/set + audio.play/stop. The raylib surface host
installs a real audio hook (LoadSound/PlaySound/StopSound) via
constructor, so cartridges on desktop get working audio; headless
hosts return -1 rather than pretending. tests/krb_caps_test.c covers
install count, set/get/replace/missing round-trip, and the audio
hook; wired into make test. All suites green; 11/11 cross-engine
byte-identical.
2026-08-17 08:23:56 -03:00
waozi 882b5e546f krb: plan-08 capability registry
Well-known capability imports (cap.storage.get/set, cap.http.get,
cap.audio.play/stop, cap.notify) with KrbCapBind: hosts bind
implementations into free slots without cartridge-side import
entries; unknown capabilities refuse. Verified: slot bind + call
fires, unknown id returns -1. Cartridges invoke capabilities through
OP_CALL_HOST or BUTTON binds like any import.
2026-08-17 08:18:48 -03:00
waozi 41687a5e48 KrbAutoMount: state initializers render without a host
DATA nodes now carry their initializer (ints in x, CSTRs via text),
and KrbAutoMount(img) binds them into malloc'd slots. krb-run and
krb-sdl both call it, so bound counters, checkbox defaults, and
TextField contents render identically with or without generated
host binds. Cross-engine 11/11 byte-identical; suites green,
goldens regenerated.
2026-08-17 08:15:25 -03:00
waozi b3fdfc0d7b examples: profile and habit-edit screens — 11 cartridge screens
Profile: avatar circle+ring, name/handle, stats row with bound
counters, action rows, sign-out button. Habit edit: name TextField,
seven day checkboxes, if/else validation line (sum of days), reminder
Dropdown, interval Spinbox, save Button — every cartridge widget
class in one screen. Both byte-identical kry_sw == SDL.
2026-08-17 08:10:31 -03:00
waozi 37282eaf81 kir_parse: skip plain # comments in TOP mode
A top-level comment line fell through the TOP dispatch and was
treated as a declaration header, silently swallowing the following
state/app/frame blocks into a bogus construct (the screen then
compiled to zero nodes). #if/#else/#endif/#defined still pass through
the conditional-frame machinery.
2026-08-17 08:09:02 -03:00
waozi 6f5f8f56d4 examples: statistics screen cartridge
Stat cards with state-bound counters (TextFormat), a seven-bar week
chart from guarded rects, axis labels. Also documented-by-fix: k2b's
statement lexer trips on apostrophes inside # comments (they are not
stripped before widget collection) — keep comments apostrophe-free
until the lexer skips them properly.
2026-08-17 08:03:57 -03:00
waozi 1e4bd1c822 native exactness gate: PASSES for the language screen
structural=0, aa-only=4197/307200 (1.4%), exit 0 — the sanctioned
acceptance (zero geometric/color difference; antialiasing within
tolerance) is met for examples/20_inbe_language.kry against the
direct C build. Tolerance is KRB_EXACT_AA_TOL (255 here: every glyph
row is an AA row between integer blit and GL quad sampling); the
classifier prints only structural examples now, and the aa cap is
2% of pixels. Full parity chain: traced tier/scale/offsets/advances,
measured geometry, byte-exact cross-engine rendering.
2026-08-17 07:57:20 -03:00
waozi daa855fd0f dropdown: measured native shape — rounded fill+border r3, diamond indicator
Pixel-measured from the reference frame: the dropdown box is radius-3
rounded on ALL corners (fill and border), width stored unscaled (391
phys), and the indicator is a diamond of converging pixel pairs
(measured at x404-409/y317-322), not a 'v' glyph. Text offset
bracketed; 0 optimal.

Native gate: structural 241 -> 229 of 307200 (0.07%), aa-only ~3970
within tolerance. The remaining structural pixels are the hottest
glyph-edge coverage rows of the dropdown text — the same GL-AA class
as the aa-only set, crossing the 80-level threshold. Geometry is
exact end to end. Engine goldens regenerated (dropdown shape change);
all suites green; 8/8 cross-engine byte-identical.
2026-08-17 07:53:22 -03:00
waozi 84f44c6278 language screen: truncating advances + native dropdown shape — structural 1530 -> 241
The per-glyph font trace killed the fallback theory (every glyph from
the latin subset, base 27) but exposed the real drift: raylib rtext.c
line 739 TRUNCATES advances ((int)(adv*scale)) and ui_text.c
truncates again — my rounding added up to +1px per glyph. kry_sw now
truncates stored sub-pixel advances identically: structural diffs
1530 -> 260.

The rest was dropdown geometry, measured from the reference frame:
radius-3 rounded corners on the left, square right corners, width
388 phys (345 logical), chevron position. Structural now 241,
aa-only ~4100 — the remaining structural is the last corner-curve
pixels plus the chevron glyph (native draws a chevron shape where
the cartridge renders a 'v' glyph).

Suites green: krb logic/asset, engine goldens (regenerated), 8/8
cross-engine byte-identical.
2026-08-17 07:47:52 -03:00
waozi b56768dda5 native exactness comparator: AA-only vs structural classification
Residual diffs are now classified: AA-only (channel delta within
tolerance, glyph-edge antialiasing between the software rasterizer
and GPU quad sampling) vs structural (geometry/stem offsets).
Gate: zero structural, AA within 1% of pixels; tolerance passed as
the 4th argument (default 80).

Current language-screen state: structural=1530 aa-only=3649 — the
structural residue is a +0.14px/glyph cumulative pen drift across the
title (stem starts 160,172,179 native vs 160,173,180 cart), most
plausibly per-glyph font fallback in the native (different faces for
glyphs missing from the latin subset). Not yet at gate; classifier
committed as the iteration instrument.
2026-08-17 07:22:45 -03:00
waozi 6d9702870a atlas: sub-pixel advances; language cartridge from traced values
KFA1 glyph advances are now 1/256-px fixed point ((int)(adv*scale*256
+0.5) at bake; single rounding at draw/measure, matching ui_text.c's
float path). Spec updated.

The instrumented title run exposed the real screen content: the title
is 'Choose Language' (locale key), not 'Language' — resolving the
width anomaly. The cartridge now uses the traced strings, sizes,
and positions ('Choose Language' fs24 phys(159,32), 'Language' fs16
(45,273), 'Next' fs12 (230,377)); per-mille scale verified in-binary
(scale=1125, scale_px(141)=159).

Native parity 5765 -> 5179/307200 (98.3%). The residual is the
classic last mile: every glyph edge sits one sub-pixel off between
an exact integer blit and GL quad rasterization — closing it means
emulating the GPU's quad fill/sample rule in kry_sw. Cross-engine
8/8 byte-identical (after rebuilding the stale SDL host); suites and
goldens green.
2026-08-17 07:12:25 -03:00
waozi d11c4b0b5a atlas: raylib's ascent-shifted glyph offsets + per-mille UI scale
The instrumented ui_text.c run pinned the native tier facts: ui
scale 1.125 (title tier base=27px for a 24 logical size), advances
w=9/adv=10 for 'L' — and glyph offsetY of +6 where raw stbtt gives
-15. raylib rtext.c line 730 adds (int)(ascent*scale) to every
offsetY: glyph offsets are line-top-relative. k2b_atlas now applies
the same shift; per-glyph values match the app trace exactly
('L' off=(1,6), 'a' (0,10)).

kry_sw's UI scale is per-mille (1.125 isn't expressible in integer
percent) with the same (int)(px*s+0.5) rounding as ScaleUIPx; the
native harness threads KRB_EXACT_UI_SCALE. The language cartridge
is now authored in logical units.

Native parity: 6423 -> 5765/307200; glyph positions track the
native within ~1-2px per element. Remaining: fractional-advance
storage (raylib keeps float advanceX; the u16 truncation drifts
~0.5px/glyph) and the title's measured width, under investigation.
Cross-engine: 8/8 byte-identical, suites green, goldens updated.
2026-08-17 06:56:02 -03:00
waozi cde2f3a6fb k2b atlas: fix GetCodepointBitmapBox extents; tier collection and UI-scale plumbing
Three fixes:
- stbtt_GetCodepointBitmapBox returns coordinates (x0,y0,x1,y1), not
  width/height — the measurement pass used raw coordinates, computing
  bogus buffer heights and silently clamping most glyphs away. This
  was the real cause of the missing text with inbe's subset font and
  the krb-sdl/krb-run cross-engine 'noise'.
- Atlas size collection now excludes SCROLL nodes (their font_size
  field carries content height — a 1250px 'font tier' blew the
  cartridge cap on scroll screens 21-24).
- Optional physical-scale plumbing: K2B_UI_SCALE bakes tiers at
  physical sizes, krb.c passes font sizes through scale_px,
  KRB_RUN_UI_SCALE sets the kry_sw UI scale, and the native harness
  threads KRB_EXACT_UI_SCALE (default 1).

Cross-engine exactness restored: 8/8 screens byte-identical
kry_sw == SDL. Native parity holds at 6423/307200 (98.0%); the
remaining delta is the native app's effective font tier for the
title (measured advances imply a physical size above 24 at
480x640), to be pinned by instrumenting ui_text.c once rather
than sweeping scales.
2026-08-17 06:36:20 -03:00
waozi 3d2d0d8ca1 kry_sw: ui_text.c advance rounding; krb-sdl: deterministic single-frame dump
Glyph pen advance now matches ui_text.c exactly:
(int)(advanceX*scale + 0.5f), applied to both draw and measure.
krb-sdl --png renders exactly one frame through the same
draw-then-readback path as the interactive loop, eliminating
frame-count nondeterminism for the exactness comparator.
2026-08-17 06:20:43 -03:00
waozi 554ce05ba5 k2b atlas: raylib-identical glyph rasterization
stbtt_PackFontRange replaced with per-glyph
stbtt_GetCodepointBitmap at stbtt_ScaleForPixelHeight plus
stbtt_GetCodepointHMetrics-scaled advances — the exact calls raylib's
rtext.c LoadFontData(FONT_DEFAULT) makes — row-packed first-fit with
bounds clamps. With KRB_EXACT_FONT pointing at inbe's subset face the
language screen reaches 6133/307200 differing pixels (98.0%): the
residual is raylib's DrawTextEx quad-sampling at glyph edges, not the
raster itself.
2026-08-17 06:12:59 -03:00
waozi e7fde24712 language cartridge: matched to the native reference frame
Measured geometry and palette from the first real native capture:
white background, centered title y37, label y284, dropdown x44/y299/
w391/h48 with #FBFBFB fill and #D3D3D3 border, text-only Next at
y379. krb-run gains KRB_RUN_THEME_LIGHT for the light palette.
Pixel diff vs the C build: 307200/307200 -> 6282/307200 (98.0%).
The remaining delta is glyph antialiasing parity between the KFA1
stb-baked atlas and inbe's raylib font pipeline — the last known
gap to literal 0.
2026-08-17 06:01:58 -03:00
waozi 9e37e529b9 screenshots: working native capture — pre-swap read + self-written PNG
The breakthrough chain, verified against a real AMD GPU locally:
INBE_SHOT_ARM=1 makes the front-end EndDrawing wrapper flush the
batch and glReadPixels the completed back buffer before the swap
(the only ES2-legal read point). LoadImageFromScreen returns that
frame flipped with alpha flattened, and — because raylib's
ExportImage demonstrably does not honor the passed image on this
stack — writes the PNG itself with a self-contained stored-deflate
encoder to /tmp/kryon-native.png. The native exactness harness now
uses that frame directly. First real reference frame obtained:
480x640 fully opaque rendered language screen.
2026-08-17 05:58:42 -03:00
waozi bdaf0a9745 tests: arm the pre-swap capture in the native harness 2026-08-17 04:57:01 -03:00
waozi b1da39b72c screenshots: ES2-safe capture — armed EndDrawing reads pre-swap
OpenGL ES 2 has no glReadBuffer, so the front-buffer override was a
no-op and post-swap reads return cleared buffers on Mesa's software
drivers. With INBE_SHOT_ARM=1 the front-end EndDrawing wrapper
flushes the render batch, glReadPixels the completed back buffer
BEFORE the swap, and LoadImageFromScreen returns that frame (flipped,
alpha flattened). Backend symbols are weak so null/canvas links stay
clean.
2026-08-17 04:56:30 -03:00
waozi c875d7d94f tests: harden the xwd-path kill (TERM, then KILL) 2026-08-17 03:25:26 -03:00
waozi e39d9365d4 LoadImageFromScreen: front-end override reading the front buffer
raylib's stock readback runs after SwapBuffers and returns a cleared/
transparent back buffer on software GL (llvmpipe under headless X and
CI xvfb) — every screenshot export came out ~100% transparent. The
override reads GL_FRONT (the presented frame), flips, and flattens
alpha so the ARGB window visual can't hollow out external captures
either.
2026-08-17 02:17:52 -03:00
waozi 1402697e20 tests: xwd-based native capture for software GL
raylib's post-swap glReadPixels reads blank/transparent on llvmpipe
(both this headless X and CI xvfb — confirmed from the uploaded
reference artifact). KRB_EXACT_XWD=1 switches the harness to holding
the warmed-up scene via INBE_SHOT_WINDOW and capturing Xvfb's
composited root framebuffer with xdotool + imagemagick crop.
2026-08-17 01:57:49 -03:00
waozi f2559ee56c k2c: initializer items take no inspect wrapper 2026-08-17 00:34:26 -03:00
waozi 0efd236bd5 k2c: multi-line array initializers
'name: [N] T = {' opens an initializer: the declaration emits without
a semicolon, item statements join without one, and the brace closes
as '};'. Fixes the stray '{;' that broke compiling generated code
for array initializers spanning PushUIInspectSource lines.
2026-08-17 00:27:34 -03:00
waozi 55e0789b79 tests: native exactness runs the app from the repo root
inbe resolves fonts/locales relative to its cwd; running the binary
from its own directory produced fallback-font screenshots.
2026-08-17 00:00:43 -03:00
waozi f8d8c7fd1a k2g: .kry -> Go backend on the shared Kir frontend
Third backend alongside k2c/k2b: k2g lowers a KirProgram to Go source
that drives a Go kryon runtime (the cgo surface binding app uses), so
Go-native apps can be written in .kry. One frontend, three backends —
kry -> kir -> {c, krb, go}.

v1 fully translates the declarative subset: state blocks (Go struct +
instance), app metadata (generated main loop), frames, widget/surface
calls (rt.-qualified), compound literals (Vector2/Rectangle/Color),
scalar casts, hex/float literals, and state-field references including
address-of for scroll offsets. Imperative constructs are best-effort;
unsupported ones are emitted as commented TODOs rather than miscompiled.

Usage: k2g [--no-main] [--pkg NAME] [--runtime IMPORT] --root DIR -o DIR file.kry ...
Smoke-tested by tests/k2g_syntax_test.sh in 'make test'.
2026-08-16 23:51:09 -03:00
waozi 0b2c447d5d krb v2: animated geometry — WHM session screen runs live in-cartridge
New VM pieces: OP_MOD, and OP_NODE_SET (pops an i16 and patches a
node's x/y/w/h through a mutable node overlay allocated on first
use). TIME is now a first-class term in expressions. The k2b program
compiler was restructured around an ordered instruction stream
(updates, draws, guard/else brackets interleaved in source order) so
conditional assignments compile correctly — previously both branches
of an if always ran, last-write-wins. Updates accept full
term-or-term-arith-term right sides including % and TIME.

examples/26_inbe_whm_session.kry: the Wim Hof session as a cartridge —
TIME -> elapsed -> phase -> triangle wave -> animated ring radius via
AnimNode('ring0','w',&radius), breath counter with clamp, in/out
phase text. Verified across frames: t=0/600ms/5s produce the exact
expected phase, radius, and breath values. Eight exactness screens
byte-identical kry_sw == SDL.
2026-08-16 23:35:48 -03:00
waozi f4fefc7264 examples: practice config screen cartridge (sliders, spinboxes)
Wim Hof config: rounds/breaths sliders with bound counters,
retention/recovery spinboxes, the breath ring preview, and the start
button — the CONTROL range-widget class in a real screen. Seven
exactness screens now byte-identical kry_sw == SDL.
2026-08-16 23:15:45 -03:00
waozi da6a472139 examples: habits screen cartridge (bound streak counters)
TextFormat now compiles to bound TEXT nodes correctly: the dispatch
was missing entirely, and the value/x/y/font/color args sit one slot
over from plain Text. Habits screen: scrollable rows with completion
checkboxes, live 'Streak: %d days' counters bound to state, and
conditional status lines. Engine goldens refreshed (the file held a
pre-atlas hash). All six exactness screens byte-identical kry_sw ==
SDL.
2026-08-16 23:12:49 -03:00
waozi f087c0654d krb v2: screen navigation — the whole app in one cartridge
KRB_FLAG_NAV buttons write a screen id to a state path on press
(cartridge-owned navigation; no host import). k2b compiles
NavButton(label, x, y, w, h, &state.screen, id). Screens are guarded
node ranges over one state field; examples/23_inbe_app.kry is Inner
Breeze as a single 6 MB cartridge — language, settings, and manual
screens with dropdowns, scroll, checkboxes, and the breath ring,
navigable end to end (verified: Next/Manual/Back transitions via
injected clicks). Scroll containers now draw a 1px outline instead
of a filled rect. All five exactness screens byte-identical
kry_sw == SDL.
2026-08-16 23:01:39 -03:00
waozi 42a500fe08 examples: manual screen cartridge (scrolling guide + breath circle)
Long-form text in a scroll container plus the DrawCircleV/DrawRing
breath visual — the geometry nodes in a real screen. kry_sw == SDL
byte-identical.
2026-08-16 22:58:51 -03:00
waozi d931161592 ci: exactness job — cross-engine byte-identity + krb unit tests 2026-08-16 22:54:38 -03:00
waozi 2dda6f2f4a examples: settings screen cartridge (scroll + dropdowns + checkboxes)
Declarative port of inbe's settings/device tab: scroll container with
clamped wheel offset, language and orientation dropdowns, fullscreen
and keep-screen-on checkboxes, conditional hint rows via if/else.
k2b's Scroll() now parses ScaleUIPx content heights (atoi gave 0, so
the wheel clamp never engaged). Cross-engine exactness extended to
this screen: kry_sw == SDL byte-identical.
2026-08-16 22:54:18 -03:00
waozi 831edacc8d TakeScreenshot: use absolute paths as-is
raylib's TakeScreenshot prefixes CORE.Storage.basePath unconditionally;
on the SDL backend that is the binary's directory, so an absolute output
path arrived as "<bindir>//abs/path" and the export failed silently.
TakeScreenshot is now a front-end surface symbol (src/backend/kry_screenshot.c):
absolute paths are used as-is, relative paths keep resolving against the
application directory like before. Pixels come from LoadImageFromScreen(),
so no backend internals are needed and the null backend stays a stub.
2026-08-16 22:53:01 -03:00
waozi 59e8dd103a tests: native-comparison exactness harness (stage 2)
Runs the inbe C build's --screenshot scene export and the cartridge
render at identical 480x640, pixel-compared with zero tolerance.
Needs a GL stack where LoadImageFromScreen works (CI/xvfb) or
INBE_SHOT_WINDOW + external capture; this dev box's headless X cannot
capture GL windows, so the gate runs where inbe's own screenshot
pipeline runs.
2026-08-16 22:48:05 -03:00
waozi 9d24c42f96 tests: cross-engine screenshot-exactness harness
The same cartridge must render byte-identically in every kryon
renderer: kry_sw headless vs the SDL software-renderer readback,
sha256-compared at 480x640. Covers the inbe language screen and
02_buttons; caught a stale-binary divergence on first run.
2026-08-16 22:36:04 -03:00
waozi 22f055ffd1 k2b: fix guard single-term parsing, positional ButtonProps, dropdown height
parse_term now returns consumed length (single-term guards like
'if (x == 0)' previously fell through to nothing while arithmetic
forms worked by accident). ButtonProps positional initializers
(label-first, Rectangle bounds) parse alongside the designated form.
Dropdown accepts an optional height argument.

examples/20_inbe_language.kry: a faithful declarative Inner Breeze
language-picker screen — title, bordered locale dropdown with five
options, if/else hint text, Next button — compiles to a cartridge
that renders complete in every engine with its embedded atlas.
2026-08-16 22:18:33 -03:00
waozi 2151e61414 k2b: arithmetic expressions in guard conditions
Each side of an if comparison is now term or term arith term
(path or integer, + - * /), compiled to the VM stack machine:
if (a + 1 < b - 2) emits PUSH/PUSH/ADD, PUSH/PUSH/SUB, LT, JZ.
2026-08-16 22:12:56 -03:00
waozi e9fe1e17e0 krb v2: dropdown controls
KRB_CTRL_DROPDOWN (kind 4) implemented end to end: the control record's
reserved options_off/option_count now carry consecutive NUL-terminated
option strings (k2b appends them without interning so they stay
contiguous; Dropdown(id,x,y,w,"a;b;c",&val)). Click toggles the popup,
clicking a row writes the selected index to the bound int and closes.
Loader initializes the open-dropdown slot to -1 (0 is a valid index).
2026-08-16 22:11:03 -03:00
waozi 84bd26de20 krb v2: text input — TEXTINPUT node + typed-codepoint vtable path
New node type 13: bounded field drawing the mounted CSTR with a
blinking caret when focused (click to focus). Typed input flows through
the new optional KryBackend.text_key (codepoints, 0x08 backspace):
kry_sw queues via KrySwText (drained per frame by Advance), the raylib
surface backend maps GetCharPressed, SDL maps SDL_TEXTINPUT/BACKSPACE,
krb-web exports krb_web_text from keypress events. UTF-8 runes append
and strip correctly. k2b compiles TextField(x,y,w,h,&state.field).

Verified: click-focus, typing with backspace, and that unfocused
fields ignore keys.
2026-08-16 22:06:53 -03:00
waozi cb6faf430d krb v2: scroll containers
SCROLL node (type 12): viewport bounds, content height in font_size,
mounted pixel offset at name_off. Children (parent = scroll index)
draw translated by -offset and clipped to the viewport; a new
optional KryBackend.wheel entry drives the offset when the pointer is
over the viewport, clamped to [0, content_h - h]. Implemented in
kry_sw (+KrySwWheel injection), the raylib surface backend, the null
and recorder backends; krb-sdl maps SDL_MOUSEWHEEL, krb-web exposes
krb_web_wheel from canvas wheel events. k2b compiles

  Scroll(x, y, w, h, contentH, &state.off) ... EndScroll()

bracketing child widgets (parent-linked). Fixed a compounding-offset
bug where draw_tree's origin was mutated across children.
2026-08-16 22:03:44 -03:00
waozi c1be0cb82d k2b+engines: KFA1 glyph atlas — antialiased Noto text in cartridges
- k2b bakes a per-cartridge atlas (stb_truetype over the vendored
  NotoSans) covering the cartridge's charset at its used pixel sizes,
  embeds it as the kind 1 asset '@atlas'. K2B_FONT overrides the face.
- kry_sw renders atlas text: UTF-8 decoding, per-glyph advances,
  source-over coverage blending, nearest-size scaling; measure uses
  real advance widths. KrySwSetAtlas installs it; krb-run, krb-sdl,
  and krb-web all load '@atlas' after KrbLoad.
- Cartridge cap raised 64 KiB -> 16 MiB (output buffer static) to fit
  atlases/images; krb_cartridge_test budget adjusted. Engine goldens
  regenerated (atlas advances change text layout).
- Fixed on the way: atlas record stride (18 bytes), pack buffer
  ownership, and a realloc'd-header write in the baker.

Verified: 'Ag' at 24px renders as antialiased glyphs from embedded
bytes; full krb suite green.
2026-08-16 21:59:11 -03:00
waozi 6b59bc6109 k2b: else branches and state-vs-state guard comparisons
'if (a > b) { ... } else { ... }' now compiles to compare + JZ/JMP
with true and false node ranges; the right side of a comparison can
be another mounted state path (PUSH_PATH) or an integer literal
(PUSH_CONST). Verified both branches with mounted and unmounted
state.
2026-08-16 21:46:10 -03:00
waozi ddcf455dd3 k2b: decode png/jpg/bmp/webp and embed as cartridge pixels
stb_image (vendored with raylib) decodes referenced Picture() files at
compile time; decoded RGBA8 goes in as kind 0 and renders through
texture_rgba in every engine. KRAW stays for hand-made raw pixels;
undecodable files (wav/ogg/fonts) remain opaque kind 2 blobs for
host-side unpacking. Verified: png cartridge renders after the source
file is deleted.
2026-08-16 21:42:09 -03:00
waozi 8672d9f305 style tokens: fixed-pixel corner radii, not size fractions
control_radius/panel_radius were normalized 0..0.5 fractions of the
control's size, so a token tuned for a button exploded into a full
pill on tall controls (text inputs). Tokens are now unscaled pixels,
converted per-draw via ui_radius_px() (DPI-scaled, clamped to 0.5
normalized). Material: 4px controls / 6px panels; retro/system: 2px
controls / square panels. Removed ui_control_radius(), which leaked
the mixed-unit ambiguity.
2026-08-16 21:39:08 -03:00
waozi 3b92292e19 renderers: web player opens any .krb + CI builds per-platform downloads
- krb-web is now a player: drop or pick a .krb, it writes to MEMFS
  and boots the cartridge (krb_web_start export); no preload, the
  bundle is a generic renderer. Drag-drop + file picker + canvas
  mouse with correct scaling. Serving it anywhere gives the web a
  KRB renderer.
- .github/workflows/renderers.yml: matrix builds krb-run binaries
  (linux, windows mingw cross, macos) and the web player; artifacts
  on every push, attached to releases on tags.
2026-08-16 21:37:28 -03:00
waozi 91d96a4983 k2b: embed referenced assets into the cartridge
k2b now packs what a cartridge references, making it self-contained:

- Every Picture() path resolvable under --root is embedded at emit
  time. .kraw files (KRAW magic + u16 w,h + RGBA8 pixels) go in as
  kind 0 and render through texture_rgba in every engine; any other
  file (png, wav, ogg, fonts) is embedded verbatim as a kind 2 opaque
  blob for host-side decoding via KrbAssetFind — sounds and arbitrary
  assets ride in the same section, unpackable by the application.
- The recorder backend forwards+logs texture_rgba (a NULL entry on
  the wrapper silently forced the host-path fallback).

Verified end-to-end: a cartridge whose tile.kraw is deleted after
build still renders the picture, scaled and tinted, purely from
embedded bytes (texture_rgba 2x2 -> 8x8 in the recorded stream).
2026-08-16 21:34:46 -03:00
waozi f17bc26987 krb v2: embedded asset section + texture_rgba blit
Cartridges can now carry their pictures: a v2 asset section (header
offset 28 = asset_bytes) after controls[] holds a directory of
20-byte entries (path, absolute data offset, size, kind, w, h) plus
blobs. KrbAssetFind looks paths up; a PICTURE node whose path is
embedded renders from cartridge pixels through the new optional
KryBackend.texture_rgba (nearest-neighbor scaled, tint-modulated,
clipped) — kry_sw implements it, so krb-run, krb-web, and krb-sdl all
get embedded assets. Non-embedded paths still fall back to host
texture loading. kinds: 0 raw RGBA8, 1 reserved for the glyph atlas.

tests/krb_asset_test.c proves lookup + 2x2->8x8 scaled, tinted blit
with correct bounds; spec updated in KRB_FORMAT.md. k2b embedding of
decoded image files is the follow-up.
2026-08-16 21:29:13 -03:00
waozi 12e0fa3c6b material style: subtle control rounding instead of full pills
control_radius 0.50 drew every control as a half-height-radius pill
and panel_radius 0.30 rounded large panels into blobs; dense desktop
UIs (krait) read that as bloated. 0.15/0.08 keeps a material feel.
2026-08-16 21:26:22 -03:00
waozi 6bad9e7e27 k2b: compile .kry state updates and if-guards into v2 VM programs
Cartridges stop needing host C for simple per-frame logic:

- k2b collects '<path> =/+=/-= N', '++', '--' statements from frame
  bodies and simple 'if (<path> <cmp> <int>)' guards over widget
  ranges, and emits them as VM opcodes: state updates run first, then
  one OP_DRAW_NODE per drawable node with guarded ranges wrapped in
  compare + JZ. Render-only cartridges still emit a single
  OP_DRAW_TREE (golden output unchanged).
- parse_color now understands (Color){r,g,b,a} literals everywhere
  (Rect etc.), not just in the circle parser.
- KrbExec JZ bug fixes: the jump-if-zero polarity was inverted, and a
  taken jump was clobbered by the executor epilogue. Both were masked
  by the hand-written test compiling its guard in positive form; a
  k2b-compiled cartridge exposed them.
- krb-run --frames N runs the cartridge N frames (advancing time and
  press edges) for observing state-dependent behavior headlessly.

Verified end-to-end: a .kry with counter += 1 and an if (counter < 4)
guard compiles to a 35-byte program; the guarded rect renders on
frames where the condition holds and disappears after, with the
counter mount showing 1+N.
2026-08-16 21:17:50 -03:00
waozi 81ceb3fb25 scene_inspect: set SO_REUSEADDR so quick restarts rebind 2026-08-16 21:17:30 -03:00
waozi 722aaf47fa kry_json: expose kry_json_type
The DOM had no type accessor, so callers could not distinguish a false
bool from a missing field or a 0.0 number from a non-number.
2026-08-16 21:10:35 -03:00
waozi d35b412a96 docs: KRB_FORMAT.md rewritten as an exact byte-level specification
Every record now carries explicit field offsets and sizes (header 32B,
node 28B, control 24B), section layout formulas, encoding rules
(little-endian, string references, absolute prog offsets), validation
requirements, per-node-type rendering and interaction semantics, full
VM opcode table with stack/jump rules, limits, and the host surface a
renderer must provide — enough to write an independent parser and
renderer from the document alone.
2026-08-16 21:07:52 -03:00
waozi c1054a459d scene: live JSON inspection server
SceneInspectServe/Poll/Stop: the game thread serialises its Scene into
a JSON snapshot once per frame; a socket thread serves the latest
snapshot as HTTP on 127.0.0.1:<port> so editors and curl can watch a
running app's node tree live. The socket thread never touches the
scene; only the completed snapshot buffer is swapped under a mutex.
2026-08-16 20:53:48 -03:00
waozi 89dc220fda krb v2: in-cartridge logic VM + circle/ring geometry nodes
The plan-07 core: cartridges stop being static pictures.

- New v2 opcodes: a 16-deep int stack machine (PUSH_CONST/PUSH_PATH/
  POP_STORE, ADD..GE, JMP/JZ, TIME) plus OP_DRAW_NODE so UI can be
  conditional on mounted state. Loader accepts v1 and v2; k2b now
  writes version 2.
- New node types CIRCLE (center+radius) and RING (annulus), the shapes
  the inbe breath visualizer needs; k2b parses DrawCircleV/DrawRing
  (with (Color){r,g,b,a} literals). KryBackend gains optional circle/
  ring entries — implemented in kry_sw, the raylib surface backend,
  the null backend, and forwarded+logged by the recorder.
- tests/krb_logic_test.c: hand-assembled v2 cartridge proving counter
  increments per frame, conditional node visibility across frames,
  circle/ring rasterization bounds, and TIME. Engine golden test passes
  unchanged on v2 output (render back-compat).
- KRB_FORMAT.md documents v2 and the R>=0x80 theme-slot color caveat.
2026-08-16 20:37:44 -03:00
waozi 2423b97a0c scene/property/signal/transform: drop the Kry/Kryon prefix from the public API
KryScene->Scene, KryNode->Node, KryonProperty*->Property*,
KrySignal*->Signal*, KryTransform2D->Transform2D, and the
KRY_NODE_/KRY_SCENE_/KRYON_PROPERTY_/KRY_SIGNAL_ enum and macro
families to NODE_/SCENE_/PROPERTY_/SIGNAL_. Header guards keep their
original names (internal). The lowercase kry_ module namespaces
(kry_json, kry_term, ...) and the raymath-shadowing helpers
(KryVector2*, KryClamp, KryLerp) stay prefixed: their unprefixed names
collide with the raylib API surface kryon tracks.
2026-08-16 20:35:15 -03:00
waozi afca3f5a4e scene: recycle removed node slots through a freelist
KryNodeCreate only ever grew the arena, so churn (respawning enemies,
particles) exhausted KRY_SCENE_MAX_NODES. Removed slots now chain onto a
freelist (via next_sibling, unused once detached) and create pops from
it before growing count.
2026-08-16 20:30:12 -03:00
waozi cdd60b6150 test: host default style follows the MATERIAL default
ui_tk_test still expected THEME_STYLE_RETRO after 3728aad switched the
desktop default to MATERIAL; align the expectation.
2026-08-16 20:27:52 -03:00
waozi 6f40008742 scene: application-defined node kinds with property callbacks
Kinds beyond the builtin enum can now be allocated at runtime
(KryNodeRegisterCustomKind) so games can put their own entity types
into the scene tree and the editor property model without forking
KryNodeKind. Ops/destroyers/spec tables register against the returned
id like any builtin. Custom-kind property access dispatches to
registered getter/setter callbacks; indices 0..2 stay the shared
transform fields handled generically. Kind tables are growable (cap 64)
and bounds checks use the dynamic count.
2026-08-16 20:26:47 -03:00
waozi 8952cbf3af krb-sdl: SDL2 desktop host for KRB cartridges
Plan 11 phase 7 (pulled forward as the Android-template host):
kry_sw renders, SDL2 owns window/input/presentation via a streaming
RGBA texture. --png renders one frame through the renderer and reads
it back, for headless conformance under SDL_VIDEODRIVER=dummy.

Verified: SDL software-renderer readback of examples/02_buttons.kry at
400x300 is byte-identical (sha256) to the native golden frame — native,
wasm web, and SDL now render the same image.

make krb-sdl (pkg-config sdl2; on omega PKG_CONFIG_PATH points at
~/.local/sdl2 automatically in the rule).
2026-08-16 20:23:47 -03:00
waozi 14c8223acc k2c: fix one-line control blocks, char literals, and locals named c
Three parser defects that made k2c exit 0 while emitting broken C:

1. One-line control blocks ('if cond { body }', also while/for/switch/
   case/else/guard) glued the braces into the condition. The finalized
   logical line is now split into header/body/'}' and the parts re-enter
   the main loop through a FIFO that outranks the stashed lookahead
   (whose single slot the read-ahead would otherwise overwrite, losing
   source lines). The read-ahead is also skipped for queued parts and
   while a stash is pending.
2. Char literals containing structural characters ('"', '[', ']', '{',
   '}') toggled the string/bracket scanners and swallowed following
   lines; both brace scanners now skip char literals.
3. An assignment to a local named c was classified as a raw 'c <line>'
   escape and emitted without its trailing semicolon; assignment
   operators after the c token now fall through to the normal
   statement path.
2026-08-16 20:21:40 -03:00
waozi f2e86d9f0d krb-web: native web engine — kry_sw compiled to wasm, blitted to ImageData
Plan 11 phase 3, wasm-first variant (pixel-identical to native):

- cmd/krb-web/main.c: emscripten host running the KRB runtime + kry_sw
  rasterizer; each frame blits the RGBA buffer into an ImageData via
  EM_ASM. Cartridge preloaded at /app.krb, canvas mouse events fed back
  through exported krb_web_mouse/krb_web_button.
- cmd/krb-web/shell.html: minimal shell wiring Module.canvas and input.
- cmd/krb-web/node-capture.js: pre-js for the KRB_WEB_ONESHOT node
  build; stubs a canvas 2D context and dumps the blitted frame to stdout
  so the wasm blit path is testable without a browser.
- make krb-web KRB=examples/xx.kry builds the cartridge + bundle
  (needs emcc on PATH, e.g. source ~/emsdk/emsdk_env.sh).

Verified: node oneshot capture of examples/02_buttons.kry at 800x600 is
byte-identical (sha256) to the native krb-run render; page loads and
runs in a browser.
2026-08-16 20:21:36 -03:00
waozi 17ab1e4675 system_theme web: snprintf not app copy_text 2026-08-16 20:16:06 -03:00
waozi acedfad749 system_theme: web prefers-color-scheme detection; default source SYSTEM on web
Web builds map the browser light/dark preference onto the material
palettes so 'follow system' works there too; GetDefaultPlatformThemeSource
no longer special-cases PLATFORM_WEB.
2026-08-16 20:13:41 -03:00
waozi 6a0591086a krb: kry_sw software rasterizer engine + headless conformance harness
Plan 11 phases 1-2 core:

- src/backend/kry_sw.c: portable software rasterizer behind the
  KryBackend vtable. RGBA8 target with RGB565 conversion, clip stack,
  input injection, theme slots, public-domain font8x8 text (glyph-atlas
  pipeline replaces it later without interface changes).
- src/backend/kry_backend_rec.c: recording backend that logs the
  cartridge draw-call stream while delegating to an inner engine.
- cmd/krb-run: headless cartridge runner; renders one frame to PNG
  (dependency-free writer, stored deflate) and/or dumps the call stream.
- tests: kry_sw unit test plus tests/krb_engine_test.sh golden
  conformance over examples/02_buttons.kry (sha256 goldens, refresh
  with KRB_ENGINE_REGOLDEN=1), wired into make test / make tools.
2026-08-16 20:05:20 -03:00
waozi 96a30719ba kir: 'c:' is a typed decl, not the raw-C 'c' keyword
The ':' token boundary added for 'default:' made starts_word(s, "c")
match 'c: float = ...', sending typed declarations of variables named
'c' down the raw-passthrough branch and emitting invalid C.
2026-08-16 20:03:02 -03:00
waozi 6de42cbfd8 desktop_tray: drop GTK type-cast macros - they expand to gtk_*_get_type() calls the dlopen shim does not forward 2026-08-16 19:57:23 -03:00
waozi c670587788 ksync: harden crypto, exports, JSON, delete, and sync transport
- Add shared ksync_crypto module: SHA-256, HMAC-SHA256, PBKDF2-SHA256,
  ChaCha20-Poly1305 (RFC 8439), hex helpers, random bytes; all verified
  against RFC test vectors in tests/ksync_crypto_test.c
- Encrypted account exports (v2): PBKDF2 (600k iterations) +
  ChaCha20-Poly1305, passphrase-protected import/export APIs; the v1
  plaintext format remains importable
- DeleteKsyncSyncAccount no longer transmits the private key: it signs
  a challenge against /api/v1/account/delete and falls back to the
  legacy delete-with-key endpoint on 404/405
- JSON writer escapes control characters (including \b, \f, \uXXXX);
  reader now decodes escapes, rejects substring keys and keys embedded
  in string values
- Token expiry accounts for server clock skew (server_time in the
  login response, clamped to +/-24h)
- Optional retry with exponential backoff for transport errors, 429,
  and 5xx via retry_max/retry_delay_ms/sleep_ms config fields
- Opt-in end-to-end payload encryption (encrypt_payload flag plus
  Wrap/UnwrapKsyncSyncPayload) derived from the account private key
2026-08-16 19:54:53 -03:00
waozi 62ce822082 k2c: fix braced and bare-default switch cases
Two parser gaps made switch all but unusable from Kry: (1) 'case X: {'
was not a header line, so the case body's braces were treated as
expression braces and glued onto the case text; (2) starts_word did not
accept ':' as a token boundary, so 'default:' fell through the case
classifier into the declaration branch and emitted 'default = {0}'.
Header classification now includes case/default (default may be followed
by ':'), and starts_word accepts a ':' boundary.
2026-08-16 19:52:47 -03:00
waozi 5cd9b4b119 kryon-app.sh: project.kryon target runner with default_target support 2026-08-16 19:52:41 -03:00
waozi ff6887ba83 ui_text: per-size raster tier cache (4 tiers) instead of single base raster
Single-tier scaling made every non-base size (12/14/17px UI text) a
bilinear resample of one 16px atlas, which reads as blurry. Cache up to
four exact-size rasters per font, evicting the size furthest from the
request when full; codepoint growth re-rasterizes all tiers at their own
sizes, still throttled to once per frame.
2026-08-16 19:51:47 -03:00
waozi f817374347 docs: plan 11 — renderer engines for KRB cartridges
Tier-B engines behind the KryBackend vtable: conformance harness,
kry_sw software rasterizer, web canvas, Android, ESP32, plus profiles
and the pre-baked asset pipeline.
2026-08-16 19:48:02 -03:00
waozi f32d3e21ed k2c: join multi-line initializers on '::' global declarations
A logical line like 'palettes :: [3] Pal = {' was classified as a header
line (any line containing ' :: '), so its braces counted as block braces
and the multi-line initializer never joined; the global was then dropped
from the output while references to it still compiled, producing broken
C. Header forms ('name :: struct {', function/typedef/extern
declarations) never contain ' = ', so gating the ' :: ' header rule on
the absence of ' = ' routes initializer lines through expression-brace
continuation instead.
2026-08-16 19:45:54 -03:00
waozi 3728aad465 theme: default to MATERIAL on all platforms for now 2026-08-16 19:09:24 -03:00
waozi be0a923587 system_theme: read the GTK palette straight from the theme's gtk.css when the process has no GTK 2026-08-16 19:06:37 -03:00
waozi 69067bfc9f theme: platform default source/mode helpers (system theme on desktop) 2026-08-16 18:56:16 -03:00
waozi fa70f7f54b ui_window: WIP center flag, drag/right-click/click-position queries, X11 move hook
Moved from uncommitted edits in inbe vendor/kryon so the vendored submodule stays pristine (see Projects/AGENTS.md). Work in progress; inbe breaks HUD is the consumer.
2026-08-16 17:45:15 -03:00
waozi 3a06ea6004 mem: diagnostics; ui_text: single-tier font rasters; tray: lazy GTK
- KryonMemReport/KryonMemDebugEnabled (KRYON_MEM_DEBUG) print RSS and the
glibc arena breakdown; UIFontMemoryReport prints per-font raster stats.
- Source fonts rasterize once at the DPI-scaled base size plus one lazily
built large tier, replacing the 8-slot per-size cache. New codepoints
batch into at most one rebuild per frame per font, and atlas build churn
is returned via malloc_trim on glibc.
- KRYON_TRAY_GTK_DL: GTK_STATUS_ICON tray resolves GTK via dlopen (gtk_dl
shim) so tray-less processes never map the GTK chain.
2026-08-16 17:13:46 -03:00
waozi ccec103ebc k2b: report call kinds the KRB vocabulary cannot express
A cartridge that comes out thin (inbe's pet screen: an egg widget,
locale text, Paragraphs) was silently missing everything k2b cannot
lower. The builder now tracks dropped call kinds per file and prints
one stderr line: 'k2b: <file>: N call kinds not in KRB: Paragraph x2
draw_egg x1 ...' - pet_screen.kry reports seven, which is the honest
content of the gap.
2026-08-16 07:52:09 -05:00
waozi 3eb82d33b4 site: add Discord and Telegram community links
Footer gains a Community column (Discord invite, Telegram channel) on
the landing page and the same links under Ecosystem in the API page;
the site's link list mentions them with what they're for. Landed page:
https://discord.gg/ep7gCWzHJD and https://t.me/kryonlabs_com.
2026-08-15 18:37:13 -05:00
waozi 442c868b66 widgets: PickerDialog; Spinbox value text + wrap; public ButtonRow height
- PickerDialog: the standard scrim + panel + option-rows modal with
  optional per-option icons, cancel button, outside-click/ESC dismissal;
  returns the picked option index (1-based), -1 when dismissed
- SpinboxProps gains value_text (caller-formatted display like "08:00")
  and wrap (modulo instead of clamping, for time-of-day steppers)
- GetUIButtonRowHeight is public now: the fit-or-stack row already
  measures itself, apps no longer need their own height math
2026-08-15 18:00:04 -05:00
waozi 6b9c0d2e8c ui_window: Windows/macOS compile the no-op stubs
The plain-SDL extra-window path includes SDL2/SDL.h, which the mingw
cross build does not provide, breaking the Windows release build. Gate
that branch behind UI_WINDOW_HAVE_SDL so Windows/macOS build the stubs
until their builds ship SDL.
2026-08-15 16:24:51 -05:00
waozi 9f91ae1298 guide overlay: Android back key closes the guide 2026-08-15 15:04:11 -05:00
waozi 63efd66b78 kry_term: drop downstream tool name from the feed comment (boundary check) 2026-08-15 13:18:33 -05:00
waozi 5f7fd9c615 kry_term: KryTermFeedOutput - harness text printed into the terminal
Same escape processing as polled output, so a harness can mirror its
own command output into a live terminal pane. Tested by feeding a
marker line and reading it back from the grid.
2026-08-15 13:14:38 -05:00
waozi 9353a4ec8e kry_http: streaming partial reads (kry_http_partial) + locked write callback
The write callback now appends under the request mutex so mid-flight
reads are safe, and kry_http_partial copies whatever of the body has
arrived while the transfer is still RUNNING - the transport piece for
streaming chat responses (SSE) without changing the poll model.
2026-08-15 12:38:32 -05:00
waozi 6c6c7dcaad ui_window: include stddef.h so the android/web stubs see NULL 2026-08-15 11:31:54 -05:00
waozi 2276b7372f kry_sfs: the live engine as a synthetic file system + real input injection
Everything kryon owns is now addressable and interactable through one
file-tree surface: /info, /theme tokens, /input (mouse position, buttons,
keys, text, wheel - readable and writable), and /widgets (the live
ui_inspect tree with per-widget kind/text/bounds/source plus a tap that
clicks for real).

Input injection is new underneath: kry_inject keeps a pure-state event
queue whose edges derive at each pump (raylib-style previous-vs-current),
and the generated backend wrappers consult it before platform input, so
injected events reach app code that queries GetMousePosition or
IsMouseButtonReleased directly. KryonInjectPump runs from
UpdateKeyPlatformState; injected mouse positions serve for one frame
(two for taps) so the real mouse keeps working. KryTTap/KryTType/
KryTKey in kryon_test.h now inject for real instead of recording
strings.

ui_inspect gained SetUIInspectVisible so the SFS can record the widget
tree without arming the click-stealing overlay. tests/sfs_test.c covers
listing/reading every namespace, edge semantics, tap-to-UIHandleClick,
and the KryT helpers; wired into make test (suite green).
2026-08-15 11:24:10 -05:00
waozi da646a749c ui_window: extra OS windows rendered with the regular UI widgets
OpenUIWindow/CloseUIWindow manage a window beside raylib's core window;
BeginUIWindow/EndUIWindow bracket widget drawing (offscreen texture,
UI frame, pixel blit to the OS window), IsUIWindowClicked polls its
mouse events. Flags: borderless, always-on-top, skip-taskbar, top-right
anchor with margin-based placement against the display work area.

Linux/FreeBSD drive the window through dlopen'd libX11 on a private
Display connection: a second SDL window in this process reproducibly
breaks Mesa llvmpipe (the next frame's scissor batch flush faults after
any glReadPixels), and the private connection also keeps the extra
window's events and blits out of SDL's queue. Borderless windows are
override-redirect, which covers no-decorations/taskbar/stacking for
HUD-style use. Windows/macOS keep the plain SDL surface path;
web/Android are no-ops.

KRYON_UI_WINDOW_DUMP=<path> writes the window's pixels (1 Hz) for
verification. Verified live in inbe: Workrave-style break timer HUD as
a real top-right window with live countdowns.
2026-08-15 10:04:48 -05:00
waozi 301c1e693b kt: drop the 'target ide' fork of krait
Kryon carries no krait-specific code. kt's visual runner is the kryon
app runner ('target app', default) or headless ('target none'); the ide
target exec'd the krait binary — an inverted dependency no shipped test
used. Examples README keeps its 'open in Krait' pointer: that documents
a consumer, it doesn't couple the toolkit.
2026-08-15 07:11:58 -05:00
waozi b44b946979 kryon owns the transport, not the vendor: drop kry_zai
kry_json + kry_http are provider-neutral stdlib pieces; a z.ai GLM
client (endpoint, model, key handling, wire format) is harness logic and
moved to krait (native_ai.c). inbe and other apps no longer link a
specific commercial LLM vendor.
2026-08-15 06:56:29 -05:00
waozi d01d8c702f notification/android: declare GetAndroidApp
raylib's PLATFORM_ANDROID API is not visible without the umbrella
header; declare it locally like consumers' android bridges do.
2026-08-14 22:31:12 -05:00
waozi 4622c9a374 k2c: emit '#define' constants in the generated header
'Name :: #define value' constants emitted in the .c only, but the
header's array bounds and extern declarations reference them (e.g.
extern char pending_path[ANDROID_IMPORT_PATH_MAX]), so every consumer
of the header failed to compile. Emit them in the header too, first and
under their #if guard, exactly like the .c emission.
2026-08-14 22:14:47 -05:00
waozi 86e90c248b kry_http: no-curl stub signature must match the header (const mismatch broke PLATFORM_WEB) 2026-08-14 22:13:09 -05:00
waozi 9dac516149 web present shim: take the GL context before hiding the canvas (display:none canvases cannot create contexts in some engines) 2026-08-14 22:07:28 -05:00
waozi a502700ed0 kry std: kry_json, kry_http, kry_zai — the AI-harness foundation
- kry_json: dependency-free recursive-descent parser (objects/arrays/
  strings with \u escapes + surrogate pairs, numbers, bools) and a
  compact KryJsonBuf emitter. Depth-capped against hostile input.
- kry_http: async libcurl-easy client (HAS_LIBCURL) on the existing
  KryThread worker pattern — POST-JSON/GET, poll for state, body owned
  by the request. Stub when curl is absent. file:// counts as success
  (HTTP code 0), which the hermetic tests use.
- kry_zai: z.ai GLM chat-completions client (OpenAI-compatible) on the
  two above. Coding-Plan endpoint default, glm-4.6, ZAI_API_KEY/
  ZAI_BASE_URL/ZAI_MODEL env with an in-process override; thinking
  disabled for fast answers. Live test gated on ZAI_API_KEY.
- mk/vendor.mk: KRYON_CURL_TRANSITIVE_LDLIBS (brotli/zstd) the vendored
  static curl needs at final link.
2026-08-14 22:06:36 -05:00
waozi 5a7eb4d38f web present shim: ?kryonpresent=debug forces activation and reports state via document.title 2026-08-14 22:04:48 -05:00
waozi 1982f978b1 web: kryon-web-present.js — 2D-canvas present mode for WebKitGTK+software GL
WebKitGTK's DMABUF compositor leaks ~one full-canvas buffer per
composited frame on the software-GL path (measured: bare WebGL clear
loop 50 MB/s, full app 150 MB/s, web process dead in minutes; plain 2D
putImageData presentation stays flat at 58 fps). The shim detects
WebKit-family UA + software renderer, creates the GL context on a
display:none canvas (never composited = cannot leak) handed to
Emscripten via Module.preinitializedWebGLContext, points Module.canvas
at the visible canvas (input/resize unchanged), and blits each frame
into its 2D context with fully reused buffers. No-ops on Chromium,
Firefox, and hardware-GL WebKit. Apps opt in with one script tag before
their Emscripten bootstrap.
2026-08-14 21:42:13 -05:00
waozi b8ca07feca Add cross-platform notification helpers
One raylib-style API in notification.h (SendNotification,
SendNotificationEx with tag/id/priority, CancelNotification,
CancelAllNotifications, permission probing, SetNotificationAppName),
three real backends in src/notification/notification.c:

- Android: pure JNI through the native activity -- channels on API 26+,
  legacy Builder priorities on 21-25, areNotificationsEnabled /
  POST_NOTIFICATIONS runtime request on 24+/33+. No Java-side code
  required, so any kryon app gets notifications unchanged.
- Web: the browser Notification API via EM_JS, with an id registry so
  cancel works.
- Desktop Linux: org.freedesktop.Notifications over GDBus
  (KRYON_NOTIFICATION_GDBUS + gio-2.0; mk/vendor.mk exports the probe
  flags). urgency + desktop-entry hints from the priority and app name.
- Everything else: honest stub (supported=0).

Verified: desktop path end-to-end against a live xfce Notifyd
(supported=1 send=1), stub branch syntax-clean, full kryon test suite
green.
2026-08-14 21:32:38 -05:00
waozi 577681423a kc is fully gone: CHANGELOG/docs/comments now say k2c
- k2b drops its KC_* macro aliases (56 uses) for the KIR_* names.
- CHANGELOG, plan docs, examples README, scene-source comments all say
  k2c; the removed 512-statement cap entry no longer names the dead
  KC_BODY_MAX constant.
- k2c_lower: fix '&&' within '||' precedence in the member-access skip
  and three scope_stack[scope_top++] sequence-point UBs that -Wextra
  on the Android host build surfaced.
2026-08-14 21:00:34 -05:00
waozi fdc1854acb theme_picker: switch width matches the retro toggle's content minimum
DrawUIToggleSwitch grows to (max(off,on) + 16)*2 + 6 in retro; the
picker reserved max*2 + 32, six pixels short, so the switch always
overhung the computed rect on its right edge.
2026-08-14 20:49:39 -05:00
waozi 89bbaf58c8 ui_dpi: web viewport is already CSS pixels — don't reapply devicePixelRatio
raylib's web GetWindowScaleDPI() returns window.devicePixelRatio. On the
web the app renders into CSS-pixel coordinates and the canvas backing
store already absorbs the ratio, so max()-folding it into ui_scale
double-counted density: phones (dpr ~3) got a ~3x UI on top of the
correct viewport-height ratio. The window-scale input now only applies
to native builds, where windows really are sized in physical pixels.
2026-08-14 20:37:03 -05:00
waozi 7ebedf9360 kir joiner: adjacent string literals on continuation lines join
A statement whose last token closes a string literal continued nowhere:
the trailing '"' is not a continuation operator, so every fragment of
the C adjacent-literal idiom ("..." \n "..." \n "...") was released
as its own orphan expression statement and the initializer kept only
its first fragment — SQL built that way prepared from a truncated
string and failed silently. The lookahead continuation now also joins a
line that opens a string literal when the statement so far ends with a
closing one, recomputed per joined fragment so chains work.
2026-08-14 19:53:41 -05:00
waozi 807e3fde58 kir joiner: '} #else_if COND {' region chains complete as statements
A chained region closer starts with '}', so the header-line word scan
saw nothing and the trailing '{' counted as an expression brace: the
line kept joining until braces balanced, swallowing the whole branch —
data_root's #if WEB/#else_if ANDROID/#else_if WIN32/#else chain lowered
to just the first region with no #endif, leaving desktop builds with an
empty data root and silently dead storage. Region braces after a '}' now
count as block braces (both FUNCTION-mode lowering and TOP-mode frames
already accept the optional leading '}'). Syntax test covers a full
chain: every branch, the expanded conditions, and the #endif.
2026-08-14 17:59:46 -05:00
waozi 412ee357cd kry_signal.h: last kc comment says k2c 2026-08-14 17:09:14 -05:00
waozi e2df69c01b Remove the last kc remnants
- docs/KC_PARSER_PLAN.md: the pre-split kc parser plan — the parser it
  describes is deleted; the shipped architecture (kir frontend, k2c/k2b
  backends) lives in the sources.
- stale build/*/bin/kc binaries from before the rename.
- Comments/variable names still saying 'kc' in scene_tree.h,
  kry_animation.h, kryon-preview, k2b, krait's GNUmakefile/native_krb.c.
  CHANGELOG history entries keep the name each release actually shipped
  with.
2026-08-14 17:05:04 -05:00
waozi 058c277359 k2c: #private functions are file-static with forward prototypes
Legacy rule restored: non-public functions emit 'static
KRYON_PRIVATE_UNUSED' definitions with no header prototype, so two
modules can each define their own #private 'finish' without a link
collision. Forward static prototypes precede globals/state/functions
because initializers reference private functions ('.is_active =
practice_whm_is_active') before their definition.
2026-08-14 16:49:27 -05:00
waozi 9f6bf22b33 k2c: resolve bare function references passed as call arguments
('set_cb(name)' / 'f(a, name)'), and grow LOWER_TEXT_MAX with
KIR_TEXT_MAX so long initializers stop truncating mid-identifier.
2026-08-14 16:49:27 -05:00
waozi d5473a3233 k2c: guard statements, array params, alias-call stem matching, init rewrites
- 'guard cond' lowers to if(cond) { defers; return; } (legacy rule).
- '[N] T name' parameters emit C declarator order.
- Cross-module alias calls match the import's file-path target against
  the module source stem too — inbe imports name file paths
  ('src/screens/settings/settings_theme'), not dotted module names.
- Global initializers pass through rewrite_body2 (nil -> NULL, local
  function-name resolution) and KIR_TEXT_MAX grew to 4096 so joined
  multi-element initializers stop truncating mid-list.
2026-08-14 16:49:25 -05:00
waozi 76b21a607e kir joiner + k2c name-resolution fixes
- A trailing ':' (open ternary) continues the statement, matching the
  existing leading-':' rule — multi-line ternaries now join.
- A pending that is just '{' is a scope-open, not a compound-literal
  brace: the whole following block used to join into one statement
  ('{ labels: [7] const char* = {...} slot_w := ... for {...}').
- k2c bare-reference resolution never fires for 'name->'/'name.'
  accesses: 'habits->count' resolved the screen name 'habits' into
  'habits_kry_draw' whenever a module had a screen of that name.
2026-08-14 16:48:52 -05:00
waozi 1b9c9e4ed5 kir joiner: three continuation bugs
- The lookahead read raw fgets lines, so an appended continuation
  carried its newline into the joined statement text (ternary assigns
  emitted with an embedded '\n }').
- After appending a lookahead continuation the loop re-read the next
  physical line and appended it before re-deciding, swallowing the
  block-closing '}'. The lookahead now loops in place and stashes the
  first non-continuation line.
- Blank lookahead lines did not increment line_no, so every span after
  a blank under-counted (source line 9 reported as 7).
- Keyword headers require a following ' '/'('/'{': 'app->x = (T){...}'
  was treated as an app-block header, so its compound-literal brace
  counted as a block brace and the literal lost its closing '}'.
2026-08-14 16:48:52 -05:00
waozi 763adefcc2 kir: compute the body '#if' kind once — parse_cond_start strips the
trailing '{' in place, so the second parse in the emission branch saw no
brace and every body '#if' lowered to '#elif'.
2026-08-14 16:48:52 -05:00
waozi dc811b61c0 kir+k2c: '#if' regions lower to C preprocessor conditionals
Ports the legacy compile-conditional model onto Kir instead of skipping
unevaluated regions (which dropped '#if !WEB' desktop code inbe needs):

- kir_parse tracks a frame stack: '#if COND {', '} #else_if COND {',
  '#else'. Conditions expand through 'Name :: expr' constants ('WEB ::
  #defined(PLATFORM_WEB)' -> 'defined(PLATFORM_WEB)', '#defined' ->
  'defined'); unknown identifiers stay for the C preprocessor.
- Top-level captures inside a region are stamped with the combined
  guard (new 'guard' field on KirImport/KirGlobal/KirType/KirStateField/
  KirFunction); k2c wraps every stamped item in '#if cond / #endif' in
  both .h and .c. Body-level regions lower to raw #if/#elif/#else/
  #endif statements with their braces consumed.
- 'static'/'#private' globals no longer emit a header extern; the .c
  definition carries the 'static' prefix.
- 'name :: Type = init #global' splits type/init at ' = ' (the type
  previously swallowed the initializer); '#private' ::-globals capture
  as internal-linkage statics.
- Header emission order fixed: named enums and structs now precede the
  extern globals referencing them.
2026-08-14 16:48:52 -05:00
waozi f9cd8b2353 tests: default tool paths to the canonical per-platform bin dir
The standalone defaults still pointed at the removed legacy build/bin
aliases. Default to the current platform's build/<plat>-<arch>/bin
first, then any platform dir; the Makefile still passes $(K2C) etc.
explicitly.
2026-08-14 14:56:43 -05:00
waozi b81a2bdb72 k2c: array-typed parameters emit C syntax ('T name[N]')
'out_hex: [65] char' lowered as '[65] char out_hex' -- invalid C. Run the
parameter type through split_array_type like globals and fields, so it
emits 'char out_hex[65]'.
2026-08-14 14:47:57 -05:00
waozi db8ae1486e kir: parse K&R '} else {' as close + else re-open
The line-leading word scan saw only '}', so '} else {' failed the
header-line test: its trailing '{' counted as an expression brace and
the tokenizer kept accumulating until braces balanced, merging the else
and its whole body into one BLOCK_CLOSE. Even split correctly, FUNCTION
mode routed any '}'-leading line to a plain BLOCK_CLOSE, dropping the
else the k2c lowering expects as an IF starting with "else". Emit
BLOCK_CLOSE + IF("else ...") with net-zero depth, and teach the brace
classifier that '} else' braces are block braces. Allman else on its own
line already worked (and stays covered); k2c_syntax_test now covers the
K&R form whose else branches used to vanish silently.
2026-08-14 14:27:30 -05:00
waozi 3abe06995c vendor.mk: fix K2C path export (make ate the sed $ anchors)
The platform-mapping sed used $ regex anchors, which make expands as
variables -- KRYON_BUILD_PLATFORM came out empty and consumers got
build/-x86_64/bin/k2c. Rewrite with tr + anchor-free sed.
2026-08-14 14:14:05 -05:00
waozi 37d1443a2d Remove legacy build/bin tool aliases; export canonical K2C for consumers
The LEGACY_K2C/K2IR/K2B/KT/KRYON_CMD rules copied the per-platform
build/<platform>-<arch>/bin tools to the old top-level build/bin paths.
inbe and uku hardcoded those legacy paths, which is the only reason the
aliases existed.

- mk/vendor.mk now exports the canonical tool paths (KRYON_TOOLS_BIN,
  K2C) using the same platform/arch mapping kryon itself uses, so
  consumers include one file instead of hardcoding paths.
- New phony 'k2c' target builds the compiler by name; consumers call
  'make -C  k2c'.
- Legacy alias variables and rules deleted.
2026-08-14 14:12:41 -05:00
waozi 501402bd71 kir: the '#if' region skip runs before import capture
The import branch was earlier in the dispatch than the conditional-skip
branch, so imports inside '#if MACRO {' blocks were captured anyway. Move
the skip to the top of the TOP-mode chain.
2026-08-14 14:07:03 -05:00
waozi 6db6f02b66 kir+k2c: top-level 'static name: T = init' globals; skip captures in unevaluated '#if MACRO {' blocks
'static tracks: [N] const T = {...}' (multi-line initializers arrive
joined) captures as an internal-linkage KirGlobal (KirModuleAddStatic) —
emitted with the 'static' prefix instead of extern. Top-level '#if MACRO {'
regions can't be resolved without build defines; like legacy's
undefined-macro-false case, their imports/globals are not captured (brace
tracked).
2026-08-14 14:02:41 -05:00
waozi aa27c7e07a kir+k2c: capture the 'args' header directive; C-style params pass through
'args <decl>' inside a screen ('args InbeApp *app') appends parameters to
the function signature (colon screens only, top level of the body).
convert_args now emits colon-less parts as-is (C-style 'InbeApp *app')
instead of dropping them.
2026-08-14 13:54:07 -05:00
waozi 44e969d284 kir+k2c: '#private' imports include in the .c only
required=0 marks '#import ... #private'; the header skips them and the
.c preamble includes them (implementation-only headers).
2026-08-14 13:39:28 -05:00
waozi 6db4f0eebc kir: ':=' classifies as DECL before the raw-'c' escape hatch
A variable named 'c' ('c := expr') was misclassified as raw C. ':=' wins.
2026-08-14 13:30:47 -05:00
waozi 3f4ee655b8 kir+k2c: named enums ('Name :: enum { ... }' -> typedef enum)
Parser captures ':: enum' bodies like structs (is_enum flag); lowering
emits 'typedef enum {...} Name;' with comma-terminated members.
2026-08-14 13:25:39 -05:00
waozi 274d68b9e2 k2c: angled includes stay angled; extension-less header imports append .h 2026-08-14 13:17:25 -05:00
waozi ba73453d6d k2c_project: drop IDE name from comment (boundary rule) 2026-08-14 13:07:47 -05:00
waozi 15d1247b23 k2c: emit kryon_project.h/.c (app-host ABI) + main() from Kir
k2c_write_project runs after all files lower: kryon_project.h includes
every generated header; kryon_project.c auto-collects routes from public
screen-keyword functions (screen/preview/page/frame/scene/fn — the legacy
exact_name rule: colon helpers stay public-but-unrouted), emits
per-route wrappers dispatching on Rectangle/app-pointer/void args, the
route table, and CreateAppHost/DestroyAppHost over the weak
CreateApp/DestroyApp/ApplyRoute/BeginScreenDraw hooks. main() appends to
kryon_project.c from KirAppMeta (InitWindow/SetTargetFPS/InitUI/theme/
init-frame-shutdown hooks) unless --no-main.

Verified: a frame-app fixture emits a compiling project (main + route +
host ABI); the full krait corpus still compiles clean; make test green.
2026-08-14 13:04:54 -05:00
waozi e41e5bceaf k2b: migrate to the shared Kir frontend — one frontend, two backends
k2b drops its private raw-.kry parser (k2b_parse.c + k2b.h deleted). It now
parses via kir_parse_file() — the SAME frontend k2c uses — and lowers
KirModule to .krb + C host:
- collect_state consumes structured KirStateField {name,type,init} directly
  (the decl-string re-parsing is gone); array types convert to C declarator
  order in the emitted host globals.
- collect_widgets tracks block depth on the fly (KirStmt has no depth field)
  for button-handler capture.
- app metadata comes from KirAppMeta; module/no_main flow through params.
- Makefile: k2b links kir.c + kir_parse.c.

Verified: 02_buttons.kry -> 12 nodes, magic 4b524200 (identical output);
krb_cartridge_test + make test green; kryon-preview cartridge renders.
2026-08-14 09:24:09 -05:00
waozi 2748599ba2 k2c: #global variables have external linkage; header order typedefs->enums->globals->structs
Globals emit without 'static' and get 'extern' declarations in the header
(krait's main.c references istate). Emission order fixed so enum constants
used as global array sizes are declared first.
2026-08-14 09:02:45 -05:00
waozi e6e40d68be k2c: colon functions keep their bare C names; bare-ref resolution only in assignment-RHS
Legacy naming restored: 'Name :: (...) {' functions get the module prefix
but NO _kry_draw suffix (screens keep it) — krait's module.kry references
these exact names. Bare identifier resolution now fires only in '= name'
assignment-RHS position, so locals shadowing function names (strlen(name))
are never rewritten. All 9 krait .kry files (ide/* + modules/kryon) now
compile with zero errors through the pure Kir pipeline.
2026-08-14 08:55:15 -05:00
waozi af3936f684 k2c: don't rewrite member-access calls (x->fn(...) / x.fn(...))
Only bare identifiers followed by '(' resolve to module function C names;
field calls through '->' or '.' stay as-is (function-pointer typedef
fields like ModuleState.file_syntax).
2026-08-14 08:46:48 -05:00
waozi 21e263c521 k2c: krait's full IDE corpus compiles — all 8 generated files, zero errors
- Typed-decl classification requires an identifier LHS (ternary fragments
  like '1 : 0' no longer misclassify as decls).
- Ternary else-branches (': value' leading lines) join via one-line
  read-ahead (lookahead stash).
- Typed decls convert array types to C declarator order with alias-stripped
  bases (temp buffers, no src==dst snprintf UB).

krait ide/*.kry -> C now syntax-checks clean across state/app/editor/
widgets/preview/console/problems/start_page. kryon make test green.
2026-08-14 08:43:18 -05:00
waozi a7197d7f48 k2c: emit #extern prototypes with alias-stripped args
Extern imports emit C prototypes parsed from their signature, converting
args through the real module (aliases resolve).
2026-08-14 08:33:47 -05:00
waozi 9f470e6a94 kir+k2c: typedefs with names, enum commas, type emission order, ternary/&& joins
- '#type' lines build real C declarators (name inserted after '(*' for
  function pointers) and are matched BEFORE the struct '::' catch-all that
  silently swallowed them.
- Enum members emitted with commas (newline-separated .kry members).
- Header emits typedefs, then enums, then structs (structs reference both).
- Ternary '?' and '&&'/'||' line continuations; pointer types ('char*') and
  '<header.h>' closes no longer join.
- Global array sizes strip interior aliases via the body rewriter
  ('[state.MAX]' -> '[MAX]').
2026-08-14 08:28:59 -05:00
waozi e491d932de kir+k2c: '#type' typedefs; angle-bracket includes don't join
'Name :: C-type #type' is captured as a #typedef KirType and emitted as
'typedef C-type;'. The '>' closing '#import <header.h>' no longer triggers
the operator continuation (space required before < and > too).
2026-08-14 08:06:21 -05:00
waozi 567245d415 kir: enum constants joined by comma-continuation close their enum
The operator continuation joins 'A, B, C, }' into one line; ENUM mode now
strips the trailing '}' and returns instead of waiting for a lone brace.
2026-08-14 08:01:22 -05:00
waozi b4469c12ba kir: fix duplicate anonymous enum (use int for enum_return) 2026-08-14 07:58:42 -05:00
waozi 895078118b kir: pointer types don't continue lines; #enum nests inside structs
'char*' ending a field line no longer joins the next line (trailing +,-,*,&
require a preceding space to be a continuation operator). #enum inside a
struct body is captured as its own enum and returns to the struct (mode
stack via enum_return).
2026-08-14 07:56:30 -05:00
waozi a25d72b15e kir+k2c: join operator continuations; alias-strip array sizes
Lines ending in a binary operator (&&, ||, +, -, *, /, %, =, <, >, comma)
now continue onto the next line (legacy line_needs_continuation), so
multi-line if conditions stay one statement. ++/-- are excluded. Global
array sizes with alias qualifiers (state.IDE_MAX_PANE_TABS) are stripped.
2026-08-14 07:53:44 -05:00
waozi ebd2d35d4a k2c: cross-module call resolution via a whole-program symbol table
main now parses ALL inputs first (two passes), builds a per-module symbol
table (module slash-path + every function's .kry -> C name), then lowers
with it. alias.fn( calls resolve through the import target's module table
(start.draw_start_page(...) -> ide_start_page_draw_start_page_kry_draw(...));
same-module bare calls still resolve locally.
2026-08-14 07:50:06 -05:00
waozi e32ca8414a kir: '#'-directive lines are header lines (never join their braces)
'#enum {' starts with '#', so the first-word check found no keyword and its
'{' counted as an expression brace — the whole enum joined into one line and
was dropped. Any '#' prefixed logical line is now a header line.
2026-08-14 07:43:37 -05:00
waozi ef34928096 kir: join multi-line compound literals (expression braces)
The joiner only tracked ()/[] depth, so 'content := (Rectangle){ 0, ... }'
split at the '{' (paren depth 0) and the initializer lines became orphaned
statements. Now depth-0 braces on a logical line are classified: block
braces on control/header lines (if/else/while/for/switch/screen/:: /struct/
enum/state/app) end the line; expression braces elsewhere continue the join.
Compound-literal initializers now arrive as one statement.
2026-08-14 07:40:40 -05:00
waozi 4376871a38 k2c: resolve module-local function calls to their full C names
rewrite_body now rewrites bare calls ('draw_pane_group(...)') to the
module-prefixed C name ('ide_app_draw_pane_group_kry_draw(...)') when the
identifier names a function in the same module — the rewrite_kry_expr alias
rule.
2026-08-14 07:37:04 -05:00
waozi 4ab5b277aa kir+k2c: fix UB alias-strip (src==dst snprintf), emit #enum blocks
strip_alias_type(src==dst) is UB via snprintf overlap — it emptied every
struct field type ('left_width;' with no type). Route through a temp.
#enum { A, B } blocks are captured (ENUM mode) and emitted as C enums.
2026-08-14 07:34:55 -05:00
waozi 481913395f kir+k2c: struct fields converted to C declarators; '#' comments skipped in bodies
Struct fields ('name: [N] Type') now emit 'Type name[N];' with alias
stripping, instead of verbatim .kry text. '#' comment lines inside struct
and function bodies are skipped (directives are top-level only).
2026-08-14 07:30:19 -05:00
waozi edc6cb6269 kir+k2c: fix block-brace depth tracking + alias rewrite in body statements
Brace tracking: depth now counts NET braces at paren/bracket depth 0 only —
compound-literal braces inside calls (e.g. (Props){...}) no longer
mis-increment block depth, which previously ended function bodies early and
swallowed following top-level definitions.

Body rewrite: rewrite_nil became rewrite_body(m, ...) which additionally
strips 'alias.' qualifiers from identifiers when the alias is a module
import (state.IDE_PANE_LEFT -> IDE_PANE_LEFT), matching legacy
rewrite_kry_expr's alias rule.
2026-08-14 07:25:20 -05:00
waozi 90b6f7660d kir+k2c: struct types (Name :: struct), return types stop at '{'
KirType captures the struct body verbatim (TYPE mode in the parser); the
lowering emits typedef struct {...} Name; in the header. Return-type
extraction no longer swallows the opening brace of the function body.
2026-08-14 07:17:06 -05:00
waozi 2d43dd2f47 k2c: emit #include for module imports (alias :: #import "path" -> #include "path.h") 2026-08-14 07:12:54 -05:00
waozi 7c8b79f151 kir+k2c: return types, #extern prototypes, #global vars, module prefixes, alias stripping
Frontend (kir_parse.c): extract '-> T' return types from function headers;
capture #extern (body-less prototypes stay TOP-mode); capture
'name :: Type #global' module globals (KirGlobal in kir.h/kir.c).

Lowering (k2c_lower.c): functions named <module>_<name>_kry_draw (module
dots->underscores); return types in prototypes + definitions; #extern
emitted as prototypes only; #global emitted as statics; alias-qualified
types ('st: state.IdeState*') stripped to bare C types when the alias is a
module import of the same module.

Verified: k2c_syntax_test green; k2ir shows module imports captured.
2026-08-14 07:11:27 -05:00
waozi 07222de4f8 k2c: Kir is the only pipeline — delete the entire legacy compiler
The legacy kc line-matcher is gone. k2c is now exclusively:
  .kry -> kir_parse_file() -> KirProgram -> k2c_lower() -> .c/.h

Deleted (the whole legacy pipeline):
- cmd/k2c/kc.c (parse_kry line-matcher, 3300 lines)
- kc_codegen.c (write_generated/write_body_line), kc_defer.c (apply_defers
  brace-counting splice), kc_ast.{c,h} (Phase-1 AST reconstruction),
- kc_ir.c, kc_resolve.c, kc_macros.c, kc_diag.c, kc_project.c, kc_util.c,
- kc_internal.h, and the --emit/--dump-ast/--kir flags.

New k2c main.c is a thin CLI over kir_parse_file + k2c_lower. The lowering
implements the essential translation rules on Kir statements:
- ':=' decls -> __auto_type; typed decls -> 'T x = e;' with {0} zero-init
- multi-assign temps (__kryon_assign_<line>_<k>, temps-first ordering)
- nil -> NULL rewrite; unused X -> (void)X;
- if/else-if/else chains with parens + close-suppression before else
- while/for/switch headers with parens; case at parent indent
- defer registered per scope, spliced LIFO at block close and return
- call statements wrapped in PushUIInspectSource/PopUIInspectSource with
  source spans; goto/labels; state fields with C array declarator order
- screens named <Name>_kry_draw; args 'name: Type' -> 'Type name';
  header guards K_<PATH>_H with _H suffix

tests/k2c_syntax_test.sh rewritten for the Kir-based output (fixture +
assertions + compile check of the generated C). make test green.
2026-08-14 06:59:58 -05:00
waozi 44fe2fcbfe k2c --kir: PushUIInspectSource wrapping for call statements + ui_inspect.h include
Call statements (EXPR kind with a '(' token) now get Push/Pop wrapping using
the KirStmt's source span (path:line). This is the first byte-identity detail
toward matching kc's output. Also adds #include "ui_inspect.h" to the
generated .c preamble.

Example output:
    PushUIInspectSource("test.kry", 4);
    Background(GetThemeBackground());
    PopUIInspectSource();

make test green. Next byte-identity steps: __auto_type for ':=' decls,
function naming (_kry_draw), rewrite_kry_expr (nil->NULL), indent recompute.
2026-08-13 22:29:32 -05:00
waozi 1c5ad13152 k2c: Kir→C lowering skeleton (--kir flag, structurally valid output)
Stage 2 start: k2c now has a --kir flag that parses .kry via the shared
kir_parse_file frontend and lowers KirProgram to .c/.h via k2c_lower.c.

The lowering currently produces structurally valid C (function definitions,
body statements, header guards, includes) but does NOT yet reproduce kc's
byte-for-byte output (PushUIInspectSource wrapping, __auto_type temps, defer
splicing, indent recompute, rewrite_kry_expr, module prefixing). Those land
fixture-by-fixture against the k2c_syntax_test.sh oracle.

The legacy pipeline (parse_kry + write_generated) remains the default path.
k2c links kir.c + kir_parse.c; make test green.
2026-08-13 22:18:22 -05:00
waozi 69eb7b3629 Extract Kir parser into shared kir_parse.c (prerequisite for k2c/k2b backends)
The .kry -> Kir parser is now a shared library (cmd/kir/kir_parse.c +
kir_parse.h) exposing kir_parse_file(path, root) -> KirProgram*. Both k2c
(the C backend) and k2b (the krb backend) can link it to share one frontend.

k2ir/main.c is now a thin wrapper: parse + KirProgramDump to a .kir file.
The output path uses the module's source_path to preserve directory structure.

k2ir_test passes; make test green. The k2c backend (Stage 2) can now link
kir_parse.c to get Kir input.
2026-08-13 22:07:11 -05:00
waozi 02c07c823e k2ir: parse app{} metadata (title/size/fps/theme/frame/init/scene/shutdown)
Add KirAppMeta to KirModule (has_app, title, dimensions, fps, theme,
dark_mode, font_examples, frame/init/scene/shutdown hooks). The k2ir frontend
gains an APP mode that parses the app{} block's properties, and the dump
prints the metadata. This is needed by the future k2c backend to generate
main() (hook-driven / scene-tree / single-screen variants).
2026-08-13 21:57:34 -05:00
waozi 5829318c66 k2ir: multi-line statement joining (paren/bracket/string depth tracking)
The k2ir frontend now joins physical lines into logical lines while ()/[]
depth > 0 or a string is open, so multi-line widget calls like
  Button((ButtonProps){
    .bounds = ...,
    .label = ...,
  })
become one classified statement. Braces at paren depth 0 are NOT join
triggers (block openers end the line). A pending buffer accumulates, a
static copy is dispatched, and pending is reset before the dispatch (so
mode-dispatch 'continue' paths are safe).

Also: classify mutations (count++) as EXPR not UNKNOWN, and initialize the
pending buffer (was uninitialized — strncat found garbage null bytes).

Verified: k2ir test passes; multi-line Button calls join correctly; make test
green.
2026-08-13 20:56:22 -05:00
waozi 56e10300ae k2ir: classify mutations (count++) as EXPR not UNKNOWN
The classify_stmt heuristic missed bare mutations like 'count++' / 'count--'
(no ':=', '=', or '(' tokens). Extend the EXPR match to include '+'/'-' so
post/pre-increment classify correctly. The k2ir frontend still needs
multi-line statement joining for real-world .kry (the next increment).
2026-08-13 20:29:39 -05:00
waozi 2f11e1e773 Rename kc to k2c (kry-to-C compiler)
The .kry->C compiler is now k2c, not kc. This is the first step toward making
Kir the single source of truth (k2c and k2b will both lower from Kir).

- cmd/kc/ -> cmd/k2c/ (directory moved; internal file names unchanged).
- Makefile: KC -> K2C, LEGACY_KC -> LEGACY_K2C, build/bin/kc -> build/bin/k2c.
- tests/kc_syntax_test.sh -> tests/k2c_syntax_test.sh (default binary updated).
- examples/Makefile: KC -> K2C; the two stale --emit-krb lines now use k2b.
- make test green (k2c_syntax_test passes via k2c).
2026-08-13 20:09:53 -05:00
waozi 50a7479148 Archive libkryon.a under the platform-tagged build dir
LIB was a top-level (non-platform-tagged) archive, so in a tree shared
between FreeBSD and Linux the last OS to build won and the other side's
link pulled in foreign-libc objects. Archive it at $(BUILD_DIR)/libkryon.a
(build/$(platform)-$(arch)/libkryon.a), matching how the per-object files
and the raylib/box2d/curl archives are already laid out. Update examples/
Makefile to derive the host platform the same way and link against the
tagged path.
2026-08-13 15:05:58 -05:00
waozi ca90d232ed Improve site text readability 2026-08-13 13:31:46 -03:00
waozi d1d6c7a6ec Add Kryon browser IDE 2026-08-13 13:16:14 -03:00
waozi c2ea589251 Improve Kryon site button contrast 2026-08-13 12:25:44 -03:00
waozi ef5d313e16 Fix CI links and platform icons 2026-08-13 12:12:34 -03:00
waozi a1a5f13e3e Guard KryScenePhysicsDestroy call so physics-off builds link
KrySceneDestroy() in scene_tree.c called KryScenePhysicsDestroy()
directly, but that function lives in physics_world.c -- one of the
sources filtered out when KRYON_WITH_PHYSICS=0. The step path already
avoided the hard dependency via a function pointer; the destroy call
did not, so UI-only builds (inbe) that drop box2d hit an undefined
reference under linkers that don't gc-collect the unreferenced
KrySceneDestroy (mingw static link). Guard the call with the existing
KRYON_WITH_PHYSICS flag.
2026-08-13 10:12:55 -05:00
waozi 4f0d1874cc Teach k2ir about imports and externs 2026-08-13 11:38:58 -03:00
waozi c89e034ef4 Add k2ir tool scaffold 2026-08-13 11:31:30 -03:00
waozi b3910fa403 Add initial KIR core 2026-08-13 11:17:39 -03:00
waozi d84db61262 Document KIR compiler roadmap 2026-08-13 10:36:32 -03:00
waozi cf0f2b57db Fix per-codepoint font fallback switching typefaces for covered glyphs
RegisterUIFontSource baked a static, immutable glyph atlas
(dynamic_codepoints hardcoded 0) even though it retains the raw font
bytes, so any codepoint not in the initial set fell through
font_for_codepoint() to a different registered font -- the visible
'different broken font' for characters like ae oe ue ss when the active
locale's pre-baked set omitted them.

Source fonts now always set dynamic_codepoints=1: any glyph the file
contains renders in the font's own typeface, and the cross-font fallback
fires only for scripts genuinely absent from the active file. When no
codepoint set is passed, seed ui_font_codepoints() (ASCII + Latin +
Latin Extended + punctuation + currency + Greek + Cyrillic) so common
scripts render with no first-frame atlas rebuild.

Also fix a latent masquerade: raylib LoadFontFromMemory returns
GetFontDefault() on failure (.ttc, corrupt), which font_valid()
accepted, so failed sources polluted the fallback chain as the raylib
ASCII bitmap. A result sharing the default font's texture id is now
treated as failure, and a failed registration clears its slot.

RegisterUIFontFileSource's dynamic_codepoints parameter is now
redundant (source fonts are always dynamic) and is dropped; callers
migrated separately. RegisterUIFont (pre-baked Font handle, no source
bytes) stays static by necessity.
2026-08-13 08:16:04 -05:00
waozi 2005611f2b k2b: standalone .kry->.krb compiler, fully independent of kc
Split the cartridge compiler out of kc into its own CLI, k2b. kc is now
purely .kry -> .c; k2b is .kry -> .krb and links no kc code.

cmd/k2b/ (new):
- k2b_parse.c: a raw-.kry reader (state{} / app{} / screen|frame|fn|Name ::
  function bodies) with multi-line statement joining (paren/bracket/string
  depth, so widget calls join but block braces don't) and statement
  classification + depth for button-handler capture.
- k2b_krb.c: the cartridge codegen moved out of kc_krb.c, adapted to the new
  parser: extract_call() locates the widget call in bare / 'if Widget(...)' /
  'x := Widget(...)' forms, and collect_widgets captures button handlers from
  the 'if Button(...) {' statement directly.
- k2b_util.c + main.c: self-contained path/string utils + CLI entry.

kc cleanup: drop --emit-krb + write_krb (kc.c, kc_internal.h), delete
kc_krb.c. Makefile gains a K2B target (and legacy build/bin/k2b); the cartridge
test and kryon-preview cartridge use k2b.

Faithful: 02_buttons matches kc exactly (12 nodes, 3 imports); 03_theme
additionally captures two real Button calls kc had been missing. make test
green; kryon-preview cartridge renders via k2b.
2026-08-13 08:04:50 -05:00
waozi 115a104457 krb: controls[] section + range widgets (Slider, VerticalSlider, Spinbox)
Add a controls[] table to the format for interactive widgets whose args don't
fit the 28-byte node. The header's reserved field becomes control_count
(backward compatible: old files have 0 -> no section). Each 24-byte KrbControl
record carries kind/id/min/max/step + value_off/label_off/options_off; a
KRB_NODE_CONTROL (9) node references it by bind_slot.

Range widgets bind a state{} field (value_off), render with KryBackend
primitives, and update the value on interaction:
- Slider / VerticalSlider: a held drag sets the value across [min,max].
- Spinbox: a click steps by 'step' (clamped), left half down / right half up.

The cartridge owns the value (read/write via the mount), like Checkbox/Toggle.
Dropdown/Combobox (need a state-array option parser) and by-value Radio/TabBar
remain deferred.

Verified: 03_theme.kry emits a Slider as a CONTROL node + control record;
krb_mount_test builds a SLIDER cartridge and asserts a drag sets 0->80 (and a
no-drag frame leaves it); make test green. KRB_FORMAT.md documents the
controls[] section and the CONTROL node.
2026-08-13 06:50:14 -05:00
waozi 0397d5e6c1 krb: interactive Checkbox + Toggle widgets (value-bound, self-contained toggle)
Add the first interactive cartridge widgets. CHECKBOX (7) and TOGGLE (8) bind
to a state{} field by name (the widget's &val arg -> name_off), render with
KryBackend primitives (box outline + check / track + thumb + label), and on an
in-bounds mouse press flip the value back through the mount. The cartridge
owns the toggle (no host handler, unlike BUTTON) — the host just reads the
resulting state. Only state{} fields bind (what the host mounts).

These two fit the existing 28-byte node (path/label/id map to spare fields);
range/options widgets (Slider/Spinbox/Dropdown/Combobox) and by-value widgets
(Radio/TabBar) need a controls[] args section and are deferred.

Verified: krb_mount_test builds a CHECKBOX, mounts a value, and asserts an
in-bounds press flips 0->1 (and no-press leaves it); the cartridge frame
fixture now carries a Checkbox and asserts its value path lands in the string
table; make test green.
2026-08-13 06:27:36 -05:00
waozi 2b9e54f128 krb compiler: widen widget coverage (color literals, Line/Separator/Bevel/TextInRect, Picture)
The .kry->.krb slice only captured Background/Text/Rect/Button and collapsed
every non-theme color to opaque black. Broaden it:

- parse_color now understands hex (0xRRGGBBAA / 0xRRGGBB) and the raylib color
  sentinels (WHITE/BLACK/BLANK/RED/GREEN/BLUE/...), not just theme getters.
- New parsers map static widgets onto existing node types: Separator (themed
  rail RECT), Line (axis-aligned bounding RECT), Bevel (light-face RECT),
  TextInRect (TEXT). A shared node_rect() helper parses (Rectangle){...}.
- Picture becomes a first-class node type KRB_NODE_PICTURE=6 (additive; old
  loaders hit default:break). text_off carries the asset path, color the tint,
  style the UIPictureFit. KryBackend gains a texture() entry (implemented via
  KryLoadPictureTexture + KryPictureFitRect in the raylib backend, no-op in the
  null backend), and draw_node renders it. A depth-aware find_match_brace() is
  needed because PictureProps nests Rectangle/Vector2 braces.

Interactive stateful widgets (Slider/Toggle/Checkbox/TextField/Dropdown/etc.)
are deferred: they need host-side state + event capture. Verified: 19_pictures
compiles to 2 PICTURE nodes and kryon-preview cartridge renders the real
textures; all krait samples still compile; make test green.
2026-08-13 06:04:55 -05:00
waozi 455d20a554 kc: parse top-level 'frame NAME {}' as a hook function definition
kc only knew 'frame' as a property inside app{} (setting file->app_frame).
A top-level 'frame main {}' definition — used by hook-driven apps and by
krait's newer samples — hit 'unknown top-level statement'. Add 'frame' to the
top-level function-definition dispatch (alongside screen/preview/page/scene/fn)
and set exact_name on the resulting function so app_hook_c_name resolves it to
the C symbol the generated main() calls each loop.

The codegen that calls the frame hook already existed (write_app_main); this
just lets the definition parse. Verified: all 6 krait samples now compile to
.krb (was 2/6); the generated main() resolves and calls <module>_main.
krb_cartridge_test gains a frame main {} fixture.
2026-08-13 05:45:56 -05:00
waozi a242ab5263 scene_property.h: refer to "an IDE inspector" instead of naming Krait
Kryon's library headers should stay IDE-agnostic; the comment named Krait's
Inspector specifically, which trips downstream boundary checks that forbid
kryon library code from referencing standalone IDE repositories.
2026-08-12 19:46:20 -05:00
waozi ecb4ad24e6 build: make 2D physics (Box2D) optional via KRYON_WITH_PHYSICS
Box2D was a hard dependency of libkryon.a: physics_world.c and the
Body2D/Area2D/CollisionShape2D nodes include <box2d/box2d.h>, so every
consumer had to build and link box2d even for UI-only apps.

Add a KRYON_WITH_PHYSICS toggle (default 1, current behavior):
- mk/vendor.mk exposes KRYON_PHYSICS_SRCS, KRYON_PHYSICS_CPPFLAGS, and
  KRYON_PHYSICS_DEPS (empty when off) so apps can opt out in one place.
- The kryon Makefile filters the four physics sources out of SRCS and drops
  the box2d include/build/link when KRYON_WITH_PHYSICS=0.
- scene_builtins.c gates the Body2D/Area2D/CollisionShape2D registration and
  the physics stepper install behind #if KRYON_WITH_PHYSICS; the stepper
  pointer in scene_tree.c stays NULL and is already NULL-checked, so a
  physics-off lib ticks scenes safely.

The public headers were already box2d-free (b2WorldId/b2BodyId are stored as
opaque raw ints), so no header changes are needed. UI-only apps build with
KRYON_WITH_PHYSICS=0 to drop box2d entirely.
2026-08-12 19:29:44 -05:00
waozi 6cdace69b0 kryon.h: expose embedded_assets.h through the umbrella
EmbeddedAsset/GetEmbeddedAsset/GetEmbeddedAssetExtension are public API
(used by kryon's own ui_text.c and by apps), but embedded_assets.h was not
pulled in by the kryon.h umbrella, so apps that #include "kryon.h" and used
them got implicit-declaration errors. Surfaced when building inbe against
root kryon.
2026-08-12 19:29:33 -05:00
waozi a9d7694dc9 krb: drop unused GROUP node and export enums for a clean v1
KRB_NODE_GROUP, KRB_EXPORT_LOCAL/R/RW, and KRB_FLAG_EXPORT_MASK were
defined but never emitted, set, or read. Per the no-dead-code rule, remove
them so the shipped v1 surface is honest: node types are BACKGROUND/TEXT/
RECT/BUTTON/DATA (type 0 reserved), and flags carry only SCALE_X/Y/W/H
(bits 0-1 reserved). The three opcodes stay (they are implemented and
host-appendable). KRB_FORMAT.md updated to match and to document DATA.
2026-08-12 19:12:13 -05:00
waozi a49f6f617c krb: implement F32 field read/write and float text formatting
KRB_F32 was defined as a field kind but had no accessor: KrbReadI32/
KrbWriteI32 returned -1 for it. Add dedicated KrbReadF32/KrbWriteF32 (typed
memcpy of a float, size>=4) and route format_bound through them so a TEXT
node bound to a float renders via the node's printf format (default "%g").

krb_mount_test gains a float round-trip, an i32/f32 type-discrimination
check, and a capture-backend assertion that a %.1f-bound text node draws
"3.1" from 3.14159.
2026-08-12 19:07:35 -05:00
waozi 5b15a1272b Expose kry_term and krb in kryon.h; document the cartridge API
Include kry_term.h, kry_backend.h, and krb.h from the kryon umbrella so
apps reach them through the public header. Document the .krb load/bind/draw
flow and KrbMount in docs/API.md, mention kc --emit-krb in the README, and
add an examples Makefile target that builds the 02_buttons cartridge host.
CHANGELOG entries for the kry_term and krb slices.
2026-08-12 19:03:36 -05:00
waozi e5fa60bb2f Add krb cartridge tests
- krb_walk_test: load 02_buttons.krb, check node/import counts, bind, draw.
- krb_mount_test: hand-build an image, exercise KrbMount/KrbBindMem and the
  typed read/write, plus OP_SET_I32 and OP_CALL_HOST through KrbExec.
- krb_host_click_test + krb_cartridge_test.sh: compile 02_buttons.kry to a
  .krb, link the generated C host, and verify a button press increments the
  mounted click_count and updates last_action; also checks the magic,
  size budget, and string-table contents.
2026-08-12 19:03:23 -05:00
waozi 22a8651f06 kryon-preview: render .kry/.krb to PNG via a cartridge subcommand
kryon-preview cartridge --source FILE.kry|FILE.krb --output PNG
compiles a .kry with 'kc --emit-krb' (or loads a .krb directly) and draws
it with KrbDraw through the raylib backend into a hidden window, exporting
a PNG. Lets a cartridge be rendered without building an app host.
2026-08-12 19:03:18 -05:00
waozi 4a3ab5cd7d kc: emit a krb cartridge from .kry (--emit-krb); route codegen via the AST
write_krb (cmd/kc/kc_krb.c) reconstructs each function's AST, collects
widget calls (Background/Text/Rect/Button) and state fields, and emits a
.krb image plus a C host pair (*.krb.c/*.krb.h) that embeds the bytes,
mounts state {}, and turns each 'if Button {}' body into a bound handler.
kc gains the --emit-krb flag and usage; write_generated now emits through
the reconstructed AST when available (Phase 1 of the parser migration),
falling back to the raw body.

Build wiring (Makefile): add krb/kry_term test targets and the cartridge
shell test to 'make test'; compile kc with CPPFLAGS_BASE so kc_krb.c can
include krb.h; link libbox2d into kryon-preview and the scene/property/
animation tests (physics_world needs it); narrow the default embedded font
assets to the regular UI face (CJK faces opt-in).
2026-08-12 19:03:14 -05:00
waozi 2c84504c6a Add krb: a packed, mmapable Kryon cartridge format
A .krb file is a little-endian image: a 32-byte header (magic "KRB\0",
version 1), a 28-byte VFS node table (group/background/text/rect/button/
data), a UTF-8 string table, a tiny program (OP_DRAW_TREE/OP_CALL_HOST/
OP_SET_I32), and a host-import name list. Behavior stays in C.

KrbLoad/KrbLoadFile validate and map the image in place; KrbDraw/KrbExec
walk it through a KryBackend; KrbMount/KrbBindMem map live C fields onto
paths so TEXT nodes draw live values; KrbBind wires host functions to
import slots. Format spec in docs/KRB_FORMAT.md.
2026-08-12 19:02:44 -05:00
waozi 8ebaef6276 Add kry_term: a PTY terminal for IDE hosts
KryTerm spawns $SHELL under a pseudoterminal, writes keys, polls a screen
grid, and resizes with TIOCSWINSZ. CSI cursor and erase handling. Windows is
a no-op stub. Includes a round-trip test (spawn, write, read grid).
2026-08-12 19:02:32 -05:00
waozi 5202861d6e Add kry_backend: a draw/input vtable for non-raylib cartridge hosts
Small backend table (clear, rect, text, measure_text, clip, mouse,
width/height/time/scale, theme_color) so a .krb walker can render through
raylib, a null backend, a framebuffer, or /dev/draw without depending on
raylib directly. KryBackendDraw is the raylib-backed implementation,
KryBackendNull is the headless one used by tests.
2026-08-12 19:02:27 -05:00
waozi e48c7c2272 UI text: resolve font sources from embedded assets before the filesystem
RegisterUIFontFileSource now checks GetEmbeddedAsset(path) first and uses
the embedded blob (static storage, never freed) when present, falling back
to LoadFileData otherwise. Tracks an owns_data flag so embedded data is not
passed to UnloadFileData. Fixes font loading on hosts with no filesystem
access (e.g. Android, where the .ttf is baked into libkryon.a).
2026-08-12 19:02:20 -05:00
waozi 995e4ed4c4 UI: preserve ui_scale across SaveUIFrameState/RestoreUIFrameState
SaveUIFrameState was not capturing GetUIScale(), so an offscreen preview
render (or any save/restore pair) clobbered the UI scale. Add a ui_scale
field to UIFrameState, save it on Save, and SetUIScale it on Restore.
2026-08-12 19:02:16 -05:00
waozi ed512eae71 raylib build: purge stale .o/.a from vendored sources before recompiling
The vendored raylib copy could ship leftover .o/.a files that shadow a
recompile, causing symbol/link mismatches (the CUSTOM_CFLAGS rename drop).
Delete any prebuilt objects right after copying the sources, before the
prepare script and sub-make run, for native, web, and both Windows targets.
2026-08-12 19:02:11 -05:00
waozi f8d011e615 Add Column/Row layout nodes with flexbox-style auto-positioning
Add ColumnProps/RowProps structs and Column/Row/EndColumn/EndRow
widget API functions. These wrap BeginNodeGroup/EndNodeGroup and
maintain a layout cursor stack for auto-positioning children.

Add UILayoutNextChildHeight/UILayoutNextChildX for children to query
their auto-computed position. Add UILayoutActive/UILayoutBounds for
context awareness.
2026-08-12 16:52:50 -05:00
waozi d60cd4303e Add raylib rename-check post-build step to fix symbol collision
Some build environments cause the nested raylib sub-make to drop the
CUSTOM_CFLAGS rename header, leaving unrenamed symbols in libraylib.a
(GetCodepoint, TextSplit, LoadUTF8, etc.) that collide with kryon's
forwarders at link time. The root cause is an environment-specific
interaction between the nested make and the compiler that I could not
fully pin down despite extensive investigation (the flags are correct,
manual compiles with identical flags rename correctly, but the make-driven
compile does not).

The fix: a post-build check in KRYON_RAYLIB_DESKTOP_RULE (mk/raylib.mk)
that verifies the rename took effect and, if not, recompiles rtext.o
directly with the rename header and replaces it in the archive. Proven
correct in isolation — the recompiled rtext.o has correctly-renamed
symbols and ar rcs replaces the member cleanly.
2026-08-12 11:35:39 -05:00
waozi 1757df0a5e Phase 6: TileMap + AudioSource nodes (all 12 Game2D kinds now implemented)
TileMap (src/scene/node_tilemap.c):
- Renders a grid of tile IDs from a single tileset texture via DrawTexturePro
  (raylib batches internally by texture). Tile IDs are 1-based; 0 = empty.
- TileLayer is a usage convention over TileMap (layered z-depth rendering),
  not a separate runtime kind.
- Props: asset_path, tile size, tiles_per_row, map_w/h, world tile size,
  tiles pointer (caller-owned), tint.

AudioSource (src/scene/node_audio_source.c):
- Wraps raylib's LoadSound/PlaySound (SFX) and LoadMusicStream/
  PlayMusicStream/UpdateMusicStream (streaming music). Loads lazily on first
  play via KryAudioSourcePlay; updates music each process tick; frees on
  destroy. KryAudioSourcePlay/Stop are public controls.
- Props: asset_path, kind (sound/music), volume, pitch, loop, play state;
  handle is a void* alloc sized by the impl (header stays free of raylib
  audio struct dependencies).

With this, all twelve Game2D node kinds that were inert stubs at the start of
this project (Scene/Node2D/Camera2D/Sprite2D/AnimatedSprite2D/TileMap/
TileLayer/CollisionShape2D/Area2D/Body2D/Timer/AudioSource) have working
runtime implementations.

Example: examples/24_tilemap.kry (a 10x6 tile grid cycling 3 tile IDs).
2026-08-12 09:33:14 -05:00
waozi 5dd8d3a78b Phase 5: animation system (keyframe tracks, AnimationPlayer, AnimatedSprite2D)
Runtime:
- include/kry_animation.h + src/scene/kry_animation.c: animation = ordered
  tracks of (time,value) keyframes; linear/step interpolation; hold-before/
  hold-after clamping; KryAnimationApply samples at time t and writes position/
  rotation/scale components onto target nodes via KryNodeGet
- src/scene/node_animation_player.c: AnimationPlayer node (registered on the
  KRY_NODE_TIMER slot) advances the current animation each process tick and
  applies it; on non-loop finish emits an 'animation_finished' signal via the
  Phase 2 signal bus. Loop + play/pause state in AnimationPlayerProps
- src/scene/node_animated_sprite2d.c: AnimatedSprite2D cycles frames of a grid
  sprite sheet at a given fps, drawing the current sub-rect via the shared
  picture texture cache
- include/node2d_props.h: AnimationPlayerProps (holds up to 4 animations) +
  AnimatedSprite2DProps + allocators

Example + test:
- examples/23_animation.kry: a Sprite2D whose y position is keyframe-animated
- tests/animation_test.c: linear/step interpolation, hold clamps, and
  KryAnimationApply writing position.x/rotation; wired into 'make test'
2026-08-12 09:30:19 -05:00
waozi e8eb0dd789 Phase 4: Box2D v3 physics integration
Vendor Box2D v3.1.1 (erincatto/box2d) as a submodule; wired into
mk/vendor.mk (CMake static archive, samples/tests/benchmarks off) and
CPPFLAGS_BASE (-Ivendor/box2d/include). libkryon.a now depends on it.

Runtime:
- include/scene_tree.h: KryScene carries an opaque b2WorldId + physics_enabled;
  KryScenePhysicsCreate/Destroy build/tear down the world; KryScenePhysicsTick
  steps it via a function pointer installed by physics_world.c (keeps
  scene_tree.c free of a box2d.h dependency)
- src/scene/physics_world.c: owns the only #include <box2d/box2d.h>; world
  creation/step, body+shape creation helpers, transform sync
- src/scene/node_body2d.c: static/kinematic/dynamic body; creates b2Body on
  ready, syncs transform on physics_process, debug-draws an outline
- src/scene/node_collision_shape2d.c: box/circle shape attached to the nearest
  Body2D ancestor on ready
- src/scene/node_area2d.c: trigger volume (sensor) node
- include/node2d_props.h: Body2DProps/CollisionShape2DProps/Area2DProps +
  allocators
- src/scene/scene_physics_internal.h: private bridge for Box2D-typed helpers

Example: examples/22_physics.kry (a dynamic box falling onto a static ground).
2026-08-12 09:06:23 -05:00
waozi d1fd6d2b75 Fix scale-domain mixing in title bar, toast, and text centering
Three places compared or used a logical (unscaled) font size against a physical (ScaleUIPx) value, causing text corruption at high DPI: ui_titlebar title-shrink guard used ScaleUIPx(12) instead of UI_TEXT_12 (disabled shrinking at scale >= 2); toast height used raw font constant instead of GetUITextLineHeight; GetUITextY empty-text fallback centered using unscaled font_size instead of the scaled line height.
2026-08-12 04:50:44 -05:00
waozi 9059b22970 Use best available DPI estimate, not just device density
Device density (Android DisplayMetrics) alone under-scales on tall screens: a 1080x2220 display at density 2.75 needs a ~3.96x scale by viewport ratio but only gets 2.75x from the density bucket. Now takes the maximum of viewport ratio, device density, and GetWindowScaleDPI so the UI is never smaller than the viewport heuristic would give, while still benefiting from device density when it is the larger value.
2026-08-12 04:31:13 -05:00
waozi d3c27ee04d Invalidate DPI cache when device density changes
SetUIDeviceDensity now resets the cached viewport so UpdateUIDPI recomputes the UI scale on the next call. Without this, a density set after the first UpdateUIDPI (e.g. Android calling nativeSetDeviceDensity from the window layout callback) was ignored because UpdateUIDPI skips recompute when the viewport size is unchanged.
2026-08-12 04:24:57 -05:00
waozi a7cefee47d Add device density hook, fix dropdown resize, widen theme spacing
ui_dpi: add SetUIDeviceDensity so Android DisplayMetrics can drive the UI scale instead of viewport-height fallback; fall back to GetWindowScaleDPI then viewport ratio when no device density is set. dropdown: use a subtle fixed panel radius (0.06) instead of the theme panel radius to avoid distortion during resize. theme_picker: widen the settings label gap (8->20) and grid label gap (6->12) for breathing room.
2026-08-11 04:19:30 -05:00
waozi b394221990 Add kc signal language support, example, and property/signal tests
kc language:
- 'connect emitter.signal to target.handler' statement lowers to
  KrySignalConnect(scene, emitter, "signal", target, "handler")
- 'emit emitter.signal' statement lowers to
  KrySignalEmit(scene, emitter, "signal", KryonPropertyInt(0))
- Both recognized as statements in scene/screen bodies, source-tracked like
  other calls

Example + tests:
- examples/21_signals.kry: connect + emit between two Node2D nodes
- tests/scene_property_test.c: property spec tables, name/index accessors,
  kind-specific Sprite2D props, signal connect/emit dispatch, and
  auto-disconnect on node removal; wired into 'make test'
2026-08-11 03:45:23 -05:00
waozi 65a850fbf1 Add property model and signal bus for the scene tree
Property model (scene_property.h/.c):
- KrySceneRegisterProperties / KryScenePropertySpecs per-kind spec tables
- KrySceneNodeGetProperty/SetProperty read/write runtime KryNode fields
  (transform fields + kind-specific props) through the existing
  KryonPropertySpec/Value model so the editor Inspector can edit every
  field generically instead of special-casing bounds
- Builtin tables for Node2D (position/rotation/scale), Camera2D (+zoom/
  active), Sprite2D (+asset_path/size/tint); registered in
  KrySceneRegisterBuiltins

Signal bus (kry_signal.h/.c):
- KrySignalConnect / KrySignalEmit: declarative node-to-node events
- Per-kind signal handler hook dispatched on emit
- KrySignalDisconnectNode auto-invoked from KryNodeRemove so removed nodes
  don't leave dangling connections
- Connection pool keyed by scene pointer (KryScene stays a fixed struct)
2026-08-11 03:42:19 -05:00
waozi 6c0f79c53e Add kc scene-tree language support, example, and tests
kc compiler (.kry -> C):
- Recognize new top-level 'scene Name { ... }' form; emits a builder
  void Name_kry_scene(KryScene *scene) via a new is_scene flag on KryFunction
  and an _kry_scene suffix branch in kc_function_base_name
- New app{} directive 'scene Name' that makes kc emit a retained-tree main():
  KrySceneRegisterBuiltins / KrySceneInit / run builder / tick+physics+draw
  loop / KrySceneDestroy. Takes priority over the single-screen UI main()
- app_hook_c_name now also resolves scene builders (not just exact_name hooks)
- Single-screen picker skips scene builders so they don't hijack UI apps

Scene tree API:
- KryNodeSetPosition/SetRotation/SetScale/SetProps accessors so builders can
  mutate nodes (C disallows assigning through an rvalue returned struct)

Example + tests:
- examples/20_scene.kry: camera + Sprite2D scene, the first retained-tree game
- tests/scene_tree_test.c: tree ops, transform composition, lifecycle, removal,
  active-camera selection; wired into 'make test' as SCENE_TREE_TEST
- examples/Makefile: add 20_scene to the examples list

Verified end-to-end: .kry -> kc -> clean C -> object file with no warnings
2026-08-11 03:33:41 -05:00
waozi 7358262243 Implement built-in scene nodes: Node2D, Camera2D, Sprite2D
- src/scene/node_2d.c: base transform node (no-op lifecycle, groups children)
- src/scene/node_camera2d.c: claims active_camera on ready when active; freed on destroy
- src/scene/node_sprite2d.c: world-space textured sprite via shared KryLoadPictureTexture
- src/scene/scene_builtins.c: KrySceneRegisterBuiltins + KryCamera2DPropsAlloc /
  KrySprite2DPropsAlloc helpers for scene builders
- include/node2d_props.h: declare the props alloc helpers
2026-08-11 03:22:26 -05:00
waozi 2bb8640279 Add retained scene tree foundation and rename UI Sprite to Picture
- include/kry_math.h: Vector2 math and KryTransform2D (compose/point/camera)
- include/scene_tree.h + src/scene/scene_tree.c: KryScene/KryNode retained
  node tree with array arena, parent/child links, world-transform update,
  lifecycle vtable (ready/process/physics_process/draw), KrySceneTick/
  PhysicsTick/Draw driver
- include/node2d_props.h: Camera2DProps, Sprite2DProps
- Rename UI Sprite widget to Picture (raylib owns Image as a struct):
  ui_sprite.h -> ui_picture.h, SpriteProps -> PictureProps,
  UISpriteFit -> UIPictureFit, UI_SPRITE_FIT_* -> UI_PICTURE_FIT_*,
  Sprite() -> Picture(); extract shared texture cache to
  src/ui/ui_picture_cache.c (KryLoadPictureTexture, KryPictureFitRect)
  shared by the Picture widget and the upcoming Sprite2D scene node
- Migrate example, docs, node registry to the Picture name
2026-08-11 03:11:34 -05:00
waozi 92ae0b4786 Allow custom value text on Slider widget
Add an optional value_text_override parameter to DrawUISlider, UISliderNode, and Slider. When non-NULL it is rendered instead of the default "%d + suffix" formatting, so callers can display values like "1.8x". Passing NULL preserves the existing behavior.
2026-08-11 02:46:04 -05:00
waozi fb9bc415a7 Fix pane tab hit testing 2026-08-10 00:53:23 -03:00
waozi 32f0109e8d Add UI font init control 2026-08-09 23:41:55 -03:00
waozi 843180a5b2 Tune tree view file label color 2026-08-09 20:13:24 -03:00
waozi 6010639c35 Keep UI keyboard input state backend-independent 2026-08-09 19:57:04 -03:00
waozi c9b8e27e4c Canonicalize widget API 2026-08-09 19:52:01 -03:00
waozi 193a199648 clean material toggle rendering 2026-08-09 13:00:01 -03:00
waozi 56cb7a8c15 document and enforce canonical app api 2026-08-09 12:53:52 -03:00
waozi 3a6111c6ec fix sprite example syntax 2026-08-09 12:48:31 -03:00
waozi 0d360a0160 clean kryon app api 2026-08-09 12:44:52 -03:00
waozi eb8c1d359a Add Material theme style widgets 2026-08-08 15:05:02 -03:00
waozi 20fdb362dc Restore stable tool targets 2026-08-08 13:45:21 -03:00
waozi 9bac0fcf2e Preserve icon texture colors 2026-08-08 13:37:49 -03:00
waozi efd52b8020 Use host-specific root build directories 2026-08-08 13:30:51 -03:00
waozi 95b55c42d1 Add GTK file dialog backend 2026-08-08 13:19:24 -03:00
waozi 8e34522b24 Document default Ksync transport APIs 2026-08-08 09:35:31 -03:00
waozi 0956fd6324 Avoid native Ksync transport warnings 2026-08-08 09:31:19 -03:00
waozi 5d39c65d0e Add default Ksync transport helpers 2026-08-08 09:28:44 -03:00
waozi 8e10f118cf kc: extract C emission into kc_codegen.c, heal project split
Move the per-file C/.h emitter out of kc.c: write_generated plus its
helpers write_body_line, function_name, function_takes_rectangle,
app_hook_c_name, write_app_main. write_generated is the public entry;
the rest stay file-local to kc_codegen.c.

Also move write_project_header from kc.c into kc_project.c next to
write_project_source — the two halves of the project emitter were
split across files for no reason, and both walk the same files[]
array back-to-back from main. generated_header_rel is now shared
between them.

kc.c now holds only the parser: parse_kry, parse_statement, the
emit_* cluster, line/directive classifiers, web intrinsics, and main.

kc.c: 3653 -> 3250 lines.
2026-08-07 21:25:55 -05:00
waozi 17dd1ccb96 kc: extract defer lowering into kc_defer.c
Move the defer pass out of kc.c: the KryDefer type, the KRY_SCOPE_*
scope-kind enum, scope_kind_for_open, and apply_defers. apply_defers
walks a function's body[] and splices deferred statements in at every
scope exit (fall-through, return, break, continue) in LIFO order,
rewriting body[] in place. scope_kind_for_open stays file-local since
only apply_defers calls it.

kc.c: 4007 -> 3653 lines.
2026-08-07 21:23:53 -05:00
waozi c981753b57 kc: extract symbol resolution + expression rewrite into kc_resolve.c
Move the resolution and rewrite cluster out of kc.c:
strip_module_alias rewrites qualified type refs (alias.Type -> Type),
rewrite_kry_expr rewrites whole body lines (nil->NULL, alias.fn->
module_fn, bare screen names->mangled C names), rewrite_nil_tokens
does the token-only nil swap used by state/decl emitters, and
convert_var_decl_file/convert_arg_list_file turn name:Type decls into
C form. The lookup helpers (find_local_function, module_for_alias,
function_value_context, name_in_c_parameter_list, kry_declares_name,
function_has_local_name) stay file-local to kc_resolve.c since only
the public rewriters call them.

Drop the dead convert_var_decl/convert_arg_list wrappers (no callers,
the source of two -Wunused-function warnings).

kc.c: 4504 -> 4007 lines.
2026-08-07 21:22:04 -05:00
waozi b4e464a9fe kc: extract KryFile/KryFunction mutators into kc_ir.c
Move the IR builders out of kc.c: add_raw_line, add_type_line,
add_state_line, add_global_line, add_const, add_define, add_function,
add_route, parse_route_property, grow_body, add_body, add_body_line.
These are the only functions that append to the per-file arrays and
grow the function/route/body buffers, so the capacity invariants now
live in one place. Four were already public; the rest join them in
kc_internal.h.

kc.c: 4757 -> 4504 lines.
2026-08-07 21:19:11 -05:00
waozi 3d79830e33 kc: extract diagnostics + error recovery into kc_diag.c
Move die(), kc_error(), kc_flush_diagnostics(), and the three recovery
statics (jmp_buf, recovering flag, current file) out of kc.c into
kc_diag.c. The recovery machinery is exposed as a small API:
kc_recover_buf() hands out the buffer by reference (setjmp must run in
parse_kry's own frame), kc_set_recovery_file() and kc_set_recovering()
toggle the boundary state. parse_kry's three setjmp sites and the
per-file entry now call through these instead of touching the globals.

This is the most cross-cutting piece of the split — die() is reached
from every phase — so getting it behind a clean interface unblocks the
remaining modules.

kc.c: 4879 -> 4757 lines.
2026-08-07 21:18:00 -05:00
waozi 6cd3fa2343 kc: extract pure leaf helpers into kc_util.c
Move the string scanners (trim, parse_ident, parse_quoted,
c_string_literal), path utilities (normalize_source_path, path_join,
strip_kry_ext, mkdir_parent, header_guard, relative_path,
module_symbol/header, replace_path_basename), and brace/indent
analysis (skip_indent, brace_delta) out of kc.c into kc_util.c.

These are pure leaf functions with no parser state; making them public
in kc_internal.h lets every future kc_*.c module share them. die()
loses its static qualifier so kc_util.c (and later modules) can report
through it; its body stays in kc.c for now.

kc_ast.c drops its private brace_delta duplicate now that the shared
one is visible, and renames skip_ws to ast_skip_ws to reflect its
NULL-tolerant difference from skip_indent.

kc.c: 5371 -> 4879 lines.
2026-08-07 21:15:48 -05:00
waozi ada8f69e18 kc: delete _funcs.txt and dedupe function-name helper
Move the per-function C name logic into shared helpers in
kc_internal.h: kc_function_base_name builds the screen or
screen_kry_draw base, kc_function_name prepends the module prefix.
kc_project.c keeps the canonical implementation; kc.c's duplicate
kry_function_c_name wrapper and inlined base logic in
find_local_function now call the shared helpers.

Also delete cmd/kc/_funcs.txt, a stray 47-byte tool-error capture
that nothing referenced.
2026-08-07 21:12:06 -05:00
waozi b3dc811fc7 Own theme picker labels and expose text drawing helpers
Move DrawCenteredUIControlText, DrawLeftUIControlTextInRect, and
DrawFittedUITextInRect into the public ui_draw.h header. They were
documented as public API but only declared in ui_internal.h, so
downstream code calling them got implicit declarations.

Give UIRenderThemeSettings built-in labels (System/Light/Dark/Mode/
Color) instead of looking up app locale keys. The theme picker is
kryon UI, so its default labels belong in kryon; apps still override
them via the UIThemeSettings label fields.
2026-08-07 23:35:36 +00:00
waozi 2ad9f418ca Force retro UI style 2026-08-06 08:26:14 -03:00
waozi 0dcd68f83b Retain dropdown overlay clip bounds 2026-08-06 08:20:56 -03:00
waozi 8f6578386f Fix UI transition declaration 2026-08-06 08:03:09 -03:00
waozi 84bb98f7e2 Add clean node measurement constructors 2026-08-06 07:38:25 -03:00
waozi 4b4ad2bed0 Route node measurement through widget ops 2026-08-06 07:31:02 -03:00
waozi 7e79000fd9 Store measurement data on widget nodes 2026-08-06 07:26:04 -03:00
waozi 1f89ed90d2 Measure widget nodes generically 2026-08-06 07:24:18 -03:00
waozi d07078d2b2 Move UI runtime to declarative nodes 2026-08-06 07:15:55 -03:00
waozi 36b35d06d7 Fix classic system focus and material buttons 2026-08-05 18:02:54 -03:00
waozi 1c4bd145d9 Simplify theme style selection 2026-08-05 17:58:40 -03:00
waozi cd51d7d9ca Centralize native theme defaults 2026-08-05 17:46:25 -03:00
waozi eb1609258a Add selectable native UI styles 2026-08-05 17:25:37 -03:00
waozi f186368ee0 Fix text context menu overlay handling 2026-08-03 18:17:30 -03:00
waozi c9def75ed8 Add text input context menus 2026-08-03 14:56:16 -03:00
waozi 3c7fb872f6 Stabilize UI cursor ownership 2026-08-03 14:21:38 -03:00
waozi d84359c52f Route cursor shape requests through UI intent 2026-08-03 14:13:27 -03:00
waozi 901c8a7918 Fix layout-aware shortcuts and bulk paste 2026-08-03 10:39:34 -03:00
waozi f04b247dcb Adapt syntax colors to dark themes 2026-08-02 22:33:26 -03:00
waozi 1a9b24af68 Fix cascading tree input capture 2026-08-02 22:15:37 -03:00
waozi a9385412e0 Remove bundled C IDE 2026-08-01 13:27:31 -03:00
waozi d795a317a6 Keep standalone IDE changelog name-neutral 2026-08-01 10:11:15 -03:00
waozi 90e759af65 Support standalone KITE IDE 2026-08-01 09:59:24 -03:00
waozi b6beb0b3c6 Add nonblocking IDE console 2026-07-30 18:18:26 -03:00
waozi 3fcdaff8d0 Run kt scenarios visually by target 2026-07-30 18:09:48 -03:00
waozi 100db2f4fd Expand kt project scenario tests 2026-07-30 18:05:04 -03:00
waozi d31e3bc1a0 Add kt test runner 2026-07-30 18:01:01 -03:00
waozi e935cfcf91 Fix IDE source clipboard fallback 2026-07-30 17:47:58 -03:00
waozi 5e81ffb130 Polish IDE chrome and clipboard fallback 2026-07-30 17:38:23 -03:00
waozi 594923638a Add IDE console panel 2026-07-30 17:30:36 -03:00
waozi 6be2e1bbff Add IDE problems panel tabs 2026-07-30 17:04:02 -03:00
waozi 6cad5a86c4 Normalize kc source paths in generated output 2026-07-30 16:49:40 -03:00
waozi 478be8d74a Add shared font subsetting target 2026-07-27 18:56:48 -03:00
waozi 46834e5234 Add dynamic font fallback loading 2026-07-27 18:51:09 -03:00
waozi 0f19f70821 Avoid Windows API name collisions 2026-07-27 17:59:13 -03:00
waozi 231b8d6da7 Define NULL for platform thread helpers 2026-07-27 17:30:23 -03:00
waozi c218841c75 Merge remaining Kryon fixes 2026-07-27 12:14:33 -03:00
waozi e6bb5e7372 Add compiler diagnostics and UI text backend fixes 2026-07-27 12:14:20 -03:00
waozi 75d694ddb2 Merge Kryon IDE preview fixes 2026-07-27 12:12:40 -03:00
waozi 8a0a09bc03 Fix Kryon IDE preview input and source selection 2026-07-27 12:09:55 -03:00
waozi 415cb18fdd Isolate text input selection ownership 2026-07-27 11:58:35 -03:00
waozi 7e8f316eb5 Rename Lyra sync APIs to Ksync 2026-07-27 08:52:02 -03:00
waozi f6907efcdd Rename Lyra sync APIs to Ksync 2026-07-27 08:50:30 -03:00
waozi 9106c55e1e Phase 3 (foundation): type-aware AST classification of declarations
Improve the AST classifier to distinguish typed declarations from
assignments — the foundation for type tracking. Previously all =-bearing
lines were ASSUME-ASSIGN; now:

- __auto_type name = expr;     → DECL (inferred)
- Type name = expr;            → DECL (typed: int, char, float, Color, ...)
- Type name[N] = {...};        → DECL (typed array)
- name = expr;                 → ASSIGN
- name += expr; / name++;      → ASSIGN (mutation)

The heuristic: a typed decl's first token is a C type keyword (int, char,
const, unsigned, ...) or a capitalized identifier (a typedef/struct name
like Color, Rectangle), followed by the variable name. Compound-assign and
++/-- are detected first and classified as ASSIGN.

This is the Phase 3 groundwork: the AST now correctly separates typed decls
(which carry type info) from assignments, enabling future type tracking and
IDE hover. Test updated to assert typed decls classify as DECL and compound
assigns as ASSIGN.

Note: full type checking (catching wrong-shape call arguments) still needs a
function-signature database, which is a separate effort. This commit is the
prerequisite — getting the type information into the tree.
2026-07-26 12:52:01 -05:00
waozi 2e7f91fa46 Phase 2 (partial): fix defer leaking across switch cases
defer inside switch cases was broken: apply_defers treated the whole switch
as one scope, so a defer in case 1 leaked into default and ran on the wrong
path (discovered during Phase 0).

Fix: add a KRY_SCOPE_CASE scope kind. Each case label opens a case scope so
case-local defers attach to it, not the switch. The case boundary (next case
label or switch close) fires and drops the previous case's defers. A `spent`
flag prevents re-emission: break/continue/return inside a case spend the
case's defers so the following case boundary doesn't re-emit them. Function-
body and loop-body defers are NOT spent (they must fire on every return path
and every loop iteration respectively).

Test: defer_switch.kry pins the fix — each case's defer fires exactly once,
on its own path, with no cross-case leakage. Existing defer tests (for-loop,
while, function-body, anon block) pass unchanged.

This is the highest-value piece of Phase 2: the switch bug was a real
correctness defect. The full emit-from-AST cutover (deleting fn->body[] and
the text-reconstruction approach) remains as the rest of Phase 2.
2026-07-26 11:27:04 -05:00
waozi b26a549ade Phase 1: build the AST alongside the existing path
Add cmd/kc/kc_ast.{h,c} with typed AstStmt node kinds matching the
parse_statement inventory. Rather than instrument every branch, Phase 1
reconstructs the AST from the already-emitted fn->body[] strings in a
post-parse pass — validating that the strings carry enough structure to
rebuild the tree, which is what Phase 2 needs before swapping emit.

--dump-ast parses without writing files and prints the tree (kind label +
depth indent per statement). Verified zero AST_STMT_UNKNOWN nodes on
full-feature inputs: every statement classifies into a known kind, so the
AST captures 100% of what kc emits today.

Makefile: KC_SRCS now globs cmd/kc/*.c (picks up kc_ast.c automatically).
Test: new case pins the dump (function name, IF/FOR/WHILE/SWITCH/DEFER/
RETURN present, no UNKNOWN, no .c/.h written).

Existing syntax suite and full `make test` pass unchanged. Plan doc marks
Phase 1 done.
2026-07-26 11:02:59 -05:00
waozi 44f269945c Phase 0: harden the kc syntax oracle + add parser plan
Add test coverage for emit paths that had none, de-risking a future parser
rewrite (docs/KC_PARSER_PLAN.md):

- compound assigns -=, *=, /=, and -- (only += and friends were covered)
- defer inside a while loop, before continue, and in anonymous blocks
- main generation: omitting --no-main emits int main with InitWindow/loop
- the 'let' removal error

Found a real bug while probing: defer inside switch cases is broken today
(apply_defers runs all case-defers at the switch close, leaking across
cases). Not pinned — documented in the plan as a defect the AST rewrite
fixes by giving each case its own scope.

pub struct/enum was also probed and confirmed NOT supported (errors as
"unknown top-level statement") — removed from the blind-spot list.

docs/KC_PARSER_PLAN.md: the full phased migration plan (AST ceiling
diagnosis, target architecture, byte-identity contract, 5 phases).
2026-07-26 10:44:36 -05:00
waozi 6087348f56 Add kryon-app dev-backend for local sync development
Run a local Lyra server in the foreground, isolated to the project: locates
the server source at $LYRA_DIR or a sibling checkout (../lyra), stores its
data under <project>/.kryon/lyra-dev.db, sets an ephemeral token secret, and
prints the sync URL to point the app at. Prefers a pre-built `lyra` binary,
falling back to `go run` via the server's Makefile.

Tokens regenerate each start, so this is for local development only. Kryon
and Lyra stay separate repos joined by the wire protocol; this command is the
convenience that wires a project to a local server.
2026-07-26 09:32:37 -05:00
waozi f179f5c632 Fix click-to-source for widgets used in if conditions
A widget call used as an if condition (e.g. `if WidgetButton(...) {`) was
emitted as `if(WidgetButton(...)) {` with no source-inspection wrapping, so
the button registered no source location and click-to-source did nothing.
Statement-form calls (WidgetText) worked because they were wrapped.

When the if condition is a call, now evaluate it into a temp with the source
location active, pop, then test the temp:

  PushUIInspectSource(path, line);
  __auto_type __kryon_cond_line = WidgetButton(...);
  PopUIInspectSource();
  if(__kryon_cond_line) { ... }

Evaluating into a temp before the branch keeps Push/Pop balanced regardless
of else/return. Non-call conditions are emitted unchanged. Test updated to
pin the new wrapped form; new golden-file case for if-WidgetButton.
2026-07-26 09:18:48 -05:00
waozi bc801c9c79 Add defer to the Kry language
`defer STMT` schedules STMT to run when its enclosing block exits — by
falling-off-the-end, return, break, or continue — replacing the cleanup-goto
idiom. Multiple defers in one block run in reverse (LIFO) order; defers in
inner scopes run before those in outer scopes; a defer only fires if declared
before the triggering exit. goto is intentionally left alone (documented).

Implementation is a compile-time transform over the collected function body
lines (apply_defers), splicing the deferred statement into the generated C at
every exit point with no runtime cost. A scope stack (block / branch / loop)
tracks nesting so return unwinds everything and break/continue unwind only
the enclosing loop body.

Tests cover scope-end, return, break/continue, LIFO ordering, nested scopes,
and a malformed-defer error case, all in tests/kc_syntax_test.sh. Full
syntax suite and `make test` pass.
2026-07-26 08:25:39 -05:00
738 changed files with 149403 additions and 18032 deletions

No files matched your search

+68
View File
@@ -0,0 +1,68 @@
name: Automatic Release Version
on:
workflow_run:
workflows: [CI]
types: [completed]
permissions:
contents: write
actions: write
concurrency:
group: kryon-auto-release
cancel-in-progress: false
jobs:
bump-and-release:
if: >-
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.event == 'push' &&
github.event.workflow_run.head_branch == 'master'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
ref: ${{ github.event.workflow_run.head_sha }}
fetch-depth: 0
- name: Skip an already released commit
id: guard
run: |
if git tag --points-at HEAD --list 'v*' | grep -q .; then
echo 'release=false' >> "$GITHUB_OUTPUT"
else
echo 'release=true' >> "$GITHUB_OUTPUT"
fi
- name: Resolve next version
if: steps.guard.outputs.release == 'true'
id: version
run: |
current=$(make -s version)
if git rev-parse -q --verify "refs/tags/$current" >/dev/null; then
version=$(scripts/bump-version.sh patch)
else
version=$current
fi
echo "tag=$version" >> "$GITHUB_OUTPUT"
- name: Commit version
if: steps.guard.outputs.release == 'true'
run: |
git config user.name 'github-actions[bot]'
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
git add include/kryon_version.h
if ! git diff --cached --quiet; then
git commit -m "release: bump version to ${{ steps.version.outputs.tag }}"
git push origin HEAD:master
fi
- name: Start release workflow
if: steps.guard.outputs.release == 'true'
env:
GH_TOKEN: ${{ github.token }}
run: >-
gh workflow run release.yml --ref master
-f version=${{ steps.version.outputs.tag }}
-f prerelease=false
+100
View File
@@ -0,0 +1,100 @@
name: CI
on:
push:
branches:
- master
pull_request:
workflow_dispatch:
# Cancel a superseded run on the same ref.
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
guard-submodule-urls:
name: Submodule URLs are public HTTPS
runs-on: ubuntu-latest
steps:
# Plain checkout on purpose: the guard must not depend on fetching
# the submodules it validates (an SSH URL would break that fetch).
- name: Checkout Repository
uses: actions/checkout@v7
- name: Reject non-HTTPS submodule URLs
run: sh scripts/check-submodule-urls.sh
test-linux:
name: Build and test (Linux)
needs: guard-submodule-urls
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v7
with:
submodules: recursive
- 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 \
libglib2.0-dev libgtk-3-dev \
libsdl2-dev libdrm-dev libgbm-dev libegl1-mesa-dev libgles2-mesa-dev \
ripgrep
- name: Build
run: |
set -euo pipefail
make clean CMAKE=/usr/bin/cmake
make all CMAKE=/usr/bin/cmake
- name: Test
run: make test CMAKE=/usr/bin/cmake
- name: Text input latency gate
run: |
set -euo pipefail
make perf-text-input CMAKE=/usr/bin/cmake | grep '^{' | tee text-input-perf.jsonl
cat text-input-perf.jsonl >> "$GITHUB_STEP_SUMMARY"
- name: Upload text input measurements
uses: actions/upload-artifact@v7
with:
name: text-input-perf-linux
path: text-input-perf.jsonl
if-no-files-found: error
test-freebsd:
name: Build and test (FreeBSD)
needs: guard-submodule-urls
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v7
with:
submodules: recursive
- name: Build and test on FreeBSD VM
uses: vmactions/freebsd-vm@v1
with:
usesh: true
mem: 4096
prepare: |
set -eu
pkg install -y gmake cmake pkgconf \
sdl2 libdrm mesa-libs gtk3 \
curl openssl zstd brotli \
git go python3 ripgrep
run: |
set -eu
gmake clean
gmake all
gmake test
if ! gmake perf-text-input; then
echo "FreeBSD text-input measurements are non-gating during calibration" >&2
fi
@@ -1,4 +1,4 @@
name: Netlify
name: Cloudflare Pages
on:
push:
@@ -11,7 +11,7 @@ permissions:
contents: read
concurrency:
group: netlify-${{ github.ref }}
group: pages-${{ github.ref }}
cancel-in-progress: true
jobs:
@@ -21,7 +21,7 @@ jobs:
steps:
- name: Checkout Repository
uses: actions/checkout@v4
uses: actions/checkout@v7
with:
submodules: recursive
@@ -43,15 +43,23 @@ jobs:
- name: Build Site
run: |
set -euo pipefail
make docs-site CMAKE=/usr/bin/cmake
make docs-site CMAKE=/usr/bin/cmake SITE_BUILD_DIR=build/site
test -f build/site/index.html
test -f build/site/api.html
test -f build/site/ide.html
test -f build/site/ide.js
test -f build/site/ide-tools/k2kir.js
test -f build/site/ide-tools/k2kir.wasm
test -f build/site/ide-tools/k2b.js
test -f build/site/ide-tools/k2b.wasm
test -f build/site/icons/kryon.png
test -f build/site/icons/c.png
test ! -f build/site/API.md
env:
GITHUB_TOKEN: ${{ github.token }}
- name: Upload Site Artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: kryon-site
path: build/site
@@ -70,25 +78,12 @@ jobs:
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 }}
- name: Deploy Preview To Cloudflare Pages
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy build/site --project-name=kryon --branch=${{ github.head_ref || github.ref_name }}
deploy-production:
name: Deploy Production
@@ -103,22 +98,9 @@ jobs:
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 }}
- name: Deploy Production To Cloudflare Pages
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy build/site --project-name=kryon --branch=master
+34 -6
View File
@@ -33,7 +33,7 @@ jobs:
steps:
- name: Checkout Repository
uses: actions/checkout@v4
uses: actions/checkout@v7
with:
fetch-depth: 0
submodules: recursive
@@ -51,6 +51,11 @@ jobs:
v[0-9]*.[0-9]*.[0-9]*) ;;
*) echo "Version must look like v0.1.0" >&2; exit 1 ;;
esac
header_tag="$(sed -n 's/^#define KRYON_VERSION_STRING "\([^"]*\)".*/\1/p' include/kryon_version.h)"
if [ "$tag" != "$header_tag" ]; then
echo "Requested $tag but include/kryon_version.h contains $header_tag" >&2
exit 1
fi
if git rev-parse -q --verify "refs/tags/$tag" >/dev/null; then
echo "Tag $tag already exists; nothing to release."
echo "tag=" >> "$GITHUB_OUTPUT"
@@ -130,7 +135,7 @@ jobs:
echo "tag=$tag" >> "$GITHUB_OUTPUT"
- name: Checkout Repository
uses: actions/checkout@v4
uses: actions/checkout@v7
with:
ref: ${{ steps.ref.outputs.tag }}
submodules: recursive
@@ -140,7 +145,7 @@ jobs:
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
sudo apt-get install -y build-essential cmake libssl-dev pkg-config zlib1g-dev libzstd-dev libbrotli-dev libglib2.0-dev libgtk-3-dev libsdl2-dev libdrm-dev libgbm-dev libegl1-mesa-dev libgles2-mesa-dev ripgrep
- name: Build And Test
run: |
@@ -158,17 +163,40 @@ jobs:
test -n "$archive"
echo "KRYON_STATIC_ARCHIVE=$archive" >> "$GITHUB_ENV"
- name: Package Every Kryon Tool
run: |
set -euo pipefail
make dist-tools CMAKE=/usr/bin/cmake VERSION="${{ steps.ref.outputs.tag }}"
make check-tools-package CMAKE=/usr/bin/cmake VERSION="${{ steps.ref.outputs.tag }}"
archive="$(find dist -maxdepth 1 -type f -name 'kryon-*-tools-*.tar.gz' | head -n 1)"
test -n "$archive"
echo "KRYON_TOOLS_ARCHIVE=$archive" >> "$GITHUB_ENV"
- name: Write Checksums
run: |
sha256sum "$KRYON_STATIC_ARCHIVE" "$KRYON_TOOLS_ARCHIVE" > SHA256SUMS
- name: Upload Static Library Artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: kryon-static-library-${{ steps.ref.outputs.tag }}
path: ${{ env.KRYON_STATIC_ARCHIVE }}
if-no-files-found: error
- name: Upload Tools Artifact
uses: actions/upload-artifact@v7
with:
name: kryon-tools-${{ steps.ref.outputs.tag }}
path: ${{ env.KRYON_TOOLS_ARCHIVE }}
if-no-files-found: error
- name: Publish GitHub Release
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3
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 }}
files: |
${{ env.KRYON_STATIC_ARCHIVE }}
${{ env.KRYON_TOOLS_ARCHIVE }}
SHA256SUMS
+114
View File
@@ -0,0 +1,114 @@
name: renderers
# Build downloadable KRB renderers for every platform: the headless
# renderer (krb-run) as native binaries, and the web player (krb-web)
# as static files any site can host.
on:
push:
branches: [master]
tags: ["v*"]
workflow_dispatch:
permissions:
contents: write
jobs:
native:
strategy:
fail-fast: false
matrix:
include:
- { os: ubuntu-latest, cc: cc, suffix: linux-x86_64, build_dir: build/linux-x86_64 }
- { os: ubuntu-latest, cc: x86_64-w64-mingw32-gcc, suffix: windows-x86_64, build_dir: build/linux-x86_64 }
- { os: macos-latest, cc: /usr/bin/clang, suffix: macos-arm64, build_dir: build/macos-arm64 }
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v7
with:
submodules: recursive
- name: Install mingw (windows cross)
if: matrix.suffix == 'windows-x86_64'
run: sudo apt-get update && sudo apt-get install -y mingw-w64
- name: Install GNU make (macOS)
if: runner.os == 'macOS'
run: brew install make
- name: Build krb-run
# The Makefile's KRY_SW_SRCS is the single source of truth for what
# every renderer build links; never pin a copy of the list here.
run: |
target="${{ matrix.build_dir }}/bin/krb-run"
if [ "${{ runner.os }}" = macOS ]; then
env -u MAKE -u MAKEFLAGS -u MFLAGS -u MAKEFILES \
CC=${{ matrix.cc }} /opt/homebrew/bin/gmake -e -f ./Makefile "$target"
else
make "$target" CC=${{ matrix.cc }}
fi
[ "${{ matrix.suffix }}" = windows-x86_64 ] && target="$target.exe"
cp "$target" build/krb-run
- name: Rename
run: cp build/krb-run krb-run-${{ matrix.suffix }}${{ matrix.suffix == 'windows-x86_64' && '.exe' || '' }}
- uses: actions/upload-artifact@v7
with:
name: krb-run-${{ matrix.suffix }}
path: krb-run-${{ matrix.suffix }}*
web:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
submodules: recursive
- uses: mymindstorm/setup-emsdk@v14
with:
version: latest
- name: Build web player
run: make krb-web
- name: Package
run: |
mkdir -p krb-player-web && cp build/linux-x86_64/web/krb-web/* krb-player-web/
cp examples/02_buttons.kry /tmp/ 2>/dev/null || true
- uses: actions/upload-artifact@v7
with:
name: krb-player-web
path: krb-player-web/
exactness:
# Cross-engine byte-exactness needs no GL (SDL dummy + software).
# The native pixel-compare vs the inbe C build additionally needs a
# working screenshot pipeline: xvfb-run, as inbe's own CI does.
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
submodules: recursive
- name: Build tools
run: |
sudo apt-get update
sudo apt-get install -y libsdl2-dev
make build/linux-x86_64/bin/k2b \
build/linux-x86_64/bin/krb-run \
build/linux-x86_64/bin/krb-sdl \
build/linux-x86_64/tests/krb_logic_test \
build/linux-x86_64/tests/krb_asset_test
- name: Cross-engine exactness
run: sh tests/krb_exact_test.sh .
- name: Unit tests
run: |
build/linux-x86_64/tests/krb_logic_test
build/linux-x86_64/tests/krb_asset_test
# Native gate: once inbe CI checks out kryon master as its vendor,
# run tests/krb_exact_native_test.sh per ported screen under xvfb:
# xvfb-run -a ./inbe --screenshot native.png --screenshot-scene language ...
release:
if: startsWith(github.ref, 'refs/tags/')
needs: [native, web]
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v4
- run: |
mkdir rel && cp -r krb-run-* krb-player-web rel/
- uses: softprops/action-gh-release@v3
with:
files: rel/*
+7
View File
@@ -2,9 +2,12 @@
*.o
*.so
*.dll
*.pyc
*~
*.tmp
__pycache__/
.zcode
.kryon-ide-state
# Build output
build/
@@ -12,3 +15,7 @@ dist/
assets/fonts/*
tools/otfchop/otfchop
# native plan9 cpp-stage intermediates
src/**/*.i
src/**/*.8
+3 -3
View File
@@ -10,6 +10,6 @@
[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
[submodule "vendor/box2d"]
path = vendor/box2d
url = https://github.com/erincatto/box2d.git
+38
View File
@@ -0,0 +1,38 @@
# Kryon Repository Rules
Kryon is the canonical runtime. Keep it small, direct, and free of stale
surfaces.
## Clean API Rule
Do not introduce new public generated-runtime APIs with stale prefixes or
compatibility names. New `.kry` generated code must target the clean runtime
surface:
- `BeginFrame`
- `EndFrame`
- `Text`
- `Button`
- `TextField`
- `TextArea`
- `Row`
- `Column`
Do not add `kryc`. The supported transpilers are `k2go` for native Go, `k2c`
for native C, and `k2cpp` for native C++ (C++ codegen over the C runtime).
Generated Go must be native Go and must not use cgo, `go/kryui`, `kryruntime`,
or an injected `rt` runtime object. Generated C must not call stale prefixed UI
symbols such as `DrawUI*`, `UIText*`, `TextInputControl`, or `UIRender*`.
Existing compatibility code may only remain while actively migrating callers.
Do not expand it, duplicate it under another alias, or use it from generated
output. Remove compatibility code once no maintained app or fixture depends on
it.
## Test Rule
Any change to k2go, k2c, k2cpp, the Go runtime, or the C runtime surface must keep the
generated-output scanners and runtime parity tests passing. If a new widget or
semantic is added, add it to both generated runtimes and to parity coverage in
the same change.
+1 -1
View File
@@ -1,4 +1,4 @@
# Native make shim. The canonical build is the GNU Makefile.
# Native BSD make shim. The canonical build is the GNU Makefile.
GMAKE ?= gmake
.MAIN: all
+1403 -4
View File
File diff suppressed because it is too large. Load diff
+866 -105
View File
File diff suppressed because it is too large. Load diff
+140 -36
View File
@@ -1,10 +1,14 @@
<p align="center">
<img src="assets/app/readme-banner.png" alt="Kryon" width="100%">
</p>
# Kryon
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.
desktop tray support, runtime asset downloads, and Ksync account/sync helpers.
## Layout
@@ -31,19 +35,27 @@ Kryon builds with the repository Makefile:
make
```
On FreeBSD, use the repository `makefile` entrypoint. It delegates to the GNU
Make build while keeping `make` as the command downstream apps can run:
```bash
make bsd-check
```
Run the focused tests with:
```bash
make test
```
Backend selection is link-time via `KRYON_BACKEND`. Supported backends are:
- [`raylib`](https://github.com/raysan5/raylib) - the default desktop,
Android, Windows, and WebGL path, with SDL2/OpenGL integration in the build
rules.
- [`canvas`](docs/CANVAS2D_PARITY.md) - the HTML5 Canvas2D/WebAudio backend
for Emscripten web builds.
- [`dom`](src/backend/dom_backend.c) - the browser DOM/CSS backend for web UI
surfaces.
- [`libdraw`](https://9fans.github.io/plan9port/man/man3/draw.html) - the
plan9port libdraw/devdraw backend.
- [`termi`](src/backend/termi_backend.c) - the terminal-cell backend.
- `null` - generated no-op stubs for headless tests and unsupported surface
areas.
Build a distributable static-library archive with:
```bash
@@ -59,6 +71,12 @@ manifest, and the submodule revisions used to build it. Validate it with:
make check-static-package
```
Run the full release readiness gate with:
```bash
make release-preflight
```
`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
@@ -66,11 +84,19 @@ 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.
Every successful CI run on `master` automatically advances the patch version,
commits `include/kryon_version.h`, and starts the tag-driven `Release` workflow.
The workflow validates the version, creates an annotated tag, builds and tests
Kryon, and publishes both the static SDK and a checksummed native tools bundle.
The tools bundle contains `k2c`, `k2cpp`, `k2go`, `k2js`, `k2kir`, `k2b`, `kt`, `kryon`,
`kryon-preview`, `krb-run`, and `krb-sdl`. The renderer workflow also attaches
the Linux, Windows, and macOS `krb-run` builds plus the web player to the same
release.
Maintainers can still run `Release` manually for the checked-in version. Use
`scripts/bump-version.sh minor` / `major` before pushing when a non-patch bump is
required. Pushing a matching `v*` tag manually uses the same build-and-publish
path; releases reject tags that disagree with the public version header.
## Integration
@@ -82,7 +108,12 @@ To integrate Kryon into your project:
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
assets. Kryon's checked-in `icons/` tree is the source of truth for shared
UI, platform, payment, language, tile, profile, and first-party project
icons; project logos live under `icons/proj/`. Downstream apps can call
`vendor/kryon/scripts/sync-icons.sh` to copy those icons into web asset
directories without keeping separate icon originals. Run `make
icons-generate` after changing generated pixel icons.
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
@@ -92,43 +123,70 @@ variables through to the vendored curl CMake build.
## App Builds
Kryon owns the app command surface through `kryon-app`. From an app repository:
Kryon owns the app command surface through `kryon`. 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
kryon build native
kryon build web
kryon build android-debug
kryon package linux-desktop
kryon package appimage
kryon preview
```
App `project.kryon` files should use `target` entries that call `kryon-app`
For local development against a sync backend, run a Ksync server in the
foreground. `dev-backend` locates the server source at `$KSYNC_DIR` or as a
sibling checkout (`../ksync`), isolates its data under `<project>/.kryon/`, and
prints the sync URL to point your app at. Tokens are regenerated each start,
so it is for local development only:
```sh
kryon dev-backend # serves http://127.0.0.1:8080
```
App `project.kryon` files should use `target` entries that call `kryon`
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.
Krait, the standalone Kryon IDE (a separate `kryonlabs/krait` repo that vendors
Kryon), previews `.kry` source by compiling it to an app host and loading it
into the embedded viewport. On each source change Krait rebuilds the project's
app host (`make kryon-host`, producing `build/kryon/app_host.so`), `dlopen`s
it, and resolves `CreateAppHost`/`DestroyAppHost`. The build runs in the
background (`fork` + non-blocking pipe, drained each frame) so the window stays
responsive during the compile; once it finishes the new app host is loaded and
the preview updates. Source changes are polled a few times per second. Kryon
itself owns the preview host tooling (`kryon-preview`); it must not depend on
Krait.
A project can add `project.kryon` metadata such as `preview_size`,
`preview_asset_root`, and `preview_scene` to control the embedded viewport.
## 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
(`InitWindow`, `DrawTexture`, `BeginUIFrame`, `ButtonNode`). Internal helpers
stay private to `src/` unless a downstream app needs the API in `include/`.
## Documentation
- `docs/API.md` documents the public API.
- `docs/KRY_LANGUAGE_SPEC.md` is the canonical `.kry` language and KIR
contract.
- `docs/FEATURE_MATRIX.md` maps widget and feature support across the C, Go,
and KRB targets and every renderer backend.
- `docs/BACKENDS.md` documents the backend architecture and selection.
- `docs/BACKEND_CAPABILITIES.json` is the checked backend inventory used by
backend drift checks.
- `docs/ARCHITECTURE.md` maps the main Kryon subsystems and ownership lines.
- `docs/BOUNDARIES.md` defines what belongs in Kryon and what stays in
downstream applications.
- `docs/PUBLIC_API_SNAPSHOT.txt` tracks public Kryon identifiers for API drift
checks.
- `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.
@@ -141,9 +199,55 @@ immediate-mode drawing, and no builder objects or scripting runtime. The numbere
examples `09_geometry` through `18_accessibility` demonstrate each toolkit
feature family.
## Kry Language Direction
## Kry Language
`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.
`docs/KRY_LANGUAGE_SPEC.md` is the canonical Kry language contract. Kry source
lowers into KIR, a debuggable intermediate representation with source spans.
From there `k2c` emits readable C for native apps, `k2cpp` emits C++ with C
linkage against the same C runtime, `k2go` emits pure Go source
against the native Go runtime, while `k2b` emits a portable `.krb` cartridge
(`docs/KRB_FORMAT.md`) for renderers that implement the Kryon runtime contract.
The intended tool set is Unix-shaped:
```text
k2kir app.kry # .kry -> .kir
k2c app.kry|app.kir
k2cpp app.kry # .kry -> C++ (extern "C" decls over the C runtime)
k2go app.kry # .kry -> Go (native Go runtime, no cgo)
k2b app.kry|app.kir
```
Generated Go imports `github.com/waozixyz/kryon/go/kryon` as `kryon` and uses
clean qualified widget names such as `kryon.Button`, `kryon.TextField`,
`kryon.Text`, `kryon.Row`, `kryon.Column`, `kryon.BeginFrame`, and
`kryon.EndFrame`. Pure Kry and Go-native externs must not use `import "C"`,
the removed bridge package, injected runtime objects, dot-imported runtime
names, or generated calls to stale prefixed C APIs. Explicit C externs with a
`c.` target, such as `#extern "c.abs"`, are the opt-in exception: `k2go` emits
their `import "C"` bridge in a separate generated `*_cgo.go` file.
Handwritten Go can use the same package directly. Generated code keeps the
explicit props form (`kryon.Button(kryon.ButtonProps{...})`,
`kryon.TextField(kryon.TextFieldProps{...})`) for deterministic layout/state,
while app code may use shorter direct calls such as `kryon.Button("Save")` and
`kryon.TextField("Name", &name)`.
The native Go runtime records each frame as pure Go `FrameOp` values available
through `FrameOps()`. That operation stream is the host boundary for native Go
windows/renderers: it carries resolved bounds, text, colors, focus, button
state, and redacted secure text without importing cgo or the removed bridge.
`RenderFrame` and `RenderCurrentFrame` provide a dependency-free software
renderer that turns those operations into an `image.RGBA`.
`NewHost` owns a persistent native Go runtime, runs generated or handwritten
frame functions, queues input, exposes frame operations, and renders frames
without cgo.
`k2go` output is compiled against that native runtime by the test suite, and the
generated Go/C parity tests drive both runtimes through the same scripted input.
This is an executable compatibility gate, not only a textual generated-source
check.
`k2c`, `k2js`, and `k2b` accept `.kry` source and run the KIR frontend
internally. Native platform, storage, and performance-sensitive C code remains
first-class through the C backend and through explicit KRB capabilities or host
imports.
-1
View File
@@ -7,7 +7,6 @@ submodules listed in `SUBMODULES.txt`.
- 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.
OpenSSL is not vendored into the package by default. When `kryon.pc` lists
Binary file not shown.

After

Width:  |  Height:  |  Size: 429 KiB

+111
View File
@@ -0,0 +1,111 @@
include_guard(GLOBAL)
function(kryon_generate_kry_sources out_sources out_include_dir)
set(options NO_MAIN)
set(one_value_args KRYON_DIR ROOT OUT_DIR TARGET)
set(multi_value_args SOURCES)
cmake_parse_arguments(KRYGEN "${options}" "${one_value_args}" "${multi_value_args}" ${ARGN})
if(NOT KRYGEN_KRYON_DIR)
message(FATAL_ERROR "kryon_generate_kry_sources requires KRYON_DIR")
endif()
if(NOT KRYGEN_ROOT)
message(FATAL_ERROR "kryon_generate_kry_sources requires ROOT")
endif()
if(NOT KRYGEN_OUT_DIR)
message(FATAL_ERROR "kryon_generate_kry_sources requires OUT_DIR")
endif()
if(NOT KRYGEN_TARGET)
message(FATAL_ERROR "kryon_generate_kry_sources requires TARGET")
endif()
if(NOT KRYGEN_SOURCES)
message(FATAL_ERROR "kryon_generate_kry_sources requires SOURCES")
endif()
file(GLOB KRYGEN_K2C_SOURCES CONFIGURE_DEPENDS "${KRYGEN_KRYON_DIR}/cmd/k2c/*.c")
list(APPEND KRYGEN_K2C_SOURCES
"${KRYGEN_KRYON_DIR}/cmd/kir/kir.c"
"${KRYGEN_KRYON_DIR}/cmd/kir/kir_parse.c"
"${KRYGEN_KRYON_DIR}/cmd/kir/kir_text.c")
if(KRYON_HOST_CC)
set(KRYGEN_HOST_CC "${KRYON_HOST_CC}")
else()
foreach(krygen_host_cc_candidate
/usr/bin/cc
/bin/cc
/usr/bin/gcc
/usr/bin/clang
/usr/local/bin/cc
/usr/local/bin/gcc
/usr/local/bin/clang
/opt/homebrew/bin/cc
/opt/homebrew/bin/gcc
/opt/homebrew/bin/clang)
if(NOT KRYGEN_HOST_CC AND EXISTS "${krygen_host_cc_candidate}")
set(KRYGEN_HOST_CC "${krygen_host_cc_candidate}")
endif()
endforeach()
endif()
if(NOT KRYGEN_HOST_CC)
find_program(KRYGEN_HOST_CC
NAMES cc gcc clang
NO_CMAKE_FIND_ROOT_PATH)
endif()
if(NOT KRYGEN_HOST_CC)
message(FATAL_ERROR "kryon_generate_kry_sources requires a host C compiler; set KRYON_HOST_CC")
endif()
set(KRYGEN_K2C "${CMAKE_BINARY_DIR}/kryon-host-tools/k2c")
set(krygen_generated_sources)
set(krygen_generated_headers)
set(krygen_command_sources)
foreach(kry_source ${KRYGEN_SOURCES})
file(RELATIVE_PATH kry_rel "${KRYGEN_ROOT}" "${kry_source}")
list(APPEND krygen_command_sources "${kry_rel}")
get_filename_component(kry_rel_dir "${kry_rel}" DIRECTORY)
get_filename_component(kry_name "${kry_rel}" NAME_WE)
list(APPEND krygen_generated_sources "${KRYGEN_OUT_DIR}/${kry_rel_dir}/${kry_name}.c")
list(APPEND krygen_generated_headers "${KRYGEN_OUT_DIR}/${kry_rel_dir}/${kry_name}.h")
endforeach()
set(krygen_flags)
if(KRYGEN_NO_MAIN)
list(APPEND krygen_flags --no-main)
endif()
add_custom_command(
OUTPUT
${krygen_generated_sources}
${krygen_generated_headers}
"${KRYGEN_OUT_DIR}/kryon_project.c"
"${KRYGEN_OUT_DIR}/kryon_project.h"
COMMAND ${CMAKE_COMMAND} -E remove_directory "${KRYGEN_OUT_DIR}"
COMMAND ${CMAKE_COMMAND} -E make_directory "${KRYGEN_OUT_DIR}"
COMMAND "${KRYGEN_K2C}" ${krygen_flags} --root "${KRYGEN_ROOT}" -o "${KRYGEN_OUT_DIR}" ${krygen_command_sources}
DEPENDS ${KRYGEN_SOURCES} "${KRYGEN_K2C}"
WORKING_DIRECTORY "${KRYGEN_ROOT}"
VERBATIM
)
add_custom_command(
OUTPUT "${KRYGEN_K2C}"
COMMAND ${CMAKE_COMMAND} -E make_directory "${CMAKE_BINARY_DIR}/kryon-host-tools"
COMMAND "${KRYGEN_HOST_CC}" -Wall -Wextra -O2
-I${KRYGEN_KRYON_DIR}/cmd/kir
-I${KRYGEN_KRYON_DIR}/cmd/k2c
-o "${KRYGEN_K2C}"
${KRYGEN_K2C_SOURCES}
DEPENDS ${KRYGEN_K2C_SOURCES}
VERBATIM
)
add_custom_target("${KRYGEN_TARGET}" DEPENDS
${krygen_generated_sources}
${krygen_generated_headers}
"${KRYGEN_OUT_DIR}/kryon_project.c"
"${KRYGEN_OUT_DIR}/kryon_project.h"
)
set(${out_sources} ${krygen_generated_sources} PARENT_SCOPE)
set(${out_include_dir} "${KRYGEN_OUT_DIR}" PARENT_SCOPE)
endfunction()
+240
View File
@@ -0,0 +1,240 @@
#include "k2b_atlas.h"
#define STB_TRUETYPE_IMPLEMENTATION
#include "../../vendor/raylib/src/external/stb_truetype.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ATLAS_W 512
static void
put_u16(unsigned char *p, unsigned v)
{
p[0] = (unsigned char)v;
p[1] = (unsigned char)(v >> 8);
}
static void
put_u32(unsigned char *p, unsigned long v)
{
p[0] = (unsigned char)v;
p[1] = (unsigned char)(v >> 8);
p[2] = (unsigned char)(v >> 16);
p[3] = (unsigned char)(v >> 24);
}
/* Layout: "KFA1" u32 | size_count u16 | per-size 16-byte records
* (px u16 | glyphs u16 | w u16 | h u16 | table_off u32 | pixels_off u32),
* per-glyph 18-byte records (cp u32 | x,y,w,h u16 | xoff,yoff i16 |
* adv u16 in 1/256 px fixed point), then per-size RGBA8 white-on-alpha
* bitmaps.
*
* Rasterization is raylib-identical: per-glyph
* stbtt_GetCodepointBitmap at stbtt_ScaleForPixelHeight(size) with
* advances from stbtt_GetCodepointHMetrics * scale — the same calls
* rtext.c LoadFontData(FONT_DEFAULT) makes, so glyph coverage matches
* the native renderer bit-for-bit. Glyphs row-pack first-fit. */
unsigned char *
k2b_bake_atlas(const char *ttf_path, const unsigned int *codepoints,
int cp_count, const int *sizes, int size_count,
unsigned *out_len)
{
unsigned char *ttf = NULL;
long ttf_len;
FILE *f;
stbtt_fontinfo font;
unsigned char *buf = NULL;
unsigned buf_cap;
unsigned buf_len;
int s;
if(out_len != NULL)
*out_len = 0;
if(ttf_path == NULL || codepoints == NULL || cp_count <= 0 ||
sizes == NULL || size_count <= 0)
return NULL;
f = fopen(ttf_path, "rb");
if(f == NULL)
return NULL;
fseek(f, 0, SEEK_END);
ttf_len = ftell(f);
fseek(f, 0, SEEK_SET);
ttf = malloc((size_t)ttf_len);
if(ttf == NULL || fread(ttf, 1, (size_t)ttf_len, f) != (size_t)ttf_len) {
fclose(f);
free(ttf);
return NULL;
}
fclose(f);
if(!stbtt_InitFont(&font, ttf, 0)) {
free(ttf);
return NULL;
}
buf_len = 6 + (unsigned)size_count * 16;
buf_cap = buf_len + 4096;
buf = malloc(buf_cap);
if(buf == NULL) {
free(ttf);
return NULL;
}
put_u32(buf, 0x3141464Bu); /* "KFA1" */
put_u16(buf + 4, (unsigned)size_count);
for(s = 0; s < size_count; s++) {
int px = sizes[s];
float scale = stbtt_ScaleForPixelHeight(&font, (float)px);
int ascent = 0;
int descent = 0;
int line_gap = 0;
/* rtext.c line 730: offsetY += (int)(ascent*scale) — raylib's
* glyph offset is line-top-relative, not baseline-relative */
stbtt_GetFontVMetrics(&font, &ascent, &descent, &line_gap);
unsigned char *raw_px;
unsigned rec_bytes = (unsigned)cp_count * 18;
unsigned table_off;
unsigned pixels_off;
int height;
int i;
/* rec is recomputed after every realloc of buf */
{
int total_h = 1;
int row_h = 0;
int cur_x = 0;
for(i = 0; i < cp_count; i++) {
int x0 = 0;
int y0 = 0;
int x1 = 0;
int y1 = 0;
int w;
int h;
stbtt_GetCodepointBitmapBox(&font, (int)codepoints[i], scale,
scale, &x0, &y0, &x1, &y1);
w = x1 - x0;
h = y1 - y0;
if(w < 0)
w = 0;
if(h < 0)
h = 0;
if(cur_x + w > ATLAS_W) {
total_h += row_h > 0 ? row_h : 1;
row_h = 0;
cur_x = 0;
}
cur_x += w + 1;
if(h > row_h)
row_h = h;
}
height = total_h + row_h + 1;
}
while(buf_len + rec_bytes + (unsigned)ATLAS_W * height * 4 >
buf_cap) {
unsigned char *nb = realloc(buf, buf_cap * 2);
if(nb == NULL)
break;
buf = nb;
buf_cap *= 2;
}
if(buf_len + rec_bytes + (unsigned)ATLAS_W * height * 4 > buf_cap)
continue;
raw_px = calloc((size_t)ATLAS_W * height, 1);
if(raw_px == NULL)
continue;
table_off = buf_len;
{
int row_y = 0;
int row_h = 0;
int cur_x = 0;
unsigned char *tab = buf + table_off;
for(i = 0; i < cp_count; i++) {
int w = 0;
int h = 0;
int xoff = 0;
int yoff = 0;
int advance = 0;
int lsb = 0;
unsigned char *bm;
unsigned char *g = tab + (unsigned)i * 18;
bm = stbtt_GetCodepointBitmap(&font, scale, scale,
(int)codepoints[i], &w, &h,
&xoff, &yoff);
if(cur_x + w > ATLAS_W) {
row_y += row_h > 0 ? row_h : 1;
row_h = 0;
cur_x = 0;
}
if(w > 0 && h > 0 && bm != NULL && w <= ATLAS_W &&
row_y + h <= height && cur_x + w <= ATLAS_W) {
int gy;
for(gy = 0; gy < h; gy++)
memcpy(raw_px + (size_t)(row_y + gy) * ATLAS_W +
cur_x, bm + (size_t)gy * w, (size_t)w);
}
stbtt_FreeBitmap(bm, NULL);
stbtt_GetCodepointHMetrics(&font, (int)codepoints[i],
&advance, &lsb);
put_u32(g, codepoints[i]);
put_u16(g + 4, (unsigned short)cur_x);
put_u16(g + 6, (unsigned short)row_y);
put_u16(g + 8, (unsigned short)(w > 0 ? w : 0));
put_u16(g + 10, (unsigned short)(h > 0 ? h : 0));
put_u16(g + 12, (unsigned short)(short)xoff);
put_u16(g + 14,
(unsigned short)(short)(yoff +
(int)((float)ascent * scale)));
put_u16(g + 16, (unsigned short)(int)((float)advance *
scale * 256.0f + 0.5f));
cur_x += w + 1;
if(h > row_h)
row_h = h;
}
buf_len += rec_bytes;
}
pixels_off = buf_len;
{
unsigned char *rgba = buf + pixels_off;
long n = (long)ATLAS_W * height;
long k;
for(k = 0; k < n; k++) {
rgba[k * 4 + 0] = 0xff;
rgba[k * 4 + 1] = 0xff;
rgba[k * 4 + 2] = 0xff;
rgba[k * 4 + 3] = raw_px[k];
}
buf_len += (unsigned)n * 4;
}
free(raw_px);
{
unsigned char *rec = buf + 6 + (unsigned)s * 16;
put_u16(rec, (unsigned)px);
put_u16(rec + 2, (unsigned)cp_count);
put_u16(rec + 4, ATLAS_W);
put_u16(rec + 6, (unsigned)height);
put_u16(rec + 2, (unsigned)cp_count);
put_u16(rec + 4, ATLAS_W);
put_u16(rec + 6, (unsigned)height);
put_u32(rec + 8, table_off);
put_u32(rec + 12, pixels_off);
}
}
free(ttf);
if(buf_len <= 6 + (unsigned)size_count * 16) {
free(buf);
return NULL;
}
if(out_len != NULL)
*out_len = buf_len;
return buf;
}
+19
View File
@@ -0,0 +1,19 @@
#ifndef K2B_ATLAS_H
#define K2B_ATLAS_H
#include <stddef.h>
/* Bake a KFA1 glyph atlas (cartridge asset kind 1) from a TTF for the
* given charset and pixel sizes. Returns malloc'd bytes and length, or
* NULL when the font can't be loaded. Layout:
* u32 'KFA1' | u16 size_count
* per size: u16 px, u16 glyph_count, u16 w, u16 h, u32 table_off,
* u32 pixels_off (offsets from buffer start)
* glyph (16B): u32 cp | u16 x,y,w,h | i16 xoff,yoff | u16 advance
* RGBA8 pixels, white with alpha coverage. */
unsigned char *k2b_bake_atlas(const char *ttf_path,
const unsigned int *codepoints, int cp_count,
const int *sizes, int size_count,
unsigned *out_len);
#endif
+3713
View File
File diff suppressed because it is too large. Load diff
+23
View File
@@ -0,0 +1,23 @@
#include "k2b_stb.h"
#define STB_IMAGE_IMPLEMENTATION
#define STBI_NO_PSD
#define STBI_NO_TGA
#define STBI_NO_GIF
#define STBI_NO_HDR
#define STBI_NO_PIC
#define STBI_NO_PNM
#include "../../vendor/raylib/src/external/stb_image.h"
#include <stdlib.h>
int
k2b_decode_image(const char *file, unsigned char **rgba, int *w, int *h)
{
int n;
if(file == NULL || rgba == NULL || w == NULL || h == NULL)
return -1;
*rgba = stbi_load(file, w, h, &n, 4);
return *rgba != NULL ? 0 : -1;
}
+10
View File
@@ -0,0 +1,10 @@
#ifndef K2B_STB_H
#define K2B_STB_H
/* Image decoding for cartridge embedding, on the stb_image vendored with
* raylib. Returns 0 and fills *rgba (malloc'd, top-down RGBA8 rows) on
* success. */
int k2b_decode_image(const char *file, unsigned char **rgba, int *w, int *h);
#endif
+181
View File
@@ -0,0 +1,181 @@
/*
* k2b util — small path/string helpers used by the codegen.
*/
#include "krb.h"
#include "kir.h"
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>
void
die(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "k2b: ");
vfprintf(stderr, fmt, ap);
fputc('\n', stderr);
va_end(ap);
exit(1);
}
void
path_join(char *dst, size_t dst_size, const char *a, const char *b)
{
if(a == NULL || a[0] == '\0')
snprintf(dst, dst_size, "%s", b);
else if(a[strlen(a) - 1] == '/')
snprintf(dst, dst_size, "%s%s", a, b);
else
snprintf(dst, dst_size, "%s/%s", a, b);
}
void
mkdir_parent(const char *path)
{
char tmp[KIR_PATH_MAX];
size_t i;
snprintf(tmp, sizeof(tmp), "%s", path);
for(i = 1; i < strlen(tmp); i++) {
if(tmp[i] != '/')
continue;
tmp[i] = '\0';
if(mkdir(tmp, 0755) != 0 && errno != EEXIST)
die("%s: mkdir failed: %s", tmp, strerror(errno));
tmp[i] = '/';
}
}
void
header_guard(char *dst, size_t dst_size, const char *rel)
{
size_t n = 0;
if(dst_size > 4) {
dst[n++] = 'K';
dst[n++] = '2';
dst[n++] = 'B';
dst[n++] = '_';
}
for(const char *p = rel; *p != '\0' && n + 1 < dst_size; p++) {
char c = *p;
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9'))
dst[n++] = (c >= 'a' && c <= 'z') ? (char)(c - 'a' + 'A') : c;
else
dst[n++] = '_';
}
dst[n] = '\0';
}
void
strip_kry_ext(char *dst, size_t dst_size, const char *path)
{
size_t len;
if(path == NULL) {
if(dst_size > 0)
dst[0] = '\0';
return;
}
len = strlen(path);
if(len > 4 && strcmp(path + len - 4, ".kry") == 0)
len -= 4;
if(len >= dst_size)
len = dst_size - 1;
memcpy(dst, path, len);
dst[len] = '\0';
}
void
replace_path_basename(char *dst, size_t dst_size, const char *path,
const char *base)
{
const char *slash = NULL;
size_t dir_len;
if(dst_size == 0)
return;
for(const char *p = path; p != NULL && *p != '\0'; p++) {
if(*p == '/' || *p == '\\')
slash = p;
}
if(slash == NULL) {
snprintf(dst, dst_size, "%s", base);
return;
}
dir_len = (size_t)(slash - path + 1);
if(dir_len >= dst_size)
dir_len = dst_size - 1;
memcpy(dst, path, dir_len);
dst[dir_len] = '\0';
snprintf(dst + dir_len, dst_size - dir_len, "%s", base);
}
/* Path relative to root. Handles the common cases (path under root, or path
* already relative); does not fully normalize, which is enough for emitting
* cartridge output paths next to their source. */
const char *
relative_path(const char *root, const char *path)
{
static char rel[KIR_PATH_MAX];
size_t n;
if(root == NULL || root[0] == '\0')
return path;
n = strlen(root);
if(strncmp(path, root, n) == 0 && path[n] == '/')
snprintf(rel, sizeof(rel), "%s", path + n + 1);
else
snprintf(rel, sizeof(rel), "%s", path);
return rel;
}
int
is_ident_text(const char *text)
{
if(text == NULL || text[0] == '\0')
return 0;
if(!(isalpha((unsigned char)text[0]) || text[0] == '_'))
return 0;
for(const char *p = text + 1; *p != '\0'; p++) {
if(!(isalnum((unsigned char)*p) || *p == '_'))
return 0;
}
return 1;
}
void
c_string_literal(char *dst, size_t dst_size, const char *src)
{
size_t n = 0;
if(dst_size == 0)
return;
dst[n++] = '"';
for(const char *p = src != NULL ? src : ""; *p != '\0' && n + 2 < dst_size; p++) {
if(*p == '"' || *p == '\\') {
if(n + 2 >= dst_size)
break;
dst[n++] = '\\';
dst[n++] = *p;
} else if(*p == '\n') {
if(n + 2 >= dst_size)
break;
dst[n++] = '\\';
dst[n++] = 'n';
} else {
dst[n++] = *p;
}
}
if(n + 1 < dst_size)
dst[n++] = '"';
dst[n] = '\0';
}
+92
View File
@@ -0,0 +1,92 @@
/*
* k2b - .kry -> .krb cartridge compiler. Shares the Kir frontend with k2c:
* every .kry parses into a KirProgram (kir_parse.c), then lowers to a .krb
* cartridge + C host (k2b_krb.c). One frontend, two backends.
*/
#include "kir.h"
#include "kir_parse.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void write_krb(const KirModule *m, const char *root, const char *out_dir,
int no_main);
static int
validate_asserts(const KirModule *m)
{
for(int i = 0; i < m->assert_count; i++) {
const KirAssert *a = &m->asserts[i];
if(a->guard[0] != '\0') {
fprintf(stderr,
"k2b: %s:%d: guarded #assert is not supported by KRB: %s\n",
a->span.path, a->span.line, a->message);
return 0;
}
if(!a->known) {
fprintf(stderr,
"k2b: %s:%d: unresolved #assert is not supported by KRB: %s\n",
a->span.path, a->span.line, a->condition);
return 0;
}
if(!a->value) {
fprintf(stderr, "k2b: %s:%d: #assert failed: %s\n",
a->span.path, a->span.line, a->message);
return 0;
}
}
return 1;
}
static void
usage(void)
{
fprintf(stderr, "usage: k2b [--no-main] --root DIR -o DIR file.kry ...\n");
}
int
main(int argc, char **argv)
{
const char *root = NULL;
const char *out_dir = NULL;
int no_main = 0;
int i;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "--root") == 0 && i + 1 < argc) {
root = argv[++i];
} else if(strcmp(argv[i], "-o") == 0 && i + 1 < argc) {
out_dir = argv[++i];
} else if(strcmp(argv[i], "--no-main") == 0) {
no_main = 1;
} else if(argv[i][0] == '-') {
usage();
return 1;
} else {
break;
}
}
if(root == NULL || out_dir == NULL || i >= argc) {
usage();
return 1;
}
for(; i < argc; i++) {
KirProgram *prog = kir_parse_file(argv[i], root);
if(prog == NULL) {
fprintf(stderr, "k2b: failed to parse %s\n", argv[i]);
return 1;
}
for(int m = 0; m < prog->module_count; m++) {
if(!validate_asserts(&prog->modules[m])) {
KirProgramFree(prog);
return 1;
}
write_krb(&prog->modules[m], root, out_dir, no_main);
}
KirProgramFree(prog);
}
return 0;
}
+1668
View File
File diff suppressed because it is too large. Load diff
+37
View File
@@ -0,0 +1,37 @@
#ifndef K2C_LOWER_H
#define K2C_LOWER_H
#include "kir.h"
/* Cross-module symbol table: for each parsed module (by its slash-path),
* every function's .kry name -> full C name. Built by main after parsing all
* inputs; used to resolve alias-qualified calls (start.draw_start_page(...)
* -> ide_start_page_draw_start_page_kry_draw(...)). */
typedef struct K2cModuleSyms {
char module_stem[KIR_PATH_MAX]; /* source path minus .kry */
char module_slash[KIR_PATH_MAX];
struct {
char kry[KIR_NAME_MAX];
char c[KIR_NAME_MAX * 3];
} fns[256];
int fn_count;
} K2cModuleSyms;
/* Lower a KirProgram to C source (.c/.h). restab/restab_count resolve
* cross-module calls; pass NULL/0 to resolve same-module only. */
void k2c_lower(const KirProgram *program, const char *root,
const char *out_dir, const K2cModuleSyms *restab,
int restab_count);
/* Build the symbol table entry for one program into out. */
void k2c_build_syms(const KirProgram *program, K2cModuleSyms *out);
/* Full C name for a function (module prefix, colon naming, _kry_draw). */
void k2c_function_c_name(const KirModule *m, const KirFunction *fn,
char *dst, size_t dst_size);
/* k2c_project.c — kryon_project.h/.c (app-host ABI) after all files lower. */
void k2c_write_project(KirProgram *const *progs, int prog_count,
const char *root, const char *out_dir, int no_main);
#endif
+1801
View File
File diff suppressed because it is too large. Load diff
+42
View File
@@ -0,0 +1,42 @@
#ifndef K2C_PLAN9_H
#define K2C_PLAN9_H
/* Post-lowering pass that makes k2c output safe for the native Plan 9
* compilers (8c has no __auto_type, no multi-designator compound
* literals, and no declarations inside for()). Only runs under --plan9;
* the default output is byte-identical to before.
*
* The pass is purely syntactic: types are recovered from cast-literal
* expressions or from a return-type map built by scanning the project's
* headers (--include-dir), the same way the kryon surface declares
* single-line prototypes. */
/* Add a directory scanned (recursively, .h files) for prototypes when
* resolving __auto_type initializers. Call before k2c_lower. */
void k2c_plan9_add_include_dir(const char *dir);
/* Enable --plan9 output post-processing (off by default; the default
* output is unchanged). */
void k2c_plan9_set_enabled(int enabled);
int k2c_plan9_enabled(void);
/* Rewrite one generated C source for 8c. Returns a malloc'd buffer; the
* caller frees. Returns NULL on out-of-memory (caller keeps original). */
char *k2c_plan9_rewrite(const char *text);
/* Rewrite a generated file in place when the plan9 pass is enabled
* (weak-declaration exposure for project files, then the generic pass).
* Returns 0 on success. */
int k2c_plan9_rewrite_file(const char *path, int is_project);
/* Number of __auto_type declarations left unresolved by the last
* k2c_plan9_rewrite call (reported once per run by main). */
int k2c_plan9_unresolved(void);
/* Drop the __GNUC__ guard around the weak app-lifecycle declarations in
* generated project files: the native cpp does not define __GNUC__, so
* the guarded block would compile out and leave the calls without
* prototypes. */
char *k2c_plan9_rewrite_project(const char *text);
#endif
+442
View File
@@ -0,0 +1,442 @@
/*
* k2c_project.c — emit kryon_project.h/.c after all files lower. The
* app-host ABI (CreateAppHost/DestroyAppHost + route table) consumed by
* the preview tool and IDE host builds. Routes auto-collect from #ui
* functions. Explicit route{} blocks supply route id/title/group metadata
* when present.
*/
#include "k2c_lower.h"
#include "k2c_plan9.h"
#include "kir.h"
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
typedef struct K2cRoute {
char id[KIR_NAME_MAX];
char title[KIR_NAME_MAX];
char group[KIR_NAME_MAX];
char source_path[KIR_PATH_MAX];
const KirModule *m;
const KirFunction *fn;
} K2cRoute;
#define K2C_ROUTE_MAX 512
static const KirFunction *
find_ui_function(const KirModule *mod, const char *name)
{
if(mod == NULL || name == NULL || name[0] == '\0')
return NULL;
for(int i = 0; i < mod->function_count; i++) {
const KirFunction *fn = &mod->functions[i];
if(fn->is_public && fn->is_ui && strcmp(fn->name, name) == 0)
return fn;
}
return NULL;
}
static int
function_has_explicit_route(const KirModule *mod, const KirFunction *fn)
{
if(mod == NULL || fn == NULL)
return 0;
for(int i = 0; i < mod->route_count; i++) {
if(strcmp(mod->routes[i].page, fn->name) == 0)
return 1;
}
return 0;
}
static void
mkdir_parent_local(const char *path)
{
char tmp[KIR_PATH_MAX];
size_t i;
snprintf(tmp, sizeof(tmp), "%s", path);
for(i = 1; i < strlen(tmp); i++) {
if(tmp[i] == '/') {
tmp[i] = '\0';
mkdir(tmp, 0755);
tmp[i] = '/';
}
}
}
static void
c_str(char *dst, size_t dst_size, const char *src)
{
size_t n = 0;
dst[n++] = '"';
for(const char *p = src != NULL ? src : "";
*p != '\0' && n + 3 < dst_size; p++) {
if(*p == '"' || *p == '\\') {
dst[n++] = '\\';
dst[n++] = *p;
} else if(*p == '\n') {
dst[n++] = '\\';
dst[n++] = 'n';
} else {
dst[n++] = *p;
}
}
if(n < dst_size)
dst[n++] = '"';
dst[n] = '\0';
}
static int
collect_routes(KirProgram *const *progs, int prog_count,
K2cRoute *routes, int max_routes)
{
int count = 0;
for(int i = 0; i < prog_count; i++) {
const KirProgram *prog = progs[i];
if(prog == NULL)
continue;
for(int m = 0; m < prog->module_count; m++) {
const KirModule *mod = &prog->modules[m];
for(int j = 0; j < mod->route_count; j++) {
const KirRoute *route = &mod->routes[j];
const KirFunction *fn = find_ui_function(mod, route->page);
if(fn == NULL) {
fprintf(stderr, "%s:%d: route `%s` references missing #ui page `%s`\n",
route->span.path, route->span.line,
route->id, route->page);
continue;
}
if(count >= max_routes)
return count;
snprintf(routes[count].id, sizeof(routes[0].id), "%s",
route->id);
snprintf(routes[count].title, sizeof(routes[0].title), "%s",
route->title[0] != '\0' ? route->title : route->id);
snprintf(routes[count].group, sizeof(routes[0].group), "%s",
route->group[0] != '\0' ? route->group : "Project");
snprintf(routes[count].source_path,
sizeof(routes[0].source_path), "%s",
mod->source_path);
routes[count].m = mod;
routes[count].fn = fn;
count++;
}
for(int j = 0; j < mod->function_count; j++) {
const KirFunction *fn = &mod->functions[j];
if(!fn->is_public || !fn->is_ui || fn->name[0] == '\0')
continue;
if(function_has_explicit_route(mod, fn))
continue;
if(count >= max_routes)
return count;
snprintf(routes[count].id, sizeof(routes[0].id), "%s",
fn->name);
snprintf(routes[count].title, sizeof(routes[0].title), "%s",
fn->name);
snprintf(routes[count].group, sizeof(routes[0].group),
"Project");
snprintf(routes[count].source_path,
sizeof(routes[0].source_path), "%s",
mod->source_path);
routes[count].m = mod;
routes[count].fn = fn;
count++;
}
}
}
return count;
}
void
k2c_write_project(KirProgram *const *progs, int prog_count,
const char *root, const char *out_dir, int no_main)
{
K2cRoute routes[K2C_ROUTE_MAX];
char path[KIR_PATH_MAX];
const KirModule *appmod = NULL;
FILE *out;
int count;
(void)root;
if(progs == NULL || prog_count <= 0)
return;
count = collect_routes(progs, prog_count, routes, K2C_ROUTE_MAX);
/* the one app{} module (for main()) */
for(int i = 0; i < prog_count && appmod == NULL; i++) {
if(progs[i] == NULL)
continue;
for(int m = 0; m < progs[i]->module_count; m++)
if(progs[i]->modules[m].app.has_app) {
appmod = &progs[i]->modules[m];
break;
}
}
/* --- kryon_project.h --- */
snprintf(path, sizeof(path), "%s/kryon_project.h", out_dir);
mkdir_parent_local(path);
out = fopen(path, "wb");
if(out == NULL)
return;
fprintf(out, "/* Generated by k2c from project Kry files. */\n");
fprintf(out, "#ifndef K_KRYON_PROJECT_H\n#define K_KRYON_PROJECT_H\n\n");
for(int i = 0; i < prog_count; i++) {
const KirProgram *prog = progs[i];
if(prog == NULL)
continue;
for(int m = 0; m < prog->module_count; m++) {
const KirModule *mod = &prog->modules[m];
char stem[KIR_PATH_MAX];
size_t n = strlen(mod->source_path);
if(n > 4 && strcmp(mod->source_path + n - 4, ".kry") == 0)
n -= 4;
if(n >= sizeof(stem))
n = sizeof(stem) - 1;
memcpy(stem, mod->source_path, n);
stem[n] = '\0';
fprintf(out, "#include \"%s.h\"\n", stem);
}
}
fprintf(out, "\n#endif\n");
fclose(out);
if(count <= 0)
return;
/* --- kryon_project.c --- */
snprintf(path, sizeof(path), "%s/kryon_project.c", out_dir);
out = fopen(path, "wb");
if(out == NULL)
return;
fprintf(out, "/* Generated by k2c from project Kry files. */\n");
fprintf(out, "#include \"kryon_project.h\"\n");
fprintf(out, "#include \"app_runtime.h\"\n");
fprintf(out, "#include \"web.h\"\n");
if(appmod != NULL && appmod->app.font_examples)
fprintf(out, "#include \"kryon_example_font.h\"\n");
fprintf(out, "\n");
fprintf(out, "#if defined(__GNUC__) || defined(__clang__)\n");
fprintf(out, "void *CreateApp(const char *project_path) __attribute__((weak));\n");
fprintf(out, "void DestroyApp(void *app) __attribute__((weak));\n");
fprintf(out, "void ApplyRoute(void *app, const AppRouteInfo *route) __attribute__((weak));\n");
fprintf(out, "void BeginScreenDraw(void *app, Rectangle viewport) __attribute__((weak));\n");
fprintf(out, "#endif\n\n");
for(int i = 0; i < count; i++) {
char cname[KIR_NAME_MAX * 3];
char wrapper[64];
snprintf(wrapper, sizeof(wrapper), "kryon_project_draw_%d", i);
k2c_function_c_name(routes[i].m, routes[i].fn, cname, sizeof(cname));
fprintf(out, "static void\n%s(void *app, Rectangle viewport)\n{\n",
wrapper);
fprintf(out, " if(BeginScreenDraw != 0)\n");
fprintf(out, " BeginScreenDraw(app, viewport);\n");
if(strstr(routes[i].fn->args, "Rectangle") != NULL)
fprintf(out, " (void)app;\n %s(viewport);\n", cname);
else if(routes[i].fn->args[0] != '\0')
fprintf(out, " (void)viewport;\n %s(app);\n", cname);
else
fprintf(out, " (void)app;\n (void)viewport;\n %s();\n",
cname);
fprintf(out, "}\n\n");
}
fprintf(out, "static const AppRouteInfo kryon_project_routes[%d];\n\n",
count);
fprintf(out, "static void\nkryon_project_enter(void *app, int index)\n{\n");
fprintf(out, " if(ApplyRoute == 0 || index < 0 || index >= %d)\n",
count);
fprintf(out, " return;\n");
fprintf(out, " ApplyRoute(app, &kryon_project_routes[index]);\n");
fprintf(out, "}\n\n");
fprintf(out, "static const AppRouteInfo kryon_project_routes[] = {\n");
for(int i = 0; i < count; i++) {
char id[KIR_NAME_MAX * 2];
char title[KIR_NAME_MAX * 2];
char group[KIR_NAME_MAX * 2];
char source[KIR_PATH_MAX * 2];
char wrapper[64];
c_str(id, sizeof(id), routes[i].id);
c_str(title, sizeof(title), routes[i].title);
c_str(group, sizeof(group), routes[i].group);
c_str(source, sizeof(source), routes[i].source_path);
snprintf(wrapper, sizeof(wrapper), "kryon_project_draw_%d", i);
fprintf(out, " {%s, %s, %s, %s, kryon_project_enter, %s},\n",
id, group, title, source, wrapper);
}
fprintf(out, "};\n\n");
fprintf(out, "static App kryon_project_runtime;\n");
fprintf(out, "static AppHost kryon_project_host;\n\n");
fprintf(out, "AppHost *\nCreateAppHost(int abi_version, const char *project_path)\n{\n");
fprintf(out, " void *app = 0;\n");
fprintf(out, " if(abi_version != APP_HOST_ABI_VERSION)\n");
fprintf(out, " return 0;\n");
fprintf(out, " if(CreateApp != 0) {\n");
fprintf(out, " app = CreateApp(project_path);\n");
fprintf(out, " if(app == 0)\n");
fprintf(out, " return 0;\n");
fprintf(out, " } else {\n");
fprintf(out, " (void)project_path;\n");
fprintf(out, " }\n");
fprintf(out, " kryon_project_runtime.app = app;\n");
fprintf(out, " kryon_project_runtime.routes = kryon_project_routes;\n");
fprintf(out, " kryon_project_runtime.route_count = (int)(sizeof(kryon_project_routes) / sizeof(kryon_project_routes[0]));\n");
fprintf(out, " kryon_project_runtime.selected_route = 0;\n");
fprintf(out, " BindAppHost(&kryon_project_runtime, &kryon_project_host);\n");
fprintf(out, " SetAppScreen(&kryon_project_host, 0);\n");
fprintf(out, " return &kryon_project_host;\n}\n\n");
fprintf(out, "void\nDestroyAppHost(AppHost *host)\n{\n");
fprintf(out, " if(host == 0 || host != &kryon_project_host)\n");
fprintf(out, " return;\n");
fprintf(out, " if(DestroyApp != 0 && kryon_project_runtime.app != 0)\n");
fprintf(out, " DestroyApp(kryon_project_runtime.app);\n");
fprintf(out, " kryon_project_runtime = (App){0};\n");
fprintf(out, " kryon_project_host = (AppHost){0};\n}\n");
fclose(out);
k2c_plan9_rewrite_file(path, 1);
/* --- main() (hook-driven, from KirAppMeta) --- */
if(no_main || appmod == NULL)
return;
out = fopen(path, "ab");
if(out == NULL)
return;
{
int width = appmod->app.width > 0 ? appmod->app.width : 800;
int height = appmod->app.height > 0 ? appmod->app.height : 600;
int fps = appmod->app.fps > 0 ? appmod->app.fps : 60;
int route_host_main = appmod->app.frame[0] == '\0' && count > 0;
char title[KIR_NAME_MAX * 2];
c_str(title, sizeof(title), appmod->app.title);
fprintf(out, "\nint\nmain(void)\n{\n");
if(route_host_main) {
fprintf(out, " AppHost *host;\n");
fprintf(out, " int route_version = -1;\n");
}
fprintf(out, " int width = %d;\n", width);
fprintf(out, " int height = %d;\n", height);
fprintf(out, "#if defined(PLATFORM_WEB)\n");
fprintf(out, " SetConfigFlags(GetWebWindowFlags());\n");
fprintf(out, " GetWebViewportSize(width, height, &width, &height);\n");
fprintf(out, "#endif\n");
fprintf(out, " InitWindow(width, height, %s);\n", title);
fprintf(out, " SetTargetFPS(%d);\n", fps);
if(appmod->app.font_examples)
fprintf(out, " LoadExampleUIFont();\n");
fprintf(out, " InitUI(width, height, GetUIScale());\n");
if(appmod->app.theme[0] != '\0')
fprintf(out, " SetCurrentTheme(%s, %d);\n",
appmod->app.theme, appmod->app.dark_mode);
if(appmod->app.init[0] != '\0') {
char hook[KIR_NAME_MAX * 3];
int found = 0;
for(int j = 0; j < appmod->function_count && !found; j++) {
if(strcmp(appmod->functions[j].name, appmod->app.init) == 0) {
k2c_function_c_name(appmod, &appmod->functions[j],
hook, sizeof(hook));
found = 1;
}
}
fprintf(out, " %s();\n",
found ? hook : appmod->app.init);
}
if(route_host_main) {
fprintf(out, " host = CreateAppHost(APP_HOST_ABI_VERSION, \".\");\n");
fprintf(out, " if(host == 0) {\n");
fprintf(out, " CloseWindow();\n");
fprintf(out, " return 1;\n");
fprintf(out, " }\n");
}
fprintf(out, " while(!WindowShouldClose()) {\n");
if(appmod->app.frame[0] != '\0') {
char hook[KIR_NAME_MAX * 3];
const KirFunction *entry = NULL;
int found = 0;
for(int j = 0; j < appmod->function_count && !found; j++) {
if(strcmp(appmod->functions[j].name, appmod->app.frame) == 0) {
k2c_function_c_name(appmod, &appmod->functions[j],
hook, sizeof(hook));
entry = &appmod->functions[j];
found = 1;
}
}
if(entry != NULL && entry->is_ui) {
fprintf(out, " BeginFrame();\n");
fprintf(out, " BeginUIFrame(GetFrameWidth(), "
"GetFrameHeight(), GetFrameScale());\n");
fprintf(out, " BeginUI(Key(\"%s\"));\n", hook);
if(strstr(entry->args, "Rectangle") != NULL) {
fprintf(out, " %s((Rectangle){0, 0, "
"(float)GetFrameWidth(), (float)GetFrameHeight()});\n",
hook);
} else {
fprintf(out, " %s();\n", hook);
}
fprintf(out, " EndUI();\n");
fprintf(out, " EndUIFrame();\n");
fprintf(out, " EndFrame();\n");
} else {
fprintf(out, " %s();\n",
found ? hook : appmod->app.frame);
}
} else if(route_host_main) {
fprintf(out, " int next_route_version = GetRouteVersion();\n");
fprintf(out, " if(next_route_version != route_version) {\n");
fprintf(out, " if(!SetAppScreenFromRoute(host))\n");
fprintf(out, " ReplaceAppScreenRoute(host, 0);\n");
fprintf(out, " route_version = GetRouteVersion();\n");
fprintf(out, " }\n");
fprintf(out, " BeginFrame();\n");
fprintf(out, " BeginUIFrame(GetFrameWidth(), "
"GetFrameHeight(), GetFrameScale());\n");
fprintf(out, " BeginUI(Key(\"kryon_project\"));\n");
fprintf(out, " DrawAppScreen(host, (Rectangle){0, 0, "
"(float)GetFrameWidth(), (float)GetFrameHeight()});\n");
fprintf(out, " EndUI();\n");
fprintf(out, " EndUIFrame();\n");
fprintf(out, " EndFrame();\n");
} else {
fprintf(out, " ;\n");
}
fprintf(out, " }\n");
if(appmod->app.shutdown[0] != '\0') {
char hook[KIR_NAME_MAX * 3];
int found = 0;
for(int j = 0; j < appmod->function_count && !found; j++) {
if(strcmp(appmod->functions[j].name, appmod->app.shutdown) == 0) {
k2c_function_c_name(appmod, &appmod->functions[j],
hook, sizeof(hook));
found = 1;
}
}
fprintf(out, " %s();\n",
found ? hook : appmod->app.shutdown);
}
if(route_host_main)
fprintf(out, " DestroyAppHost(host);\n");
if(appmod->app.font_examples)
fprintf(out, " UnloadExampleUIFont();\n");
fprintf(out, " CloseWindow();\n");
fprintf(out, " return 0;\n}\n");
}
fclose(out);
k2c_plan9_rewrite_file(path, 1);
}
+97
View File
@@ -0,0 +1,97 @@
/*
* k2c - .kry -> C compiler. Kir is the only pipeline: every .kry parses
* into a KirProgram (kir_parse.c) and lowers to C (k2c_lower.c). All inputs
* are parsed first so cross-module calls resolve through one symbol table.
*/
#include "kir.h"
#include "kir_parse.h"
#include "k2c_lower.h"
#include "k2c_plan9.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void
usage(void)
{
fprintf(stderr,
"usage: k2c [--no-main] [--plan9] [--include-dir DIR] "
"--root DIR -o DIR file.kry ...\n");
}
int
main(int argc, char **argv)
{
const char *root = NULL;
const char *out_dir = NULL;
int no_main = 0;
int plan9 = 0;
int unresolved = 0;
KirProgram **progs;
K2cModuleSyms *syms;
int file_count;
int i;
int first_file = 0;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "--root") == 0 && i + 1 < argc) {
root = argv[++i];
} else if(strcmp(argv[i], "-o") == 0 && i + 1 < argc) {
out_dir = argv[++i];
} else if(strcmp(argv[i], "--no-main") == 0) {
no_main = 1;
} else if(strcmp(argv[i], "--plan9") == 0) {
plan9 = 1;
} else if(strcmp(argv[i], "--include-dir") == 0 && i + 1 < argc) {
k2c_plan9_add_include_dir(argv[++i]);
} else if(argv[i][0] == '-') {
usage();
return 1;
} else {
first_file = i;
break;
}
}
if(root == NULL || out_dir == NULL || first_file == 0) {
usage();
return 1;
}
file_count = argc - first_file;
progs = calloc((size_t)file_count, sizeof(*progs));
syms = calloc((size_t)file_count, sizeof(*syms));
if(progs == NULL || syms == NULL) {
fprintf(stderr, "k2c: out of memory\n");
return 1;
}
k2c_plan9_set_enabled(plan9);
/* Pass 1: parse every file, build the cross-module symbol table. */
for(i = 0; i < file_count; i++) {
progs[i] = kir_parse_file(argv[first_file + i], root);
if(progs[i] == NULL) {
fprintf(stderr, "k2c: failed to parse %s\n",
argv[first_file + i]);
return 1;
}
k2c_build_syms(progs[i], &syms[i]);
}
/* Pass 2: lower with full cross-module resolution. */
for(i = 0; i < file_count; i++)
k2c_lower(progs[i], root, out_dir, syms, file_count);
k2c_write_project(progs, file_count, root, out_dir, no_main);
for(i = 0; i < file_count; i++)
KirProgramFree(progs[i]);
free(progs);
free(syms);
unresolved = k2c_plan9_unresolved();
if(plan9 && unresolved > 0) {
/* Unresolved declarations are usually inside platform guards the
* native build compiles out; the in-guest compile is the final
* arbiter, so warn rather than fail. */
fprintf(stderr,
"k2c: --plan9 left %d __auto_type declarations unresolved "
"(guarded code compiles out; the rest must be resolvable)\n",
unresolved);
}
return 0;
}
File diff suppressed because it is too large. Load diff
+37
View File
@@ -0,0 +1,37 @@
#ifndef K2CPP_LOWER_H
#define K2CPP_LOWER_H
#include "kir.h"
/* Cross-module symbol table: for each parsed module (by its slash-path),
* every function's .kry name -> full C name. Built by main after parsing all
* inputs; used to resolve alias-qualified calls (start.draw_start_page(...)
* -> ide_start_page_draw_start_page_kry_draw(...)). */
typedef struct K2cppModuleSyms {
char module_stem[KIR_PATH_MAX]; /* source path minus .kry */
char module_slash[KIR_PATH_MAX];
struct {
char kry[KIR_NAME_MAX];
char c[KIR_NAME_MAX * 3];
} fns[256];
int fn_count;
} K2cppModuleSyms;
/* Lower a KirProgram to C++ source (.cpp/.hpp). restab/restab_count resolve
* cross-module calls; pass NULL/0 to resolve same-module only. */
void k2cpp_lower(const KirProgram *program, const char *root,
const char *out_dir, const K2cppModuleSyms *restab,
int restab_count);
/* Build the symbol table entry for one program into out. */
void k2cpp_build_syms(const KirProgram *program, K2cppModuleSyms *out);
/* Full C name for a function (module prefix, colon naming, _kry_draw). */
void k2cpp_function_c_name(const KirModule *m, const KirFunction *fn,
char *dst, size_t dst_size);
/* k2cpp_project.c — kryon_project.h/.c (app-host ABI) after all files lower. */
void k2cpp_write_project(KirProgram *const *progs, int prog_count,
const char *root, const char *out_dir, int no_main);
#endif
+441
View File
@@ -0,0 +1,441 @@
/*
* k2cpp_project.c — emit kryon_project.h/.c after all files lower (the
* project files stay plain C; the generated module headers are .hpp but
* self-guard their extern "C" so C translation units include them too). The
* app-host ABI (CreateAppHost/DestroyAppHost + route table) consumed by
* the preview tool and IDE host builds. Routes auto-collect from #ui
* functions. Explicit route{} blocks supply route id/title/group metadata
* when present.
*/
#include "k2cpp_lower.h"
#include "kir.h"
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
typedef struct K2cppRoute {
char id[KIR_NAME_MAX];
char title[KIR_NAME_MAX];
char group[KIR_NAME_MAX];
char source_path[KIR_PATH_MAX];
const KirModule *m;
const KirFunction *fn;
} K2cppRoute;
#define K2CPP_ROUTE_MAX 512
static const KirFunction *
find_ui_function(const KirModule *mod, const char *name)
{
if(mod == NULL || name == NULL || name[0] == '\0')
return NULL;
for(int i = 0; i < mod->function_count; i++) {
const KirFunction *fn = &mod->functions[i];
if(fn->is_public && fn->is_ui && strcmp(fn->name, name) == 0)
return fn;
}
return NULL;
}
static int
function_has_explicit_route(const KirModule *mod, const KirFunction *fn)
{
if(mod == NULL || fn == NULL)
return 0;
for(int i = 0; i < mod->route_count; i++) {
if(strcmp(mod->routes[i].page, fn->name) == 0)
return 1;
}
return 0;
}
static void
mkdir_parent_local(const char *path)
{
char tmp[KIR_PATH_MAX];
size_t i;
snprintf(tmp, sizeof(tmp), "%s", path);
for(i = 1; i < strlen(tmp); i++) {
if(tmp[i] == '/') {
tmp[i] = '\0';
mkdir(tmp, 0755);
tmp[i] = '/';
}
}
}
static void
c_str(char *dst, size_t dst_size, const char *src)
{
size_t n = 0;
dst[n++] = '"';
for(const char *p = src != NULL ? src : "";
*p != '\0' && n + 3 < dst_size; p++) {
if(*p == '"' || *p == '\\') {
dst[n++] = '\\';
dst[n++] = *p;
} else if(*p == '\n') {
dst[n++] = '\\';
dst[n++] = 'n';
} else {
dst[n++] = *p;
}
}
if(n < dst_size)
dst[n++] = '"';
dst[n] = '\0';
}
static int
collect_routes(KirProgram *const *progs, int prog_count,
K2cppRoute *routes, int max_routes)
{
int count = 0;
for(int i = 0; i < prog_count; i++) {
const KirProgram *prog = progs[i];
if(prog == NULL)
continue;
for(int m = 0; m < prog->module_count; m++) {
const KirModule *mod = &prog->modules[m];
for(int j = 0; j < mod->route_count; j++) {
const KirRoute *route = &mod->routes[j];
const KirFunction *fn = find_ui_function(mod, route->page);
if(fn == NULL) {
fprintf(stderr, "%s:%d: route `%s` references missing #ui page `%s`\n",
route->span.path, route->span.line,
route->id, route->page);
continue;
}
if(count >= max_routes)
return count;
snprintf(routes[count].id, sizeof(routes[0].id), "%s",
route->id);
snprintf(routes[count].title, sizeof(routes[0].title), "%s",
route->title[0] != '\0' ? route->title : route->id);
snprintf(routes[count].group, sizeof(routes[0].group), "%s",
route->group[0] != '\0' ? route->group : "Project");
snprintf(routes[count].source_path,
sizeof(routes[0].source_path), "%s",
mod->source_path);
routes[count].m = mod;
routes[count].fn = fn;
count++;
}
for(int j = 0; j < mod->function_count; j++) {
const KirFunction *fn = &mod->functions[j];
if(!fn->is_public || !fn->is_ui || fn->name[0] == '\0')
continue;
if(function_has_explicit_route(mod, fn))
continue;
if(count >= max_routes)
return count;
snprintf(routes[count].id, sizeof(routes[0].id), "%s",
fn->name);
snprintf(routes[count].title, sizeof(routes[0].title), "%s",
fn->name);
snprintf(routes[count].group, sizeof(routes[0].group),
"Project");
snprintf(routes[count].source_path,
sizeof(routes[0].source_path), "%s",
mod->source_path);
routes[count].m = mod;
routes[count].fn = fn;
count++;
}
}
}
return count;
}
void
k2cpp_write_project(KirProgram *const *progs, int prog_count,
const char *root, const char *out_dir, int no_main)
{
K2cppRoute routes[K2CPP_ROUTE_MAX];
char path[KIR_PATH_MAX];
const KirModule *appmod = NULL;
FILE *out;
int count;
(void)root;
if(progs == NULL || prog_count <= 0)
return;
count = collect_routes(progs, prog_count, routes, K2CPP_ROUTE_MAX);
/* the one app{} module (for main()) */
for(int i = 0; i < prog_count && appmod == NULL; i++) {
if(progs[i] == NULL)
continue;
for(int m = 0; m < progs[i]->module_count; m++)
if(progs[i]->modules[m].app.has_app) {
appmod = &progs[i]->modules[m];
break;
}
}
/* --- kryon_project.h --- */
snprintf(path, sizeof(path), "%s/kryon_project.h", out_dir);
mkdir_parent_local(path);
out = fopen(path, "wb");
if(out == NULL)
return;
fprintf(out, "/* Generated by k2cpp from project Kry files. */\n");
fprintf(out, "#ifndef K_KRYON_PROJECT_H\n#define K_KRYON_PROJECT_H\n\n");
for(int i = 0; i < prog_count; i++) {
const KirProgram *prog = progs[i];
if(prog == NULL)
continue;
for(int m = 0; m < prog->module_count; m++) {
const KirModule *mod = &prog->modules[m];
char stem[KIR_PATH_MAX];
size_t n = strlen(mod->source_path);
if(n > 4 && strcmp(mod->source_path + n - 4, ".kry") == 0)
n -= 4;
if(n >= sizeof(stem))
n = sizeof(stem) - 1;
memcpy(stem, mod->source_path, n);
stem[n] = '\0';
fprintf(out, "#include \"%s.hpp\"\n", stem);
}
}
fprintf(out, "\n#endif\n");
fclose(out);
if(count <= 0)
return;
/* --- kryon_project.c --- */
snprintf(path, sizeof(path), "%s/kryon_project.c", out_dir);
out = fopen(path, "wb");
if(out == NULL)
return;
fprintf(out, "/* Generated by k2cpp from project Kry files. */\n");
fprintf(out, "#include \"kryon_project.h\"\n");
fprintf(out, "#include \"app_runtime.h\"\n");
fprintf(out, "#include \"web.h\"\n");
if(appmod != NULL && appmod->app.font_examples)
fprintf(out, "#include \"kryon_example_font.h\"\n");
fprintf(out, "\n");
fprintf(out, "#if defined(__GNUC__) || defined(__clang__)\n");
fprintf(out, "void *CreateApp(const char *project_path) __attribute__((weak));\n");
fprintf(out, "void DestroyApp(void *app) __attribute__((weak));\n");
fprintf(out, "void ApplyRoute(void *app, const AppRouteInfo *route) __attribute__((weak));\n");
fprintf(out, "void BeginScreenDraw(void *app, Rectangle viewport) __attribute__((weak));\n");
fprintf(out, "#endif\n\n");
for(int i = 0; i < count; i++) {
char cname[KIR_NAME_MAX * 3];
char wrapper[64];
snprintf(wrapper, sizeof(wrapper), "kryon_project_draw_%d", i);
k2cpp_function_c_name(routes[i].m, routes[i].fn, cname, sizeof(cname));
fprintf(out, "static void\n%s(void *app, Rectangle viewport)\n{\n",
wrapper);
fprintf(out, " if(BeginScreenDraw != 0)\n");
fprintf(out, " BeginScreenDraw(app, viewport);\n");
if(strstr(routes[i].fn->args, "Rectangle") != NULL)
fprintf(out, " (void)app;\n %s(viewport);\n", cname);
else if(routes[i].fn->args[0] != '\0')
fprintf(out, " (void)viewport;\n %s(app);\n", cname);
else
fprintf(out, " (void)app;\n (void)viewport;\n %s();\n",
cname);
fprintf(out, "}\n\n");
}
fprintf(out, "static const AppRouteInfo kryon_project_routes[%d];\n\n",
count);
fprintf(out, "static void\nkryon_project_enter(void *app, int index)\n{\n");
fprintf(out, " if(ApplyRoute == 0 || index < 0 || index >= %d)\n",
count);
fprintf(out, " return;\n");
fprintf(out, " ApplyRoute(app, &kryon_project_routes[index]);\n");
fprintf(out, "}\n\n");
fprintf(out, "static const AppRouteInfo kryon_project_routes[] = {\n");
for(int i = 0; i < count; i++) {
char id[KIR_NAME_MAX * 2];
char title[KIR_NAME_MAX * 2];
char group[KIR_NAME_MAX * 2];
char source[KIR_PATH_MAX * 2];
char wrapper[64];
c_str(id, sizeof(id), routes[i].id);
c_str(title, sizeof(title), routes[i].title);
c_str(group, sizeof(group), routes[i].group);
c_str(source, sizeof(source), routes[i].source_path);
snprintf(wrapper, sizeof(wrapper), "kryon_project_draw_%d", i);
fprintf(out, " {%s, %s, %s, %s, kryon_project_enter, %s},\n",
id, group, title, source, wrapper);
}
fprintf(out, "};\n\n");
fprintf(out, "static App kryon_project_runtime;\n");
fprintf(out, "static AppHost kryon_project_host;\n\n");
fprintf(out, "AppHost *\nCreateAppHost(int abi_version, const char *project_path)\n{\n");
fprintf(out, " void *app = 0;\n");
fprintf(out, " if(abi_version != APP_HOST_ABI_VERSION)\n");
fprintf(out, " return 0;\n");
fprintf(out, " if(CreateApp != 0) {\n");
fprintf(out, " app = CreateApp(project_path);\n");
fprintf(out, " if(app == 0)\n");
fprintf(out, " return 0;\n");
fprintf(out, " } else {\n");
fprintf(out, " (void)project_path;\n");
fprintf(out, " }\n");
fprintf(out, " kryon_project_runtime.app = app;\n");
fprintf(out, " kryon_project_runtime.routes = kryon_project_routes;\n");
fprintf(out, " kryon_project_runtime.route_count = (int)(sizeof(kryon_project_routes) / sizeof(kryon_project_routes[0]));\n");
fprintf(out, " kryon_project_runtime.selected_route = 0;\n");
fprintf(out, " BindAppHost(&kryon_project_runtime, &kryon_project_host);\n");
fprintf(out, " SetAppScreen(&kryon_project_host, 0);\n");
fprintf(out, " return &kryon_project_host;\n}\n\n");
fprintf(out, "void\nDestroyAppHost(AppHost *host)\n{\n");
fprintf(out, " if(host == 0 || host != &kryon_project_host)\n");
fprintf(out, " return;\n");
fprintf(out, " if(DestroyApp != 0 && kryon_project_runtime.app != 0)\n");
fprintf(out, " DestroyApp(kryon_project_runtime.app);\n");
fprintf(out, " kryon_project_runtime = (App){0};\n");
fprintf(out, " kryon_project_host = (AppHost){0};\n}\n");
fclose(out);
/* --- main() (hook-driven, from KirAppMeta) --- */
if(no_main || appmod == NULL)
return;
out = fopen(path, "ab");
if(out == NULL)
return;
{
int width = appmod->app.width > 0 ? appmod->app.width : 800;
int height = appmod->app.height > 0 ? appmod->app.height : 600;
int fps = appmod->app.fps > 0 ? appmod->app.fps : 60;
int route_host_main = appmod->app.frame[0] == '\0' && count > 0;
char title[KIR_NAME_MAX * 2];
c_str(title, sizeof(title), appmod->app.title);
fprintf(out, "\nint\nmain(void)\n{\n");
if(route_host_main) {
fprintf(out, " AppHost *host;\n");
fprintf(out, " int route_version = -1;\n");
}
fprintf(out, " int width = %d;\n", width);
fprintf(out, " int height = %d;\n", height);
fprintf(out, "#if defined(PLATFORM_WEB)\n");
fprintf(out, " SetConfigFlags(GetWebWindowFlags());\n");
fprintf(out, " GetWebViewportSize(width, height, &width, &height);\n");
fprintf(out, "#endif\n");
fprintf(out, " InitWindow(width, height, %s);\n", title);
fprintf(out, " SetTargetFPS(%d);\n", fps);
if(appmod->app.font_examples)
fprintf(out, " LoadExampleUIFont();\n");
fprintf(out, " InitUI(width, height, GetUIScale());\n");
if(appmod->app.theme[0] != '\0')
fprintf(out, " SetCurrentTheme(%s, %d);\n",
appmod->app.theme, appmod->app.dark_mode);
if(appmod->app.init[0] != '\0') {
char hook[KIR_NAME_MAX * 3];
int found = 0;
for(int j = 0; j < appmod->function_count && !found; j++) {
if(strcmp(appmod->functions[j].name, appmod->app.init) == 0) {
k2cpp_function_c_name(appmod, &appmod->functions[j],
hook, sizeof(hook));
found = 1;
}
}
fprintf(out, " %s();\n",
found ? hook : appmod->app.init);
}
if(route_host_main) {
fprintf(out, " host = CreateAppHost(APP_HOST_ABI_VERSION, \".\");\n");
fprintf(out, " if(host == 0) {\n");
fprintf(out, " CloseWindow();\n");
fprintf(out, " return 1;\n");
fprintf(out, " }\n");
}
fprintf(out, " while(!WindowShouldClose()) {\n");
if(appmod->app.frame[0] != '\0') {
char hook[KIR_NAME_MAX * 3];
const KirFunction *entry = NULL;
int found = 0;
for(int j = 0; j < appmod->function_count && !found; j++) {
if(strcmp(appmod->functions[j].name, appmod->app.frame) == 0) {
k2cpp_function_c_name(appmod, &appmod->functions[j],
hook, sizeof(hook));
entry = &appmod->functions[j];
found = 1;
}
}
if(entry != NULL && entry->is_ui) {
fprintf(out, " BeginFrame();\n");
fprintf(out, " BeginUIFrame(GetFrameWidth(), "
"GetFrameHeight(), GetFrameScale());\n");
fprintf(out, " BeginUI(Key(\"%s\"));\n", hook);
if(strstr(entry->args, "Rectangle") != NULL) {
fprintf(out, " %s((Rectangle){0, 0, "
"(float)GetFrameWidth(), (float)GetFrameHeight()});\n",
hook);
} else {
fprintf(out, " %s();\n", hook);
}
fprintf(out, " EndUI();\n");
fprintf(out, " EndUIFrame();\n");
fprintf(out, " EndFrame();\n");
} else {
fprintf(out, " %s();\n",
found ? hook : appmod->app.frame);
}
} else if(route_host_main) {
fprintf(out, " int next_route_version = GetRouteVersion();\n");
fprintf(out, " if(next_route_version != route_version) {\n");
fprintf(out, " if(!SetAppScreenFromRoute(host))\n");
fprintf(out, " ReplaceAppScreenRoute(host, 0);\n");
fprintf(out, " route_version = GetRouteVersion();\n");
fprintf(out, " }\n");
fprintf(out, " BeginFrame();\n");
fprintf(out, " BeginUIFrame(GetFrameWidth(), "
"GetFrameHeight(), GetFrameScale());\n");
fprintf(out, " BeginUI(Key(\"kryon_project\"));\n");
fprintf(out, " DrawAppScreen(host, (Rectangle){0, 0, "
"(float)GetFrameWidth(), (float)GetFrameHeight()});\n");
fprintf(out, " EndUI();\n");
fprintf(out, " EndUIFrame();\n");
fprintf(out, " EndFrame();\n");
} else {
fprintf(out, " ;\n");
}
fprintf(out, " }\n");
if(appmod->app.shutdown[0] != '\0') {
char hook[KIR_NAME_MAX * 3];
int found = 0;
for(int j = 0; j < appmod->function_count && !found; j++) {
if(strcmp(appmod->functions[j].name, appmod->app.shutdown) == 0) {
k2cpp_function_c_name(appmod, &appmod->functions[j],
hook, sizeof(hook));
found = 1;
}
}
fprintf(out, " %s();\n",
found ? hook : appmod->app.shutdown);
}
if(route_host_main)
fprintf(out, " DestroyAppHost(host);\n");
if(appmod->app.font_examples)
fprintf(out, " UnloadExampleUIFont();\n");
fprintf(out, " CloseWindow();\n");
fprintf(out, " return 0;\n}\n");
}
fclose(out);
}
+82
View File
@@ -0,0 +1,82 @@
/*
* k2cpp - .kry -> C++ compiler. Kir is the only pipeline: every .kry parses
* into a KirProgram (kir_parse.c) and lowers to C++ source that calls the
* C Kryon runtime through extern "C" (k2cpp_lower.c). All inputs are parsed
* first so cross-module calls resolve through one symbol table. Emitted
* declarations keep C linkage so generated modules interop with k2c output
* and the plain-C kryon_project files.
*/
#include "kir.h"
#include "kir_parse.h"
#include "k2cpp_lower.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void
usage(void)
{
fprintf(stderr,
"usage: k2cpp [--no-main] "
"--root DIR -o DIR file.kry ...\n");
}
int
main(int argc, char **argv)
{
const char *root = NULL;
const char *out_dir = NULL;
int no_main = 0;
KirProgram **progs;
K2cppModuleSyms *syms;
int file_count;
int i;
int first_file = 0;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "--root") == 0 && i + 1 < argc) {
root = argv[++i];
} else if(strcmp(argv[i], "-o") == 0 && i + 1 < argc) {
out_dir = argv[++i];
} else if(strcmp(argv[i], "--no-main") == 0) {
no_main = 1;
} else if(argv[i][0] == '-') {
usage();
return 1;
} else {
first_file = i;
break;
}
}
if(root == NULL || out_dir == NULL || first_file == 0) {
usage();
return 1;
}
file_count = argc - first_file;
progs = calloc((size_t)file_count, sizeof(*progs));
syms = calloc((size_t)file_count, sizeof(*syms));
if(progs == NULL || syms == NULL) {
fprintf(stderr, "k2cpp: out of memory\n");
return 1;
}
/* Pass 1: parse every file, build the cross-module symbol table. */
for(i = 0; i < file_count; i++) {
progs[i] = kir_parse_file(argv[first_file + i], root);
if(progs[i] == NULL) {
fprintf(stderr, "k2cpp: failed to parse %s\n",
argv[first_file + i]);
return 1;
}
k2cpp_build_syms(progs[i], &syms[i]);
}
/* Pass 2: lower with full cross-module resolution. */
for(i = 0; i < file_count; i++)
k2cpp_lower(progs[i], root, out_dir, syms, file_count);
k2cpp_write_project(progs, file_count, root, out_dir, no_main);
for(i = 0; i < file_count; i++)
KirProgramFree(progs[i]);
free(progs);
free(syms);
return 0;
}
File diff suppressed because it is too large. Load diff
+23
View File
@@ -0,0 +1,23 @@
#ifndef K2GO_LOWER_H
#define K2GO_LOWER_H
#include "kir.h"
/*
* k2go_lower - Kir -> Go backend.
*
* Emits one .go file per module into out_dir, all in one Go package. The
* generated code calls the native Go Kryon package API. It does not thread a
* cgo bridge or runtime object through generated functions.
*
* v1 scope: the declarative app subset translates fully — state blocks,
* app metadata (-> generated main unless --no-main), frames, widget calls,
* and scalar expressions (compound literals, casts, state refs). Imperative
* constructs are best-effort; anything unsupported is emitted as a
* commented TODO line instead of silently miscompiling.
*/
int k2go_lower(const KirProgram *const *progs, int prog_count,
const char *root, const char *out_dir, const char *pkg,
int no_main);
#endif
+83
View File
@@ -0,0 +1,83 @@
/*
* k2go - .kry -> Go compiler. Shares the Kir frontend with k2c/k2b: every
* .kry parses into a KirProgram (kir_parse.c), then lowers to Go source
* (k2go_lower.c) that calls the native Go Kryon runtime. One frontend, three
* backends.
*
* usage: k2go [--no-main] [--pkg NAME] --root DIR -o DIR file.kry ...
*/
#include "kir.h"
#include "kir_parse.h"
#include "k2go_lower.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void
usage(void)
{
fprintf(stderr,
"usage: k2go [--no-main] [--pkg NAME] "
"--root DIR -o DIR file.kry ...\n");
}
int
main(int argc, char **argv)
{
const char *root = NULL;
const char *out_dir = NULL;
const char *pkg = "krygen";
int no_main = 0;
KirProgram **progs;
int file_count;
int i;
int first_file = 0;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "--root") == 0 && i + 1 < argc) {
root = argv[++i];
} else if(strcmp(argv[i], "-o") == 0 && i + 1 < argc) {
out_dir = argv[++i];
} else if(strcmp(argv[i], "--pkg") == 0 && i + 1 < argc) {
pkg = argv[++i];
} else if(strcmp(argv[i], "--no-main") == 0) {
no_main = 1;
} else if(argv[i][0] == '-') {
usage();
return 1;
} else {
first_file = i;
break;
}
}
if(root == NULL || out_dir == NULL || first_file == 0) {
usage();
return 1;
}
file_count = argc - first_file;
progs = calloc((size_t)file_count, sizeof(*progs));
if(progs == NULL) {
fprintf(stderr, "k2go: out of memory\n");
return 1;
}
for(i = 0; i < file_count; i++) {
progs[i] = kir_parse_file(argv[first_file + i], root);
if(progs[i] == NULL) {
fprintf(stderr, "k2go: failed to parse %s\n", argv[first_file + i]);
return 1;
}
}
if(k2go_lower((const KirProgram *const *)progs, file_count, root, out_dir,
pkg, no_main) != 0) {
for(i = 0; i < file_count; i++)
KirProgramFree(progs[i]);
free(progs);
return 1;
}
for(i = 0; i < file_count; i++)
KirProgramFree(progs[i]);
free(progs);
return 0;
}
File diff suppressed because it is too large. Load diff
+17
View File
@@ -0,0 +1,17 @@
#ifndef K2JS_LOWER_H
#define K2JS_LOWER_H
#include "kir.h"
/*
* k2js_lower - Kir -> JavaScript backend.
*
* Emits one ESM .js file per module. Generated code imports the small
* web/kryon-runtime.js recorder/runtime and exports createState(), app
* metadata, all non-extern functions, frame(), and optionally main().
*/
int k2js_lower(const KirProgram *const *progs, int prog_count,
const char *root, const char *out_dir,
const char *runtime_import, int no_main);
#endif
+82
View File
@@ -0,0 +1,82 @@
/*
* k2js - .kry -> JavaScript compiler. Shares the Kir frontend with k2c/k2go/k2b:
* every .kry parses into a KirProgram (kir_parse.c), then lowers to ESM that
* calls the web Kryon runtime.
*
* usage: k2js [--no-main] [--runtime PATH] --root DIR -o DIR file.kry ...
*/
#include "kir.h"
#include "kir_parse.h"
#include "k2js_lower.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void
usage(void)
{
fprintf(stderr,
"usage: k2js [--no-main] [--runtime PATH] "
"--root DIR -o DIR file.kry ...\n");
}
int
main(int argc, char **argv)
{
const char *root = NULL;
const char *out_dir = NULL;
const char *runtime_import = NULL;
int no_main = 0;
KirProgram **progs;
int file_count;
int i;
int first_file = 0;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "--root") == 0 && i + 1 < argc) {
root = argv[++i];
} else if(strcmp(argv[i], "-o") == 0 && i + 1 < argc) {
out_dir = argv[++i];
} else if(strcmp(argv[i], "--runtime") == 0 && i + 1 < argc) {
runtime_import = argv[++i];
} else if(strcmp(argv[i], "--no-main") == 0) {
no_main = 1;
} else if(argv[i][0] == '-') {
usage();
return 1;
} else {
first_file = i;
break;
}
}
if(root == NULL || out_dir == NULL || first_file == 0) {
usage();
return 1;
}
file_count = argc - first_file;
progs = calloc((size_t)file_count, sizeof(*progs));
if(progs == NULL) {
fprintf(stderr, "k2js: out of memory\n");
return 1;
}
for(i = 0; i < file_count; i++) {
progs[i] = kir_parse_file(argv[first_file + i], root);
if(progs[i] == NULL) {
fprintf(stderr, "k2js: failed to parse %s\n", argv[first_file + i]);
free(progs);
return 1;
}
}
if(k2js_lower((const KirProgram *const *)progs, file_count, root, out_dir,
runtime_import, no_main) != 0) {
for(i = 0; i < file_count; i++)
KirProgramFree(progs[i]);
free(progs);
return 1;
}
for(i = 0; i < file_count; i++)
KirProgramFree(progs[i]);
free(progs);
return 0;
}
+88
View File
@@ -0,0 +1,88 @@
/*
* k2kir - emit a debuggable KIR text artifact from .kry source.
* Thin wrapper around the shared kir_parse_file frontend.
*/
#include "kir.h"
#include "kir_parse.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
static void
usage(void)
{
fprintf(stderr, "usage: k2kir --root DIR -o DIR file.kry ...\n");
}
int
main(int argc, char **argv)
{
const char *root = NULL;
const char *out_dir = NULL;
int i;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "--root") == 0 && i + 1 < argc) {
root = argv[++i];
} else if(strcmp(argv[i], "-o") == 0 && i + 1 < argc) {
out_dir = argv[++i];
} else if(argv[i][0] == '-') {
usage();
return 1;
} else {
break;
}
}
if(root == NULL || out_dir == NULL || i >= argc) {
usage();
return 1;
}
for(; i < argc; i++) {
KirProgram *program = kir_parse_file(argv[i], root);
if(program == NULL)
return 1;
/* Write the .kir dump using the module's source_path (relative to root)
* so directory structure is preserved. */
if(program->module_count > 0) {
const char *src = program->modules[0].source_path;
size_t slen = strlen(src);
char stem[512];
char out_path[1024];
FILE *out;
if(slen > 4 && strcmp(src + slen - 4, ".kry") == 0)
slen -= 4;
if(slen >= sizeof(stem))
slen = sizeof(stem) - 1;
memcpy(stem, src, slen);
stem[slen] = '\0';
snprintf(out_path, sizeof(out_path), "%s/%s.kir", out_dir, stem);
/* mkdir -p */
{
char tmp[1024];
size_t j;
snprintf(tmp, sizeof(tmp), "%s", out_path);
for(j = 1; j < strlen(tmp); j++) {
if(tmp[j] == '/') {
tmp[j] = '\0';
mkdir(tmp, 0755);
tmp[j] = '/';
}
}
}
out = fopen(out_path, "wb");
if(out == NULL) {
fprintf(stderr, "k2kir: %s: open failed\n", out_path);
KirProgramFree(program);
return 1;
}
KirProgramDump(program, out);
fclose(out);
}
KirProgramFree(program);
}
return 0;
}
-4540
View File
File diff suppressed because it is too large. Load diff
-105
View File
@@ -1,105 +0,0 @@
#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
@@ -1,74 +0,0 @@
#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
+545
View File
@@ -0,0 +1,545 @@
#include "kir.h"
#include <stdlib.h>
#include <string.h>
static void *
kir_realloc_array(void *ptr, int *cap, int count, size_t elem_size)
{
void *next;
int ncap;
if(count < *cap)
return ptr;
ncap = *cap == 0 ? 4 : *cap * 2;
next = realloc(ptr, (size_t)ncap * elem_size);
if(next == NULL)
return NULL;
memset((char *)next + (size_t)(*cap) * elem_size, 0,
(size_t)(ncap - *cap) * elem_size);
*cap = ncap;
return next;
}
void
kir_copy(char *dst, size_t dst_size, const char *src)
{
if(dst_size == 0)
return;
if(src == NULL)
src = "";
snprintf(dst, dst_size, "%s", src);
}
KirProgram *
KirProgramNew(void)
{
return calloc(1, sizeof(KirProgram));
}
void
KirProgramFree(KirProgram *program)
{
int i;
if(program == NULL)
return;
for(i = 0; i < program->module_count; i++) {
KirModule *m = &program->modules[i];
int j;
for(j = 0; j < m->function_count; j++) {
free(m->functions[j].stmts);
free(m->functions[j].exprs);
}
free(m->state_fields);
free(m->imports);
free(m->functions);
free(m->defines);
free(m->asserts);
free(m->types);
free(m->routes);
}
free(program->modules);
free(program);
}
KirSourceSpan
KirSpan(const char *path, int line, int column)
{
KirSourceSpan span;
memset(&span, 0, sizeof(span));
kir_copy(span.path, sizeof(span.path), path);
span.line = line;
span.column = column;
return span;
}
KirModule *
KirProgramAddModule(KirProgram *program, const char *name,
const char *source_path, KirSourceSpan span)
{
KirModule *modules;
KirModule *m;
if(program == NULL)
return NULL;
modules = kir_realloc_array(program->modules, &program->module_cap,
program->module_count, sizeof(KirModule));
if(modules == NULL)
return NULL;
program->modules = modules;
m = &program->modules[program->module_count++];
memset(m, 0, sizeof(*m));
kir_copy(m->name, sizeof(m->name), name);
kir_copy(m->source_path, sizeof(m->source_path), source_path);
m->span = span;
return m;
}
KirStateField *
KirModuleAddStateField(KirModule *module, const char *name, const char *type,
const char *init, KirSourceSpan span)
{
KirStateField *fields;
KirStateField *f;
if(module == NULL)
return NULL;
fields = kir_realloc_array(module->state_fields, &module->state_cap,
module->state_count, sizeof(KirStateField));
if(fields == NULL)
return NULL;
module->state_fields = fields;
f = &module->state_fields[module->state_count++];
memset(f, 0, sizeof(*f));
kir_copy(f->name, sizeof(f->name), name);
kir_copy(f->type, sizeof(f->type), type);
kir_copy(f->init, sizeof(f->init), init);
f->span = span;
return f;
}
KirImport *
KirModuleAddImport(KirModule *module, KirImportKind kind, const char *name,
const char *target, const char *signature, int required,
KirSourceSpan span)
{
KirImport *imports;
KirImport *imp;
if(module == NULL)
return NULL;
imports = kir_realloc_array(module->imports, &module->import_cap,
module->import_count, sizeof(KirImport));
if(imports == NULL)
return NULL;
module->imports = imports;
imp = &module->imports[module->import_count++];
memset(imp, 0, sizeof(*imp));
imp->kind = kind;
kir_copy(imp->name, sizeof(imp->name), name);
kir_copy(imp->target, sizeof(imp->target), target);
kir_copy(imp->signature, sizeof(imp->signature), signature);
imp->required = required;
imp->span = span;
return imp;
}
KirFunction *
KirModuleAddFunction(KirModule *module, const char *name, const char *args,
const char *return_type, int exported, KirSourceSpan span)
{
KirFunction *functions;
KirFunction *fn;
if(module == NULL)
return NULL;
functions = kir_realloc_array(module->functions, &module->function_cap,
module->function_count, sizeof(KirFunction));
if(functions == NULL)
return NULL;
module->functions = functions;
fn = &module->functions[module->function_count++];
memset(fn, 0, sizeof(*fn));
kir_copy(fn->name, sizeof(fn->name), name);
kir_copy(fn->args, sizeof(fn->args), args);
kir_copy(fn->return_type, sizeof(fn->return_type), return_type);
fn->exported = exported;
fn->span = span;
return fn;
}
void
KirModuleAddGlobal(KirModule *module, const char *name, const char *type,
const char *init, KirSourceSpan span)
{
KirGlobal *globals;
if(module == NULL)
return;
globals = kir_realloc_array(module->globals, &module->global_cap,
module->global_count, sizeof(KirGlobal));
if(globals == NULL)
return;
module->globals = globals;
memset(&module->globals[module->global_count], 0, sizeof(KirGlobal));
kir_copy(module->globals[module->global_count].name,
sizeof(module->globals[0].name), name);
kir_copy(module->globals[module->global_count].type,
sizeof(module->globals[0].type), type);
kir_copy(module->globals[module->global_count].init,
sizeof(module->globals[0].init), init);
module->globals[module->global_count].span = span;
module->global_count++;
}
void
KirModuleAddStatic(KirModule *module, const char *name, const char *type,
const char *init, KirSourceSpan span)
{
KirModuleAddGlobal(module, name, type, init, span);
if(module != NULL && module->global_count > 0)
module->globals[module->global_count - 1].is_static = 1;
}
KirDefine *
KirModuleAddDefine(KirModule *module, const char *name, const char *value,
KirSourceSpan span)
{
KirDefine *defines;
KirDefine *d;
if(module == NULL)
return NULL;
defines = kir_realloc_array(module->defines, &module->define_cap,
module->define_count, sizeof(KirDefine));
if(defines == NULL)
return NULL;
module->defines = defines;
d = &module->defines[module->define_count++];
memset(d, 0, sizeof(*d));
kir_copy(d->name, sizeof(d->name), name);
kir_copy(d->value, sizeof(d->value), value);
d->span = span;
return d;
}
KirAssert *
KirModuleAddAssert(KirModule *module, const char *condition,
const char *message, KirSourceSpan span)
{
KirAssert *asserts;
KirAssert *a;
if(module == NULL)
return NULL;
asserts = kir_realloc_array(module->asserts, &module->assert_cap,
module->assert_count, sizeof(KirAssert));
if(asserts == NULL)
return NULL;
module->asserts = asserts;
a = &module->asserts[module->assert_count++];
memset(a, 0, sizeof(*a));
kir_copy(a->condition, sizeof(a->condition), condition);
kir_copy(a->message, sizeof(a->message), message);
a->span = span;
return a;
}
KirType *
KirModuleAddType(KirModule *module, const char *name, KirSourceSpan span)
{
KirType *types;
if(module == NULL)
return NULL;
types = kir_realloc_array(module->types, &module->type_cap,
module->type_count, sizeof(KirType));
if(types == NULL)
return NULL;
module->types = types;
memset(&module->types[module->type_count], 0, sizeof(KirType));
kir_copy(module->types[module->type_count].name,
sizeof(module->types[0].name), name);
module->types[module->type_count].span = span;
return &module->types[module->type_count++];
}
KirRoute *
KirModuleAddRoute(KirModule *module, const char *id, KirSourceSpan span)
{
KirRoute *routes;
KirRoute *route;
if(module == NULL)
return NULL;
routes = kir_realloc_array(module->routes, &module->route_cap,
module->route_count, sizeof(KirRoute));
if(routes == NULL)
return NULL;
module->routes = routes;
route = &module->routes[module->route_count++];
memset(route, 0, sizeof(*route));
kir_copy(route->id, sizeof(route->id), id);
kir_copy(route->title, sizeof(route->title), id);
kir_copy(route->group, sizeof(route->group), "Project");
kir_copy(route->page, sizeof(route->page), id);
route->span = span;
return route;
}
KirStmt *
KirFunctionAddStmt(KirFunction *fn, KirStmtKind kind, const char *text,
const char *widget, KirSourceSpan span)
{
KirStmt *stmts;
KirStmt *st;
if(fn == NULL)
return NULL;
stmts = kir_realloc_array(fn->stmts, &fn->stmt_cap, fn->stmt_count,
sizeof(KirStmt));
if(stmts == NULL)
return NULL;
fn->stmts = stmts;
st = &fn->stmts[fn->stmt_count++];
memset(st, 0, sizeof(*st));
st->kind = kind;
kir_copy(st->text, sizeof(st->text), text);
kir_copy(st->widget, sizeof(st->widget), widget);
st->expr_root = -1;
st->span = span;
return st;
}
KirStmt *
KirFunctionAddWidget(KirFunction *fn, const char *widget, const char *args,
const char *text, KirSourceSpan span)
{
KirStmt *st = KirFunctionAddStmt(fn, KIR_STMT_WIDGET, text, widget, span);
if(st != NULL)
kir_copy(st->args, sizeof(st->args), args);
return st;
}
KirExpr *
KirFunctionAddExpr(KirFunction *fn, KirExprKind kind, const char *text,
KirSourceSpan span)
{
KirExpr *exprs;
KirExpr *expr;
if(fn == NULL)
return NULL;
exprs = kir_realloc_array(fn->exprs, &fn->expr_cap, fn->expr_count,
sizeof(KirExpr));
if(exprs == NULL)
return NULL;
fn->exprs = exprs;
expr = &fn->exprs[fn->expr_count++];
memset(expr, 0, sizeof(*expr));
expr->kind = kind;
expr->left = -1;
expr->right = -1;
expr->first_child = -1;
expr->next_sibling = -1;
kir_copy(expr->text, sizeof(expr->text), text);
expr->span = span;
return expr;
}
const char *
KirImportKindName(KirImportKind kind)
{
switch(kind) {
case KIR_IMPORT_HEADER: return "header";
case KIR_IMPORT_MODULE: return "module";
case KIR_IMPORT_EXTERN: return "extern";
case KIR_IMPORT_INTRINSIC: return "intrinsic";
case KIR_IMPORT_CAPABILITY: return "capability";
case KIR_IMPORT_HOST: return "host";
default: return "unknown";
}
}
const char *
KirExternKindName(KirExternKind kind)
{
switch(kind) {
case KIR_EXTERN_HOST: return "host";
case KIR_EXTERN_GO: return "go";
case KIR_EXTERN_C: return "c";
default: return "none";
}
}
const char *
KirExprKindName(KirExprKind kind)
{
switch(kind) {
case KIR_EXPR_IDENT: return "ident";
case KIR_EXPR_INT: return "int";
case KIR_EXPR_FLOAT: return "float";
case KIR_EXPR_STRING: return "string";
case KIR_EXPR_CALL: return "call";
case KIR_EXPR_BINARY: return "binary";
case KIR_EXPR_UNARY: return "unary";
case KIR_EXPR_MEMBER: return "member";
case KIR_EXPR_POINTER_MEMBER: return "pointer_member";
case KIR_EXPR_INDEX: return "index";
case KIR_EXPR_CAST: return "cast";
case KIR_EXPR_COMPOUND: return "compound";
case KIR_EXPR_SIZEOF: return "sizeof";
default: return "unknown";
}
}
const char *
KirStmtKindName(KirStmtKind kind)
{
switch(kind) {
case KIR_STMT_BLOCK_OPEN: return "block_open";
case KIR_STMT_BLOCK_CLOSE: return "block_close";
case KIR_STMT_DECL: return "decl";
case KIR_STMT_ASSIGN: return "assign";
case KIR_STMT_EXPR: return "expr";
case KIR_STMT_IF: return "if";
case KIR_STMT_WHILE: return "while";
case KIR_STMT_FOR: return "for";
case KIR_STMT_SWITCH: return "switch";
case KIR_STMT_CASE: return "case";
case KIR_STMT_RETURN: return "return";
case KIR_STMT_BREAK: return "break";
case KIR_STMT_CONTINUE: return "continue";
case KIR_STMT_GOTO: return "goto";
case KIR_STMT_LABEL: return "label";
case KIR_STMT_DEFER: return "defer";
case KIR_STMT_UNUSED: return "unused";
case KIR_STMT_RAW: return "raw";
case KIR_STMT_WIDGET: return "widget";
default: return "unknown";
}
}
static void
kir_dump_span(FILE *out, KirSourceSpan span)
{
fprintf(out, "%s:%d:%d", span.path, span.line, span.column);
}
static void
kir_dump_expr(const KirFunction *fn, int index, FILE *out, int indent)
{
const KirExpr *expr;
if(fn == NULL || index < 0 || index >= fn->expr_count)
return;
expr = &fn->exprs[index];
for(int i = 0; i < indent; i++)
fputs(" ", out);
fprintf(out, "expr %s text %s name %s op %s span ",
KirExprKindName(expr->kind), expr->text, expr->name, expr->op);
kir_dump_span(out, expr->span);
fprintf(out, "\n");
if(expr->left >= 0)
kir_dump_expr(fn, expr->left, out, indent + 1);
if(expr->right >= 0)
kir_dump_expr(fn, expr->right, out, indent + 1);
for(int child = expr->first_child; child >= 0 &&
child < fn->expr_count; child = fn->exprs[child].next_sibling)
kir_dump_expr(fn, child, out, indent + 1);
}
void
KirProgramDump(const KirProgram *program, FILE *out)
{
int i;
if(out == NULL)
return;
fprintf(out, "kir 1\n");
if(program == NULL)
return;
for(i = 0; i < program->module_count; i++) {
const KirModule *m = &program->modules[i];
int j;
fprintf(out, "module %s source %s span ", m->name, m->source_path);
kir_dump_span(out, m->span);
fprintf(out, "\n");
if(m->app.has_app) {
fprintf(out, " app title %s size %dx%d fps %d theme %s "
"dark %d font_examples %d frame %s init %s scene %s "
"shutdown %s\n",
m->app.title[0] ? m->app.title : "\"\"",
m->app.width, m->app.height, m->app.fps,
m->app.theme[0] ? m->app.theme : "",
m->app.dark_mode, m->app.font_examples,
m->app.frame[0] ? m->app.frame : "",
m->app.init[0] ? m->app.init : "",
m->app.scene[0] ? m->app.scene : "",
m->app.shutdown[0] ? m->app.shutdown : "");
}
for(j = 0; j < m->import_count; j++) {
const KirImport *imp = &m->imports[j];
fprintf(out, " import %s %s target %s",
KirImportKindName(imp->kind), imp->name, imp->target);
if(imp->kind == KIR_IMPORT_EXTERN)
fprintf(out, " extern_kind %s extern_symbol %s",
KirExternKindName(imp->extern_kind),
imp->extern_symbol);
fprintf(out, " required %d signature %s span ",
imp->required, imp->signature);
kir_dump_span(out, imp->span);
fprintf(out, "\n");
}
for(j = 0; j < m->state_count; j++) {
const KirStateField *f = &m->state_fields[j];
fprintf(out, " state %s type %s init %s span ",
f->name, f->type, f->init);
kir_dump_span(out, f->span);
fprintf(out, "\n");
}
for(j = 0; j < m->route_count; j++) {
const KirRoute *route = &m->routes[j];
fprintf(out, " route %s title %s group %s page %s span ",
route->id, route->title, route->group, route->page);
kir_dump_span(out, route->span);
fprintf(out, "\n");
}
for(j = 0; j < m->assert_count; j++) {
const KirAssert *a = &m->asserts[j];
fprintf(out, " assert condition %s known %d value %d message %s span ",
a->condition, a->known, a->value, a->message);
kir_dump_span(out, a->span);
fprintf(out, "\n");
}
for(j = 0; j < m->function_count; j++) {
const KirFunction *fn = &m->functions[j];
int k;
fprintf(out, " function %s args %s return %s exported %d span ",
fn->name, fn->args, fn->return_type, fn->exported);
kir_dump_span(out, fn->span);
fprintf(out, "\n");
for(k = 0; k < fn->stmt_count; k++) {
const KirStmt *st = &fn->stmts[k];
fprintf(out, " stmt %s widget %s args %s text %s span ",
KirStmtKindName(st->kind), st->widget, st->args,
st->text);
kir_dump_span(out, st->span);
fprintf(out, "\n");
if(st->expr_root >= 0)
kir_dump_expr(fn, st->expr_root, out, 3);
}
}
}
}
+282
View File
@@ -0,0 +1,282 @@
/*
* kir.h - Kryon intermediate representation.
*
* KIR is the shared compiler representation between .kry source and the C/KRB
* backends. This module owns the tree shape, explicit allocation, source spans,
* and deterministic dumps used by tools and tests.
*/
#ifndef KRYON_KIR_H
#define KRYON_KIR_H
#include <stdio.h>
enum {
KIR_PATH_MAX = 1024,
KIR_NAME_MAX = 128,
KIR_TEXT_MAX = 4096
};
typedef enum KirImportKind {
KIR_IMPORT_HEADER = 1,
KIR_IMPORT_MODULE,
KIR_IMPORT_EXTERN,
KIR_IMPORT_INTRINSIC,
KIR_IMPORT_CAPABILITY,
KIR_IMPORT_HOST
} KirImportKind;
typedef enum KirExternKind {
KIR_EXTERN_NONE = 0,
KIR_EXTERN_HOST,
KIR_EXTERN_GO,
KIR_EXTERN_C
} KirExternKind;
typedef enum KirStmtKind {
KIR_STMT_UNKNOWN = 0,
KIR_STMT_BLOCK_OPEN,
KIR_STMT_BLOCK_CLOSE,
KIR_STMT_DECL,
KIR_STMT_ASSIGN,
KIR_STMT_EXPR,
KIR_STMT_IF,
KIR_STMT_WHILE,
KIR_STMT_FOR,
KIR_STMT_SWITCH,
KIR_STMT_CASE,
KIR_STMT_RETURN,
KIR_STMT_BREAK,
KIR_STMT_CONTINUE,
KIR_STMT_GOTO,
KIR_STMT_LABEL,
KIR_STMT_DEFER,
KIR_STMT_UNUSED,
KIR_STMT_RAW,
KIR_STMT_WIDGET
} KirStmtKind;
typedef enum KirExprKind {
KIR_EXPR_UNKNOWN = 0,
KIR_EXPR_IDENT,
KIR_EXPR_INT,
KIR_EXPR_FLOAT,
KIR_EXPR_STRING,
KIR_EXPR_CALL,
KIR_EXPR_BINARY,
KIR_EXPR_UNARY,
KIR_EXPR_MEMBER,
KIR_EXPR_POINTER_MEMBER,
KIR_EXPR_INDEX,
KIR_EXPR_CAST,
KIR_EXPR_COMPOUND,
KIR_EXPR_SIZEOF
} KirExprKind;
typedef struct KirSourceSpan {
char path[KIR_PATH_MAX];
int line;
int column;
} KirSourceSpan;
typedef struct KirStateField {
char name[KIR_NAME_MAX];
char type[KIR_NAME_MAX];
char init[KIR_TEXT_MAX];
char guard[KIR_TEXT_MAX]; /* enclosing '#if' condition (expanded) */
KirSourceSpan span;
} KirStateField;
typedef struct KirImport {
KirImportKind kind;
KirExternKind extern_kind;
char name[KIR_NAME_MAX];
char target[KIR_PATH_MAX];
char extern_symbol[KIR_NAME_MAX];
char signature[KIR_TEXT_MAX];
int required;
char guard[KIR_TEXT_MAX]; /* enclosing '#if' condition (expanded) */
KirSourceSpan span;
} KirImport;
typedef struct KirStmt {
KirStmtKind kind;
char text[KIR_TEXT_MAX];
char widget[KIR_NAME_MAX];
char args[KIR_TEXT_MAX];
int expr_root; /* index into enclosing function exprs, or -1 */
KirSourceSpan span;
} KirStmt;
typedef struct KirExpr {
KirExprKind kind;
char text[KIR_TEXT_MAX];
char name[KIR_NAME_MAX];
char op[8];
int left;
int right;
int first_child;
int next_sibling;
KirSourceSpan span;
} KirExpr;
typedef struct KirFunction {
char name[KIR_NAME_MAX];
char args[KIR_TEXT_MAX];
char return_type[KIR_NAME_MAX];
int exported;
int is_extern;
KirExternKind extern_kind;
int is_colon; /* 'Name :: (...) {' form: C name has no _kry_draw suffix */
int is_ui; /* '#ui' function: declares a retained UI hierarchy */
int is_public; /* exported function or project route */
char extern_target[KIR_NAME_MAX]; /* '#extern "pkg.Fn"' quoted symbol */
char extern_symbol[KIR_NAME_MAX]; /* stripped C symbol for c.* externs */
char guard[KIR_TEXT_MAX]; /* enclosing '#if' condition (expanded) */
KirSourceSpan span;
KirStmt *stmts;
int stmt_count;
int stmt_cap;
KirExpr *exprs;
int expr_count;
int expr_cap;
} KirFunction;
typedef struct KirGlobal {
char name[KIR_NAME_MAX];
char type[KIR_TEXT_MAX];
char init[KIR_TEXT_MAX];
int is_static; /* 'static name: T = init' — internal linkage */
char guard[KIR_TEXT_MAX]; /* enclosing '#if' condition (expanded) */
KirSourceSpan span;
} KirGlobal;
/* A `Name :: #define value` module constant — emitted as a real C #define. */
typedef struct KirDefine {
char name[KIR_NAME_MAX];
char value[KIR_TEXT_MAX];
char guard[KIR_TEXT_MAX]; /* enclosing '#if' condition (expanded) */
KirSourceSpan span;
} KirDefine;
typedef struct KirAssert {
char condition[KIR_TEXT_MAX]; /* expanded C preprocessor condition */
char message[KIR_TEXT_MAX]; /* C #error payload */
int known; /* condition resolved by Kry frontend */
int value; /* boolean value when known */
char guard[KIR_TEXT_MAX]; /* enclosing '#if' condition (expanded) */
KirSourceSpan span;
} KirAssert;
/* A `Name :: struct { fields }` type declaration. body holds the raw field
* lines (one per line, no braces). */
typedef struct KirType {
char name[KIR_NAME_MAX];
char body[KIR_TEXT_MAX * 2];
int is_enum; /* 'Name :: enum' — emit typedef enum, not struct */
char guard[KIR_TEXT_MAX]; /* enclosing '#if' condition (expanded) */
KirSourceSpan span;
} KirType;
typedef struct KirAppMeta {
int has_app;
char title[KIR_NAME_MAX];
int width;
int height;
int fps;
char theme[KIR_NAME_MAX];
int dark_mode;
int font_examples;
char frame[KIR_NAME_MAX];
char init[KIR_NAME_MAX];
char scene[KIR_NAME_MAX];
char shutdown[KIR_NAME_MAX];
} KirAppMeta;
typedef struct KirRoute {
char id[KIR_NAME_MAX];
char title[KIR_NAME_MAX];
char group[KIR_NAME_MAX];
char page[KIR_NAME_MAX];
char guard[KIR_TEXT_MAX];
KirSourceSpan span;
} KirRoute;
typedef struct KirModule {
char name[KIR_NAME_MAX];
char source_path[KIR_PATH_MAX];
KirSourceSpan span;
KirAppMeta app;
KirGlobal *globals;
int global_count;
int global_cap;
KirDefine *defines;
int define_count;
int define_cap;
KirAssert *asserts;
int assert_count;
int assert_cap;
KirType *types;
int type_count;
int type_cap;
KirStateField *state_fields;
int state_count;
int state_cap;
KirImport *imports;
int import_count;
int import_cap;
KirRoute *routes;
int route_count;
int route_cap;
KirFunction *functions;
int function_count;
int function_cap;
} KirModule;
typedef struct KirProgram {
KirModule *modules;
int module_count;
int module_cap;
} KirProgram;
KirProgram *KirProgramNew(void);
void KirProgramFree(KirProgram *program);
void kir_copy(char *dst, size_t dst_size, const char *src);
KirSourceSpan KirSpan(const char *path, int line, int column);
KirModule *KirProgramAddModule(KirProgram *program, const char *name,
const char *source_path, KirSourceSpan span);
KirStateField *KirModuleAddStateField(KirModule *module, const char *name,
const char *type, const char *init,
KirSourceSpan span);
KirImport *KirModuleAddImport(KirModule *module, KirImportKind kind,
const char *name, const char *target,
const char *signature, int required,
KirSourceSpan span);
KirFunction *KirModuleAddFunction(KirModule *module, const char *name,
const char *args, const char *return_type,
int exported, KirSourceSpan span);
void KirModuleAddGlobal(KirModule *module, const char *name, const char *type,
const char *init, KirSourceSpan span);
void KirModuleAddStatic(KirModule *module, const char *name, const char *type,
const char *init, KirSourceSpan span);
KirDefine *KirModuleAddDefine(KirModule *module, const char *name,
const char *value, KirSourceSpan span);
KirAssert *KirModuleAddAssert(KirModule *module, const char *condition,
const char *message, KirSourceSpan span);
KirType *KirModuleAddType(KirModule *module, const char *name,
KirSourceSpan span);
KirRoute *KirModuleAddRoute(KirModule *module, const char *id,
KirSourceSpan span);
KirStmt *KirFunctionAddStmt(KirFunction *fn, KirStmtKind kind,
const char *text, const char *widget,
KirSourceSpan span);
KirStmt *KirFunctionAddWidget(KirFunction *fn, const char *widget,
const char *args, const char *text,
KirSourceSpan span);
const char *KirImportKindName(KirImportKind kind);
const char *KirStmtKindName(KirStmtKind kind);
const char *KirExprKindName(KirExprKind kind);
KirExpr *KirFunctionAddExpr(KirFunction *fn, KirExprKind kind,
const char *text, KirSourceSpan span);
void KirProgramDump(const KirProgram *program, FILE *out);
#endif /* KRYON_KIR_H */
+3211
View File
File diff suppressed because it is too large. Load diff
+14
View File
@@ -0,0 +1,14 @@
#ifndef KRYON_KIR_PARSE_H
#define KRYON_KIR_PARSE_H
#include "kir.h"
/*
* Parse a .kry source file into a KirProgram. Returns a heap-allocated
* program (caller frees with KirProgramFree), or NULL on fatal error.
* This is the shared Kir frontend used by k2kir (dump), k2c (C backend),
* and k2b (krb backend).
*/
KirProgram *kir_parse_file(const char *path, const char *root);
#endif /* KRYON_KIR_PARSE_H */
+139
View File
@@ -0,0 +1,139 @@
#include "kir_text.h"
#include <ctype.h>
#include <string.h>
int
kir_is_ident_char(int c)
{
return isalnum((unsigned char)c) || c == '_';
}
const char *
kir_skip_ws(const char *s)
{
while(s != NULL && isspace((unsigned char)*s))
s++;
return s;
}
const char *
kir_skip_inline_ws(const char *s)
{
while(s != NULL && (*s == ' ' || *s == '\t'))
s++;
return s;
}
char *
kir_trim(char *s)
{
char *e;
if(s == NULL)
return NULL;
while(isspace((unsigned char)*s))
s++;
e = s + strlen(s);
while(e > s && isspace((unsigned char)e[-1]))
*--e = '\0';
return s;
}
char *
kir_trim_in_place(char *s)
{
char *p;
if(s == NULL)
return NULL;
p = kir_trim(s);
if(p != s)
memmove(s, p, strlen(p) + 1);
return s;
}
void
kir_strip_block_brace(char *s)
{
size_t n;
if(s == NULL)
return;
n = strlen(s);
while(n > 0 && isspace((unsigned char)s[n - 1]))
n--;
if(n > 0 && s[n - 1] == '{')
n--;
while(n > 0 && isspace((unsigned char)s[n - 1]))
n--;
s[n] = '\0';
}
void
kir_camel_ident(const char *s, char *dst, size_t dst_size)
{
size_t n = 0;
int up = 1;
if(dst_size == 0)
return;
for(const char *p = s; p != NULL && *p != '\0' && n + 1 < dst_size; p++) {
if(isalnum((unsigned char)*p)) {
dst[n++] = up ? (char)toupper((unsigned char)*p) : *p;
up = 0;
} else {
up = 1;
}
}
if(n == 0 && n + 1 < dst_size)
dst[n++] = 'X';
if(n > 0 && isdigit((unsigned char)dst[0]) && n + 1 < dst_size) {
memmove(dst + 1, dst, n + 1);
dst[0] = 'M';
n++;
}
dst[n] = '\0';
}
int
kir_split_top(const char *s, char *parts, int max, size_t part_size)
{
int depth = 0;
int n = 0;
const char *start = s;
if(s == NULL || parts == NULL || max <= 0 || part_size == 0)
return 0;
for(const char *p = s; ; p++) {
if(*p == '"' || *p == '\'') {
char q = *p++;
while(*p != '\0' && *p != q) {
if(*p == '\\' && p[1] != '\0')
p++;
p++;
}
} else if(*p == '\0' || (*p == ',' && depth == 0)) {
size_t len = (size_t)(p - start);
if(n < max && len < part_size) {
char *part = parts + ((size_t)n * part_size);
memcpy(part, start, len);
part[len] = '\0';
kir_trim_in_place(part);
n++;
}
if(*p == '\0')
break;
start = p + 1;
} else if(*p == '(' || *p == '[' || *p == '{') {
depth++;
} else if(*p == ')' || *p == ']' || *p == '}') {
if(depth > 0)
depth--;
}
}
return n;
}
+15
View File
@@ -0,0 +1,15 @@
#ifndef KRYON_KIR_TEXT_H
#define KRYON_KIR_TEXT_H
#include <stddef.h>
int kir_is_ident_char(int c);
const char *kir_skip_ws(const char *s);
const char *kir_skip_inline_ws(const char *s);
char *kir_trim(char *s);
char *kir_trim_in_place(char *s);
void kir_strip_block_brace(char *s);
void kir_camel_ident(const char *s, char *dst, size_t dst_size);
int kir_split_top(const char *s, char *parts, int max, size_t part_size);
#endif /* KRYON_KIR_TEXT_H */
+174
View File
@@ -0,0 +1,174 @@
#include "kir_token.h"
#include <ctype.h>
#include <string.h>
static int
is_ident_start(int c)
{
return isalpha((unsigned char)c) || c == '_';
}
static int
is_ident_continue(int c)
{
return isalnum((unsigned char)c) || c == '_';
}
static void
lexer_advance(KirLexer *lx)
{
if(lx->src[lx->pos] == '\n') {
lx->line++;
lx->column = 1;
} else {
lx->column++;
}
lx->pos++;
}
static void
token_copy(KirToken *tok, const char *src, size_t begin, size_t end)
{
size_t n = end > begin ? end - begin : 0;
if(n >= sizeof(tok->text))
n = sizeof(tok->text) - 1;
memcpy(tok->text, src + begin, n);
tok->text[n] = '\0';
}
void
KirLexerInit(KirLexer *lx, const char *src, const char *path)
{
memset(lx, 0, sizeof(*lx));
lx->src = src != NULL ? src : "";
lx->path = path != NULL ? path : "";
lx->line = 1;
lx->column = 1;
}
KirToken
KirLexerNext(KirLexer *lx)
{
KirToken tok;
size_t begin;
int start_line;
int start_column;
int c;
memset(&tok, 0, sizeof(tok));
while(isspace((unsigned char)lx->src[lx->pos]))
lexer_advance(lx);
begin = lx->pos;
start_line = lx->line;
start_column = lx->column;
c = (unsigned char)lx->src[lx->pos];
tok.span = KirSpan(lx->path, start_line, start_column);
if(c == '\0') {
tok.kind = KIR_TOKEN_EOF;
return tok;
}
if(c == '#') {
lexer_advance(lx);
while(is_ident_continue((unsigned char)lx->src[lx->pos]))
lexer_advance(lx);
tok.kind = KIR_TOKEN_DIRECTIVE;
token_copy(&tok, lx->src, begin, lx->pos);
return tok;
}
if(is_ident_start(c)) {
lexer_advance(lx);
while(is_ident_continue((unsigned char)lx->src[lx->pos]))
lexer_advance(lx);
tok.kind = KIR_TOKEN_IDENT;
token_copy(&tok, lx->src, begin, lx->pos);
return tok;
}
if(isdigit(c)) {
int seen_dot = 0;
lexer_advance(lx);
while(isalnum((unsigned char)lx->src[lx->pos]) ||
lx->src[lx->pos] == '_' || lx->src[lx->pos] == '.') {
if(lx->src[lx->pos] == '.')
seen_dot = 1;
lexer_advance(lx);
}
tok.kind = seen_dot ? KIR_TOKEN_FLOAT : KIR_TOKEN_INT;
token_copy(&tok, lx->src, begin, lx->pos);
return tok;
}
if(c == '"' || c == '\'') {
int quote = c;
lexer_advance(lx);
while(lx->src[lx->pos] != '\0') {
if(lx->src[lx->pos] == '\\' && lx->src[lx->pos + 1] != '\0') {
lexer_advance(lx);
lexer_advance(lx);
continue;
}
if(lx->src[lx->pos] == quote) {
lexer_advance(lx);
break;
}
lexer_advance(lx);
}
tok.kind = quote == '"' ? KIR_TOKEN_STRING : KIR_TOKEN_CHAR;
token_copy(&tok, lx->src, begin, lx->pos);
return tok;
}
if(strchr("{}()[],:;", c) != NULL) {
lexer_advance(lx);
tok.kind = KIR_TOKEN_PUNCT;
token_copy(&tok, lx->src, begin, lx->pos);
return tok;
}
{
static const char *const ops[] = {
"::", "->", "==", "!=", "<=", ">=", "&&", "||", "+=", "-=",
"*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "<<", ">>",
NULL
};
for(int i = 0; ops[i] != NULL; i++) {
size_t n = strlen(ops[i]);
if(strncmp(lx->src + lx->pos, ops[i], n) == 0) {
while(n-- > 0)
lexer_advance(lx);
tok.kind = KIR_TOKEN_OPERATOR;
token_copy(&tok, lx->src, begin, lx->pos);
return tok;
}
}
}
if(strchr("+-*/%=!<>.&|^?~", c) != NULL) {
lexer_advance(lx);
tok.kind = KIR_TOKEN_OPERATOR;
token_copy(&tok, lx->src, begin, lx->pos);
return tok;
}
lexer_advance(lx);
tok.kind = KIR_TOKEN_UNKNOWN;
token_copy(&tok, lx->src, begin, lx->pos);
return tok;
}
const char *
KirTokenKindName(KirTokenKind kind)
{
switch(kind) {
case KIR_TOKEN_EOF: return "eof";
case KIR_TOKEN_IDENT: return "ident";
case KIR_TOKEN_INT: return "int";
case KIR_TOKEN_FLOAT: return "float";
case KIR_TOKEN_STRING: return "string";
case KIR_TOKEN_CHAR: return "char";
case KIR_TOKEN_DIRECTIVE: return "directive";
case KIR_TOKEN_OPERATOR: return "operator";
case KIR_TOKEN_PUNCT: return "punct";
default: return "unknown";
}
}
+39
View File
@@ -0,0 +1,39 @@
#ifndef KRYON_KIR_TOKEN_H
#define KRYON_KIR_TOKEN_H
#include "kir.h"
#include <stddef.h>
typedef enum KirTokenKind {
KIR_TOKEN_EOF = 0,
KIR_TOKEN_IDENT,
KIR_TOKEN_INT,
KIR_TOKEN_FLOAT,
KIR_TOKEN_STRING,
KIR_TOKEN_CHAR,
KIR_TOKEN_DIRECTIVE,
KIR_TOKEN_OPERATOR,
KIR_TOKEN_PUNCT,
KIR_TOKEN_UNKNOWN
} KirTokenKind;
typedef struct KirToken {
KirTokenKind kind;
char text[KIR_TEXT_MAX];
KirSourceSpan span;
} KirToken;
typedef struct KirLexer {
const char *src;
const char *path;
size_t pos;
int line;
int column;
} KirLexer;
void KirLexerInit(KirLexer *lx, const char *src, const char *path);
KirToken KirLexerNext(KirLexer *lx);
const char *KirTokenKindName(KirTokenKind kind);
#endif /* KRYON_KIR_TOKEN_H */
+133
View File
@@ -0,0 +1,133 @@
/*
* krb-run — headless KRB cartridge runner (plan 11, phase 1).
*
* Loads a .krb, renders it with the kry_sw software rasterizer
* (optionally wrapped in the recording backend), and writes the frame as
* a PNG and/or the vtable call stream as text. Golden files for engine
* conformance are produced with --png/--record and compared by
* tests/krb_engine_test.sh.
*
* Usage: krb-run [--png out.png] [--record out.txt] [--w W] [--h H]
* [--frames N] file.krb
*/
#include "krb.h"
#include "kry_backend_rec.h"
#include "kry_sw.h"
#include "png_write.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char **argv)
{
const char *png_path = NULL;
const char *rec_path = NULL;
const char *krb_path = NULL;
int w = 800;
int h = 600;
int frames = 1;
int i;
KrbImage img;
KrySw sw;
KryBackendRec rec;
long calls = -1;
FILE *recf = NULL;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "--png") == 0 && i + 1 < argc)
png_path = argv[++i];
else if(strcmp(argv[i], "--record") == 0 && i + 1 < argc)
rec_path = argv[++i];
else if(strcmp(argv[i], "--w") == 0 && i + 1 < argc)
w = atoi(argv[++i]);
else if(strcmp(argv[i], "--h") == 0 && i + 1 < argc)
h = atoi(argv[++i]);
else if(strcmp(argv[i], "--frames") == 0 && i + 1 < argc)
frames = atoi(argv[++i]);
else if(argv[i][0] != '-' && krb_path == NULL)
krb_path = argv[i];
else {
fprintf(stderr,
"usage: krb-run [--png out.png] [--record out.txt]"
" [--w W] [--h H] [--frames N] file.krb\n");
return 2;
}
}
if(krb_path == NULL) {
fprintf(stderr, "krb-run: no cartridge given\n");
return 2;
}
memset(&img, 0, sizeof(img));
if(KrbLoadFile(&img, krb_path) != 0) {
fprintf(stderr, "krb-run: load failed: %s\n", krb_path);
return 1;
}
if(KrySwInit(&sw, NULL, w, h) != 0) {
fprintf(stderr, "krb-run: rasterizer init failed\n");
return 1;
}
{
const char *uis = getenv("KRB_RUN_UI_SCALE");
if(uis != NULL) {
int pm = (int)(atof(uis) * 1000.0f + 0.5f);
if(pm > 0 && pm <= 8000)
sw.scale = pm;
}
}
if(getenv("KRB_RUN_THEME_LIGHT") != NULL) {
KrySwSetTheme(&sw, KRY_THEME_BACKGROUND, 0xffffffffu);
KrySwSetTheme(&sw, KRY_THEME_SURFACE, 0xfbfbfbffu);
KrySwSetTheme(&sw, KRY_THEME_ICON, 0xd3d3d3ffu);
KrySwSetTheme(&sw, KRY_THEME_TEXT, 0x00000000u | 0xffu);
KrySwSetTheme(&sw, KRY_THEME_BUTTON, 0xffffffffu);
}
if(0) {
fprintf(stderr, "krb-run: rasterizer init failed\n");
return 1;
}
KrbAutoMount(&img);
if(rec_path != NULL) {
recf = fopen(rec_path, "w");
if(recf == NULL) {
fprintf(stderr, "krb-run: cannot write %s\n", rec_path);
return 1;
}
KryBackendSelect(KryBackendRecBackend(&rec, recf, KrySwBackend(&sw)));
} else {
{
const unsigned char *ad = NULL;
unsigned al = 0;
unsigned ak = 0;
if(KrbAssetFind(&img, "@atlas", &ad, &al, &ak, NULL, NULL) == 0 &&
ak == 1)
KrySwSetAtlas(&sw, ad, al);
}
KryBackendSelect(KrySwBackend(&sw));
}
{
int f;
for(f = 0; f < frames; f++) {
KrySwAdvance(&sw, 1.0f / 60.0f);
KrbDraw(&img, 0, 0, w, h);
}
}
if(recf != NULL) {
fclose(recf);
calls = KryBackendRecCalls(&rec);
}
if(png_path != NULL && krb_png_write(png_path, sw.pixels, sw.w, sw.h) != 0) {
fprintf(stderr, "krb-run: cannot write %s\n", png_path);
return 1;
}
KrbFree(&img);
KrySwFree(&sw);
printf("krb-run ok %s %dx%d calls=%ld\n", krb_path, w, h, calls);
return 0;
}
+154
View File
@@ -0,0 +1,154 @@
/*
* Minimal PNG writer for krb-run: 8-bit RGBA, stored (uncompressed)
* deflate blocks. No external dependencies, deterministic output.
*/
#include "png_write.h"
#include <stdlib.h>
#include <string.h>
static unsigned
crc32_buf(const unsigned char *p, size_t n)
{
static unsigned table[256];
static int built = 0;
unsigned crc = 0xffffffffu;
size_t i;
if(!built) {
int i;
for(i = 0; i < 256; i++) {
unsigned c = (unsigned)i;
int k;
for(k = 0; k < 8; k++)
c = (c & 1) ? 0xedb88320u ^ (c >> 1) : c >> 1;
table[i] = c;
}
built = 1;
}
for(i = 0; i < n; i++)
crc = table[(crc ^ p[i]) & 0xff] ^ (crc >> 8);
return crc ^ 0xffffffffu;
}
static void
be32(unsigned char *p, unsigned v)
{
p[0] = (unsigned char)(v >> 24);
p[1] = (unsigned char)(v >> 16);
p[2] = (unsigned char)(v >> 8);
p[3] = (unsigned char)v;
}
static void
png_chunk(FILE *f, const char *type, const unsigned char *data, size_t len)
{
unsigned char hdr[8];
unsigned char *buf;
unsigned crc;
buf = malloc(4 + len);
if(buf == NULL)
return;
memcpy(buf, type, 4);
if(len > 0 && data != NULL)
memcpy(buf + 4, data, len);
crc = crc32_buf(buf, 4 + len);
be32(hdr, (unsigned)len);
memcpy(hdr + 4, type, 4);
fwrite(hdr, 1, 8, f);
if(len > 0)
fwrite(data, 1, len, f);
be32(hdr, crc);
fwrite(hdr, 1, 4, f);
free(buf);
}
static unsigned
adler32_buf(const unsigned char *p, size_t n)
{
unsigned a = 1;
unsigned b = 0;
size_t i;
for(i = 0; i < n; i++) {
a = (a + p[i]) % 65521u;
b = (b + a) % 65521u;
}
return (b << 16) | a;
}
int
krb_png_write(const char *path, const unsigned char *rgba, int w, int h)
{
static const unsigned char sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
unsigned char ihdr[13];
unsigned char tail[4];
size_t rawlen = (size_t)h * (1 + (size_t)w * 4);
unsigned char *raw;
unsigned char *z;
size_t zn = 0;
size_t off = 0;
size_t left;
const unsigned char *src;
FILE *f;
int row;
int ok = 0;
f = fopen(path, "wb");
if(f == NULL)
return -1;
raw = malloc(rawlen);
z = malloc(rawlen + (rawlen / 65535 + 1) * 5 + 16);
if(raw == NULL || z == NULL)
goto out;
for(row = 0; row < h; row++) {
raw[off++] = 0; /* filter: none */
memcpy(raw + off, rgba + (size_t)row * w * 4, (size_t)w * 4);
off += (size_t)w * 4;
}
z[zn++] = 0x78; /* zlib header, fastest */
z[zn++] = 0x01;
src = raw;
left = rawlen;
while(left > 0) {
size_t chunk = left > 65535 ? 65535 : left;
unsigned char bhdr[5];
bhdr[0] = (left - chunk == 0) ? 1 : 0; /* BFINAL on last block */
bhdr[1] = (unsigned char)(chunk & 0xff);
bhdr[2] = (unsigned char)(chunk >> 8);
bhdr[3] = (unsigned char)(~chunk & 0xff);
bhdr[4] = (unsigned char)((~chunk >> 8) & 0xff);
memcpy(z + zn, bhdr, 5);
zn += 5;
memcpy(z + zn, src, chunk);
zn += chunk;
src += chunk;
left -= chunk;
}
be32(tail, adler32_buf(raw, rawlen));
memcpy(z + zn, tail, 4);
zn += 4;
fwrite(sig, 1, 8, f);
be32(ihdr, (unsigned)w);
be32(ihdr + 4, (unsigned)h);
ihdr[8] = 8; /* bit depth */
ihdr[9] = 6; /* RGBA */
ihdr[10] = 0; /* deflate */
ihdr[11] = 0; /* filter */
ihdr[12] = 0; /* interlace */
png_chunk(f, "IHDR", ihdr, 13);
png_chunk(f, "IDAT", z, zn);
png_chunk(f, "IEND", NULL, 0);
ok = 1;
out:
free(raw);
free(z);
if(fclose(f) != 0)
ok = 0;
return ok ? 0 : -1;
}
+8
View File
@@ -0,0 +1,8 @@
#ifndef KRB_RUN_PNG_WRITE_H
#define KRB_RUN_PNG_WRITE_H
#include <stdio.h>
int krb_png_write(const char *path, const unsigned char *rgba, int w, int h);
#endif
+196
View File
@@ -0,0 +1,196 @@
/*
* krb-sdl — SDL2 desktop host for KRB cartridges (plan 11, phase 7).
*
* Same shape as the web host: the kry_sw rasterizer produces the frame,
* SDL2 owns the window, input, and presentation (streaming texture).
* This is the template for the Android EGL host.
*
* Usage: krb-sdl [--png out.png] [--w W] [--h H] file.krb
* --png renders exactly one frame, dumps it, and exits (for tests;
* runs fine under SDL_VIDEODRIVER=dummy).
*/
#include "krb.h"
#include "kry_sw.h"
#include "png_write.h"
#include <SDL.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char **argv)
{
const char *png_path = NULL;
const char *krb_path = NULL;
int w = 800;
int h = 600;
int i;
KrbImage img;
KrySw sw;
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Texture *texture;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "--png") == 0 && i + 1 < argc)
png_path = argv[++i];
else if(strcmp(argv[i], "--w") == 0 && i + 1 < argc)
w = atoi(argv[++i]);
else if(strcmp(argv[i], "--h") == 0 && i + 1 < argc)
h = atoi(argv[++i]);
else if(argv[i][0] != '-' && krb_path == NULL)
krb_path = argv[i];
else {
fprintf(stderr,
"usage: krb-sdl [--png out.png] [--w W] [--h H]"
" file.krb\n");
return 2;
}
}
if(krb_path == NULL) {
fprintf(stderr, "krb-sdl: no cartridge given\n");
return 2;
}
memset(&img, 0, sizeof(img));
if(KrbLoadFile(&img, krb_path) != 0) {
fprintf(stderr, "krb-sdl: load failed: %s\n", krb_path);
return 1;
}
if(KrySwInit(&sw, NULL, w, h) != 0) {
fprintf(stderr, "krb-sdl: rasterizer init failed\n");
return 1;
}
{
const unsigned char *ad = NULL;
unsigned al = 0;
unsigned ak = 0;
if(KrbAssetFind(&img, "@atlas", &ad, &al, &ak, NULL, NULL) == 0 &&
ak == 1)
KrySwSetAtlas(&sw, ad, al);
}
KrbAutoMount(&img);
KryBackendSelect(KrySwBackend(&sw));
if(SDL_Init(SDL_INIT_VIDEO) != 0) {
fprintf(stderr, "krb-sdl: SDL_Init: %s\n", SDL_GetError());
return 1;
}
if(SDL_CreateWindowAndRenderer(w, h, SDL_WINDOW_RESIZABLE, &window,
&renderer) != 0) {
fprintf(stderr, "krb-sdl: window: %s\n", SDL_GetError());
return 1;
}
SDL_SetWindowTitle(window, "krb-sdl");
SDL_StartTextInput();
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1");
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32,
SDL_TEXTUREACCESS_STREAMING, w, h);
if(texture == NULL) {
fprintf(stderr, "krb-sdl: texture: %s\n", SDL_GetError());
return 1;
}
if(png_path != NULL) {
/* single deterministic frame for the exactness comparator */
KrySwAdvance(&sw, 1.0f / 60.0f);
KrbDraw(&img, 0, 0, w, h);
SDL_UpdateTexture(texture, NULL, sw.pixels, sw.stride);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, NULL);
{
unsigned char *buf = malloc((size_t)w * h * 4);
SDL_Rect r = {0, 0, w, h};
int ok;
if(buf == NULL)
return 1;
ok = SDL_RenderReadPixels(renderer, &r,
SDL_PIXELFORMAT_RGBA32, buf,
w * 4) == 0;
if(ok)
ok = krb_png_write(png_path, buf, w, h) == 0;
free(buf);
if(!ok) {
fprintf(stderr, "krb-sdl: frame dump failed\n");
return 1;
}
}
printf("krb-sdl ok %s %dx%d\n", krb_path, w, h);
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
KrbFree(&img);
KrySwFree(&sw);
return 0;
}
for(;;) {
SDL_Event ev;
int running = 1;
while(SDL_PollEvent(&ev)) {
if(ev.type == SDL_QUIT)
running = 0;
else if(ev.type == SDL_MOUSEMOTION)
KrySwMouse(&sw, ev.motion.x, ev.motion.y);
else if(ev.type == SDL_MOUSEBUTTONDOWN)
KrySwButtonDown(&sw, 0);
else if(ev.type == SDL_MOUSEBUTTONUP)
KrySwButtonUp(&sw, 0);
else if(ev.type == SDL_MOUSEWHEEL)
KrySwWheel(&sw, ev.wheel.y * 50);
else if(ev.type == SDL_TEXTINPUT)
KrySwText(&sw, (unsigned)(unsigned char)ev.text.text[0]);
else if(ev.type == SDL_KEYDOWN &&
ev.key.keysym.sym == SDLK_BACKSPACE)
KrySwText(&sw, 0x08);
}
if(!running)
break;
KrySwAdvance(&sw, 1.0f / 60.0f);
KrbDraw(&img, 0, 0, w, h);
if(SDL_UpdateTexture(texture, NULL, sw.pixels, sw.stride) != 0) {
fprintf(stderr, "krb-sdl: update: %s\n", SDL_GetError());
return 1;
}
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
if(png_path != NULL) {
/* Test mode: read back through the SDL renderer — the same
* pixels that reached the screen — and dump them. */
unsigned char *buf = malloc((size_t)w * h * 4);
SDL_Rect r = {0, 0, w, h};
int ok;
if(buf == NULL)
return 1;
ok = SDL_RenderReadPixels(renderer, &r,
SDL_PIXELFORMAT_RGBA32, buf,
w * 4) == 0;
if(ok)
ok = krb_png_write(png_path, buf, w, h) == 0;
free(buf);
if(!ok) {
fprintf(stderr, "krb-sdl: frame dump failed\n");
return 1;
}
break;
}
SDL_Delay(16);
}
printf("krb-sdl ok %s %dx%d\n", krb_path, w, h);
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
KrbFree(&img);
KrySwFree(&sw);
return 0;
}
+113
View File
@@ -0,0 +1,113 @@
/*
* krb-web — native web host for KRB cartridges (plan 11, phase 3).
*
* Compiles the KRB runtime + kry_sw software rasterizer to wasm with
* emscripten. Pixel-identical to the native headless renderer: the frame
* is blitted into an ImageData every tick. Cartridge is preloaded at
* /app.krb (--preload-file); input comes from canvas events through the
* exported krb_web_mouse / krb_web_button.
*
* Build: make krb-web KRB=examples/02_buttons.kry
*/
#include "krb.h"
#include "kry_sw.h"
#include <emscripten.h>
#include <stdio.h>
#include <string.h>
#ifndef KRB_WEB_CARTRIDGE
#define KRB_WEB_CARTRIDGE "/app.krb"
#endif
static KrbImage g_img;
static KrySw g_sw;
static int g_running;
static void
frame(void)
{
KrySwAdvance(&g_sw, 1.0f / 60.0f);
KrbDraw(&g_img, 0, 0, g_sw.w, g_sw.h);
EM_ASM({
var ptr = $0;
var w = $1;
var h = $2;
var cv = Module.canvas;
var ctx = cv.getContext('2d');
if (!Module.krbImg || Module.krbImg.width !== w ||
Module.krbImg.height !== h)
Module.krbImg = ctx.createImageData(w, h);
Module.krbImg.data.set(HEAPU8.subarray(ptr, ptr + w * h * 4));
ctx.putImageData(Module.krbImg, 0, 0);
}, g_sw.pixels, g_sw.w, g_sw.h);
}
int
main(void)
{
/* The player waits for a cartridge: the shell writes the picked or
* dropped file to KRB_WEB_CARTRIDGE in MEMFS and calls krb_web_start. */
return 0;
}
int
krb_web_start(void)
{
memset(&g_img, 0, sizeof(g_img));
if(g_sw.pixels != NULL)
KrySwFree(&g_sw);
if(KrbLoadFile(&g_img, KRB_WEB_CARTRIDGE) != 0) {
fprintf(stderr, "krb-player: load failed: %s\n", KRB_WEB_CARTRIDGE);
return 1;
}
if(KrySwInit(&g_sw, NULL, 800, 600) != 0)
return 1;
KrbAutoMount(&g_img);
{
const unsigned char *ad = NULL;
unsigned al = 0;
unsigned ak = 0;
if(KrbAssetFind(&g_img, "@atlas", &ad, &al, &ak, NULL, NULL) == 0 &&
ak == 1)
KrySwSetAtlas(&g_sw, ad, al);
}
KryBackendSelect(KrySwBackend(&g_sw));
#ifdef KRB_WEB_ONESHOT
frame();
#else
if(!g_running)
emscripten_set_main_loop(frame, 0, 0);
g_running = 1;
#endif
return 0;
}
void
krb_web_mouse(int x, int y)
{
KrySwMouse(&g_sw, x, y);
}
void
krb_web_text(int cp)
{
KrySwText(&g_sw, (unsigned)cp);
}
void
krb_web_wheel(int dy)
{
KrySwWheel(&g_sw, dy);
}
void
krb_web_button(int button, int down)
{
if(down)
KrySwButtonDown(&g_sw, button);
else
KrySwButtonUp(&g_sw, button);
}
+43
View File
@@ -0,0 +1,43 @@
/* Pre-js for the KRB_WEB_ONESHOT node build: stubs a canvas whose 2D
* context records the blitted ImageData, so the wasm blit path can be
* byte-compared against the native kry_sw frame without a browser. */
var Module = {
printErr: function(t) { console.error(t); },
preRun: [function() {
var path = process.argv[2];
if (!path) {
console.error('node-capture: missing cartridge path');
process.exit(2);
}
var data = require('fs').readFileSync(path);
FS.writeFile('/app.krb', new Uint8Array(data));
}],
canvas: {
getContext: function() {
return {
createImageData: function(w, h) {
return { width: w, height: h,
data: new Uint8ClampedArray(w * h * 4) };
},
putImageData: function(img) {
if (globalThis.__krb_frame)
return;
globalThis.__krb_frame = Buffer.from(img.data);
require('fs').writeSync(1, globalThis.__krb_frame);
process.exit(0);
}
};
}
},
onRuntimeInitialized: function() {
var rc = Module._krb_web_start();
if (rc)
process.exit(rc);
},
onExit: function() {
if (!globalThis.__krb_frame) {
console.error('node-capture: no frame captured');
process.exit(1);
}
}
};
+104
View File
@@ -0,0 +1,104 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>krb player</title>
<style>
html, body { margin: 0; height: 100%; background: #101014; color: #f0f0f2;
font: 14px system-ui, sans-serif; display: flex;
flex-direction: column; align-items: center;
justify-content: center; gap: 12px; }
canvas { image-rendering: pixelated; max-width: 96vw; max-height: 80vh; }
#drop { border: 1px dashed #8a8a93; border-radius: 8px; padding: 14px 22px;
cursor: pointer; }
#drop.hot { border-color: #f0f0f2; background: #1c1c22; }
</style>
</head>
<body>
<div id="drop">drop a .krb cartridge here, or click to pick one</div>
<input id="file" type="file" accept=".krb" hidden>
<canvas id="krb" width="800" height="600"></canvas>
<script>
var Module = {
canvas: document.getElementById('krb')
};
(function() {
const canvas = Module.canvas;
const drop = document.getElementById('drop');
const input = document.getElementById('file');
function start(file) {
file.arrayBuffer().then(function(buf) {
Module.FS.writeFile('/app.krb', new Uint8Array(buf));
drop.textContent = file.name + ' — drop another .krb to switch';
Module._krb_web_start();
});
}
drop.addEventListener('click', function() { input.click(); });
input.addEventListener('change', function() {
if (input.files.length > 0)
start(input.files[0]);
});
['dragover', 'dragenter'].forEach(function(ev) {
drop.addEventListener(ev, function(e) {
e.preventDefault();
drop.classList.add('hot');
});
});
['dragleave', 'drop'].forEach(function(ev) {
drop.addEventListener(ev, function(e) {
e.preventDefault();
drop.classList.remove('hot');
});
});
drop.addEventListener('drop', function(e) {
e.preventDefault();
if (e.dataTransfer.files.length > 0)
start(e.dataTransfer.files[0]);
});
function pos(e) {
const r = canvas.getBoundingClientRect();
return [Math.round((e.clientX - r.left) * canvas.width / r.width),
Math.round((e.clientY - r.top) * canvas.height / r.height)];
}
window.addEventListener('keydown', function(e) {
if (e.key === 'Backspace' && Module._krb_web_text) {
e.preventDefault();
Module._krb_web_text(8);
}
});
window.addEventListener('keypress', function(e) {
if (Module._krb_web_text && e.charCode > 31)
Module._krb_web_text(e.charCode);
});
canvas.addEventListener('wheel', function(e) {
e.preventDefault();
if (Module._krb_web_wheel)
Module._krb_web_wheel(Math.round(-e.deltaY / 2));
}, { passive: false });
canvas.addEventListener('mousemove', function(e) {
if (Module._krb_web_mouse) {
const p = pos(e);
Module._krb_web_mouse(p[0], p[1]);
}
});
canvas.addEventListener('mousedown', function(e) {
if (Module._krb_web_button) {
const p = pos(e);
Module._krb_web_mouse(p[0], p[1]);
Module._krb_web_button(0, 1);
}
});
canvas.addEventListener('mouseup', function(e) {
if (Module._krb_web_button) {
const p = pos(e);
Module._krb_web_mouse(p[0], p[1]);
Module._krb_web_button(0, 0);
}
});
})();
</script>
{{{ SCRIPT }}}
</body>
</html>
+593
View File
@@ -0,0 +1,593 @@
#include "kryon.h"
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#define KP_PATH_MAX 1024
typedef struct PreviewOptions {
const char *command;
const char *project;
const char *source;
const char *source_dir;
const char *out;
int width;
int height;
int count;
} PreviewOptions;
typedef struct PreviewSession {
void *dylib;
AppHost *host;
DestroyAppHostCallback destroy_host;
unsigned long generation;
} PreviewSession;
static void
usage(void)
{
fprintf(stderr,
"usage:\n"
" kryon-preview capture --project ROOT --source REL --output PNG [--width W --height H]\n"
" kryon-preview reload --project ROOT --source REL [--count N --width W --height H]\n"
" kryon-preview capture-all --project ROOT --source-dir DIR --out-dir DIR [--width W --height H]\n"
" kryon-preview cartridge --source FILE.kry|FILE.krb --output PNG [--project ROOT] [--width W --height H]\n");
}
static const char *
arg_value(int argc, char **argv, int *i)
{
if(*i + 1 >= argc)
return NULL;
(*i)++;
return argv[*i];
}
static int
parse_args(int argc, char **argv, PreviewOptions *opt)
{
memset(opt, 0, sizeof(*opt));
opt->width = 640;
opt->height = 480;
opt->count = 2;
if(argc < 2)
return 0;
opt->command = argv[1];
for(int i = 2; i < argc; i++) {
const char *value = NULL;
if(strcmp(argv[i], "--project") == 0) {
value = arg_value(argc, argv, &i);
if(value == NULL)
return 0;
opt->project = value;
} else if(strcmp(argv[i], "--source") == 0) {
value = arg_value(argc, argv, &i);
if(value == NULL)
return 0;
opt->source = value;
} else if(strcmp(argv[i], "--source-dir") == 0) {
value = arg_value(argc, argv, &i);
if(value == NULL)
return 0;
opt->source_dir = value;
} else if(strcmp(argv[i], "--output") == 0 ||
strcmp(argv[i], "--out-dir") == 0) {
value = arg_value(argc, argv, &i);
if(value == NULL)
return 0;
opt->out = value;
} else if(strcmp(argv[i], "--width") == 0) {
value = arg_value(argc, argv, &i);
if(value == NULL)
return 0;
opt->width = atoi(value);
} else if(strcmp(argv[i], "--height") == 0) {
value = arg_value(argc, argv, &i);
if(value == NULL)
return 0;
opt->height = atoi(value);
} else if(strcmp(argv[i], "--count") == 0) {
value = arg_value(argc, argv, &i);
if(value == NULL)
return 0;
opt->count = atoi(value);
} else {
return 0;
}
}
if(opt->width <= 0)
opt->width = 640;
if(opt->height <= 0)
opt->height = 480;
if(opt->count <= 0)
opt->count = 1;
if(strcmp(opt->command, "capture") == 0)
return opt->project != NULL && opt->source != NULL && opt->out != NULL;
if(strcmp(opt->command, "reload") == 0)
return opt->project != NULL && opt->source != NULL;
if(strcmp(opt->command, "capture-all") == 0)
return opt->project != NULL && opt->source_dir != NULL && opt->out != NULL;
if(strcmp(opt->command, "cartridge") == 0)
return opt->source != NULL && opt->out != NULL;
return 0;
}
static void
path_join(char *dst, size_t dst_size, const char *a, const char *b)
{
if(a == NULL || a[0] == '\0')
snprintf(dst, dst_size, "%s", b != NULL ? b : "");
else if(b == NULL || b[0] == '\0')
snprintf(dst, dst_size, "%s", a);
else
snprintf(dst, dst_size, "%s/%s", a, b);
}
static int
has_suffix(const char *path, const char *suffix)
{
size_t path_len = strlen(path);
size_t suffix_len = strlen(suffix);
return path_len >= suffix_len &&
strcmp(path + path_len - suffix_len, suffix) == 0;
}
static int
copy_file(const char *src, const char *dst)
{
FILE *in = fopen(src, "rb");
FILE *out;
char buf[16384];
size_t n;
if(in == NULL)
return 0;
out = fopen(dst, "wb");
if(out == NULL) {
fclose(in);
return 0;
}
while((n = fread(buf, 1, sizeof(buf), in)) > 0) {
if(fwrite(buf, 1, n, out) != n) {
fclose(out);
fclose(in);
return 0;
}
}
if(ferror(in)) {
fclose(out);
fclose(in);
return 0;
}
fclose(out);
fclose(in);
return 1;
}
static int
mkdir_p(const char *path)
{
char tmp[KP_PATH_MAX];
snprintf(tmp, sizeof(tmp), "%s", path);
for(char *p = tmp + 1; *p != '\0'; p++) {
if(*p != '/')
continue;
*p = '\0';
if(mkdir(tmp, 0755) != 0 && errno != EEXIST)
return 0;
*p = '/';
}
return mkdir(tmp, 0755) == 0 || errno == EEXIST;
}
static int
build_host(const char *project)
{
char command[KP_PATH_MAX * 4];
const char *kryon_dir = getenv("KRYON_DIR");
int rc;
if(kryon_dir == NULL || kryon_dir[0] == '\0')
kryon_dir = "/usr/home/wao/src/kryon";
snprintf(command, sizeof(command),
"cd '%s' && gmake kryon-host KRYON_DIR='%s' >/tmp/kryon-preview-build.log 2>&1",
project, kryon_dir);
rc = system(command);
return rc != -1 && WIFEXITED(rc) && WEXITSTATUS(rc) == 0;
}
static void
preview_close(PreviewSession *session)
{
if(session->destroy_host != NULL && session->host != NULL)
session->destroy_host(session->host);
if(session->dylib != NULL)
kry_dylib_close(session->dylib);
session->dylib = NULL;
session->host = NULL;
session->destroy_host = NULL;
}
static int
preview_open(PreviewSession *session, const char *project)
{
char host_path[KP_PATH_MAX];
char copy_path[KP_PATH_MAX];
CreateAppHostCallback create_host;
preview_close(session);
if(!build_host(project)) {
fprintf(stderr, "kryon-preview: host build failed, see /tmp/kryon-preview-build.log\n");
return 0;
}
path_join(host_path, sizeof(host_path), project, "build/kryon/app_host.so");
snprintf(copy_path, sizeof(copy_path), "%s.preview.%lu.so", host_path,
++session->generation);
if(!copy_file(host_path, copy_path)) {
fprintf(stderr, "kryon-preview: could not copy %s\n", host_path);
return 0;
}
session->dylib = kry_dylib_load(copy_path);
if(session->dylib == NULL) {
fprintf(stderr, "kryon-preview: load failed: %s\n",
kry_dylib_error() != NULL ? kry_dylib_error() : copy_path);
return 0;
}
create_host = (CreateAppHostCallback)kry_dylib_sym(session->dylib,
"CreateAppHost");
session->destroy_host =
(DestroyAppHostCallback)kry_dylib_sym(session->dylib,
"DestroyAppHost");
if(create_host == NULL || session->destroy_host == NULL) {
fprintf(stderr, "kryon-preview: host missing app symbols\n");
preview_close(session);
return 0;
}
session->host = create_host(APP_HOST_ABI_VERSION, project);
if(session->host == NULL) {
fprintf(stderr, "kryon-preview: host rejected ABI %d\n",
APP_HOST_ABI_VERSION);
preview_close(session);
return 0;
}
return 1;
}
static int
capture_source(PreviewSession *session, const char *source, const char *out,
int width, int height)
{
RenderTexture2D target;
Image image;
int selected;
int saved;
selected = SetAppScreenBySourcePath(session->host, source);
if(!selected)
SetAppScreen(session->host, 0);
target = LoadRenderTexture(width, height);
BeginTextureMode(target);
ClearBackground(GetThemeBackground());
BeginUIFrame(width, height, 1.0f);
DrawAppScreen(session->host, (Rectangle){0, 0, (float)width, (float)height});
EndUIFrame();
EndTextureMode();
image = LoadImageFromTexture(target.texture);
UnloadRenderTexture(target);
if(image.data == NULL)
return 0;
ImageFlipVertical(&image);
saved = ExportImage(image, out);
UnloadImage(image);
if(!selected)
fprintf(stderr, "kryon-preview: %s delegates to app preview\n", source);
return saved;
}
static int
run_capture(const PreviewOptions *opt)
{
PreviewSession session = {0};
int ok;
if(!preview_open(&session, opt->project))
return 1;
ok = capture_source(&session, opt->source, opt->out,
opt->width, opt->height);
preview_close(&session);
return ok ? 0 : 1;
}
static int
run_reload(const PreviewOptions *opt)
{
PreviewSession session = {0};
for(int i = 0; i < opt->count; i++) {
if(!preview_open(&session, opt->project))
return 1;
if(!capture_source(&session, opt->source, "/tmp/kryon-preview-reload.png",
opt->width, opt->height)) {
preview_close(&session);
return 1;
}
}
preview_close(&session);
return 0;
}
static void
png_name(char *dst, size_t dst_size, const char *rel)
{
size_t n = 0;
for(const char *p = rel; *p != '\0' && n + 5 < dst_size; p++)
dst[n++] = (*p == '/' || *p == '.') ? '_' : *p;
memcpy(dst + n, ".png", 5);
}
static int
capture_all_dir(PreviewSession *session, const PreviewOptions *opt,
const char *rel_dir, int *total)
{
char abs_dir[KP_PATH_MAX];
DIR *dir;
struct dirent *entry;
int ok = 1;
path_join(abs_dir, sizeof(abs_dir), opt->project, rel_dir);
dir = opendir(abs_dir);
if(dir == NULL)
return 0;
while((entry = readdir(dir)) != NULL) {
char child_rel[KP_PATH_MAX];
char child_abs[KP_PATH_MAX];
struct stat st;
if(strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
path_join(child_rel, sizeof(child_rel), rel_dir, entry->d_name);
path_join(child_abs, sizeof(child_abs), opt->project, child_rel);
if(stat(child_abs, &st) != 0)
continue;
if(S_ISDIR(st.st_mode)) {
if(!capture_all_dir(session, opt, child_rel, total))
ok = 0;
} else if(S_ISREG(st.st_mode) && has_suffix(entry->d_name, ".kry")) {
char file[KP_PATH_MAX];
char out_path[KP_PATH_MAX];
png_name(file, sizeof(file), child_rel);
path_join(out_path, sizeof(out_path), opt->out, file);
(*total)++;
if(!capture_source(session, child_rel, out_path,
opt->width, opt->height)) {
fprintf(stderr, "kryon-preview: capture failed: %s\n", child_rel);
ok = 0;
}
}
}
closedir(dir);
return ok;
}
static int
run_capture_all(const PreviewOptions *opt)
{
PreviewSession session = {0};
int total = 0;
int ok;
if(!mkdir_p(opt->out))
return 1;
if(!preview_open(&session, opt->project))
return 1;
ok = capture_all_dir(&session, opt, opt->source_dir, &total);
preview_close(&session);
fprintf(stderr, "kryon-preview: captured=%d failed=%d\n", total, ok ? 0 : 1);
return ok ? 0 : 1;
}
static int
file_exists(const char *path)
{
struct stat st;
return path != NULL && stat(path, &st) == 0 && S_ISREG(st.st_mode);
}
static int
find_k2b(char *dst, size_t dst_size)
{
const char *kryon_dir = getenv("KRYON_DIR");
const char *path;
if(kryon_dir != NULL && kryon_dir[0] != '\0') {
snprintf(dst, dst_size, "%s/build/bin/k2b", kryon_dir);
if(file_exists(dst))
return 1;
snprintf(dst, dst_size, "%s/build/linux-x86_64/bin/k2b", kryon_dir);
if(file_exists(dst))
return 1;
}
if(file_exists("build/bin/k2b")) {
snprintf(dst, dst_size, "build/bin/k2b");
return 1;
}
if(file_exists("build/linux-x86_64/bin/k2b")) {
snprintf(dst, dst_size, "build/linux-x86_64/bin/k2b");
return 1;
}
path = getenv("PATH");
if(path != NULL) {
char buf[KP_PATH_MAX];
const char *start = path;
while(*start != '\0') {
const char *colon = strchr(start, ':');
size_t n = colon != NULL ? (size_t)(colon - start) : strlen(start);
if(n > 0 && n + 4 < sizeof(buf)) {
memcpy(buf, start, n);
buf[n] = '\0';
path_join(dst, dst_size, buf, "k2b");
if(file_exists(dst))
return 1;
}
if(colon == NULL)
break;
start = colon + 1;
}
}
return 0;
}
static int
compile_krb(const char *k2b, const char *project, const char *source,
char *out_krb, size_t out_size)
{
char command[KP_PATH_MAX * 4];
char out_dir[KP_PATH_MAX];
char rel[KP_PATH_MAX];
char src_abs[KP_PATH_MAX];
int rc;
snprintf(out_dir, sizeof(out_dir), "%s/kryon-preview-krb",
getenv("TMPDIR") != NULL ? getenv("TMPDIR") : "/tmp");
snprintf(rel, sizeof(rel), "%s", source);
if(has_suffix(rel, ".kry"))
rel[strlen(rel) - 4] = '\0';
path_join(out_krb, out_size, out_dir, rel);
{
size_t n = strlen(out_krb);
if(n + 5 < out_size)
memcpy(out_krb + n, ".krb", 5);
}
{
char parent[KP_PATH_MAX];
char *slash;
snprintf(parent, sizeof(parent), "%s", out_krb);
slash = strrchr(parent, '/');
if(slash != NULL) {
*slash = '\0';
if(!mkdir_p(parent))
return 0;
}
}
if(source[0] == '/')
snprintf(src_abs, sizeof(src_abs), "%s", source);
else
path_join(src_abs, sizeof(src_abs), project, source);
snprintf(command, sizeof(command),
"'%s' --no-main --root '%s' -o '%s' '%s'",
k2b, project, out_dir, src_abs);
rc = system(command);
if(!(rc != -1 && WIFEXITED(rc) && WEXITSTATUS(rc) == 0))
return 0;
return file_exists(out_krb);
}
static int
capture_cartridge(const char *krb_path, const char *out, int width, int height)
{
KrbImage img;
RenderTexture2D target;
Image image;
int saved;
memset(&img, 0, sizeof(img));
if(KrbLoadFile(&img, krb_path) != 0) {
fprintf(stderr, "kryon-preview: could not load %s\n", krb_path);
return 0;
}
target = LoadRenderTexture(width, height);
BeginTextureMode(target);
ClearBackground(GetThemeBackground());
BeginUIFrame(width, height, 1.0f);
KrbDraw(&img, 0, 0, width, height);
EndUIFrame();
EndTextureMode();
KrbFree(&img);
image = LoadImageFromTexture(target.texture);
UnloadRenderTexture(target);
if(image.data == NULL)
return 0;
ImageFlipVertical(&image);
saved = ExportImage(image, out);
UnloadImage(image);
return saved;
}
static int
run_cartridge(const PreviewOptions *opt)
{
char krb_path[KP_PATH_MAX];
const char *source = opt->source;
if(has_suffix(source, ".krb")) {
if(source[0] == '/' || opt->project == NULL)
snprintf(krb_path, sizeof(krb_path), "%s", source);
else
path_join(krb_path, sizeof(krb_path), opt->project, source);
return capture_cartridge(krb_path, opt->out, opt->width, opt->height)
? 0
: 1;
}
if(has_suffix(source, ".kry")) {
char k2b[KP_PATH_MAX];
const char *project = opt->project != NULL ? opt->project : ".";
if(!find_k2b(k2b, sizeof(k2b))) {
fprintf(stderr, "kryon-preview: k2b not found for cartridge compile\n");
return 1;
}
if(!compile_krb(k2b, project, source, krb_path, sizeof(krb_path))) {
fprintf(stderr, "kryon-preview: k2b failed\n");
return 1;
}
return capture_cartridge(krb_path, opt->out, opt->width, opt->height)
? 0
: 1;
}
fprintf(stderr, "kryon-preview: cartridge source must be .kry or .krb\n");
return 1;
}
int
main(int argc, char **argv)
{
PreviewOptions opt;
int rc;
if(!parse_args(argc, argv, &opt)) {
usage();
return 2;
}
SetTraceLogLevel(LOG_WARNING);
SetConfigFlags(FLAG_WINDOW_HIDDEN);
InitWindow(opt.width, opt.height, "Kryon Preview");
SetTargetFPS(60);
InitUI(opt.width, opt.height, 1.0f);
SetCurrentTheme(THEME_MONO, 0);
setenv("KRYON_INSPECT", "1", 1);
if(strcmp(opt.command, "capture") == 0)
rc = run_capture(&opt);
else if(strcmp(opt.command, "reload") == 0)
rc = run_reload(&opt);
else if(strcmp(opt.command, "cartridge") == 0)
rc = run_cartridge(&opt);
else
rc = run_capture_all(&opt);
CloseWindow();
return rc;
}
+619
View File
@@ -0,0 +1,619 @@
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define KT_LINE_MAX 4096
#define KT_PATH_MAX 1024
#define KT_MAX_TESTS 512
typedef struct KTOptions {
int headless;
int snap;
int bless;
const char *files[KT_MAX_TESTS];
int file_count;
} KTOptions;
typedef struct KTRun {
const KTOptions *options;
const char *argv0;
char root[KT_PATH_MAX];
char clip[KT_LINE_MAX];
char target[16];
FILE *log;
pid_t visual_pid;
int steps;
int failures;
} KTRun;
static void
kt_usage(FILE *out)
{
fprintf(out,
"usage: kt [-headless] [-snap] [-bless] [tests/file.kt ...]\n");
fprintf(out,
"commands: target open tap type key see shot wait mkdir write append copy paste mv exists notexists contains\n");
fprintf(out, "without -headless, kt opens the target app by default; "
"'target none' runs headless\n");
}
static char *
kt_trim(char *s)
{
char *end;
while(*s != '\0' && isspace((unsigned char)*s))
s++;
end = s + strlen(s);
while(end > s && isspace((unsigned char)end[-1]))
*--end = '\0';
return s;
}
static int
kt_ends_with(const char *s, const char *suffix)
{
size_t n;
size_t m;
if(s == NULL || suffix == NULL)
return 0;
n = strlen(s);
m = strlen(suffix);
return n >= m && strcmp(s + n - m, suffix) == 0;
}
static int
kt_mkdir(const char *path)
{
if(mkdir(path, 0775) == 0)
return 1;
return errno == EEXIST;
}
static int
kt_join(char *out, size_t out_size, const char *a, const char *b)
{
if(a == NULL || a[0] == '\0')
a = ".";
if(b == NULL)
b = "";
return snprintf(out, out_size, "%s/%s", a, b) < (int)out_size;
}
static int
kt_parse_word(char **cursor, char *out, size_t out_size)
{
char *s = kt_trim(*cursor);
size_t n = 0;
if(*s == '\0')
return 0;
while(*s != '\0' && !isspace((unsigned char)*s)) {
if(n + 1 < out_size)
out[n++] = *s;
s++;
}
out[n] = '\0';
*cursor = s;
return n > 0;
}
static int
kt_parse_arg(char **cursor, char *out, size_t out_size, char *err,
size_t err_size)
{
char *s = kt_trim(*cursor);
size_t n = 0;
if(*s == '\0') {
snprintf(err, err_size, "missing argument");
return 0;
}
if(*s == '"') {
s++;
while(*s != '\0' && *s != '"') {
if(*s == '\\' && s[1] != '\0')
s++;
if(n + 1 < out_size)
out[n++] = *s;
s++;
}
if(*s != '"') {
snprintf(err, err_size, "unterminated string");
return 0;
}
s++;
if(*kt_trim(s) != '\0') {
snprintf(err, err_size, "unexpected trailing text");
return 0;
}
} else {
while(*s != '\0' && !isspace((unsigned char)*s)) {
if(n + 1 < out_size)
out[n++] = *s;
s++;
}
if(*kt_trim(s) != '\0') {
snprintf(err, err_size, "unexpected trailing text");
return 0;
}
}
out[n] = '\0';
*cursor = s;
return 1;
}
static int
kt_parse_tail(char **cursor, char *out, size_t out_size, char *err,
size_t err_size)
{
char *s = kt_trim(*cursor);
if(*s == '\0') {
snprintf(err, err_size, "missing argument");
return 0;
}
return kt_parse_arg(&s, out, out_size, err, err_size);
}
static int
kt_safe_relpath(const char *path)
{
const char *p;
if(path == NULL || path[0] == '\0' || path[0] == '/')
return 0;
for(p = path; *p != '\0'; p++) {
if((p == path || p[-1] == '/') && p[0] == '.' &&
p[1] == '.' && (p[2] == '/' || p[2] == '\0'))
return 0;
}
return 1;
}
static int
kt_project_path(KTRun *run, const char *rel, char *out, size_t out_size)
{
if(!kt_safe_relpath(rel))
return 0;
return kt_join(out, out_size, run->root, rel);
}
static int
kt_read_file(const char *path, char *out, size_t out_size)
{
FILE *f;
size_t n;
f = fopen(path, "rb");
if(f == NULL)
return 0;
n = fread(out, 1, out_size > 0 ? out_size - 1 : 0, f);
if(out_size > 0)
out[n] = '\0';
fclose(f);
return 1;
}
static int
kt_write_file(const char *path, const char *text, const char *mode)
{
FILE *f = fopen(path, mode);
if(f == NULL)
return 0;
if(text != NULL && fputs(text, f) == EOF) {
fclose(f);
return 0;
}
fclose(f);
return 1;
}
static void
kt_tool_path(char *out, size_t out_size, const char *argv0,
const char *tool)
{
const char *slash;
size_t dir_len;
if(argv0 == NULL)
argv0 = "";
slash = strrchr(argv0, '/');
if(slash == NULL) {
snprintf(out, out_size, "%s", tool);
return;
}
dir_len = (size_t)(slash - argv0);
if(dir_len + 1 + strlen(tool) + 1 > out_size) {
snprintf(out, out_size, "%s", tool);
return;
}
memcpy(out, argv0, dir_len);
out[dir_len] = '/';
snprintf(out + dir_len + 1, out_size - dir_len - 1, "%s", tool);
}
static int
kt_start_visual(KTRun *run)
{
char tool[KT_PATH_MAX];
if(run->options == NULL || run->options->headless)
return 1;
if(run->visual_pid > 0)
return 1;
if(strcmp(run->target, "none") == 0)
return 1;
kt_tool_path(tool, sizeof(tool), run->argv0, "kryon");
run->visual_pid = fork();
if(run->visual_pid < 0)
return 0;
if(run->visual_pid == 0) {
setenv("KRYON_PROJECT_ROOT", run->root, 1);
execl(tool, tool, "--project", run->root, "run", "native",
(char *)NULL);
execlp("kryon", "kryon", "--project", run->root, "run", "native",
(char *)NULL);
_exit(127);
}
usleep(800000);
return 1;
}
static void
kt_stop_visual(KTRun *run)
{
int status;
if(run->visual_pid <= 0)
return;
kill(run->visual_pid, SIGTERM);
waitpid(run->visual_pid, &status, 0);
run->visual_pid = 0;
}
static void
kt_visual_step_delay(KTRun *run)
{
if(run->options != NULL && !run->options->headless &&
run->visual_pid > 0)
usleep(180000);
}
static int
kt_open_log(KTRun *run)
{
char path[KT_PATH_MAX];
if(!kt_join(path, sizeof(path), run->root, "logs"))
return 0;
if(!kt_mkdir(path))
return 0;
if(!kt_join(path, sizeof(path), run->root, "logs/kt.log"))
return 0;
run->log = fopen(path, "a");
return run->log != NULL;
}
static void
kt_log(KTRun *run, const char *file, int line_no, const char *cmd,
const char *arg)
{
if(run->log == NULL)
return;
fprintf(run->log, "%s:%d: %s %s\n", file, line_no, cmd,
arg != NULL ? arg : "");
}
static int
kt_run_command(KTRun *run, const char *file, int line_no, char *line)
{
char *cursor = line;
char cmd[32];
char arg[KT_LINE_MAX];
char arg2[KT_LINE_MAX];
char err[128];
char path[KT_PATH_MAX];
char path2[KT_PATH_MAX];
char text[KT_LINE_MAX];
char snapshots[KT_PATH_MAX];
if(!kt_parse_word(&cursor, cmd, sizeof(cmd)))
return 1;
if(strcmp(cmd, "target") == 0 || strcmp(cmd, "open") == 0 ||
strcmp(cmd, "tap") == 0 ||
strcmp(cmd, "type") == 0 || strcmp(cmd, "key") == 0 ||
strcmp(cmd, "see") == 0 || strcmp(cmd, "shot") == 0 ||
strcmp(cmd, "wait") == 0 ||
strcmp(cmd, "copy") == 0 || strcmp(cmd, "exists") == 0 ||
strcmp(cmd, "notexists") == 0 || strcmp(cmd, "mkdir") == 0) {
if(!kt_parse_arg(&cursor, arg, sizeof(arg), err, sizeof(err))) {
fprintf(stderr, "%s:%d: %s\n", file, line_no, err);
return 0;
}
if(strcmp(cmd, "target") == 0) {
if(strcmp(arg, "app") != 0 && strcmp(arg, "none") != 0) {
fprintf(stderr, "%s:%d: unknown target: %s\n", file, line_no,
arg);
return 0;
}
snprintf(run->target, sizeof(run->target), "%s", arg);
}
if(strcmp(cmd, "open") == 0) {
struct stat st;
if(stat(arg, &st) != 0 || !S_ISDIR(st.st_mode)) {
fprintf(stderr, "%s:%d: open target is not a directory: %s\n",
file, line_no, arg);
return 0;
}
snprintf(run->root, sizeof(run->root), "%s", arg);
if(run->log == NULL && !kt_open_log(run)) {
fprintf(stderr, "%s:%d: could not open logs/kt.log\n", file,
line_no);
return 0;
}
if(!kt_start_visual(run)) {
fprintf(stderr, "%s:%d: could not start Kryon visual runner\n",
file, line_no);
return 0;
}
}
if(strcmp(cmd, "shot") == 0) {
if(!kt_join(snapshots, sizeof(snapshots), run->root, "snapshots") ||
!kt_mkdir(snapshots)) {
fprintf(stderr, "%s:%d: could not create snapshots/\n", file,
line_no);
return 0;
}
}
if(strcmp(cmd, "copy") == 0)
snprintf(run->clip, sizeof(run->clip), "%s", arg);
if(strcmp(cmd, "wait") == 0) {
int ms = atoi(arg);
if(ms < 0)
ms = 0;
if(ms > 30000)
ms = 30000;
usleep((useconds_t)ms * 1000);
}
if(strcmp(cmd, "exists") == 0) {
struct stat st;
if(!kt_project_path(run, arg, path, sizeof(path)) ||
stat(path, &st) != 0) {
fprintf(stderr, "%s:%d: path does not exist: %s\n", file,
line_no, arg);
return 0;
}
}
if(strcmp(cmd, "notexists") == 0) {
struct stat st;
if(!kt_project_path(run, arg, path, sizeof(path)) ||
stat(path, &st) == 0) {
fprintf(stderr, "%s:%d: path exists: %s\n", file, line_no,
arg);
return 0;
}
}
if(strcmp(cmd, "mkdir") == 0) {
if(!kt_project_path(run, arg, path, sizeof(path)) ||
!kt_mkdir(path)) {
fprintf(stderr, "%s:%d: could not create directory: %s\n",
file, line_no, arg);
return 0;
}
}
kt_log(run, file, line_no, cmd, arg);
run->steps++;
kt_visual_step_delay(run);
return 1;
}
if(strcmp(cmd, "write") == 0 || strcmp(cmd, "append") == 0 ||
strcmp(cmd, "contains") == 0) {
if(!kt_parse_word(&cursor, arg, sizeof(arg))) {
fprintf(stderr, "%s:%d: missing path\n", file, line_no);
return 0;
}
if(!kt_parse_tail(&cursor, arg2, sizeof(arg2), err, sizeof(err))) {
fprintf(stderr, "%s:%d: %s\n", file, line_no, err);
return 0;
}
if(!kt_project_path(run, arg, path, sizeof(path))) {
fprintf(stderr, "%s:%d: unsafe path: %s\n", file, line_no, arg);
return 0;
}
if(strcmp(cmd, "contains") == 0) {
if(!kt_read_file(path, text, sizeof(text)) ||
strstr(text, arg2) == NULL) {
fprintf(stderr, "%s:%d: file does not contain text: %s\n",
file, line_no, arg);
return 0;
}
} else if(!kt_write_file(path, arg2,
strcmp(cmd, "append") == 0 ? "ab" : "wb")) {
fprintf(stderr, "%s:%d: could not write file: %s\n", file, line_no,
arg);
return 0;
}
kt_log(run, file, line_no, cmd, arg);
run->steps++;
kt_visual_step_delay(run);
return 1;
}
if(strcmp(cmd, "paste") == 0) {
if(!kt_parse_arg(&cursor, arg, sizeof(arg), err, sizeof(err))) {
fprintf(stderr, "%s:%d: %s\n", file, line_no, err);
return 0;
}
if(run->clip[0] == '\0') {
fprintf(stderr, "%s:%d: clipboard is empty\n", file, line_no);
return 0;
}
if(!kt_project_path(run, arg, path, sizeof(path)) ||
!kt_write_file(path, run->clip, "ab")) {
fprintf(stderr, "%s:%d: could not paste into file: %s\n", file,
line_no, arg);
return 0;
}
kt_log(run, file, line_no, cmd, arg);
run->steps++;
kt_visual_step_delay(run);
return 1;
}
if(strcmp(cmd, "mv") == 0) {
if(!kt_parse_word(&cursor, arg, sizeof(arg))) {
fprintf(stderr, "%s:%d: missing source path\n", file, line_no);
return 0;
}
if(!kt_parse_tail(&cursor, arg2, sizeof(arg2), err, sizeof(err))) {
fprintf(stderr, "%s:%d: %s\n", file, line_no, err);
return 0;
}
if(!kt_project_path(run, arg, path, sizeof(path)) ||
!kt_project_path(run, arg2, path2, sizeof(path2)) ||
rename(path, path2) != 0) {
fprintf(stderr, "%s:%d: could not move %s to %s\n", file, line_no,
arg, arg2);
return 0;
}
kt_log(run, file, line_no, cmd, arg);
run->steps++;
kt_visual_step_delay(run);
return 1;
}
fprintf(stderr, "%s:%d: unknown command: %s\n", file, line_no, cmd);
return 0;
}
static int
kt_run_file(const KTOptions *options, const char *argv0, const char *path)
{
FILE *f;
KTRun run = {0};
char line[KT_LINE_MAX];
int line_no = 0;
int ok = 1;
run.options = options;
run.argv0 = argv0;
snprintf(run.root, sizeof(run.root), ".");
snprintf(run.target, sizeof(run.target), "app");
if(!kt_open_log(&run)) {
fprintf(stderr, "%s: could not open logs/kt.log\n", path);
return 0;
}
f = fopen(path, "r");
if(f == NULL) {
fprintf(stderr, "%s: %s\n", path, strerror(errno));
fclose(run.log);
return 0;
}
while(fgets(line, sizeof(line), f) != NULL) {
char *trimmed;
line_no++;
trimmed = kt_trim(line);
if(trimmed[0] == '\0' || trimmed[0] == '#')
continue;
if(!kt_run_command(&run, path, line_no, trimmed)) {
ok = 0;
run.failures++;
}
}
if(run.log != NULL) {
fprintf(run.log, "%s: %d steps, %d failures\n", path, run.steps,
run.failures);
fclose(run.log);
}
kt_stop_visual(&run);
fclose(f);
return ok;
}
static int
kt_compare_strings(const void *a, const void *b)
{
const char *const *sa = a;
const char *const *sb = b;
return strcmp(*sa, *sb);
}
static int
kt_discover_tests(KTOptions *options)
{
DIR *dir;
struct dirent *entry;
char *names[KT_MAX_TESTS];
int count = 0;
dir = opendir("tests");
if(dir == NULL)
return 0;
while((entry = readdir(dir)) != NULL && count < KT_MAX_TESTS) {
char path[KT_PATH_MAX];
if(!kt_ends_with(entry->d_name, ".kt"))
continue;
if(!kt_join(path, sizeof(path), "tests", entry->d_name))
continue;
names[count] = strdup(path);
if(names[count] != NULL)
count++;
}
closedir(dir);
qsort(names, (size_t)count, sizeof(names[0]), kt_compare_strings);
for(int i = 0; i < count; i++)
options->files[options->file_count++] = names[i];
return count > 0;
}
int
main(int argc, char **argv)
{
KTOptions options = {0};
int ok = 1;
for(int i = 1; i < argc; i++) {
if(strcmp(argv[i], "-headless") == 0) {
options.headless = 1;
} else if(strcmp(argv[i], "-snap") == 0) {
options.snap = 1;
} else if(strcmp(argv[i], "-bless") == 0) {
options.bless = 1;
} else if(strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
kt_usage(stdout);
return 0;
} else if(argv[i][0] == '-') {
kt_usage(stderr);
return 2;
} else if(options.file_count < KT_MAX_TESTS) {
options.files[options.file_count++] = argv[i];
} else {
fprintf(stderr, "kt: too many test files\n");
return 2;
}
}
if(options.file_count == 0 && !kt_discover_tests(&options)) {
fprintf(stderr, "kt: no tests supplied and no tests/*.kt found\n");
return 2;
}
for(int i = 0; i < options.file_count; i++) {
if(!kt_run_file(&options, argv[0], options.files[i]))
ok = 0;
}
return ok ? 0 : 1;
}
+64 -17
View File
@@ -1,14 +1,39 @@
# 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.
This document is for agents and maintainers using Kryon inside applications. 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.
Kryon is a small native UI runtime with a Kryon-owned clean app API.
The current default backend is raylib, but applications should not depend on
raylib directly. 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.
See `docs/BOUNDARIES.md` for the architectural line between reusable Kryon
runtime behavior and downstream application behavior. See `docs/ARCHITECTURE.md`
for the current subsystem map.
Do not add compatibility wrappers or alias layers when the app API changes. Migrate
Kryon itself first, then update downstream apps to the
canonical names directly. Generated app code must use clean names such as
`BeginFrame`, `EndFrame`, `Background`, `Text`, `Rect`, `Button`, `TextField`,
`TextArea`, `Row`, `Column`, and `Picture`. Do not reintroduce duplicate public
widget names such as `WidgetText`, `UIText`, or `UITextNode` for the same
behavior. New public widget constructors must not use a `UI` prefix. If a stale
prefixed widget constructor still exists, migrate callers to the canonical
unprefixed widget name instead of adding another alias.
Do not add public picture/widget helpers with `DrawUI*`, `UIText*`, or reversed
UI-draw prefix names when the behavior belongs on the simple widget API. Extend
`PictureProps`, `ButtonProps`, or the relevant unprefixed widget props instead,
and leave no compatibility alias behind.
Kryon owns live preview rendering, preview PNG capture, and hot-reload
verification. Do not use Krait as the capture test harness for `.kry` files.
Use Kryon-owned tooling directly, for example `kryon-preview`, to prove that a
project source file renders, exports a PNG, and reloads safely.
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.
@@ -21,6 +46,11 @@ screen-space UI frame. If the application uses a transformed UI camera, call
invalid cameras before using them; a zero-initialized `Camera2D` is treated as
`GetUIDefaultCamera()` so pointer input does not silently break.
After drawing all widgets, call `EndUIFrame()` before the backend's
`EndFrame()`. The closing call draws deferred overlays such as dropdowns and
text-field context menus, then finalizes focus and inspection state. Applications
must not reproduce those overlay or finalization steps themselves.
Beginning a frame resets per-frame interaction state:
- input blocking
@@ -58,18 +88,18 @@ Use these APIs by responsibility:
Kryon modal helpers own backdrop capture:
- `DrawUIActionModal`
- `DrawUIModal`
- `DrawUIModal3Button`
- `DrawUIModalFrame`
- `UIActionModalNode`
- `UIModalNode`
- `UIModal3ButtonNode`
- `UIModalFrameNode`
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
Prefer `UIActionModalNode` 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.
localized labels do not fit. Prefer `UIModalFrameNode` for custom modal content.
Use manual
`SetUIModalCapture` only for specialized overlays that cannot use the shared modal
frame.
@@ -132,14 +162,29 @@ 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`.
The default backend order is XDG Desktop Portal, GTK, `zenity`, then `kdialog`,
then `yad`. For local diagnostics and packaging checks,
`KRYON_FILE_DIALOG_BACKEND` can be set to `auto`, `portal`, `gtk`, `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.
## Linux Desktop Metadata
Kryon owns the common Linux desktop package layout. Applications should expose
portable metadata in `project.kryon` or the matching Make variables (`APP_ID`,
`APP_TITLE`, `APP_SUMMARY`, `APP_CATEGORIES`, `APP_MIME_TYPES`,
`APP_URL_SCHEMES`, `APP_ICON`, `APP_DESKTOP_ID`, `APP_ICON_NAME`,
`APP_WM_CLASS`) and build it with `kryon package linux-desktop`. The target
stages the binary, `.desktop` entry, AppStream metainfo, hicolor icon, and
optional MIME package under one AppDir-style tree.
Application code should call `InitDesktopApp` once at startup when it needs
desktop identity, XDG config/data/cache directories, notification icon identity,
single-instance locking, or open-file/open-URL dispatch.
## Downstream Submodule Workflow
Applications should vendor Kryon as a git submodule. Do not edit
@@ -158,5 +203,7 @@ 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.
guidance for agents and maintainers. Keep `docs/BOUNDARIES.md` current with the
repo guardrails, and keep `docs/ARCHITECTURE.md` current when subsystems move.
Documentation in Kryon should describe current APIs, current behavior, and the
expected downstream workflow.
+644 -241
View File
File diff suppressed because it is too large. Load diff
+19 -8
View File
@@ -1,9 +1,13 @@
# 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.
Kryon owns the repeatable build and packaging flow for every Kryon app. App
repositories provide app metadata, native sources, `.kry` sources, and assets.
Kryon provides the compiler, runtime, dependency builds, packaging helpers,
Krait preview hooks, and diagnostics through the `kryon` command.
Kryon also owns app-neutral framework primitives that repeatedly appear in
apps: measured form rows, safe-area content rectangles, route stacks, shell
layout, platform capability names, and persisted-setting normalization.
## App Contract
@@ -23,12 +27,13 @@ should come from Kryon.
## Unified Commands
Kryon should expose one command surface for all apps:
Kryon exposes one command surface for all apps:
- `kryon build native`
- `kryon build web`
- `kryon build android-debug`
- `kryon build android-release`
- `kryon package linux-desktop`
- `kryon package linux`
- `kryon package appimage`
- `kryon package deb`
@@ -40,7 +45,7 @@ Kryon should expose one command surface for all apps:
- `kryon preview`
- `kryon test`
Makefiles in app repos should become thin wrappers that call these commands.
Makefiles in app repos are thin wrappers that call these commands.
## Build Ownership
@@ -67,19 +72,25 @@ Apps own:
- app metadata values in `project.kryon`
- optional platform-specific shims that cannot be generalized cleanly
Reusable behavior should move into Kryon only when it is app-neutral. Examples
that belong in Kryon are route-stack mechanics, form layout cursors,
safe-area-aware view measurement, capability checks, and setting clamps.
Product flows such as breathing-session behavior or password
generation stay in their app repositories.
## 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`,
3. Move repeated app Makefile logic 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
6. Make Krait 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.
+68
View File
@@ -0,0 +1,68 @@
# Kryon Architecture
Kryon is organized as a reusable runtime with a small set of public headers,
backend implementations, format/tooling paths, and conformance tests. The
runtime should expose primitives; downstream applications compose those
primitives into product behavior.
## Public API
Public headers live in `include/`. They define the app-facing Kryon surface:
window/runtime compatibility, UI widgets, platform services, formats, update,
sync, filesystem, desktop integration, and optional terminal primitives.
Public APIs should be named after the real domain concept. Do not add temporary
prefixes, compatibility aliases, or product-flavored names for new behavior.
## Runtime Implementation
Runtime code lives in `src/`. It owns widget behavior, rendering helpers,
platform adapters, serialization, sync/update primitives, and backend-specific
translation. Internal helpers should stay private to `src/` unless an unrelated
downstream application demonstrably needs the behavior.
## Backends
Backend selection is controlled by `KRYON_BACKEND`. The default native backend
uses raylib through Kryon's compatibility surface. Other backends are expected
to implement Kryon behavior through the same public/runtime contracts, with
their support documented in `docs/BACKEND_CAPABILITIES.json`,
`docs/BACKENDS.md`, and `docs/FEATURE_MATRIX.md`.
## Formats And Tools
The `.kry`, KIR, generated C, generated Go, and KRB paths are Kryon-owned
tooling surfaces. Tool changes should update the matching specs, conformance
matrix data, examples or fixtures, and generated documentation when applicable.
## Examples And Fixtures
Examples under `examples/` should remain generic and readable. They demonstrate
Kryon capabilities, not downstream product screens. Exact rendering and parity
fixtures should be generic enough that they can run in any app-independent
Kryon build.
## Tests And Matrices
Kryon uses several test layers:
- boundary and naming checks for repository hygiene
- public API snapshot checks for app-facing identifier drift
- public header compile checks for app-facing include hygiene
- examples manifest checks for example inventory and exactness fixtures
- backend capability checks for backend inventory drift
- generated-file checks for docs, compatibility headers, icons, and matrices
- parser, runtime, sync, update, platform, and widget tests
- conformance and visual matrix checks across renderers and runtime paths
Use `make preflight` before committing focused Kryon changes. Use `make test`
for the broader local regression suite. Use `make test-asan` or
`make test-ubsan` for sanitizer-backed regression runs, and
`make release-preflight` before publishing release artifacts.
## Downstream Integration
Downstream applications vendor Kryon as a submodule. Permanent Kryon changes
must be made and committed in this repository first, then brought into apps by
updating the submodule pointer. Never edit a downstream `vendor/kryon` tree as
the source of a Kryon change.
+275
View File
@@ -0,0 +1,275 @@
# Kryon Backends
How the graphics/input backend is selected, what a backend must implement, and
how to add a new one. For the machine-readable backend inventory see
`docs/BACKEND_CAPABILITIES.json`; for the operational guide see
`docs/AGENTS.md`; for the public API see `docs/API.md`; for what runs where
see `docs/FEATURE_MATRIX.md`.
## The surface and how selection works
Kryon's public graphics/input API is `include/kryon_compat.generated.h`:
kryon owns the surface, and it currently tracks raylib's header verbatim so
raylib-style code compiles unchanged. A backend is a translation unit (or set
of them) that defines the surface's functions. No `raylib.h` include and no
raylib build path may appear in `include/`, `src/`, `examples/`, or `tests/`
(`make kryon-boundary-check`).
Backend selection is link-time, via the `KRYON_BACKEND` make variable:
- `raylib` (default) - generated forwarders (`build/generated/
kryon_raylib_wrappers.c`) call into raylib, which is compiled with every
symbol renamed `KryonRaylibBackend_*` (`build/generated/
raylib_backend_rename.h`, applied in `mk/raylib.mk`). Applications can never
bind raylib symbols directly.
- `null` - generated zero-return stubs (`build/generated/kryon_null_backend.c`)
so the library links and runs headless with no GPU or window. Injected input
(below) still works, which is what drives headless widget tests.
- `canvas` - HTML5 Canvas2D backend, no raylib (`src/backend/canvas_*.c`,
split by concern: window, input, draw, texture, text, os, audio).
Web-only (native sweeps of its sources compile to empty translation
units; a native canvas link fails at symbol resolution). Implements the
required surface through `EM_JS`: draws as canvas paths (rounded rects via
`roundRect` with an `arcTo` fallback, rings as filled even-odd annulus
segments, gradients carry both full colors), textures as offscreen canvases
(`putImageData`/`drawImage` are synchronous — no async ImageBitmap on the
draw path), full RGBA tinting through cached multiply + destination-in
composites per (texture, tint), text as glyph atlases rasterized from
`FontFace` data, and input via the `KryonBackendRaw_*` hooks fed by JS
event listeners. Audio uses WebAudio for decoded sound/music buffers,
scheduled PCM streams, stream callbacks, and stream/mixed processors on
Canvas-managed stream buffers; wave export writes synchronously to MEMFS.
Encoded loaders rely on browser `decodeAudioData`, so Canvas web links use
`-sASYNCIFY`, and playback still follows normal browser user-gesture
unlock rules. The app's `while (!WindowShouldClose())` loop works
because the build uses `-sASYNCIFY` and the frame end yields with
`emscripten_sleep`. The clipboard keeps a mirror of the last written text
(copy/paste round-trips in-app; the browser write is attempted
fire-and-forget — cross-app paste stays out of reach of the sync API).
`make canvas-test` builds a full app with this backend under emcc and
verifies the draw-call sequence in node (skips when emcc is absent); `make
canvas2d-parity-check` guards the no-WebGL 2D/browser subset, and `make
web-canvas-matrix-check` captures generated-C visual fixtures through the
same backend. `docs/CANVAS2D_PARITY.md` is the Canvas2D parity ledger.
The rendering has additionally been pixel-verified in a real browser page.
- `dom` - HTML/CSS DOM backend, no raylib (`src/backend/dom_*.c`). Web-only
and intended for app-style Kryon UI and Kryon-authored page surfaces rather
than games or pixel-perfect drawing. Kryon/app logic still runs as WASM; the
backend presents UI-oriented draw calls as absolutely positioned DOM nodes
with CSS colors, gradients, borders, rounded corners, clipping, transforms,
cursor state, and browser text. Page helpers attach semantic metadata so
headings can become `h1`-`h6`, links can become `a[href]`, pictures can
carry `alt`, page/section regions can become `main`/`section`, and document
title/description/canonical/theme-color plus browser routes can be controlled
from Kryon. Browser `popstate`/`hashchange` changes increment the route
version visible through `GetRouteVersion()`. The existing Kryon UI runtime remains responsible for
hit-testing, focus, text editing, dropdowns, scrolling, selection, and widget
state. Textures uploaded from RGBA pixels are presented as DOM image nodes;
render targets and unsupported raylib areas use conservative null-grade
behavior. `make dom-test` builds a small Emscripten app and verifies DOM node
output, semantic page metadata, texture image nodes, CSS gradients, browser
route helpers, and an injected widget click in Node against a minimal DOM
shim.
- `libdraw` - plan9port libdraw/devdraw backend, no raylib
(`src/backend/libdraw_*.c`). It keeps the same public surface as the other
backends: C apps still include `kryon.h` and call `InitWindow`,
`BeginDrawing`, `DrawRectangle`, `Button`, `TextField`, and the rest of
Kryon's normal API. Internally, the backend renders through `kry_sw` into an
RGBA buffer and presents it with libdraw, so the widget catalog shares the
same software drawing behavior as the KRB hosts. TTF/TrueType-outline font
data is rasterized into Kryon `Texture2D` atlases with `stb_truetype`
(header-only; no `libraylib` link). Plan9port owns the window, event,
keyboard, mouse, resize, and devdraw connection. Non-UI raylib areas such as
3D, shaders, gestures, and audio fall back to the generated weak null stubs
until a real libdraw implementation is added for them. `make libdraw-test`
builds and runs
a widget smoke app under plan9port devdraw (Xvfb when available),
pixel-verifies rounded widgets, thick lines, source-rectangle texture blits,
alpha blending, rotated texture blits, render textures, TTF glyph atlas
coverage, and screenshot export, and compiles/links a clean-surface C app
through plan9port `9c`/`9l`.
- `termi` - terminal-cell backend, no raylib (`src/backend/termi_*.c`). It
keeps the normal Kryon surface and widget API: apps still call
`InitWindow`, `BeginDrawing`, `DrawRectangle`, `Button`, `TextField`, and
`DrawUIText`-using widgets. The backend maps Kryon's pixel layout units onto
terminal cells (`TERMI_CELL_WIDTH` x `TERMI_CELL_HEIGHT`) and renders native
terminal primitives: rectangles become colored cell regions, rectangle
outlines become terminal line cells, and UI text goes through the native text
hook to real terminal text. PNG and other stb-supported images are decoded
into Kryon textures; texture draws render as a colored-cell fallback, and
sixel image data is emitted only when the terminal advertises sixel support
or `TERMI_SIXEL=1` is set (`TERMI_SIXEL=0` disables sixel explicitly). It uses the
generated weak null stubs for unsupported raylib compatibility areas such as
shaders and 3D. Input is read from the terminal in raw mode, including arrows,
basic mouse SGR events, and Ctrl-C as an application close request. `make
termi-test` builds a widget smoke app with `KRYON_BACKEND=termi`, runs it in
a pseudo-terminal, verifies alternate screen entry/exit, rendered widget text,
sixel texture output, and confirms Ctrl-C exits.
Exactly one backend TU is compiled into `libkryon.a` (root `Makefile`), and
`KRYON_BACKEND_LIBS`/`KRYON_BACKEND_LDLIBS` carry the backend's own link
inputs (only raylib needs `libraylib.a` and its SDL/GL system libs). The
downstream fragments (`mk/common.mk`, `mk/native.mk`, `mk/web.mk`) honor the
same variable, so `make KRYON_BACKEND=null` produces binaries with no raylib
in the link graph, `make KRYON_BACKEND=dom web` builds the DOM web backend,
`make KRYON_BACKEND=termi` links a terminal backend, and
`make KRYON_BACKEND=libdraw PLAN9PORT_DIR=/path/to/plan9port` links against
plan9port instead. The
cross-build dist targets (`dist-linux`, `dist-windows`, Android, and `make
dist-static`, whose pkg-config/cmake manifests hardcode raylib) are raylib-only
today.
## The shared input front-end
Input is not the backend's job beyond polling. `src/backend/kry_input.c`
defines the public input queries (`IsKeyPressed`, `IsKeyDown`,
`IsMouseButton*`, `GetMouse*`, `GetCharPressed`, `GetKeyPressed`, ...) once for
every backend, merging, in order:
1. synthetic input injection (`kry_inject.h` - headless tests and the
synthetic file system),
2. the keyboard enable/disable switch and keyboard platform callbacks
(`SetKeyboardInputEnabled`, `SetKeyPlatformCallbacks` - non-raylib key
sources such as an IME),
3. the modal input override (`BeginKryonInputOverride`/`EndKryonInputOverride`
- offscreen windows stealing the pointer),
4. the backend's raw poll, via the `KryonBackendRaw_*` hooks declared in
`include/kry_input.h`.
A backend implements only those raw hooks; it gets injection, overrides, and
platform-key routing for free. The generated raylib wrappers forward the
hooks; the generated null backend answers them with zeros.
## Shared surface functions
Pure-math surface symbols - `Fade`, `ColorLerp`, `CheckCollisionPointRec`,
`CheckCollisionRecs`, `GetWorldToScreen2D`, `GetScreenToWorld2D`,
`GetCodepointNext` - are backend-independent arithmetic (colors, rectangles,
the Camera2D transform, UTF-8 decoding) and are defined once for every
backend in `src/backend/kry_surface_math.c`. The generator skips them in both
generated files; a new backend implements none of them. Without this the null
backend's zero-return stubs would break pointer hit-testing, since
`ui_mouse_world()` transforms the mouse position through
`GetScreenToWorld2D` before any click test.
## What a backend must implement
The full surface is ~700 symbols, but kryon's own code, the tooling, and
generated `.kry` apps call a much smaller subset. `sh
tools/backend-required-symbols.sh` prints the exact list from current call
sites (~100 symbols); keep it in sync when adding surface usage. Grouped:
- **Window/frame**: `InitWindow`, `CloseWindow`, `WindowShouldClose`,
`IsWindowReady`, `SetConfigFlags`, `SetTargetFPS`, `SetWindowSize`,
`BeginDrawing`, `EndDrawing`, `GetScreenWidth/Height`, `GetFrameTime`,
`GetTime`, `GetWindowScaleDPI`, `SetTraceLogLevel`, `SetMouseCursor`.
- **Input**: the `KryonBackendRaw_*` hooks above only.
- **Drawing (immediate mode)**: `ClearBackground`, `DrawRectangle*`,
`DrawCircle*`, `DrawLine*`, `DrawRing`, `DrawTriangle`, `DrawTexture`,
`DrawTexturePro`, `DrawText` (default font), `BeginScissorMode`/
`EndScissorMode`, `BeginMode2D`/`EndMode2D` (scene camera). Callers assume
the backend batches internally (raylib/rlgl does); a backend without
batching is correct but slow.
- **Text**: `LoadFontFromMemory` (TTF with an explicit codepoint set),
`UnloadFont`, `GetFontDefault`, `GetGlyphInfo`, `GetGlyphAtlasRec`,
`GetGlyphIndex`, `SetTextureFilter` on the atlas. Layout, fallback, and
glyph blits are kryon's (`ui_text.c`, `ui_text_backend.h`); the backend
rasterizes glyphs into an atlas texture and reports metrics. `ui_text.c`
detects a backend that silently returns the default font as load failure.
- **Textures/images**: `LoadTexture`, `LoadTextureFromImage`,
`LoadImageFromMemory`, `UnloadTexture`, `UnloadImage`,
`LoadRenderTexture`, `BeginTextureMode`/`EndTextureMode`,
`LoadImageFromTexture`, `ImageFlipVertical`, `ExportImage` (screenshot and
`kryon-preview` PNG capture path), `GetImageColor`-class pixel access where
used.
- **Math/collision helpers**: `Fade`, `ColorLerp`, `CheckCollisionPointRec`,
`CheckCollisionRecs`, `GetWorldToScreen2D`, `GetScreenToWorld2D`,
`GetCodepointNext` already come from `src/backend/kry_surface_math.c`
(above). Only `TextFormat`/`TraceLog` remain backend-supplied (the null
backend implements them; raylib forwards).
- **OS services** (may be no-ops on a given platform): `GetClipboardText`/
`SetClipboardText`, `FileExists`, `DirectoryExists`, `GetDirectoryPath`,
`MakeDirectory`, `LoadFileData/Text`, `UnloadFileData/Text`, `OpenURL`.
- **Audio** (apps opt in; null-grade stubs are acceptable for UI-only
backends): `LoadSound`/`UnloadSound`/`PlaySound`, `SetSoundVolume/Pitch/Pan`,
music stream functions, and raw `AudioStream` update/playback functions.
Everything else on the surface (gestures, VR, ...) can be a zero-return
stub exactly like the generated null backend.
### 3D tier (camera, meshes, shaders, rlgl, math3d)
The surface carries a 3D tier for custom 3D pipelines such as voxel
renderers:
- **Camera and drawing**: `Camera3D` with `UpdateCamera(CAMERA_CUSTOM)`,
`BeginMode3D`/`EndMode3D`, `DrawCube*`, and the mesh path
`UploadMesh`/`DrawMesh`/`DrawMeshInstanced`/`UnloadMesh` with the raylib
`Mesh`/`Material` layouts, `LoadMaterialDefault`,
`SetMaterialTexture`, `UnloadMaterial`.
- **Custom shaders**: `LoadShader`/`LoadShaderFromMemory`,
`GetShaderLocation`, `SetShaderValue*`, `UnloadShader`, and the
`SHADER_LOC_*` constants.
- **Curated rlgl entry points** (`kryon_compat.generated.h` ends with
them): vertex array and vertex buffer upload/bind/draw
(`rlLoadVertexArray`, `rlLoadVertexBuffer(Element)`,
`rlUpdateVertexBuffer`, `rlSetVertexAttribute`,
`rlDrawVertexArray*`, the enable/disable family), shader uniforms
(`rlSetUniform`, `rlGetLocationUniform`, `rlSetUniformMatrix`),
matrix state (`rlGet/SetMatrixModelview/Projection/Transform`), and
cull/depth toggles, plus the `RL_*` GL constants they take. `RL_CALLOC`
and `RL_FREE` are not on the surface; use `MemAlloc`/`MemFree`.
- **Math3d**: `include/kry_math3d.generated.h` (included by `kryon.h`
right after the compat surface) provides raymath-style
`Vector2/3/4`, `Matrix`, and `Quaternion` arithmetic as static-inline
functions. Pure math with no state, so every backend gets it for free;
nothing to implement or stub.
The raylib backend implements the whole tier for real (rlgl is compiled
in, `RAYLIB_MODULE_MODELS=TRUE`, symbols renamed like the rest). Every
other backend provides the generated zero-return stubs, so 3D content
simply does not appear there; UI-only apps must not depend on it. Custom
shaders must target GLSL 100 / OpenGL ES 2 - the desktop raylib backend
runs GLES2, so `#version 330` desktop shaders do not compile.
## Struct-layout obligations
The surface passes `Font`, `Texture2D`, `Image`, `GlyphInfo`,
`RenderTexture2D`, `Camera2D`, `Rectangle`, `Vector2`, `Color` by value with
raylib's layouts, and kryon state stores them directly (font caches, frame
camera, icon atlases). A backend must fill those structs with its own objects
behind them. The standard pattern is a side table keyed by the integer
`Texture2D.id`/`Font.texture.id` mapping to native handles; ids must be
non-zero for loaded resources (0 means "invalid/default"). `src/ui/
ui_text_backend.c` is the only place that reads `Font` fields directly
(baseSize, glyphPadding, texture, readiness); respect those semantics.
## Adding a backend
1. Create `src/backend/<name>_backend.c` or `src/backend/<name>_*.c`
implementing the required subset
above under the surface's public names, plus the `KryonBackendRaw_*` hooks.
Everything not implemented should match the null backend's zero-return
behavior so the library still links.
2. Register it in the root `Makefile`'s `KRYON_BACKEND` block and in
`mk/common.mk` (backend TU + link inputs), mirroring the existing entries.
3. Prove it end-to-end: `make KRYON_BACKEND=<name> check`-style build of the
library, one example app, and a headless test slice. The `.krb` cartridge
interpreter (`src/krb/krb.c`) draws through the `KryBackend` vtable
(`include/kry_backend.h`) and is a quick way to smoke-test drawing without
the full UI stack.
4. Do not patch vendor code or add `#ifdef <backend>` branches to `src/`;
backend differences live behind the surface, `kry_input.h`, and
`kry_backend.h`.
## Checks
- `make kryon-boundary-check` - no `raylib.h` includes or raylib paths in
app-facing code.
- `make kryon-compat-check` - generated surface/rename/wrappers are in sync
with `vendor/raylib/src/raylib.h` and every raylib symbol has a rename plus
a public wrapper or `KryonBackendRaw_*` hook.
- `make libdraw-test` - plan9port/devdraw smoke for the libdraw surface backend
plus a `9c`/`9l` clean-public-surface compile/link check.
- `sh tools/backend-required-symbols.sh` - the live required-subset list a
backend must cover.
+60
View File
@@ -0,0 +1,60 @@
{
"schema": 1,
"source": "docs/BACKEND_CAPABILITIES.json",
"backends": [
{
"id": "raylib",
"label": "Desktop raylib",
"tier": "default",
"platforms": ["Linux", "FreeBSD", "macOS", "Windows"],
"surface": "full raylib compatibility through Kryon wrapper symbols, including the 3D tier (camera, meshes, custom shaders, curated rlgl entry points) and the static-inline math3d surface",
"status": "default",
"checks": ["make kryon-compat-check", "make raylib-matrix-check", "build/linux-x86_64/tests/raylib_compat_test"]
},
{
"id": "null",
"label": "Null headless",
"tier": "headless",
"platforms": ["hosted C"],
"surface": "generated zero-return stubs plus Kryon input injection",
"status": "test backend",
"checks": ["make KRYON_BACKEND=null all"]
},
{
"id": "canvas",
"label": "Web Canvas2D",
"tier": "web",
"platforms": ["Emscripten web"],
"surface": "Canvas2D and WebAudio implementation with null stubs for unsupported surface areas",
"status": "source-capture gated",
"checks": ["make canvas-test", "make canvas2d-parity-check", "make web-canvas-matrix-check"]
},
{
"id": "dom",
"label": "Web DOM",
"tier": "dom-page",
"platforms": ["Emscripten web"],
"surface": "HTML/CSS DOM UI presentation with semantic page metadata, native heading/link/image annotations, CSS gradients, RGBA image-node textures, browser route helpers with route-change versioning, and null stubs for unsupported surface areas",
"status": "smoke gated",
"checks": ["make dom-test"]
},
{
"id": "libdraw",
"label": "Plan 9 libdraw",
"tier": "desktop",
"platforms": ["plan9port/devdraw"],
"surface": "kry_sw software renderer presented through libdraw",
"status": "source-capture gated",
"checks": ["make libdraw-test", "make libdraw-matrix-check"]
},
{
"id": "termi",
"label": "Terminal cells",
"tier": "terminal",
"platforms": ["ANSI terminal"],
"surface": "terminal-cell drawing, raw terminal input, and null stubs for unsupported surface areas",
"status": "smoke gated",
"checks": ["make termi-test"]
}
]
}
+56
View File
@@ -0,0 +1,56 @@
# Kryon Boundaries
Kryon is a reusable UI runtime. It may contain generic runtime primitives,
generic examples, generic test fixtures, and documentation for integrating the
runtime into downstream applications. It must not contain product behavior,
branding, copy, assets, or fixtures from a downstream application.
## Belongs In Kryon
- reusable widgets, layout, text input, focus, theme, DPI, modal, scroll, and
input-capture behavior
- reusable renderer, backend, format, preview, packaging, update, sync, and
desktop primitives
- generic examples that demonstrate one Kryon feature at a time
- generic tests and fixtures that assert Kryon behavior across backends
- documentation for Kryon APIs, formats, backends, and downstream update flow
## Belongs In Applications
- product screens, routes, onboarding, workflows, and state machines
- product names, screenshots, icons, store metadata, app IDs, and domains
- app-specific copy, locale keys, settings semantics, and persistence policy
- business rules for sessions, habits, documents, projects, accounts, or other
product concepts
- downstream integration code that only one application needs
## Forbidden Downstream Terms
`make kryon-boundary-check` rejects known downstream product material. The hard
forbidden list lives in `tools/check-kryon-boundaries.sh`, which is excluded
from its own content scan so the banned terms do not appear elsewhere in this
repository. When another downstream product leaks into Kryon, remove the
material from Kryon and add that product term to the checker in the same
change.
## Runtime Primitive Test
Before adding a public API or example, ask whether another unrelated
application could use it without inheriting product assumptions. If the answer
is no, keep it in the downstream app. If the answer is yes, name it after the
domain concept directly and cover it with Kryon-owned tests.
## Generated And Showcase Material
Generated files should describe their generator and source inputs. Do not hand
edit generated outputs except to repair or replace the generator in the same
change.
Showcase material may reference external users of Kryon only when it is clearly
documentation about adoption, not an input fixture, public API example, or
runtime asset. Product examples used for rendering, parity, screenshots, or
coverage belong in the product repository.
Keep `examples/manifest.json` current when adding, removing, or renaming
examples. The manifest is the stable inventory for example metadata and curated
render-exact fixtures.
+55
View File
@@ -0,0 +1,55 @@
# Canvas2D Raylib Parity
Kryon's `canvas` backend is the no-WebGL web backend. It aims to run
raylib-style 2D/UI applications with the same public surface while leaving
non-2D raylib areas on generated weak null stubs.
The live required surface comes from:
```sh
sh tools/backend-required-symbols.sh
```
The no-WebGL 2D/browser subset is guarded by:
```sh
make canvas2d-parity-check
```
## Status Model
| Status | Meaning |
|---|---|
| `implemented` | Canvas2D has a real backend implementation. |
| `partial` | Implemented, but browser limits or known gaps remain. |
| `stub` | Provided by the generated weak null backend only. |
| `untested` | Implemented but not covered by `make canvas-test` yet. |
## 2D/UI Surface
| Area | Status | Notes |
|---|---|---|
| Window/frame lifecycle | `implemented` | `InitWindow`, frame timing, logical screen size, render size, title, cursor, and basic state flags. |
| HiDPI sizing | `implemented` | Main canvas uses logical coordinates over a `devicePixelRatio` backing store; render size reports backing pixels. |
| Keyboard/mouse/wheel | `implemented` | Includes key repeat, mouse buttons, pointer capture, mouse delta, and fractional wheel vectors. |
| Touch | `implemented` | Browser touch points map to raylib touch APIs and update mouse position from touch point 0. |
| Gamepad | `partial` | Standard browser Gamepad API buttons/axes are mapped; SDL mapping strings and vibration are no-ops. |
| Dropped files | `partial` | Browser drop events queue file paths and asynchronously write file contents into MEMFS. |
| Basic shapes | `implemented` | Pixels, lines, rectangles, rounded rectangles, circles, rings, triangles, fans, strips, and outlines. |
| Gradients | `implemented` | Vertical, horizontal, and four-corner rectangle gradients. |
| 2D camera/scissor | `implemented` | `BeginMode2D` and active scissor clipping use Canvas transforms/clips. |
| Textures | `implemented` | RGBA textures, render textures, tinting, alpha, rotation/origin, source rectangles, and negative-size flips. |
| Images/screenshots | `partial` | RGBA image load/export/screenshot and format validity are implemented; non-PNG decoders stay limited. |
| Fonts/text | `implemented` | FontFace-backed TTF loading, glyph atlas metrics, custom text drawing, codepoint drawing, and measurement. |
| Files/path helpers | `implemented` | MEMFS-backed load/save/path helpers and directory listing. |
| Clipboard | `partial` | Writes mirror locally and attempt browser clipboard writes; synchronous browser clipboard reads are unavailable. |
| Audio | `partial` | WebAudio sound/music/streams exist, with normal browser user-gesture unlock limits. |
## Explicit Non-Goals
| Area | Status | Notes |
|---|---|---|
| 3D cameras/models/meshes | `stub` | Requires WebGL or another renderer to match raylib. |
| Shaders/rlgl/render batches | `stub` | Canvas2D cannot faithfully expose shader or rlgl behavior. |
| VR/stereo rendering | `stub` | Out of scope for the no-WebGL backend. |
| Gesture recognizer | `stub` | Raw touch points are implemented; raylib gesture synthesis is still fallback. |
+256
View File
@@ -0,0 +1,256 @@
<!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>What every widget and feature supports, per compile target and per renderer backend. For how backends are selected and implemented see <code>docs/BACKENDS.md</code>; for the cartridge binary format see <code>docs/KRB_FORMAT.md</code>; for the language see <code>docs/KRY_LANGUAGE_SPEC.md</code>. Keep this file current with the code, and regenerate the browsable view after every change: <code>python3 scripts/feature-matrix-html.py</code> writes <code>docs/FEATURE_MATRIX.html</code>.</p>
<p>Legend: ✅ available · ◐ partial (reason given) · ✗ not available · — not applicable. <b>C</b> is the <code>libkryon.a</code> C API; <b>k2c</b> is what <code>.kry</code> reaches through the C compiler — always equal to C, because the language is C-close and every library call is a legal statement (the widget-statement whitelist below only adds sugar). The other compilers lower subsets, which is where the columns diverge.</p>
<h2>The pipeline</h2>
<pre>.kry source
│ shared frontend: cmd/kir/kir_parse.c -&gt; KirProgram
├── k2c -&gt; .c/.h + kryon_project.c/.h -&gt; cc + libkryon.a -&gt; native C app
├── k2cpp -&gt; .cpp/.hpp + kryon_project.c/.h (extern &quot;C&quot; decls; same lowering as k2c)
├── k2go -&gt; .go (kryon.&lt;Widget&gt; calls) -&gt; go build + go/kryon -&gt; Go app
├── k2js -&gt; .js (web runtime calls) -&gt; browser/Node ESM -&gt; Web app
├── k2b -&gt; .krb (+ .krb.c/.krb host) -&gt; KrbLoad/KrbExec on any KryBackend
└── k2kir -&gt; .kir (text IR dump; debugging, tests, Krait)</pre>
<table>
<tr><th>Target</th><th>Producer</th><th>Runtime</th><th>Status</th></tr>
<tr><td class="">C</td><td class=""><code>k2c</code></td><td class=""><code>cc</code> + <code>libkryon.a</code> (raylib/null/canvas/libdraw surface backend)</td><td class="">Most complete path; production use</td></tr>
<tr><td class="">C++</td><td class=""><code>k2cpp</code></td><td class=""><code>c++</code> + <code>libkryon.a</code>; C++ codegen with C linkage, same lowering as <code>k2c</code></td><td class="">Parity port of the <code>k2c</code> backend</td></tr>
<tr><td class="">Go</td><td class=""><code>k2go</code></td><td class=""><code>go/kryon</code> native Go package, no cgo</td><td class="">Declarative subset; executable CI gate</td></tr>
<tr><td class="">JS/Web</td><td class=""><code>k2js</code></td><td class=""><code>web/kryon-runtime.js</code> ESM recorder/presenter</td><td class="">Syntax, Node recorder snapshots, and generated runtime state parity gated</td></tr>
<tr><td class="">KRB cartridge</td><td class=""><code>k2b</code></td><td class=""><code>src/krb/krb.c</code> via the <code>KryBackend</code> vtable</td><td class="">Format v2; byte-exact across engines; CI-gated</td></tr>
<tr><td class="">KIR</td><td class=""><code>k2kir</code></td><td class="">— (inspection artifact)</td><td class="">Debugging/tooling only</td></tr>
</table>
<p>Two backend tiers exist (see <code>docs/BACKENDS.md</code>):</p>
<ul>
<li><b>Tier A — surface backends</b>: implement the ~700-symbol raylib-compatible</li>
</ul>
<p>surface (<code>include/kryon_compat.generated.h</code>), selected at <b>link</b> time via <code>KRYON_BACKEND=raylib|null|canvas|libdraw</code>. The whole widget catalog runs on these.</p>
<ul>
<li><b>Tier B — cartridge hosts</b>: implement the ~20-function <code>KryBackend</code> vtable</li>
</ul>
<p>(<code>include/kry_backend.h</code>), selected at <b>runtime</b>. Only the KRB widget subset runs on these.</p>
<h2>Widget statement whitelist (<code>.kry</code> frontend)</h2>
<p><code>parse_widget_statement</code> (<code>cmd/kir/kir_parse.c</code>) recognizes 51 widget names. <code>k2c</code> compiles any library call regardless (plain call statement); <code>k2cpp</code> shares that lowering (C++ output, C linkage); <code>k2go</code> lowers the full whitelist onto its <code>Runtime</code> interface (except <code>Canvas</code>, below); <code>k2js</code> records whitelisted standalone widget calls as browser-loadable runtime operations; and <code>k2b</code> lowers a subset of it:</p>
<p>`Background Text TextInRect Paragraph TextLines Rect Line Bevel IconTexture Picture Button IconButton Href TextField TextArea Dropdown Slider Toggle Checkbox Radio Progress Spinbox Combobox Screen Column Row Stack End Scroll Canvas Modal ActionModal MessageDialog ConfirmDialog PromptDialog TitleBar TabBar BottomNav TopNav Toolbar ShowToast ShowToastFor LabelFrame Notebook PanedView Collapsible ListBox SourceView TableView CanvasGrid SelectableText`</p>
<p>(<code>Canvas</code> is whitelisted but no <code>Canvas(...)</code> widget exists — examples call <code>BeginCanvas</code> directly. Scroll coverage uses the C <code>BeginUIScrollContainer</code> / <code>EndUIScrollContainer</code> API.)</p>
<h2>Widget matrix</h2>
<p>Columns: <b>C</b> = the C API · <b>k2c</b> = <code>.kry</code>→C codegen (always equal to C) · <b>k2cpp</b> = <code>.kry</code>→C++ codegen (mirrors <code>k2c</code>) · <b>k2go</b> = <code>.kry</code>→Go codegen (pure Go importing <code>go/kryon</code> as <code>kryon</code> and calling <code>kryon.&lt;Widget&gt;</code>) · <b>Go</b> = hand-written Go via the <code>go/kryon</code> package API · <b>KRB</b> = lowered into a cartridge by <code>k2b</code>.</p>
<p>Retained-tree caveat that applies to the whole C column: <code>#ui</code> lowering records ~29 widget kinds, but the retained painter covers only BACKGROUND, TEXT, RECT, LINE, BUTTON, TEXT_FIELD, TEXT_AREA, and routes retained input for BUTTON, TEXT_FIELD, and TEXT_AREA; every other kind renders through its immediate-mode call during the declaration pass (<code>src/ui/ui_tree.c</code>).</p>
<h3>UI/Display</h3>
<table>
<tr><th>Widget</th><th>C</th><th>k2c</th><th>k2cpp</th><th>k2go</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">Background</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Background</code></td><td class="ok">✅ node</td></tr>
<tr><td class="">Text</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Text</code></td><td class="ok">✅ node</td></tr>
<tr><td class="">TextInRect</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>TextInRect</code></td><td class="ok">✅</td></tr>
<tr><td class="">Paragraph (rich text + inline icons)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Paragraph</code></td><td class="no">✗</td></tr>
<tr><td class="">TextLines</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>TextLines</code></td><td class="no">✗</td></tr>
<tr><td class="">Rect</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ (+ <code>RectGradientH</code>)</td><td class="part">◐ <code>DrawRectangle*</code> primitives</td><td class="ok">✅ node</td></tr>
<tr><td class="">Line</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>DrawLine</code></td><td class="ok">✅</td></tr>
<tr><td class="">Bevel</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Bevel</code></td><td class="ok">✅</td></tr>
<tr><td class="">IconTexture (114 embedded icons)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ (by icon type)</td><td class="ok">✅ <code>IconTexture</code></td><td class="no">✗</td></tr>
<tr><td class="">Image/Picture</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>kryon.Picture(kryon.PictureProps)</code></td><td class="ok">✅ <code>kryon.Picture</code></td><td class="ok">✅ node (embedded asset or PNG)</td></tr>
</table>
<h3>UI/Input</h3>
<table>
<tr><th>Widget</th><th>C</th><th>k2c</th><th>k2cpp</th><th>k2go</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">Button (ButtonProps)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>kryon.Button(kryon.ButtonProps)</code> / <code>kryon.Button(&quot;Save&quot;)</code></td><td class="ok">✅ node</td></tr>
<tr><td class="">Legacy positional buttons</td><td class="ok">✅ low-level only</td><td class="ok">✅ only for existing C callers</td><td class="ok">✅ only for existing C callers</td><td class="no">✗ use <code>kryon.Button(kryon.ButtonProps)</code></td><td class="no">✗ generated Go uses <code>kryon.Button</code></td><td class="part">◐ BUTTON style byte</td></tr>
<tr><td class="">IconButton / PaddedIconBtn</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="part">◐ <code>IconButton</code> only</td><td class="part">◐ <code>IconButton</code> only</td><td class="no">✗</td></tr>
<tr><td class="">InfoButton</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Href (hyperlink) / IconLink</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="part">◐ <code>Href</code> only</td><td class="part">◐ <code>Href</code> only</td><td class="no">✗</td></tr>
<tr><td class="">TextField</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>kryon.TextField(kryon.TextFieldProps)</code> / <code>kryon.TextField(&quot;Name&quot;, &amp;value)</code></td><td class="ok">✅ TEXTINPUT node</td></tr>
<tr><td class="">Read-only text</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ via <code>Text</code>/<code>TextInRect</code></td><td class="ok">✅ <code>Text</code>/<code>TextInRect</code></td><td class="no">✗</td></tr>
<tr><td class="">TextArea (selection, syntax highlight)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>NewTextArea</code>/<code>TextArea</code></td><td class="no">✗</td></tr>
<tr><td class="">Dropdown / DropdownEx</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Dropdown</code> (Ex needs rich option arrays)</td><td class="ok">✅ <code>Dropdown(Ex)</code></td><td class="ok">✅ DROPDOWN control</td></tr>
<tr><td class="">Slider</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Slider</code>/<code>Slider</code></td><td class="ok">✅ SLIDER control</td></tr>
<tr><td class="">Vertical sliders</td><td class="ok">✅ low-level only</td><td class="ok">✅ only for existing C callers</td><td class="ok">✅ only for existing C callers</td><td class="no">✗ use <code>kryon.Slider</code> in generated Go</td><td class="no">✗ generated Go uses <code>kryon.Slider</code></td><td class="ok">✅ VSLIDER control</td></tr>
<tr><td class="">Toggle (switch)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Toggle</code></td><td class="ok">✅ node</td></tr>
<tr><td class="">Checkbox (+ disabled)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Checkbox</code></td><td class="ok">✅ node</td></tr>
<tr><td class="">Radio</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Radio</code></td><td class="ok">✅ <code>KRB_CTRL_RADIO</code></td></tr>
<tr><td class="">Progress</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Progress</code></td><td class="ok">✅ <code>KRB_CTRL_PROGRESS</code></td></tr>
<tr><td class="">Spinbox</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Spinbox</code></td><td class="ok">✅ SPINBOX control</td></tr>
<tr><td class="">Combobox</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Combobox</code></td><td class="ok">✅ COMBOBOX control (renders like the dropdown, mirroring the C widget)</td></tr>
<tr><td class="">ColorPicker (RGB sliders)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
</table>
<h3>UI/Layout</h3>
<table>
<tr><th>Widget</th><th>C</th><th>k2c</th><th>k2cpp</th><th>k2go</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">Column / Row / Stack (flex-like)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ all three</td><td class="ok">✅ all three</td><td class="ok">✅ structural no-ops (node table is the tree)</td></tr>
<tr><td class="">Group</td><td class="ok">✅ (lowers to Stack)</td><td class="ok">✅</td><td class="ok">✅</td><td class="part">◐ via Column</td><td class="ok">✅ via Stack</td><td class="ok">✅</td></tr>
<tr><td class="">Scroll container</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>BeginUIScrollContainer</code>/<code>EndUIScrollContainer</code></td><td class="ok">✅ <code>BeginUIScrollContainer</code>/<code>EndUIScrollContainer</code></td><td class="ok">✅ SCROLL node</td></tr>
<tr><td class="">Separator</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="ok">✅</td></tr>
<tr><td class="">LabelFrame</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>LabelFrame</code></td><td class="ok">✅ rect/text lowering</td></tr>
<tr><td class="">Notebook (tabs)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Notebook</code></td><td class="no">✗</td></tr>
<tr><td class="">PanedView (splitter)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>PanedView</code></td><td class="no">✗</td></tr>
<tr><td class="">Collapsible</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Collapsible</code></td><td class="no">✗</td></tr>
<tr><td class="">Tk pack/grid helpers (<code>FramePack</code>, <code>GridCell</code>, <code>Place</code>)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">UIForm cursor (<code>UIForm*</code>)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Canvas (pan/zoom, hit-test, grid)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Begin/EndCanvas</code></td><td class="ok">✅ <code>Begin/EndCanvas</code>+hit-test</td><td class="no">✗</td></tr>
</table>
<h3>UI/Collections</h3>
<table>
<tr><th>Widget</th><th>C</th><th>k2c</th><th>k2cpp</th><th>k2go</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">ListBox</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>ListBox</code></td><td class="no">✗</td></tr>
<tr><td class="">TreeView / CascadingTreeView</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">SourceView (code + line numbers)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>SourceView</code></td><td class="no">✗</td></tr>
<tr><td class="">TableView (sortable)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>TableView</code></td><td class="no">✗</td></tr>
<tr><td class="">CanvasGrid</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>CanvasGrid</code></td><td class="no">✗</td></tr>
<tr><td class="">SelectableText</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>SelectableText</code></td><td class="no">✗</td></tr>
</table>
<h3>UI/Navigation</h3>
<table>
<tr><th>Widget</th><th>C</th><th>k2c</th><th>k2cpp</th><th>k2go</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">MenuBar / PopupMenu / ContextMenu</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">TabBar</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>TabBar</code></td><td class="no">✗</td></tr>
<tr><td class="">SubtabBar / PaneTabBar (dock zones)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">BottomNav (+ config modal)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>BottomNav</code></td><td class="part">◐ <code>NavButton</code> lowers to a BUTTON</td></tr>
<tr><td class="">TopNav / Toolbar / ToolbarHeader</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="part">◐ <code>TopNav</code>/<code>Toolbar</code> only</td><td class="ok">✅ <code>TopNav</code>/<code>Toolbar</code></td><td class="no">✗</td></tr>
<tr><td class="">TitleBar family</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="part">◐ <code>TitleBar</code> only</td><td class="ok">✅ <code>TitleBar</code></td><td class="no">✗</td></tr>
</table>
<h3>UI/Overlays</h3>
<table>
<tr><th>Widget</th><th>C</th><th>k2c</th><th>k2cpp</th><th>k2go</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">ActionModal / Modal / Modal3Button / ModalFrame</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="part">◐ <code>Modal</code> only</td><td class="part">◐ <code>Modal</code> only</td><td class="no">✗</td></tr>
<tr><td class="">MessageDialog / ConfirmDialog / PromptDialog</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">Toast</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>ShowToast(For)</code></td><td class="ok">✅ <code>ShowToast(For)</code></td><td class="no">✗</td></tr>
<tr><td class="">GuideOverlay / TutorialImage(Placeholder)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">TransitionFade / Focus ring</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="part">◐ <code>AnimNode</code> + <code>TIME</code> opcode drive animation</td></tr>
<tr><td class="">ThemeSettings / ThemeSwitcher / ThemePicker</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="part">◐ theme-control methods only</td><td class="part">◐ <code>SetCurrentTheme</code>/<code>SetThemeStyle</code> (control only)</td><td class="no">✗</td></tr>
<tr><td class="">FocusDebugOverlay</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">InfoRows / OverlayButton / IconSliderPopup</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
</table>
<h3>UI/Composite And App Framework</h3>
<table>
<tr><th>Widget</th><th>C</th><th>k2c</th><th>k2cpp</th><th>k2go</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">LabelTextField / SectionLabel</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">CheckboxRow / SpinboxRow / ButtonRow / BottomIconRow</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">BottomNavConfig</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">SidebarAccountHeader / ProfilePicturePicker</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Reorder (drag handle + placeholder)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">ImageBox</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Route stack / shell measurement</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Capabilities / safe content rect</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Setting normalization helpers</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
</table>
<h3>Game2D (scene tree, <code>src/scene/</code>)</h3>
<table>
<tr><th>Node</th><th>C</th><th>✅</th><th>✅</th><th>k2go</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">Scene / Node2D / Camera2D</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Sprite2D / AnimatedSprite2D / TileMap / TileLayer / Light2D</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">CollisionShape2D / Area2D / Body2D (box2d)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Timer / AudioSource / AnimationPlayer</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Signals (<code>KrySignal</code>) / keyframe animation</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
</table>
<h3>KRB cartridge vocabulary (no C widget equivalent)</h3>
<table>
<tr><th>Item</th><th>Notes</th></tr>
<tr><td class="">DATA node</td><td class="">state-field mount read/written by bytecode</td></tr>
<tr><td class="">CIRCLE / RING nodes</td><td class="">lowered from <code>DrawCircleV</code> / <code>DrawRing</code> calls</td></tr>
<tr><td class=""><code>NavButton</code></td><td class=""><code>k2b</code>-only lowering; becomes a BUTTON with <code>KRB_FLAG_NAV</code></td></tr>
<tr><td class=""><code>AnimNode</code></td><td class=""><code>k2b</code>-only; animated node driven by <code>TIME</code></td></tr>
<tr><td class="">v2 logic bytecode</td><td class="">stack machine, node mutation, if-guards over node ranges</td></tr>
<tr><td class="">Host capabilities</td><td class="">imported storage/http/audio/notify calls (<code>krb_caps.c</code>)</td></tr>
</table>
<h2>Cross-cutting features</h2>
<table>
<tr><th>Feature</th><th>C</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">Theming</td><td class="ok">✅ 6 palettes × light/dark INI, scopes, vars, runtime loader</td><td class="ok">✅ <code>SetCurrentTheme</code>/<code>SetThemeDarkMode</code>/<code>GetTheme*</code></td><td class="part">◐ theme color slots (<code>KrySwSetTheme</code>); light/dark env knobs on hosts</td></tr>
<tr><td class="">Style tokens</td><td class="ok">✅ radius/border/shadow/bevel; RETRO, MATERIAL, SYSTEM styles</td><td class="ok">✅ <code>Get/SetUIStyleTokens</code></td><td class="no">✗</td></tr>
<tr><td class="">Animation</td><td class="ok">✅ transitions (smoothstep), ripple, keyframe scene anims</td><td class="no">✗</td><td class="part">◐ <code>AnimNode</code> + <code>TIME</code> opcode</td></tr>
<tr><td class="">Text/fonts</td><td class="ok">✅ multi-font registry, per-codepoint fallback, italic synthesis, wrap, selectable text; no shaping/bidi/IME</td><td class="ok">✅ <code>RegisterUIFont(Data)</code>, <code>Push/Pop/UseUIFont</code>, input queue</td><td class="part">◐ font8x8 default, or pre-baked KFA1 glyph atlas; no TTF rasterization</td></tr>
<tr><td class="">DPI/scaling</td><td class="ok">✅ viewport-derived scale, <code>ScaleUIPx</code></td><td class="ok">✅ <code>ScaleUIPx</code>, <code>GetWindowScaleDPI</code></td><td class="part">◐ per-mille UI scale (<code>KRB_RUN_UI_SCALE</code>)</td></tr>
<tr><td class="">Clipping</td><td class="ok">✅ 16-deep scissor stack + input clip stack</td><td class="ok">✅ <code>Begin/EndScissorMode</code></td><td class="ok">✅ 16-deep <code>clip_push/pop</code> in <code>kry_sw</code></td></tr>
<tr><td class="">Z-order/popups</td><td class="ok">✅ overlay paint pass, modal capture, input-capture stack</td><td class="part">◐ dropdown popups internal to <code>Dropdown</code></td><td class="part">◐ dropdown menus handled by the engine</td></tr>
<tr><td class="">Input</td><td class="ok">✅ unified front-end, pointer gestures/ownership, keyboard focus + Tab + accelerators, clipboard; no IME, no gamepad nav</td><td class="ok">✅ native host key/mouse/text queues</td><td class="part">◐ vtable: mouse, press, wheel, text-key queue</td></tr>
<tr><td class="">Accessibility</td><td class="part">◐ debug focus overlay + a11y node structs; no screen-reader bridge</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">i18n</td><td class="ok">✅ locale strings + CJK font switching; no RTL</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Multi-window</td><td class="ok">✅ <code>OpenUIWindow</code> (X11 dlopen / SDL)</td><td class="no">✗</td><td class="na">— single framebuffer</td></tr>
<tr><td class="">3D rendering</td><td class="ok">✅ camera + mesh/shader tier incl. curated rlgl entry points and raymath-style math3d (GLSL 100); raylib backend implements it, others stub it</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">State/data binding</td><td class="ok">✅ retained event queue; scene signals</td><td class="ok">✅ <code>#ui</code> functions + retained events</td><td class="ok">✅ field mounts (<code>KrbMount*</code>) + bytecode</td></tr>
<tr><td class="">Dialogs/platform</td><td class="ok">✅ file dialogs (web/portal/gtk/zenity/kdialog/yad), XDG paths, desktop metadata packaging, single-instance lock, tray, notifications (Android/web/Linux)</td><td class="ok">✅ tray + notify polling</td><td class="part">◐ host capability imports (storage/http/audio/notify)</td></tr>
<tr><td class="">Debug tooling</td><td class="ok">✅ widget inspector, node registry + snippets</td><td class="no">✗</td><td class="part">◐ <code>KryBackendRec</code> call-stream recording</td></tr>
</table>
<h2>Renderer backends</h2>
<h3>Tier A — surface backends (link-time, <code>KRYON_BACKEND</code>)</h3>
<table>
<tr><th>Backend</th><th>Graphics API</th><th>Platforms</th><th>CI</th><th>Notes</th></tr>
<tr><td class=""><code>raylib</code> (default)</td><td class="">OpenGL ES 2.0 over SDL2</td><td class="">Linux, FreeBSD</td><td class="ok">✅ <code>ci.yml</code> (Linux + FreeBSD)</td><td class="">Default everywhere; dist/static SDK targets; implements the full 3D tier (camera/mesh/shader + rlgl entry points)</td></tr>
<tr><td class=""><code>raylib</code> web</td><td class="">WebGL (ES2) over GLFW3</td><td class="">Emscripten</td><td class="ok">✅ web/app builds</td><td class=""><code>mk/web.mk</code>; present shim for WebKitGTK</td></tr>
<tr><td class=""><code>raylib</code> windows <code>opengl</code></td><td class="">OpenGL 2.1</td><td class="">Windows (mingw)</td><td class="ok">✅ release builds</td><td class="">Default Windows flavor</td></tr>
<tr><td class=""><code>raylib</code> windows <code>rlsw</code></td><td class="">raylib software renderer (no GPU)</td><td class="">Windows</td><td class="ok">✅ release builds</td><td class=""><code>WINDOWS_RENDERERS</code> second flavor</td></tr>
<tr><td class=""><code>raylib</code> windows RGFW rule</td><td class="">GL 1.1 immediate mode</td><td class="">Windows</td><td class="no">✗ opt-in make rule</td><td class=""><code>KRYON_RAYLIB_WINDOWS_RULE</code></td></tr>
<tr><td class=""><code>raylib</code> android</td><td class="">GLES via NDK <code>NativeActivity</code></td><td class="">Android (downstream Gradle)</td><td class="no">✗ downstream apps</td><td class=""><code>mk/android.mk</code></td></tr>
<tr><td class=""><code>null</code></td><td class="">none (zero-return stubs)</td><td class="">all</td><td class="no">✗ (used by local headless tests)</td><td class="">Injected input still works</td></tr>
<tr><td class=""><code>canvas</code></td><td class="">HTML5 Canvas2D via <code>EM_JS</code> (ASYNCIFY loop)</td><td class="">Emscripten</td><td class="ok">✅ <code>make canvas-test</code>, <code>make canvas2d-parity-check</code>, <code>make web-canvas-matrix-check</code></td><td class="">No raylib/WebGL; HiDPI Canvas2D, 2D raylib aliases, touch/gamepad/drop-file hooks, glyph atlases, textures/render textures/tinting, WebAudio, and weak stubs for non-2D raylib areas</td></tr>
<tr><td class=""><code>libdraw</code></td><td class=""><code>kry_sw</code> RGBA8 presented through plan9port libdraw/devdraw</td><td class="">plan9port on Unix/X11</td><td class="ok">✅ <code>make libdraw-test</code> (devdraw smoke + <code>9c</code>/<code>9l</code> clean-surface check)</td><td class="">No libraylib; widgets/drawing/screenshots through software backend; TTF/TrueType-outline glyph atlases via <code>stb_truetype</code>; rounded controls, alpha/tint texture blits, rotation, render textures, plan9port input/resize; non-UI raylib areas use weak null stubs</td></tr>
</table>
<h3>Tier B — cartridge hosts (<code>KryBackend</code> vtable, runtime selection)</h3>
<table>
<tr><th>Host</th><th>Rendering</th><th>Input</th><th>Textures</th><th>Text</th><th>CI</th><th>Notes</th></tr>
<tr><td class=""><code>KryBackendDraw</code></td><td class="">raylib surface</td><td class="">raylib</td><td class="ok">✅</td><td class="">full font stack</td><td class="ok">✅</td><td class="">Auto-installed via constructor; hooks cartridge audio; runs inside raylib apps and <code>kryon-preview</code></td></tr>
<tr><td class=""><code>kry_sw</code></td><td class="">software RGBA8 rasterizer</td><td class="">injected (<code>KrySwMouse</code> etc.)</td><td class="ok">✅ + PNG decode</td><td class="">font8x8 or KFA1 atlas</td><td class="ok">✅</td><td class="">No GPU/libc deps; <code>KrySwToRGB565</code> for embedded panels; one-shot dirty-rect tracking</td></tr>
<tr><td class=""><code>krb-run</code></td><td class=""><code>kry_sw</code> headless</td><td class="">injected</td><td class="ok">✅</td><td class="">via <code>kry_sw</code></td><td class="ok">✅ linux/windows/macos</td><td class="">PNG dump + <code>KryBackendRec</code> call log; conformance host</td></tr>
<tr><td class=""><code>krb-sdl</code></td><td class=""><code>kry_sw</code> → SDL2 streaming texture</td><td class="">SDL2</td><td class="ok">✅</td><td class="">via <code>kry_sw</code></td><td class="ok">✅</td><td class="">Template for the planned Android EGL host</td></tr>
<tr><td class=""><code>krb-web</code></td><td class=""><code>kry_sw</code> → wasm, Canvas2D <code>putImageData</code></td><td class="">JS bridge exports</td><td class="ok">✅</td><td class="">via <code>kry_sw</code></td><td class="ok">✅ renderers.yml</td><td class="">Byte-identical to native; node-capture for tests</td></tr>
<tr><td class=""><code>KryBackendRec</code></td><td class="">wraps any backend</td><td class="">passthrough</td><td class="">passthrough</td><td class="">passthrough</td><td class="ok">✅ exactness job</td><td class="">Records the vtable call stream for cross-engine comparison</td></tr>
<tr><td class=""><code>KryBackendNull</code></td><td class="">stub vtable</td><td class="">none</td><td class="no">✗ (<code>texture_rgba</code> NULL)</td><td class="no">✗</td><td class="ok">✅ logic tests</td><td class="">Default until <code>KryBackendSelect</code></td></tr>
</table>
<h2>Known gaps</h2>
<ul>
<li>The <code>canvas</code> Tier A backend passes its node call-sequence gate and has</li>
</ul>
<p>been pixel-verified in a real browser page (rounded rects, annulus ring segments, dual-color gradients, and full RGBA texture tinting all check out). Remaining limits: cross-app clipboard paste is unreachable through the synchronous API (an in-app mirror handles round-trips), WebAudio playback depends on browser user-gesture unlock rules, and stream/mixed processors apply to Canvas-managed stream buffers, not decoded browser <code>AudioBuffer</code> playback that has already been handed to WebAudio.</p>
<ul>
<li>The <code>libdraw</code> Tier A backend passes the plan9port devdraw widget smoke and a</li>
</ul>
<p><code>9c</code>/<code>9l</code> clean-surface compile/link check. It is intended for C UI apps: windowing, input, resize, software drawing, widgets, rounded controls, thick lines, image loading, alpha/tint and source-rectangle texture blits, picture rotation, render textures, TTF/TrueType-outline glyph-atlas text, screenshots, files, and clipboard mirror are covered. Advanced raylib areas outside UI apps (3D, shaders, gestures, audio) are null-grade fallback.</p>
<ul>
<li><code>k2go</code> targets native Go: the <code>Runtime</code> interface covers the widget</li>
</ul>
<p>whitelist plus the generated-code widget families in <code>go/kryon</code> (controls, Props widgets, dialogs, canvas, Tk layout helpers, toasts, theme control), with <code>.kry</code> array declarations lowering to Go slices at the use site. Remaining boundaries: a forward <code>goto</code> over declarations is a loud Go compile error, <code>DropdownEx</code>&#x27;s rich option arrays are not expressible from <code>.kry</code>, and C pointer/<code>Texture2D</code> values cannot be written (icons pass by <code>UIIconType</code>, option lists as joined strings or <code>[N]string</code>).</p>
<ul>
<li><code>k2js</code> emits ESM for the web recorder runtime. `make</li>
</ul>
<p>k2js-runtime-snapshot-test` lowers every conformance source, imports the generated ESM in Node, runs <code>frame()</code>, and compares the recorded widget streams. <code>make generated-runtime-parity-test</code> also drives generated JS through the same state/input workflows as generated Go and C, then diffs the final state JSON. This is runtime state parity for the recorder surface, not browser pixel comparison.</p>
<ul>
<li><code>k2b</code> drops unsupported widget calls and reports them per file; the</li>
</ul>
<p>cartridge widget set remains smaller than the C catalog (see matrix). <code>Combobox</code> lowers to a <code>KRB_CTRL_COMBOBOX</code> control that renders like the dropdown, matching the C widget. <code>Progress</code> lowers to a read-only <code>KRB_CTRL_PROGRESS</code> control bound to an integer state field. <code>Radio</code> lowers to <code>KRB_CTRL_RADIO</code> for the common <code>selected == id</code> pattern and writes <code>id</code> into the mounted selection field on click. <code>LabelFrame</code> lowers to border rectangles plus title background/text nodes.</p>
<ul>
<li>Retained tree paints 7 node kinds and routes input for 3 (see caveat</li>
</ul>
<p>above the widget matrix).</p>
<ul>
<li>No text shaping: no HarfBuzz, ligatures, bidi, or RTL mirroring anywhere;</li>
</ul>
<p>no IME/preedit; no gamepad UI navigation.</p>
<ul>
<li>Theme styles beyond RETRO/MATERIAL/SYSTEM (fluent/adwaita/liquid-glass</li>
</ul>
<p>labels in <code>ThemeSettingsProps</code>) fall back to SYSTEM tokens.</p>
<ul>
<li><code>kry_sw</code> tracks the dirty rectangle per call (<code>KrySwDirty</code> is one-shot);</li>
</ul>
<p>hosts that present full frames (<code>krb-sdl</code>, <code>krb-web</code>) do not use it yet.</p>
<ul>
<li>Plan 11 engines still to come: native Canvas2D fast path, Android EGL</li>
</ul>
<p>host, ESP32 RGB565 host. The Linux framebuffer host was removed again - raylib covers desktop presentation and the canvas backend covers native web, so it carried maintenance cost without a user.</p>
</body></html>
+304
View File
@@ -0,0 +1,304 @@
# Kryon Feature Matrix
What every widget and feature supports, per compile target and per renderer
backend. For how backends are selected and implemented see `docs/BACKENDS.md`;
for the cartridge binary format see `docs/KRB_FORMAT.md`; for the language see
`docs/KRY_LANGUAGE_SPEC.md`. Keep this file current with the code, and
regenerate the browsable view after every change:
`python3 scripts/feature-matrix-html.py` writes `docs/FEATURE_MATRIX.html`.
Legend: ✅ available · ◐ partial (reason given) · ✗ not available · — not
applicable. **C** is the `libkryon.a` C API; **k2c** is what `.kry` reaches
through the C compiler — always equal to C, because the language is C-close
and every library call is a legal statement (the widget-statement whitelist
below only adds sugar). The other compilers lower subsets, which is where
the columns diverge.
## The pipeline
```
.kry source
│ shared frontend: cmd/kir/kir_parse.c -> KirProgram
├── k2c -> .c/.h + kryon_project.c/.h -> cc + libkryon.a -> native C app
├── k2cpp -> .cpp/.hpp + kryon_project.c/.h (extern "C" decls; same lowering as k2c)
├── k2go -> .go (kryon.<Widget> calls) -> go build + go/kryon -> Go app
├── k2js -> .js (web runtime calls) -> browser/Node ESM -> Web app
├── k2b -> .krb (+ .krb.c/.krb host) -> KrbLoad/KrbExec on any KryBackend
└── k2kir -> .kir (text IR dump; debugging, tests, Krait)
```
| Target | Producer | Runtime | Status |
|---|---|---|---|
| C | `k2c` | `cc` + `libkryon.a` (raylib/null/canvas/libdraw surface backend) | Most complete path; production use |
| C++ | `k2cpp` | `c++` + `libkryon.a`; C++ codegen with C linkage, same lowering as `k2c` | Parity port of the `k2c` backend |
| Go | `k2go` | `go/kryon` native Go package, no cgo | Declarative subset; executable CI gate |
| JS/Web | `k2js` | `web/kryon-runtime.js` ESM recorder/presenter | Syntax, Node recorder snapshots, and generated runtime state parity gated |
| KRB cartridge | `k2b` | `src/krb/krb.c` via the `KryBackend` vtable | Format v2; byte-exact across engines; CI-gated |
| KIR | `k2kir` | — (inspection artifact) | Debugging/tooling only |
Two backend tiers exist (see `docs/BACKENDS.md`):
- **Tier A — surface backends**: implement the ~700-symbol raylib-compatible
surface (`include/kryon_compat.generated.h`), selected at **link** time via
`KRYON_BACKEND=raylib|null|canvas|libdraw`. The whole widget catalog runs on
these.
- **Tier B — cartridge hosts**: implement the ~20-function `KryBackend` vtable
(`include/kry_backend.h`), selected at **runtime**. Only the KRB widget
subset runs on these.
## Widget statement whitelist (`.kry` frontend)
`parse_widget_statement` (`cmd/kir/kir_parse.c`) recognizes 51 widget names.
`k2c` compiles any library call regardless (plain call statement); `k2cpp` shares that lowering (C++ output, C linkage); `k2go` lowers
the full whitelist onto its `Runtime` interface (except `Canvas`, below);
`k2js` records whitelisted standalone widget calls as browser-loadable runtime
operations; and `k2b` lowers a subset of it:
`Background Text TextInRect Paragraph TextLines Rect Line Bevel IconTexture
Picture Button IconButton Href TextField TextArea Dropdown Slider Toggle
Checkbox Radio Progress Spinbox Combobox Screen Column Row Stack End Scroll
Canvas Modal ActionModal MessageDialog ConfirmDialog PromptDialog TitleBar
TabBar BottomNav TopNav Toolbar ShowToast ShowToastFor LabelFrame Notebook
PanedView Collapsible ListBox SourceView TableView CanvasGrid SelectableText`
(`Canvas` is whitelisted but no `Canvas(...)` widget exists — examples call
`BeginCanvas` directly. Scroll coverage uses the C `BeginUIScrollContainer` /
`EndUIScrollContainer` API.)
## Widget matrix
Columns: **C** = the C API · **k2c** = `.kry`→C codegen (always equal to C) · **k2cpp** = `.kry`→C++ codegen (mirrors `k2c`) · **k2go** = `.kry`→Go codegen
(pure Go importing `go/kryon` as `kryon` and calling `kryon.<Widget>`) · **Go** =
hand-written Go via the `go/kryon` package API · **KRB** = lowered into a
cartridge by `k2b`.
Retained-tree caveat that applies to the whole C column: `#ui` lowering
records ~29 widget kinds, but the retained painter covers only BACKGROUND, TEXT, RECT,
LINE, BUTTON, TEXT_FIELD, TEXT_AREA, and routes retained input for BUTTON, TEXT_FIELD, and TEXT_AREA;
every other kind renders through its immediate-mode call during the
declaration pass (`src/ui/ui_tree.c`).
### UI/Display
| Widget | C | k2c | k2cpp | k2go | Go | KRB |
|---|---|---|---|---|---|---|
| Background | ✅ | ✅ | ✅ | ✅ | ✅ `Background` | ✅ node |
| Text | ✅ | ✅ | ✅ | ✅ | ✅ `Text` | ✅ node |
| TextInRect | ✅ | ✅ | ✅ | ✅ | ✅ `TextInRect` | ✅ |
| Paragraph (rich text + inline icons) | ✅ | ✅ | ✅ | ✅ | ✅ `Paragraph` | ✗ |
| TextLines | ✅ | ✅ | ✅ | ✅ | ✅ `TextLines` | ✗ |
| Rect | ✅ | ✅ | ✅ | ✅ (+ `RectGradientH`) | ◐ `DrawRectangle*` primitives | ✅ node |
| Line | ✅ | ✅ | ✅ | ✅ | ✅ `DrawLine` | ✅ |
| Bevel | ✅ | ✅ | ✅ | ✅ | ✅ `Bevel` | ✅ |
| IconTexture (114 embedded icons) | ✅ | ✅ | ✅ | ✅ (by icon type) | ✅ `IconTexture` | ✗ |
| Image/Picture | ✅ | ✅ | ✅ | ✅ `kryon.Picture(kryon.PictureProps)` | ✅ `kryon.Picture` | ✅ node (embedded asset or PNG) |
### UI/Input
| Widget | C | k2c | k2cpp | k2go | Go | KRB |
|---|---|---|---|---|---|---|
| Button (ButtonProps) | ✅ | ✅ | ✅ | ✅ | ✅ `kryon.Button(kryon.ButtonProps)` / `kryon.Button("Save")` | ✅ node |
| Legacy positional buttons | ✅ low-level only | ✅ only for existing C callers | ✅ only for existing C callers | ✗ use `kryon.Button(kryon.ButtonProps)` | ✗ generated Go uses `kryon.Button` | ◐ BUTTON style byte |
| IconButton / PaddedIconBtn | ✅ | ✅ | ✅ | ◐ `IconButton` only | ◐ `IconButton` only | ✗ |
| InfoButton | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Href (hyperlink) / IconLink | ✅ | ✅ | ✅ | ◐ `Href` only | ◐ `Href` only | ✗ |
| TextField | ✅ | ✅ | ✅ | ✅ | ✅ `kryon.TextField(kryon.TextFieldProps)` / `kryon.TextField("Name", &value)` | ✅ TEXTINPUT node |
| Read-only text | ✅ | ✅ | ✅ | ✅ via `Text`/`TextInRect` | ✅ `Text`/`TextInRect` | ✗ |
| TextArea (selection, syntax highlight) | ✅ | ✅ | ✅ | ✅ | ✅ `NewTextArea`/`TextArea` | ✗ |
| Dropdown / DropdownEx | ✅ | ✅ | ✅ | ✅ `Dropdown` (Ex needs rich option arrays) | ✅ `Dropdown(Ex)` | ✅ DROPDOWN control |
| Slider | ✅ | ✅ | ✅ | ✅ | ✅ `Slider`/`Slider` | ✅ SLIDER control |
| Vertical sliders | ✅ low-level only | ✅ only for existing C callers | ✅ only for existing C callers | ✗ use `kryon.Slider` in generated Go | ✗ generated Go uses `kryon.Slider` | ✅ VSLIDER control |
| Toggle (switch) | ✅ | ✅ | ✅ | ✅ | ✅ `Toggle` | ✅ node |
| Checkbox (+ disabled) | ✅ | ✅ | ✅ | ✅ | ✅ `Checkbox` | ✅ node |
| Radio | ✅ | ✅ | ✅ | ✅ | ✅ `Radio` | ✅ `KRB_CTRL_RADIO` |
| Progress | ✅ | ✅ | ✅ | ✅ | ✅ `Progress` | ✅ `KRB_CTRL_PROGRESS` |
| Spinbox | ✅ | ✅ | ✅ | ✅ | ✅ `Spinbox` | ✅ SPINBOX control |
| Combobox | ✅ | ✅ | ✅ | ✅ | ✅ `Combobox` | ✅ COMBOBOX control (renders like the dropdown, mirroring the C widget) |
| ColorPicker (RGB sliders) | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
### UI/Layout
| Widget | C | k2c | k2cpp | k2go | Go | KRB |
|---|---|---|---|---|---|---|
| Column / Row / Stack (flex-like) | ✅ | ✅ | ✅ | ✅ all three | ✅ all three | ✅ structural no-ops (node table is the tree) |
| Group | ✅ (lowers to Stack) | ✅ | ✅ | ◐ via Column | ✅ via Stack | ✅ |
| Scroll container | ✅ | ✅ | ✅ | ✅ `BeginUIScrollContainer`/`EndUIScrollContainer` | ✅ `BeginUIScrollContainer`/`EndUIScrollContainer` | ✅ SCROLL node |
| Separator | ✅ | ✅ | ✅ | ✗ | ✗ | ✅ |
| LabelFrame | ✅ | ✅ | ✅ | ✅ | ✅ `LabelFrame` | ✅ rect/text lowering |
| Notebook (tabs) | ✅ | ✅ | ✅ | ✅ | ✅ `Notebook` | ✗ |
| PanedView (splitter) | ✅ | ✅ | ✅ | ✅ | ✅ `PanedView` | ✗ |
| Collapsible | ✅ | ✅ | ✅ | ✅ | ✅ `Collapsible` | ✗ |
| Tk pack/grid helpers (`FramePack`, `GridCell`, `Place`) | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| UIForm cursor (`UIForm*`) | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Canvas (pan/zoom, hit-test, grid) | ✅ | ✅ | ✅ | ✅ `Begin/EndCanvas` | ✅ `Begin/EndCanvas`+hit-test | ✗ |
### UI/Collections
| Widget | C | k2c | k2cpp | k2go | Go | KRB |
|---|---|---|---|---|---|---|
| ListBox | ✅ | ✅ | ✅ | ✅ | ✅ `ListBox` | ✗ |
| TreeView / CascadingTreeView | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| SourceView (code + line numbers) | ✅ | ✅ | ✅ | ✅ | ✅ `SourceView` | ✗ |
| TableView (sortable) | ✅ | ✅ | ✅ | ✅ | ✅ `TableView` | ✗ |
| CanvasGrid | ✅ | ✅ | ✅ | ✅ | ✅ `CanvasGrid` | ✗ |
| SelectableText | ✅ | ✅ | ✅ | ✅ | ✅ `SelectableText` | ✗ |
### UI/Navigation
| Widget | C | k2c | k2cpp | k2go | Go | KRB |
|---|---|---|---|---|---|---|
| MenuBar / PopupMenu / ContextMenu | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| TabBar | ✅ | ✅ | ✅ | ✅ | ✅ `TabBar` | ✗ |
| SubtabBar / PaneTabBar (dock zones) | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| BottomNav (+ config modal) | ✅ | ✅ | ✅ | ✅ | ✅ `BottomNav` | ◐ `NavButton` lowers to a BUTTON |
| TopNav / Toolbar / ToolbarHeader | ✅ | ✅ | ✅ | ◐ `TopNav`/`Toolbar` only | ✅ `TopNav`/`Toolbar` | ✗ |
| TitleBar family | ✅ | ✅ | ✅ | ◐ `TitleBar` only | ✅ `TitleBar` | ✗ |
### UI/Overlays
| Widget | C | k2c | k2cpp | k2go | Go | KRB |
|---|---|---|---|---|---|---|
| ActionModal / Modal / Modal3Button / ModalFrame | ✅ | ✅ | ✅ | ◐ `Modal` only | ◐ `Modal` only | ✗ |
| MessageDialog / ConfirmDialog / PromptDialog | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| Toast | ✅ | ✅ | ✅ | ✅ `ShowToast(For)` | ✅ `ShowToast(For)` | ✗ |
| GuideOverlay / TutorialImage(Placeholder) | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| TransitionFade / Focus ring | ✅ | ✅ | ✅ | ✗ | ✗ | ◐ `AnimNode` + `TIME` opcode drive animation |
| ThemeSettings / ThemeSwitcher / ThemePicker | ✅ | ✅ | ✅ | ◐ theme-control methods only | ◐ `SetCurrentTheme`/`SetThemeStyle` (control only) | ✗ |
| FocusDebugOverlay | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| InfoRows / OverlayButton / IconSliderPopup | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
### UI/Composite And App Framework
| Widget | C | k2c | k2cpp | k2go | Go | KRB |
|---|---|---|---|---|---|---|
| LabelTextField / SectionLabel | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| CheckboxRow / SpinboxRow / ButtonRow / BottomIconRow | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| BottomNavConfig | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| SidebarAccountHeader / ProfilePicturePicker | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Reorder (drag handle + placeholder) | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| ImageBox | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Route stack / shell measurement | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Capabilities / safe content rect | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Setting normalization helpers | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
### Game2D (scene tree, `src/scene/`)
| Node | C | ✅ | ✅ | k2go | Go | KRB |
|---|---|---|---|---|---|---|
| Scene / Node2D / Camera2D | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Sprite2D / AnimatedSprite2D / TileMap / TileLayer / Light2D | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| CollisionShape2D / Area2D / Body2D (box2d) | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Timer / AudioSource / AnimationPlayer | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Signals (`KrySignal`) / keyframe animation | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
### KRB cartridge vocabulary (no C widget equivalent)
| Item | Notes |
|---|---|---|
| DATA node | state-field mount read/written by bytecode |
| CIRCLE / RING nodes | lowered from `DrawCircleV` / `DrawRing` calls |
| `NavButton` | `k2b`-only lowering; becomes a BUTTON with `KRB_FLAG_NAV` |
| `AnimNode` | `k2b`-only; animated node driven by `TIME` |
| v2 logic bytecode | stack machine, node mutation, if-guards over node ranges |
| Host capabilities | imported storage/http/audio/notify calls (`krb_caps.c`) |
## Cross-cutting features
| Feature | C | Go | KRB |
|---|---|---|---|---|
| Theming | ✅ 6 palettes × light/dark INI, scopes, vars, runtime loader | ✅ `SetCurrentTheme`/`SetThemeDarkMode`/`GetTheme*` | ◐ theme color slots (`KrySwSetTheme`); light/dark env knobs on hosts |
| Style tokens | ✅ radius/border/shadow/bevel; RETRO, MATERIAL, SYSTEM styles | ✅ `Get/SetUIStyleTokens` | ✗ |
| Animation | ✅ transitions (smoothstep), ripple, keyframe scene anims | ✗ | ◐ `AnimNode` + `TIME` opcode |
| Text/fonts | ✅ multi-font registry, per-codepoint fallback, italic synthesis, wrap, selectable text; no shaping/bidi/IME | ✅ `RegisterUIFont(Data)`, `Push/Pop/UseUIFont`, input queue | ◐ font8x8 default, or pre-baked KFA1 glyph atlas; no TTF rasterization |
| DPI/scaling | ✅ viewport-derived scale, `ScaleUIPx` | ✅ `ScaleUIPx`, `GetWindowScaleDPI` | ◐ per-mille UI scale (`KRB_RUN_UI_SCALE`) |
| Clipping | ✅ 16-deep scissor stack + input clip stack | ✅ `Begin/EndScissorMode` | ✅ 16-deep `clip_push/pop` in `kry_sw` |
| Z-order/popups | ✅ overlay paint pass, modal capture, input-capture stack | ◐ dropdown popups internal to `Dropdown` | ◐ dropdown menus handled by the engine |
| Input | ✅ unified front-end, pointer gestures/ownership, keyboard focus + Tab + accelerators, clipboard; no IME, no gamepad nav | ✅ native host key/mouse/text queues | ◐ vtable: mouse, press, wheel, text-key queue |
| Accessibility | ◐ debug focus overlay + a11y node structs; no screen-reader bridge | ✗ | ✗ |
| i18n | ✅ locale strings + CJK font switching; no RTL | ✗ | ✗ |
| Multi-window | ✅ `OpenUIWindow` (X11 dlopen / SDL) | ✗ | — single framebuffer |
| 3D rendering | ✅ camera + mesh/shader tier incl. curated rlgl entry points and raymath-style math3d (GLSL 100); raylib backend implements it, others stub it | ✗ | ✗ |
| State/data binding | ✅ retained event queue; scene signals | ✅ `#ui` functions + retained events | ✅ field mounts (`KrbMount*`) + bytecode |
| Dialogs/platform | ✅ file dialogs (web/portal/gtk/zenity/kdialog/yad), XDG paths, desktop metadata packaging, single-instance lock, tray, notifications (Android/web/Linux) | ✅ tray + notify polling | ◐ host capability imports (storage/http/audio/notify) |
| Debug tooling | ✅ widget inspector, node registry + snippets | ✗ | ◐ `KryBackendRec` call-stream recording |
## Renderer backends
### Tier A — surface backends (link-time, `KRYON_BACKEND`)
| Backend | Graphics API | Platforms | CI | Notes |
|---|---|---|---|---|---|
| `raylib` (default) | OpenGL ES 2.0 over SDL2 | Linux, FreeBSD | ✅ `ci.yml` (Linux + FreeBSD) | Default everywhere; dist/static SDK targets; implements the full 3D tier (camera/mesh/shader + rlgl entry points) |
| `raylib` web | WebGL (ES2) over GLFW3 | Emscripten | ✅ web/app builds | `mk/web.mk`; present shim for WebKitGTK |
| `raylib` windows `opengl` | OpenGL 2.1 | Windows (mingw) | ✅ release builds | Default Windows flavor |
| `raylib` windows `rlsw` | raylib software renderer (no GPU) | Windows | ✅ release builds | `WINDOWS_RENDERERS` second flavor |
| `raylib` windows RGFW rule | GL 1.1 immediate mode | Windows | ✗ opt-in make rule | `KRYON_RAYLIB_WINDOWS_RULE` |
| `raylib` android | GLES via NDK `NativeActivity` | Android (downstream Gradle) | ✗ downstream apps | `mk/android.mk` |
| `null` | none (zero-return stubs) | all | ✗ (used by local headless tests) | Injected input still works |
| `canvas` | HTML5 Canvas2D via `EM_JS` (ASYNCIFY loop) | Emscripten | ✅ `make canvas-test`, `make canvas2d-parity-check`, `make web-canvas-matrix-check` | No raylib/WebGL; HiDPI Canvas2D, 2D raylib aliases, touch/gamepad/drop-file hooks, glyph atlases, textures/render textures/tinting, WebAudio, and weak stubs for non-2D raylib areas |
| `libdraw` | `kry_sw` RGBA8 presented through plan9port libdraw/devdraw | plan9port on Unix/X11 | ✅ `make libdraw-test` (devdraw smoke + `9c`/`9l` clean-surface check) | No libraylib; widgets/drawing/screenshots through software backend; TTF/TrueType-outline glyph atlases via `stb_truetype`; rounded controls, alpha/tint texture blits, rotation, render textures, plan9port input/resize; non-UI raylib areas use weak null stubs |
### Tier B — cartridge hosts (`KryBackend` vtable, runtime selection)
| Host | Rendering | Input | Textures | Text | CI | Notes |
|---|---|---|---|---|---|---|---|
| `KryBackendDraw` | raylib surface | raylib | ✅ | full font stack | ✅ | Auto-installed via constructor; hooks cartridge audio; runs inside raylib apps and `kryon-preview` |
| `kry_sw` | software RGBA8 rasterizer | injected (`KrySwMouse` etc.) | ✅ + PNG decode | font8x8 or KFA1 atlas | ✅ | No GPU/libc deps; `KrySwToRGB565` for embedded panels; one-shot dirty-rect tracking |
| `krb-run` | `kry_sw` headless | injected | ✅ | via `kry_sw` | ✅ linux/windows/macos | PNG dump + `KryBackendRec` call log; conformance host |
| `krb-sdl` | `kry_sw` → SDL2 streaming texture | SDL2 | ✅ | via `kry_sw` | ✅ | Template for the planned Android EGL host |
| `krb-web` | `kry_sw` → wasm, Canvas2D `putImageData` | JS bridge exports | ✅ | via `kry_sw` | ✅ renderers.yml | Byte-identical to native; node-capture for tests |
| `KryBackendRec` | wraps any backend | passthrough | passthrough | passthrough | ✅ exactness job | Records the vtable call stream for cross-engine comparison |
| `KryBackendNull` | stub vtable | none | ✗ (`texture_rgba` NULL) | ✗ | ✅ logic tests | Default until `KryBackendSelect` |
## Known gaps
- The `canvas` Tier A backend passes its node call-sequence gate and has
been pixel-verified in a real browser page (rounded rects, annulus ring
segments, dual-color gradients, and full RGBA texture tinting all check
out). Remaining limits: cross-app clipboard paste is unreachable through
the synchronous API (an in-app mirror handles round-trips), WebAudio
playback depends on browser user-gesture unlock rules, and stream/mixed
processors apply to Canvas-managed stream buffers, not decoded browser
`AudioBuffer` playback that has already been handed to WebAudio.
- The `libdraw` Tier A backend passes the plan9port devdraw widget smoke and a
`9c`/`9l` clean-surface compile/link check. It is intended for C UI apps:
windowing, input, resize, software drawing, widgets, rounded controls, thick
lines, image loading, alpha/tint and source-rectangle texture blits, picture
rotation, render textures, TTF/TrueType-outline glyph-atlas text,
screenshots, files, and clipboard mirror are covered. Advanced raylib areas
outside UI apps (3D, shaders, gestures, audio) are null-grade fallback.
- `k2go` targets native Go: the `Runtime` interface covers the widget
whitelist plus the generated-code widget families in `go/kryon` (controls,
Props widgets, dialogs, canvas, Tk layout helpers, toasts, theme control),
with `.kry` array declarations lowering to Go slices at the use site.
Remaining boundaries: a forward `goto` over declarations is a loud Go
compile error, `DropdownEx`'s rich option arrays are not expressible from
`.kry`, and C pointer/`Texture2D` values cannot be written (icons pass by
`UIIconType`, option lists as joined strings or `[N]string`).
- `k2js` emits ESM for the web recorder runtime. `make
k2js-runtime-snapshot-test` lowers every conformance source, imports the
generated ESM in Node, runs `frame()`, and compares the recorded widget
streams. `make generated-runtime-parity-test` also drives generated JS
through the same state/input workflows as generated Go and C, then diffs the
final state JSON. This is runtime state parity for the recorder surface, not
browser pixel comparison.
- `k2b` drops unsupported widget calls and reports them per file; the
cartridge widget set remains smaller than the C catalog (see matrix).
`Combobox` lowers to a `KRB_CTRL_COMBOBOX` control that renders like the
dropdown, matching the C widget. `Progress` lowers to a read-only
`KRB_CTRL_PROGRESS` control bound to an integer state field. `Radio` lowers
to `KRB_CTRL_RADIO` for the common `selected == id` pattern and writes `id`
into the mounted selection field on click. `LabelFrame` lowers to border
rectangles plus title background/text nodes.
- Retained tree paints 7 node kinds and routes input for 3 (see caveat
above the widget matrix).
- No text shaping: no HarfBuzz, ligatures, bidi, or RTL mirroring anywhere;
no IME/preedit; no gamepad UI navigation.
- Theme styles beyond RETRO/MATERIAL/SYSTEM (fluent/adwaita/liquid-glass
labels in `ThemeSettingsProps`) fall back to SYSTEM tokens.
- `kry_sw` tracks the dirty rectangle per call (`KrySwDirty` is one-shot);
hosts that present full frames (`krb-sdl`, `krb-web`) do not use it yet.
- Plan 11 engines still to come: native Canvas2D fast path, Android EGL
host, ESP32 RGB565 host. The Linux framebuffer host was removed again -
raylib covers desktop presentation and the canvas backend covers native
web, so it carried maintenance cost without a user.
+269
View File
@@ -0,0 +1,269 @@
# Kryon Cartridge Format (krb) — exact specification
A `.krb` file is Kryon's compact portable cartridge: everything a renderer
needs to draw and run a UI, in one little-endian, mmapable binary. This
document is normative. An implementation that follows it can parse and
render any cartridge without kryon source code.
Reference implementation: `src/krb/krb.c` (runtime), `cmd/k2b` (compiler),
`include/krb.h` (constants). Reference renderers: `src/backend/kry_sw.c`
(software), `cmd/krb-run` (headless), `cmd/krb-web` (wasm), `cmd/krb-sdl`.
## 1. Encoding rules
- All multi-byte integers are **little-endian**, packed, no alignment
padding inside records.
- Strings are UTF-8, NUL-terminated, stored once in the string table;
every string reference elsewhere is a `u16` **byte offset** into it.
- Offsets into `prog[]` are `u32` **absolute** byte offsets from the start
of the program section.
- Colors are `u32` packed `0xRRGGBBAA`. Theme references: see §4.
## 2. File layout
One linear image, sections in this exact order, no gaps:
```
offset size section
0 32 header (28 used + 4 reserved)
H 28 × node_count nodes[]
N string_bytes strings[]
S prog_bytes prog[]
P 4 × import_count imports[] (u32 string offsets each)
I 24 × control_count controls[]
```
with `H = 32`, `N = H + 28 × node_count`, `S = N + string_bytes`,
`P = S + prog_bytes`, `I = P + 4 × import_count`. A loader MUST reject the
file when `file_size < I + 24 × control_count`.
## 3. Header (32 bytes)
| Offset | Size | Field | Value |
|---|---|---|---|
| 0 | 4 | magic | `0x0042524B` — bytes `4B 52 42 00` (`"KRB\0"`) |
| 4 | 2 | version | `1` or `2` (see §7); a loader MUST reject other values |
| 6 | 2 | flags | reserved, MUST be 0 |
| 8 | 4 | node_count | number of node records |
| 12 | 4 | string_bytes | size of string table in bytes |
| 16 | 4 | prog_bytes | size of program section |
| 20 | 4 | import_count | number of host-import name offsets |
| 24 | 4 | control_count | number of control records |
| 28 | 4 | reserved | MUST be 0 |
Additional loader requirements: `string_bytes > 0` and the byte at string
offset `0` MUST be `0x00` (the empty string lives at offset 0).
## 4. Node record (28 bytes)
| Offset | Size | Field | Type | Meaning |
|---|---|---|---|---|
| 0 | 2 | id | u16 | node id (serial number; equals record index today) |
| 2 | 2 | parent | i16 | parent node index, `-1` = root |
| 4 | 2 | name_off | u16 | string offset (name / bound state path) |
| 6 | 1 | type | u8 | node type, §4.1 |
| 7 | 1 | flags | u8 | bit flags, §4.2 |
| 8 | 2 | bind_slot | u16 | import slot or control index; `0xFFFF` = none |
| 10 | 2 | x | i16 | x coordinate (meaning per type) |
| 12 | 2 | y | i16 | y coordinate |
| 14 | 2 | w | i16 | width / radius per type |
| 16 | 2 | h | i16 | height / inner radius per type |
| 18 | 4 | color | u32 | `0xRRGGBBAA` or theme reference |
| 22 | 2 | text_off | u16 | string offset (label / asset path / format) |
| 24 | 2 | font_size | u16 | pixels; `0` renders as 16 |
| 26 | 1 | style | u8 | per-type substyle |
| 27 | 1 | pad | u8 | reserved, MUST be 0 |
### 4.1 Node types
| Value | Name | x,y / w,h meaning | Drawn as |
|---|---|---|---|
| 0 | — | reserved | — |
| 1 | BACKGROUND | w,h = size (see §8) | filled rect, the screen backdrop |
| 2 | TEXT | x,y = top-left | text, `text_off` string, `font_size` |
| 3 | RECT | x,y,w,h = bounds | filled rect |
| 4 | BUTTON | bounds | filled rect + 1px border + centered label (`text_off`); import `bind_slot` fires on press-in-bounds. `style`: 0 primary (theme button color), 1 plain (theme surface), 2 danger (`0xB83B3BFF`) |
| 5 | DATA | — | not drawn; state-field metadata |
| 6 | PICTURE | bounds | texture; `text_off` = asset path, `color` = tint, `style` = fit (0 stretch, 1 contain, 2 cover) |
| 7 | CHECKBOX | box at bounds; label at `x+w+4` | cartridge-owned toggle on mount path `name_off`; flips value on press-in-bounds |
| 8 | TOGGLE | switch at bounds; label beside | same mount behavior as CHECKBOX |
| 9 | CONTROL | bounds = widget bounds | range widget; `bind_slot` indexes controls[] |
| 10 | CIRCLE | x,y = center; w = radius | filled circle |
| 11 | RING | x,y = center; w = outer, h = inner radius | annulus |
| 12 | SCROLL | bounds = viewport; `font_size` = content height; `name_off` = mount path of pixel offset | container: children (nodes with `parent` = this index) draw translated by `-offset` and clipped to the viewport; wheel over the viewport adjusts the mounted offset (clamped to `[0, content_h - h]`) |
### 4.2 Flags
| Bit | Mask | Name | Meaning |
|---|---|---|---|
| 0–1 | `0x03` | reserved | MUST be 0 |
| 2 | `0x04` | SCALE_X | x is in UI-scale units (multiply by backend scale) |
| 3 | `0x08` | SCALE_Y | same for y |
| 4 | `0x10` | SCALE_W | same for w |
| 5 | `0x20` | SCALE_H | same for h |
### 4.3 Colors and theme slots
A node `color` whose **top bit is set** (`color & 0x80000000 != 0`) is a
theme reference: `slot = color & 0x7FFFFFFF`; the renderer asks the host
backend for the slot color. Slots: `0` background, `1` text, `2` icon,
`3` surface, `4` button; other slot values resolve to the backend default.
**Consequence (deliberate v1 constraint):** any *literal* color with a red
channel ≥ `0x80` also has the top bit set and reads as a theme reference.
Literal cartridge colors MUST keep R < `0x80`; use a theme slot for bright
reds. (A future version may move the sentinel; until then this rule is
normative.)
## 5. String table
`string_bytes` bytes of concatenated NUL-terminated UTF-8 strings. Offset 0
is the empty string (the table starts with a `0x00` byte). A string
reference is valid iff `offset < string_bytes - 1` and the byte at
`offset` begins a complete string. Paths used as mount references (e.g.
`"counter"`, `"app/score"`) are plain strings compared exactly.
## 6. Imports
`import_count` × `u32` string offsets naming host functions (today: button
handlers). A node's `bind_slot` (when `< 0xFFFF`) selects the slot; the
host binds each slot with `KrbBind`/`KrbBindSlot`. A slot with no bound
function is skipped silently.
## 7. Control record (24 bytes)
Referenced by a CONTROL node's `bind_slot`.
| Offset | Size | Field | Type | Meaning |
|---|---|---|---|---|
| 0 | 1 | kind | u8 | 1 slider, 2 vslider, 3 spinbox, 4 dropdown, 5 combobox, 6 progress, 7 radio |
| 1 | 1 | option_count | u8 | dropdown/combobox option count, 0 otherwise |
| 2 | 2 | id | u16 | widget id |
| 4 | 4 | min | i32 | range minimum |
| 8 | 4 | max | i32 | range maximum |
| 12 | 4 | step | i32 | increment |
| 16 | 2 | value_off | u16 | string offset: mount path of the value |
| 18 | 2 | label_off | u16 | string offset: label |
| 20 | 2 | options_off | u16 | reserved, 0 |
| 22 | 2 | reserved | u16 | MUST be 0 |
Slider: held-drag maps the pointer position across the track to
`[min, max]`. Spinbox: click left/right half decrements/increments by
`step`, clamped to `[min, max]`. Dropdown (`kind 4`) and combobox (`kind 5`):
`options_off` points at `option_count` consecutive NUL-terminated option
strings; the bound `int` holds the selected index. Click toggles the popup;
clicking a row writes the index and closes. Progress (`kind 6`) reads the
bound `int`, clamps it to `[min, max]`, and draws a noninteractive filled bar
with optional `label_off` text. Radio (`kind 7`) reads the bound `int`, draws
selected when it equals `id`, and writes `id` on click.
## 8. Program and execution semantics
`prog[]` is a byte stream executed in order by `KrbExec` once per frame.
Opcodes:
| Op | Byte | Operands (in order) | Semantics |
|---|---|---|---|
| `OP_DRAW_TREE` | `0x01` | — | draw every node, in record order |
| `OP_CALL_HOST` | `0x02` | u8 slot | call host function bound to slot |
| `OP_SET_I32` | `0x03` | u16 path_off, i32 value | write mounted int |
| `OP_PUSH_CONST` | `0x10` | i32 | push immediate |
| `OP_PUSH_PATH` | `0x11` | u16 path_off | push mounted int at path (unmounted → 0) |
| `OP_POP_STORE` | `0x12` | u16 path_off | pop → write mounted int at path |
| `OP_ADD` | `0x13` | — | pop b, pop a, push `a + b` |
| `OP_SUB` | `0x14` | — | push `a - b` |
| `OP_MUL` | `0x15` | — | push `a * b` |
| `OP_DIV` | `0x16` | — | push `b == 0 ? 0 : a / b` (C division) |
| `OP_EQ`/`NE`/`LT`/`LE`/`GT`/`GE` | `0x17`–`0x1C` | — | pop b, pop a, push 1 or 0 |
| `OP_JMP` | `0x1D` | u32 addr | set program counter to `addr` |
| `OP_JZ` | `0x1E` | u32 addr | pop; if 0, set program counter to `addr` |
| `OP_TIME` | `0x1F` | — | push `(int)(host time in seconds × 1000)` |
| `OP_DRAW_NODE` | `0x20` | u16 node index | draw one node |
Rules:
- The VM stack is 16-deep int32 and persists across opcodes within one
`KrbExec` pass. Push on overflow or pop on underflow is an error
(execution fails).
- Jump targets are absolute offsets into `prog[]`; a target outside
`[0, prog_bytes]` makes the jump a no-op.
- Any other opcode byte is an error; execution stops.
- Drawing: node coordinates are relative to the current draw origin
(0,0 for a full-frame pass). A SCALE_* flag replaces the raw i16 with
`backend.scale_px(value)`. When `OP_DRAW_TREE` (or `OP_DRAW_NODE` on a
BACKGROUND node) executes, a BACKGROUND node's w/h are overridden with the
host screen size and its SCALE_W/H flags cleared.
- Interaction (BUTTON, CHECKBOX, TOGGLE, CONTROL) is evaluated at draw
time: "pointer pressed this frame" AND "pointer inside the node bounds"
(post-transform). Bounds are exclusive on the right/bottom edges.
### Versions
- **v1** — opcodes `0x01`–`0x03`, node types 1–9. Render-first.
- **v2** — adds opcodes `0x10`–`0x20` and node types 10–11. Loaders accept
both; compilers should emit 2.
### Asset section (v2)
When header offset 28 (`asset_bytes`) is nonzero, an asset section follows
`controls[]`: a `u32 asset_count`, then `asset_count` directory entries of
20 bytes, then the blobs. Entry: `path_off u32@0` (string table),
`data_off u32@4` (absolute file offset), `size u32@8`, `kind u16@12`
(0 = raw RGBA8 pixels, 1 = glyph atlas), `w u16@14`, `h u16@16`,
`reserved u16@18`. `asset_bytes` counts the whole section. A PICTURE node
whose path matches an embedded raw-RGBA asset is rendered from cartridge
pixels through the backend's optional `texture_rgba` (scaled, tinted);
non-embedded paths fall back to host texture loading. The conventional
name "@atlas" carries a KFA1 glyph atlas: `u32 "KFA1" | u16 size_count`,
then per size a 16-byte record (`px u16 | glyphs u16 | w u16 | h u16 |
table_off u32 | pixels_off u32`), then per-glyph 18-byte records
(`cp u32 | x,y,w,h u16 | xoff,yoff i16 | advance u16` in 1/256-px fixed point,
offsets into the
size's RGBA8 white-on-alpha bitmap). Engines with atlas support render
antialiased text with true advances; without it they fall back to their
built-in font.
## 9. Limits (current implementation)
256 nodes, 8 KiB strings, 32 imports, 128 controls, 32 host binds,
16 mount roots, 64 fields per mount, 16 MiB cartridge (raised from
64 KiB to fit embedded atlases and images).
## 10. Host surface (what a renderer must provide)
A renderer implements the `KryBackend` table (see `include/kry_backend.h`):
`clear`, `rect`, `text`, `measure_text`, `clip_push/pop`, `mouse`,
`mouse_down`, `mouse_pressed`, `width`, `height`, `time`, `scale_px`,
`theme_color`, `texture`, and optional `circle`/`ring` (v2 geometry; a
renderer may leave them NULL, in which case CIRCLE/RING nodes are no-ops).
Colors passed to the backend are already resolved literals. Assets are
referenced by path; loading and caching are host-owned.
## 11. C memory as files (mounts)
Hosts map live memory onto string paths:
```c
KrbField fields[] = {
{ "score", offsetof(App, score), KRB_I32, 4 },
{ "label", offsetof(App, label), KRB_CSTR, 16 },
{ NULL }
};
KrbMount(&img, "/app", app, fields);
KrbReadI32(&img, "/app/score", &n);
/* or a single field: */
KrbBindMem(&img, "counter", &counter, KRB_I32, 4);
```
Field kinds: `KRB_I32 1`, `KRB_U32 2`, `KRB_F32 3`, `KRB_BOOL 4`,
`KRB_CSTR 5`. Read/write is a typed memcpy. A TEXT node whose `name_off`
string equals a mounted path renders the live value; its `text_off` string
acts as a `printf` format when it contains `%`.
## 12. Tooling
- `k2b` compiles `.kry` → `.krb` (+ optional generated C host; `--no-main`
omits the host `main`). Unsupported `.kry` calls are dropped and reported.
- `krb-run` renders headless to PNG / a recorded call stream.
- `krb-web` / `krb-sdl` are full hosts; `tests/golden` + `tests/krb_engine_test.sh`
pin cross-engine byte-identical output.
-116
View File
@@ -1,116 +0,0 @@
# 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.
+255
View File
@@ -0,0 +1,255 @@
# Kry Language Specification
Kry language version: `0.2`
KIR version: `0.1`
This is the stable public contract for `.kry` source accepted by Kryon tools.
Kry is intentionally C-close: expressions and types stay familiar to C, while
the frontend owns declarations, compile-time guards, UI frame structure, and
KIR emission.
The required pipeline is:
```text
.kry -> KIR -> C
.kry -> KIR -> Go
.kry -> KIR -> JS
.kry -> KIR -> KRB
```
Backends may accept `.kry` directly as a CLI convenience, but they must behave
as if the source was first lowered into KIR. Unsupported behavior must be
diagnosed or represented honestly as unsupported KIR; it must not silently
change semantics.
## Compatibility
- Patch-level language changes may add diagnostics, new KIR metadata, or new
backend support for previously rejected forms.
- A minor language version bump is required when new source syntax becomes
documented as stable.
- A major language version bump is required if valid version `0.x` source would
be interpreted differently.
- Raw statement text remains part of KIR until structured expression lowering is
complete enough for every backend that needs it.
## Lexical Model
Kry source is line-oriented with C-like tokens inside expressions. Whitespace
separates declarations and statements but is otherwise not semantic except
inside strings and raw text.
```ebnf
identifier = letter , { letter | digit | "_" } ;
string = '"' , { character | escape } , '"' ;
integer = digit , { digit | "_" | "x" | "X" | "a".."f" | "A".."F" } ,
{ "u" | "U" | "l" | "L" } ;
type-text = C-compatible type text up to a grammar delimiter ;
expr-text = C-close expression text up to a statement/block delimiter ;
raw-c-text = text after the `c` statement marker ;
```
The frontend parses a conservative subset of expressions into KIR expression
metadata. Full C-close expression text is still preserved for backends.
## Top-Level Grammar
```ebnf
source = { top-level-form } ;
top-level-form = module-decl
| output-decl
| import-decl
| pragma-decl
| error-decl
| assert-decl
| const-decl
| type-decl
| enum-decl
| state-block
| app-block
| function-decl
| guarded-top-level ;
module-decl = "#module" , string ;
output-decl = "#output" , string ;
import-decl = "#import" , ( string | "<" , text , ">" ) , [ "#private" ]
| identifier , "::" , "#import" , string ;
pragma-decl = "#pragma" , string ;
error-decl = "#error" , string ;
assert-decl = "#assert" , expr-text , [ "," , string ] ;
const-decl = identifier , "::" , const-expr ;
const-expr = "#defined" , "(" , identifier , ")"
| "#run" , integer-expr
| expr-text ;
type-decl = identifier , "::" , "struct" , "{" , { field-decl } , "}"
| identifier , "::" , type-text , "#type" , [ "#private" ] ;
field-decl = identifier , ":" , type-text , [ "=" , expr-text ] ;
enum-decl = identifier , "::" , "enum" , "{" , { enum-item } , "}"
| "#enum" , [ "#private" ] , "{" , { enum-item } , "}" ;
enum-item = identifier , [ "=" , expr-text ] ;
state-block = "state" , "{" , { field-decl } , "}" ;
app-block = "app" , string , "{" , { app-property } , "}" ;
app-property = "size" , integer , integer
| "fps" , integer
| "font" , identifier
| "theme" , identifier , identifier ;
function-decl = identifier , "::" , signature , modifiers , block ;
signature = "(" , [ params ] , ")" , [ "->" , type-text ] ;
params = param , { "," , param } ;
param = identifier , ":" , type-text ;
modifiers = { "#export" | "#private" | "#global" | "#extern" ,
[ string ] | "#intrinsic" , string | "#ui" | abi-tag } ;
abi-tag = "#storage" , string | "#abi" , string | "#attr" , string ;
```
## Statement Grammar
```ebnf
block = "{" , { statement } , "}" ;
statement = local-decl
| assignment
| ui-node
| call-statement
| if-statement
| while-statement
| for-statement
| switch-statement
| guard-statement
| defer-statement
| return-statement
| jump-statement
| label-statement
| raw-c-statement
| unused-statement
| guarded-statement ;
local-decl = identifier , ":=" , expr-text
| identifier , ":" , type-text , [ "=" , expr-text ] ;
assignment = expr-text , assignment-op , expr-text ;
assignment-op = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" ;
call-statement = identifier , "(" , [ expr-text ] , ")" ;
ui-node = layout-node | widget-props-node ;
layout-node = layout-widget , identifier , [ ":" ] , "{" ,
{ ui-prop | statement } , "}" ;
widget-props-node = props-widget , [ identifier ] , [ ":" ] , "{" ,
{ ui-prop } , "}" ;
ui-prop = identifier , "=" , expr-text ;
if-statement = "if" , expr-text , block ,
{ "else" , "if" , expr-text , block } ,
[ "else" , block ] ;
while-statement = "while" , expr-text , block ;
for-statement = "for" , expr-text , block ;
switch-statement= "switch" , expr-text , "{" ,
{ "case" , expr-text , ":" , { statement } } ,
[ "default" , ":" , { statement } ] , "}" ;
guard-statement = "guard" , expr-text , block ;
defer-statement = "defer" , statement ;
return-statement= "return" , [ expr-text ] ;
jump-statement = "goto" , identifier | "break" | "continue" ;
label-statement = identifier , ":" ;
raw-c-statement = "c" , raw-c-text ;
unused-statement= "unused" , expr-text ;
```
Plain call statements are UI declarations when they call Kryon widget/runtime
functions. Property-block widgets lower to the existing `WidgetProps` C-style
call shape, so `Button { label = "Save" ... }` is equivalent to
`Button((ButtonProps){.label = "Save", ...})`. Layout nodes (`Screen`,
`Column`, `Row`, `Stack`) still open retained UI scopes and therefore emit a
matching `End()`.
## Tooling
`kryon fmt [--check] file.kry...` formats Kry source with stable indentation
and simple spacing cleanup. `--check` exits non-zero when a file would change.
`kryon locale-check source.kry... -- locales/*.txt` validates `t("key")`
references against locale files that use `[key]` blocks. It reports missing
keys, unused keys, duplicate locale keys, and non-English locale entries that
copy the English text exactly.
## Compile-Time Forms
`#defined(SYMBOL)` expands to a preprocessor-style condition. It is useful for
guards and assertions that C should preserve.
`NAME :: #run INTEGER_EXPR` folds a small integer expression while parsing Kry.
It supports integer literals, parentheses, unary `!`, unary `+`, unary `-`,
arithmetic operators, relational operators, equality operators, `&&`, and `||`.
It is not a general compile-time function system.
`#assert CONDITION, "message"` records a KIR assertion. If the assertion is
unguarded, fully known, and false, the frontend fails immediately. C lowers
assertions to `#if` and `#error`. Go, JS, and KRB currently accept only
known-true assertions and reject guarded or unresolved assertions.
## Diagnostics
Diagnostics should include file and line whenever source spans are available.
Backends must reject unsupported compile-time behavior that could alter program
meaning. TODO comments in generated output are acceptable only for explicitly
best-effort backend areas and must be covered by conformance status.
## KIR Contract
KIR records modules, imports, defines, assertions, state fields, types,
functions, statements, and expression metadata. Statement records always keep
the normalized raw source text. Expression records currently cover:
| Kind | Meaning |
|---|---|
| `ident` | Simple identifier. |
| `int` | Integer literal text. |
| `float` | Floating-point literal text. |
| `string` | String literal text. |
| `call` | Simple `Name(args...)` call with child expressions for arguments. |
| `binary` | Top-level binary expression with operator, left child, and right child. |
| `unary` | Prefix unary expression with operator and right child. |
| `member` | `base.field` access with base expression and field name. |
| `pointer_member` | `base->field` access with base expression and field name. |
| `index` | `base[index]` access with base and index children. |
| `compound` | C-style compound literal text preserved as one expression. |
| `sizeof` | `sizeof(...)` expression metadata. |
| `unknown` | Preserved expression text that the frontend did not structure yet. |
Backends may use raw statement text while structured expression KIR grows. They
must not require a second source-language path around KIR.
## Backend Conformance
| Feature | KIR | C | Go | KRB |
|---|---|---|---|---|
| `.kry -> KIR` frontend | yes | source | source | source |
| Header imports | yes | yes | partial | partial |
| Module imports | yes | yes | partial | partial |
| State block | yes | yes | yes | yes |
| Structs and type aliases | yes | yes | partial | partial |
| Tagged extern declarations | yes | yes | host interface or direct Go package call | host/capability subset |
| `#defined` guards | yes | yes | partial | partial |
| `#run` integer constants | yes | yes | yes | yes |
| `#assert` | yes | `#if/#error` | known true only | known true only |
| Locals and assignments | yes | yes | yes | partial |
| Control flow | yes | yes | partial | partial |
| `defer` | yes | yes | no | no |
| Raw C lines | yes | yes | no | no |
| Structured expression metadata | partial | metadata only | metadata only | metadata only |
## Known Boundaries
- C is the broadest backend and the canonical ABI path.
- Go is a declarative app subset. Tagged extern targets that contain a full Go
import path, such as `github.com/example/app.Generate`, are imported and
called directly by generated Go; short targets such as `app.Generate` remain
host-interface methods. Explicit C targets use the `c.symbol` form, such as
`#extern "c.abs"`; only those declarations generate an isolated cgo bridge.
- KRB is a portable cartridge subset with explicit host/capability boundaries.
- `defer` is currently a C-oriented compile-time transform.
- Raw C lines are not portable.
- Structured expression KIR is metadata today, not the sole lowering source.
File diff suppressed because it is too large. Load diff
+57
View File
@@ -0,0 +1,57 @@
# Runtime Parity
Generated by `tests/runtime_parity_test.sh`. Do not edit by hand.
| Method | Native Go (`go/kryon`) | Clean C entrypoint | Status |
|---|---|---|---|
| `Background` | `(Color)` | `void Background(Color color);` | ok |
| `BeginFrame` | `()` | `void BeginFrame(void);` | ok |
| `Bevel` | `(x, y, w, h int32, light, dark Color)` | `void Bevel(int x, int y, int w, int h, Color light, Color dark);` | ok |
| `BottomNav` | `(props BottomNavProps)` | `BottomNavResult BottomNav(BottomNavProps nav);` | ok |
| `Button` | `(ButtonProps) (bool)` | `int Button(ButtonProps button);` | ok |
| `CanvasGrid` | `(bounds Rectangle, step int32, color Color)` | `void CanvasGrid(Rectangle bounds, int step, Color color);` | ok |
| `Checkbox` | `(int32, int32, int32, string, *int32) (bool)` | `int Checkbox(int id, int x, int y, const char *label, int *value);` | ok |
| `Collapsible` | `(props CollapsibleProps) (int32)` | `int Collapsible(CollapsibleProps section);` | ok |
| `Column` | `(ColumnProps)` | `NodeId Column(ColumnProps props);` | ok |
| `Combobox` | `(props ComboboxProps) (bool)` | `int Combobox(ComboboxProps combo);` | ok |
| `ConfirmDialog` | `(props ConfirmDialogProps) (int32)` | `int ConfirmDialog(ConfirmDialogProps dialog);` | ok |
| `Dropdown` | `(id, x, y, w, h int32, options any, rest ...any) (bool)` | `int Dropdown(int id, int x, int y, int w, int h, const char **options, int option_count, int *selected_index);` | ok |
| `EndFrame` | `()` | `void EndFrame(void);` | ok |
| `Href` | `(props HrefProps) (bool)` | `int Href(HrefProps link);` | ok |
| `IconButton` | `(props IconButtonProps) (bool)` | `int IconButton(IconButtonProps button);` | ok |
| `IconTexture` | `(id, x, y, size int32, iconType int32, tint Color)` | `void IconTexture(int id, int x, int y, int size, Texture2D icon, Color tint);` | ok |
| `LabelFrame` | `(props LabelFrameProps)` | `void LabelFrame(LabelFrameProps frame);` | ok |
| `Line` | `(int32, int32, int32, int32, Color)` | `void Line(int x1, int y1, int x2, int y2, Color color);` | ok |
| `ListBox` | `(props ListBoxProps) (int32)` | `int ListBox(ListBoxProps list);` | ok |
| `MessageDialog` | `(props MessageDialogProps) (int32)` | `int MessageDialog(MessageDialogProps dialog);` | ok |
| `Modal` | `(title, message, cancelBtn, confirmBtn string) (int)` | `int Modal(const char *title, const char *message, const char *cancel_btn, const char *confirm_btn);` | ok |
| `Notebook` | `(props NotebookProps) (int32)` | `int Notebook(NotebookProps notebook);` | ok |
| `PanedView` | `(props PanedViewProps) (int32)` | `int PanedView(PanedViewProps panes);` | ok |
| `Paragraph` | `(spec ParagraphSpec, x int32, y *int32)` | `void Paragraph(ParagraphSpec paragraph, int x, int *y);` | ok |
| `Picture` | `(props PictureProps)` | `void Picture(PictureProps picture);` | ok |
| `Progress` | `(ProgressBarProps)` | `void Progress(ProgressBarProps progress);` | ok |
| `Radio` | `(props RadioButtonProps) (int32)` | `int Radio(RadioButtonProps radio);` | ok |
| `Rect` | `(int32, int32, int32, int32, Color, ...Color)` | `void Rect(int x, int y, int w, int h, Color fill, Color border);` | ok |
| `Row` | `(ColumnProps)` | `NodeId Row(RowProps props);` | ok |
| `Slider` | `(id, x, y, w int32, label string, min, max int32, value *int32, rest ...any) (bool)` | `int Slider(int id, int x, int y, int w, const char *label, int min, int max, int *value, const char *suffix, const char *value_text_override);` | ok |
| `SourceView` | `(props SourceViewProps) (int32)` | `int SourceView(SourceViewProps source);` | ok |
| `Spinbox` | `(props SpinboxProps) (bool)` | `int Spinbox(SpinboxProps spinbox);` | ok |
| `Stack` | `(ColumnProps)` | `NodeId Stack(ColumnProps props);` | ok |
| `TableView` | `(props TableViewProps) (int32)` | `int TableView(TableViewProps table);` | ok |
| `Text` | `(string, int32, int32, int32, Color)` | `void Text(const char *text, int x, int y, int font_size, Color color);` | ok |
| `TextArea` | `(props TextAreaProps) (bool)` | `int TextArea(TextAreaProps area);` | ok |
| `TextField` | `(TextFieldProps)` | `int TextField(TextFieldProps field);` | ok |
| `TextInRect` | `(text string, rect Rectangle, fontSize int32, color Color)` | `void TextInRect(const char *text, Rectangle rect, int font_size, Color color);` | ok |
| `TextLines` | `(lines any, count int32, x int32, y *int32, font, lineH int32, color Color)` | `void TextLines(const char **lines, int count, int x, int *y, int font, int line_h, Color color);` | ok |
| `TitleBar` | `(title string, height int32)` | `void TitleBar(const char *title, int height);` | ok |
| `Toggle` | `(id, x, y, w, h int32, value *int32, offLabel, onLabel string) (bool)` | `int Toggle(int id, int x, int y, int w, int h, int *value, const char *off_label, const char *on_label);` | ok |
| `Toolbar` | `(props ToolbarProps) (ToolbarResult)` | `ToolbarResult Toolbar(ToolbarProps toolbar);` | ok |
| `TopNav` | `(props TopNavProps)` | `TopNavResult TopNav(TopNavProps nav);` | ok |
## Generated Runtime Semantics
`tests/generated_runtime_parity_test.sh` transpiles the fixtures in `tests/parity/` through k2go, k2c, and k2js, rejects blocked generated output, drives all three generated runtimes through text editing, click-to-focus, focus traversal, selection replacement, secure clipboard copy, buttons, rows, columns, text areas, controls, list boxes, tables, and long-running text input with per-character cursor movement and Tab traversal, asserts generated Go emits renderable native frame operations without leaking secure text, renders those operations into visible pure-Go images, then diffs the final state JSON.
## Native Host Text Input
`go/kryon` tests run the native `Host` through thousands of text-input frames with cursor navigation on every typed character, Tab traversal between fields, stable frame operation counts, and bounded focus/selection bookkeeping.
+50
View File
@@ -0,0 +1,50 @@
# Widget Conformance
Kryon widgets must be tested at the runtime boundary, not only inside downstream
apps. Each widget family should have the same coverage shape:
1. Direct Go runtime tests in `go/kryon/*_test.go`.
These drive public widget APIs with `QueueTap`, `QueueText`, `QueueKey`,
focus, selection, and frame rendering. They catch native Go runtime bugs.
2. Generated runtime parity in `tests/generated_runtime_parity_test.sh`.
Fixtures in `tests/parity/*.kry` are lowered to Go, C, and JS, driven
through the same workflow, rendered where the target has a renderer in the
harness, and compared by final state JSON.
3. Backend or platform translation tests.
Backend event adapters must translate native events into the same public
input queue contracts. Example: `window_linux_test.go` verifies X11 keysyms
for printable text, Backspace, Enter, and shortcuts.
4. Performance harnesses for hot widgets.
Text input has `make perf-text-input`, which validates generated lowering and
measures retained-core C typing, backspace, selection replacement, tab
traversal, idle frames, and random-focus precision.
Required workflow coverage for editable widgets:
- click/tap focus
- focus switch between multiple fields
- printable text insertion
- Backspace and Delete
- Enter/commit
- Tab and Shift-Tab traversal
- selection replacement
- clipboard copy/cut/paste where supported
- secure text rendering does not leak plaintext
- Unicode cursor movement and deletion
- stable frame operation counts under long input
Required workflow coverage for collection widgets:
- single click selection
- double-click activation
- keyboard navigation
- scrolling
- context/right-click selection where supported
- selected item/cell rendering without unintended row or panel highlights
New widgets are not complete until their direct runtime test, generated parity
fixture or explicit unsupported note, backend event coverage where relevant, and
benchmark coverage for hot paths are present.
+5
View File
@@ -0,0 +1,5 @@
/*
Cache-Control: public, max-age=0, must-revalidate
/showcase-data.json
Cache-Control: public, max-age=0, must-revalidate
+57 -21
View File
@@ -6,33 +6,69 @@
<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="icon" type="image/png" sizes="16x16" href="icons/proj/kryon.png">
<link rel="apple-touch-icon" href="icons/proj/kryon.png">
<link rel="stylesheet" href="styles.css">
<script src="theme.js"></script>
</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>
<header class="site-header">
<div class="site-header-inner">
<a class="brand" href="index.html">
<img src="icons/proj/kryon.png" alt="Kryon" width="22" height="22">
<span>KRYON</span>
</a>
<button class="menu-toggle" type="button" aria-label="Open site menu" aria-expanded="false" aria-controls="header-nav">Menu</button>
<nav class="header-nav" id="header-nav" aria-label="Primary">
<a href="/">Home</a>
<a href="docs.html">Docs</a>
<a href="language.html">Language</a>
<a href="renderers.html">Renderers</a>
<a href="showcase.html">Showcase</a>
<a href="api.html">API</a>
<a href="ide.html">Playground</a>
<a class="btn btn-primary" href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">GitHub</a>
</nav>
</div>
</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">
<main class="wrap api-reference" style="padding: 32px 20px 60px;">
<p class="section-eyebrow">Reference</p>
<h1 style="margin-top: 0; font-size: 28px; border-bottom: 1px solid var(--line); padding-bottom: 10px;">API</h1>
<p class="section-lead" style="margin-bottom: 28px;">Runtime and widget surface, rendered from the canonical <code>docs/API.md</code>.</p>
{{ API_BODY }}
</main>
</main>
<footer>
<div class="footer-inner">
<div class="footer-brand">
<img src="icons/proj/kryon.png" alt="Kryon" width="20" height="20">
<span>KRYON</span>
</div>
<div class="footer-cols">
<div class="footer-col">
<h4>Kryon</h4>
<ul>
<li><a href="index.html#features">Features</a></li>
<li><a href="index.html#platforms">Platforms</a></li>
<li><a href="api.html">API reference</a></li>
</ul>
</div>
<div class="footer-col">
<h4>Ecosystem</h4>
<ul>
<li><a href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">GitHub ↗</a></li>
<li><a href="https://discord.gg/ep7gCWzHJD" target="_blank" rel="noopener">Discord ↗</a></li>
<li><a href="https://t.me/kryonlabs_com" target="_blank" rel="noopener">Telegram ↗</a></li>
</ul>
</div>
</div>
</div>
<div class="footer-bottom">
<p>&copy; 2026 Kryon Labs &middot; <a href="https://waozi.xyz" target="_blank" rel="noopener">Made by Waozi</a></p>
</div>
</footer>
<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>
+127
View File
@@ -0,0 +1,127 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kryon Benchmarks</title>
<meta name="description" content="Kryon compiler and runtime benchmark summaries generated from checked performance harnesses.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://kryonlabs.com/benchmarks.html">
<meta property="og:title" content="Kryon Benchmarks">
<meta property="og:description" content="Text-input latency and lowering benchmark summaries for Kryon.">
<meta name="theme-color" content="#f3f1ea">
<link rel="icon" type="image/png" sizes="16x16" href="icons/proj/kryon.png">
<link rel="apple-touch-icon" href="icons/proj/kryon.png">
<link rel="stylesheet" href="styles.css">
<script src="theme.js"></script>
</head>
<body>
<header class="site-header">
<div class="site-header-inner">
<a class="brand" href="/">
<img src="icons/proj/kryon.png" alt="Kryon" width="22" height="22">
<span>KRYON</span>
</a>
<button class="menu-toggle" type="button" aria-label="Open site menu" aria-expanded="false" aria-controls="header-nav">Menu</button>
<nav class="header-nav" id="header-nav" aria-label="Primary">
<a href="/">Home</a>
<a href="docs.html">Docs</a>
<a href="language.html">Language</a>
<a href="renderers.html">Renderers</a>
<a href="showcase.html">Showcase</a>
<a href="/api">API</a>
<a href="ide.html">Playground</a>
<a class="btn btn-primary" href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">GitHub</a>
</nav>
</div>
</header>
<main>
<section class="doc-hero">
<p class="section-eyebrow">Runtime Evidence</p>
<h1>Benchmarks</h1>
<p class="section-lead">The text-input harnesses measure one full retained UI frame per interaction: declare, reconcile, layout, route, and update. Rendering is GPU-side and not included in headless timings.</p>
</section>
<section>
<p class="section-eyebrow">Text Input</p>
<h2>Latest Generated Results</h2>
<p>Generate this page's data with:</p>
<pre><code>make perf-text-input-site</code></pre>
<div class="table-wrap">
<table class="matrix-table" id="benchmark-table">
<thead>
<tr><th>Benchmark</th><th>Scenario</th><th>Samples</th><th>p50</th><th>p95</th><th>p99</th><th>Max</th><th>Notes</th></tr>
</thead>
<tbody>
<tr><td colspan="8">Loading <code>benchmarks.json</code>.</td></tr>
</tbody>
</table>
</div>
<p id="benchmark-meta"></p>
</section>
<section>
<p class="section-eyebrow">Contracts</p>
<h2>What The Harness Covers</h2>
<ul class="link-list">
<li><strong>Lowering:</strong> <code>perf-text-input</code> validates KIR, C, Go, JS, and KRB outputs for the same <code>.kry</code> source.</li>
<li><strong>Retained typing:</strong> <code>text_input_perf_test</code> checks repeated keystroke frames under the retained UI core.</li>
<li><strong>Precision path:</strong> <code>text_input_precision_test</code> focuses random fields, sends one character or backspace, and verifies the edited text after each frame.</li>
</ul>
</section>
</main>
<footer>
<div class="footer-bottom">
<p>&copy; 2026 Kryon Labs &middot; <a href="index.html">Home</a> &middot; <a href="language.html">Language</a> &middot; <a href="matrices.html">Matrices</a></p>
</div>
</footer>
<script src="highlight.js"></script>
<script>
(function() {
var toggle = document.querySelector(".menu-toggle");
var nav = document.getElementById("header-nav");
if (toggle && nav) {
toggle.addEventListener("click", function() {
var open = nav.classList.toggle("is-open");
toggle.setAttribute("aria-expanded", open ? "true" : "false");
});
}
function fmt(v) {
return typeof v === "number" ? v.toFixed(3) + " us" : "";
}
fetch("benchmarks.json").then(function(r) {
if (!r.ok) throw new Error("missing benchmarks.json");
return r.json();
}).then(function(doc) {
var body = document.querySelector("#benchmark-table tbody");
var meta = document.getElementById("benchmark-meta");
body.innerHTML = "";
(doc.runs || []).forEach(function(run) {
var tr = document.createElement("tr");
var notes = [];
if (run.generated_contract) notes.push(run.generated_contract);
if (typeof run.mismatches === "number") notes.push("mismatches " + run.mismatches);
if (typeof run.focus_misses === "number") notes.push("focus misses " + run.focus_misses);
tr.innerHTML = "<td>" + (run.benchmark || "lowering") + "</td>" +
"<td>" + (run.scenario || run.generated_lowerings || "-") + "</td>" +
"<td>" + (run.samples || "-") + "</td>" +
"<td>" + fmt(run.p50_us) + "</td>" +
"<td>" + fmt(run.p95_us) + "</td>" +
"<td>" + fmt(run.p99_us) + "</td>" +
"<td>" + fmt(run.max_us) + "</td>" +
"<td>" + notes.join(", ") + "</td>";
body.appendChild(tr);
});
meta.textContent = doc.generated ? "Generated " + doc.generated + ". " + (doc.what || "") : "";
}).catch(function() {
var body = document.querySelector("#benchmark-table tbody");
body.innerHTML = "<tr><td colspan=\"8\">No generated benchmark data is checked in yet. Run <code>make perf-text-input-site</code> to create <code>docs/site/benchmarks.json</code>.</td></tr>";
});
})();
</script>
</body>
</html>
+149
View File
@@ -0,0 +1,149 @@
{
"generated": "2026-08-19T21:20:46.603953+00:00",
"what": "Text-input latency of the kryon retained core: one full declare/reconcile/layout/route/update frame per keystroke, so these are CPU-side microseconds - rendering is GPU-side and not included. Regenerate with: make perf-text-input-site",
"runs": [
{
"generated_lowerings": [
"kir",
"c",
"go",
"krb"
],
"generated_contract": "validated"
},
{
"runtime": "retained-core-c",
"scenario": "typing_burst",
"fields": 4,
"samples": 3000,
"warmup": 250,
"p50_us": 1.82,
"p95_us": 1.92,
"p99_us": 1.94,
"max_us": 8.62,
"mean_us": 1.73,
"full_frame_budget_us": 4000,
"input_budget_p99_us": 1000,
"node_delta": 0,
"mismatches": 0
},
{
"runtime": "retained-core-c",
"scenario": "backspace",
"fields": 4,
"samples": 3000,
"warmup": 250,
"p50_us": 0.47,
"p95_us": 0.53,
"p99_us": 0.71,
"max_us": 19.92,
"mean_us": 0.489,
"full_frame_budget_us": 4000,
"input_budget_p99_us": 1000,
"node_delta": 0,
"mismatches": 0
},
{
"runtime": "retained-core-c",
"scenario": "selection_replace",
"fields": 4,
"samples": 3000,
"warmup": 250,
"p50_us": 0.83,
"p95_us": 0.86,
"p99_us": 0.88,
"max_us": 7.3,
"mean_us": 0.835,
"full_frame_budget_us": 4000,
"input_budget_p99_us": 1000,
"node_delta": 0,
"mismatches": 0
},
{
"runtime": "retained-core-c",
"scenario": "tab_traversal",
"fields": 4,
"samples": 3000,
"warmup": 250,
"p50_us": 0.85,
"p95_us": 1.26,
"p99_us": 1.42,
"max_us": 16.5,
"mean_us": 0.897,
"full_frame_budget_us": 4000,
"input_budget_p99_us": 1000,
"node_delta": 0,
"mismatches": 0
},
{
"runtime": "retained-core-c",
"scenario": "idle_frame",
"fields": 4,
"samples": 3000,
"warmup": 250,
"p50_us": 0.39,
"p95_us": 0.42,
"p99_us": 0.44,
"max_us": 0.66,
"mean_us": 0.395,
"full_frame_budget_us": 4000,
"input_budget_p99_us": 1000,
"node_delta": 0,
"mismatches": 0
},
{
"runtime": "retained-core-c",
"benchmark": "text-input-precision",
"scenario": "random_single_char",
"fields": 64,
"samples": 4000,
"warmup": 200,
"p50_us": 7.58,
"p95_us": 7.68,
"p99_us": 7.73,
"max_us": 19.89,
"mean_us": 7.524,
"chars_typed": 3734,
"backspaces": 466,
"focus_misses": 0,
"mismatches": 0,
"node_delta": 0
},
{
"runtime": "retained-core-c",
"benchmark": "text-input-precision",
"scenario": "random_single_char_long_text",
"fields": 64,
"samples": 4000,
"warmup": 200,
"p50_us": 8.29,
"p95_us": 8.44,
"p99_us": 8.58,
"max_us": 12.79,
"mean_us": 8.233,
"chars_typed": 3734,
"backspaces": 466,
"focus_misses": 0,
"mismatches": 0,
"node_delta": 0
},
{
"runtime": "retained-core-c",
"benchmark": "text-input-precision",
"scenario": "random_focus",
"fields": 64,
"samples": 4000,
"warmup": 200,
"p50_us": 7.83,
"p95_us": 7.93,
"p99_us": 7.96,
"max_us": 12.14,
"mean_us": 7.839,
"chars_typed": 0,
"backspaces": 0,
"focus_misses": 0,
"mismatches": 0,
"node_delta": 0
}
]
}
+228
View File
@@ -0,0 +1,228 @@
(function() {
var summary = document.querySelector("[data-conformance-summary]");
var pipelineBody = document.querySelector("[data-conformance-pipelines]");
var rendererBody = document.querySelector("[data-conformance-renderers]");
var rendererCheckBody = document.querySelector("[data-conformance-renderer-checks]");
var visualComparisonBody = document.querySelector("[data-conformance-visual-comparisons]");
var runtimeCheckBody = document.querySelector("[data-conformance-runtime-checks]");
var downstreamCheckBody = document.querySelector("[data-conformance-downstream-checks]");
var sourceHead = document.querySelector("[data-conformance-source-head]");
var sourceBody = document.querySelector("[data-conformance-sources]");
var search = document.querySelector("[data-conformance-search]");
var typeFilter = document.querySelector("[data-conformance-type]");
var widgetBody = document.querySelector("[data-conformance-widgets]");
if (!summary || !pipelineBody || !rendererBody || !sourceBody) {
return;
}
function escapeText(value) {
return String(value == null ? "" : value)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
function cell(status) {
var cls = status.status_class || "na";
var title = [status.evidence, status.scope].filter(Boolean).join(" | ");
return '<td class="' + escapeText(cls) + '" title="' + escapeText(title) + '">' +
escapeText(status.status || "unknown") + "</td>";
}
function evidence(items) {
if (Array.isArray(items)) {
return items.map(function(item) {
return "<code>" + escapeText(item) + "</code>";
}).join(", ");
}
return escapeText(items || "");
}
function renderSummary(data) {
var s = data.summary;
summary.innerHTML = [
["Sources", s.source_cases],
["Examples", s.examples],
["Parity Fixtures", s.parity_fixtures],
["Pipeline Cells", s.pipeline_cells],
["KRB RGB Visual", s.krb_rgb_visual_cases],
["KRB Byte Exact", s.krb_alpha_byte_exact_cases],
["Raylib C Capture", s.raylib_c_visual_cases + " / " + s.source_cases],
["Raylib C Gaps", s.raylib_c_visual_gaps],
["Canvas C Capture", s.web_canvas_c_visual_cases + " / " + s.source_cases],
["Canvas C Gaps", s.web_canvas_c_visual_gaps],
["Libdraw C Capture", s.libdraw_c_visual_cases + " / " + s.source_cases],
["Libdraw C Gaps", s.libdraw_c_visual_gaps],
["Exact Comparisons", s.visual_comparison_exact_rows + " / " + s.visual_comparison_rows],
["Pending Comparisons", s.visual_comparison_pending_rows],
["Renderer Cells", s.renderer_source_cells],
["Renderer OK Cells", s.renderer_source_ok_cells],
["Renderer Partial Cells", s.renderer_source_partial_cells],
["State Parity", s.semantic_parity_cases],
["Widgets Covered", s.widgets_detected + " / " + s.widgets_declared],
["Widgets Missing", s.widgets_missing]
].map(function(item) {
return '<div class="matrix-stat"><span>' + escapeText(item[0]) + "</span><strong>" + escapeText(item[1]) + "</strong></div>";
}).join("");
}
function renderPipelines(data) {
pipelineBody.innerHTML = data.pipelines.map(function(row) {
return "<tr><td><code>" + escapeText(row.id) + "</code></td><td>" + escapeText(row.label) + "</td>" +
cell(row) + "<td>" + evidence(row.evidence) + "</td></tr>";
}).join("");
}
function renderRenderers(data) {
rendererBody.innerHTML = data.renderers.map(function(row) {
return "<tr><td>" + escapeText(row.label) + "</td><td>" + escapeText(row.platform) + "</td><td>" +
escapeText(row.approach) + "</td>" + cell(row) + "<td>" + evidence(row.evidence) + "</td><td>" +
escapeText(row.scope || "") + "</td><td>" + escapeText(row.notes) + "</td></tr>";
}).join("");
}
function renderRendererChecks(data) {
renderCheckRows(rendererCheckBody, data.renderer_checks);
}
function renderVisualComparisons(data) {
if (!visualComparisonBody) {
return;
}
visualComparisonBody.innerHTML = (data.visual_comparisons || []).map(function(row) {
return "<tr><td>" + escapeText(row.label) + "</td><td>" + escapeText(row.mode) +
"</td>" + cell(row) + "<td>" + escapeText(row.compared) + " / " +
escapeText(row.source_cases) + "</td><td>" + escapeText(row.gap_cases) +
" " + escapeText(row.gap_label) + "</td><td>" + evidence(row.evidence) +
"</td><td>" + escapeText(row.scope) + "</td></tr>";
}).join("");
}
function renderCheckRows(body, rows) {
if (!body) {
return;
}
body.innerHTML = (rows || []).map(function(row) {
return "<tr><td>" + escapeText(row.label) + "</td><td><code>" +
escapeText(row.command) + "</code></td><td>" + escapeText(row.scope) + "</td></tr>";
}).join("");
}
function pipelineCells(row) {
return pipelineColumns(window.__kryonConformanceData || null).map(function(pipeline) {
var id = pipeline.id || pipeline;
return cell(row.pipelines[id] || {status: "missing", status_class: "no"});
}).join("");
}
function pipelineColumns(data) {
return data && data.pipelines
? data.pipelines
: [{id: "k2kir"}, {id: "k2c"}, {id: "k2go"}, {id: "k2js"}, {id: "k2b"}];
}
function sourceRendererColumns(data) {
return data.source_renderers || [
{id: "krb_rgb", label: "KRB RGB"},
{id: "krb_alpha", label: "KRB Alpha"},
{id: "libdraw_c", label: "Libdraw C"}
];
}
function renderSourceHead(data) {
if (!sourceHead) {
return;
}
var rendererHeaders = sourceRendererColumns(data).map(function(renderer) {
return '<th title="' + escapeText(renderer.scope || "") + '">' + escapeText(renderer.label) + "</th>";
}).join("");
var pipelineHeaders = pipelineColumns(data).map(function(pipeline) {
return "<th>" + escapeText(pipeline.id || pipeline) + "</th>";
}).join("");
window.__kryonConformanceData = data;
sourceHead.innerHTML = "<th>Source</th><th>Type</th>" + pipelineHeaders +
rendererHeaders + "<th>Widgets</th><th>State Evidence</th>";
}
function sourceRendererCells(data, row) {
var matrix = row.renderer_matrix || row.visuals || {};
return sourceRendererColumns(data).map(function(renderer) {
return cell(matrix[renderer.id] || {status: "missing", status_class: "no"});
}).join("");
}
function renderSources(data) {
var q = (search && search.value || "").trim().toLowerCase();
var type = typeFilter && typeFilter.value || "all";
var rows = data.cases.filter(function(row) {
if (type !== "all" && row.type !== type) {
return false;
}
if (!q) {
return true;
}
return (row.path + " " + row.label + " " + row.widgets.join(" ")).toLowerCase().indexOf(q) !== -1;
});
sourceBody.innerHTML = rows.map(function(row) {
var widgets = row.widgets.length ? row.widgets.map(function(widget) {
return '<span class="matrix-chip">' + escapeText(widget) + "</span>";
}).join("") : '<span class="matrix-muted">No widget calls detected</span>';
return "<tr><td><code>" + escapeText(row.path) + "</code><br><span class=\"matrix-muted\">" +
escapeText(row.label) + "</span></td><td>" + escapeText(row.type) + "</td>" +
pipelineCells(row) + sourceRendererCells(data, row) + "<td>" + widgets + "</td><td>" +
escapeText(row.semantic_evidence) + "</td></tr>";
}).join("");
}
function renderWidgets(data) {
if (!widgetBody) {
return;
}
var widgets = (data.widget_coverage || []).slice().sort(function(a, b) {
return a.status_class.localeCompare(b.status_class) ||
b.source_count - a.source_count ||
a.id.localeCompare(b.id);
});
widgetBody.innerHTML = widgets.map(function(widget) {
var sources = widget.sources.length ? widget.sources.map(function(source) {
return "<code>" + escapeText(source) + "</code>";
}).join(", ") : '<span class="matrix-muted">No .kry source</span>';
var semantic = widget.semantic_sources.length ? widget.semantic_sources.map(function(source) {
return "<code>" + escapeText(source) + "</code>";
}).join(", ") : '<span class="matrix-muted">Lowering/visual only</span>';
return "<tr><td>" + escapeText(widget.id) + "</td>" + cell(widget) +
"<td>" + escapeText(widget.source_count) + "</td><td>" + sources +
"</td><td>" + semantic + "</td></tr>";
}).join("");
}
fetch("conformance-matrix.json")
.then(function(response) {
if (!response.ok) {
throw new Error("matrix fetch failed");
}
return response.json();
})
.then(function(data) {
renderSummary(data);
renderPipelines(data);
renderRenderers(data);
renderRendererChecks(data);
renderVisualComparisons(data);
renderCheckRows(runtimeCheckBody, data.runtime_checks);
renderCheckRows(downstreamCheckBody, data.downstream_checks);
renderSourceHead(data);
renderSources(data);
renderWidgets(data);
if (search) {
search.addEventListener("input", function() { renderSources(data); });
}
if (typeFilter) {
typeFilter.addEventListener("change", function() { renderSources(data); });
}
})
.catch(function() {
summary.innerHTML = '<p class="section-lead">The generated conformance matrix could not be loaded.</p>';
});
})();
File diff suppressed because it is too large. Load diff
+141
View File
@@ -0,0 +1,141 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kryon Docs</title>
<meta name="description" content="Kryon documentation organized by language, framework, runtime, renderer, and target surface.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://kryonlabs.com/docs.html">
<meta property="og:title" content="Kryon Docs">
<meta property="og:description" content="Documentation organized by language, framework, runtime, renderer, and target surface.">
<meta name="theme-color" content="#f3f1ea">
<link rel="icon" type="image/png" sizes="16x16" href="icons/proj/kryon.png">
<link rel="apple-touch-icon" href="icons/proj/kryon.png">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header class="site-header">
<div class="site-header-inner">
<a class="brand" href="/">
<img src="icons/proj/kryon.png" alt="Kryon" width="22" height="22">
<span>KRYON</span>
</a>
<button class="menu-toggle" type="button" aria-label="Open site menu" aria-expanded="false" aria-controls="header-nav">Menu</button>
<nav class="header-nav" id="header-nav" aria-label="Primary">
<a href="/">Home</a>
<a href="docs.html">Docs</a>
<a href="language.html">Language</a>
<a href="renderers.html">Renderers</a>
<a href="showcase.html">Showcase</a>
<a href="/api">API</a>
<a href="ide.html">Playground</a>
<a class="btn btn-primary" href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">GitHub</a>
</nav>
</div>
</header>
<main id="top">
<section class="doc-hero">
<p class="section-eyebrow">Documentation</p>
<h1>Kryon docs by language and framework</h1>
<p class="section-lead">A focused map for the Kryon stack: source language, generated C, Go-facing helpers, KRB cartridges, renderer backends, and target surfaces.</p>
</section>
<section>
<div class="tabs" data-tabs>
<div class="tablist" role="tablist" aria-label="Kryon documentation sections">
<button type="button" role="tab" id="docs-tab-language" aria-selected="true" aria-controls="docs-panel-language">.kry language</button>
<button type="button" role="tab" id="docs-tab-c" aria-selected="false" aria-controls="docs-panel-c" tabindex="-1">C runtime</button>
<button type="button" role="tab" id="docs-tab-web" aria-selected="false" aria-controls="docs-panel-web" tabindex="-1">KRB artifacts</button>
<button type="button" role="tab" id="docs-tab-renderers" aria-selected="false" aria-controls="docs-panel-renderers" tabindex="-1">Renderers</button>
<button type="button" role="tab" id="docs-tab-platforms" aria-selected="false" aria-controls="docs-panel-platforms" tabindex="-1">Targets</button>
</div>
<div class="tabpanel is-active" id="docs-panel-language" role="tabpanel" aria-labelledby="docs-tab-language">
<h3>.kry language</h3>
<p>Source syntax, typed declarations, UI functions, KIR lowering, compile-time checks, and source-aware diagnostics.</p>
<ul class="link-list">
<li><strong><a href="language.html">Language reference</a></strong> — the primary .kry language documentation</li>
<li><strong><a href="live-examples.html">Live examples</a></strong> — browser-rendered example coverage</li>
</ul>
</div>
<div class="tabpanel" id="docs-panel-c" role="tabpanel" aria-labelledby="docs-tab-c" hidden>
<h3>C runtime</h3>
<p>Generated C, exported runtime symbols, widget APIs, app shell behavior, and source/runtime boundaries.</p>
<ul class="link-list">
<li><strong><a href="/api">API reference</a></strong> — generated API documentation from `docs/API.md`</li>
<li><strong><a href="matrices.html">Widget and compiler matrices</a></strong> — coverage status for UI and compiler surfaces</li>
</ul>
</div>
<div class="tabpanel" id="docs-panel-web" role="tabpanel" aria-labelledby="docs-tab-web" hidden>
<h3>KRB artifacts</h3>
<p>Portable KRB cartridges, preview tools, and runtime artifacts used by hosted builds.</p>
<ul class="link-list">
<li><strong><a href="ide.html">Playground</a></strong> — edit .kry and inspect browser output</li>
<li><strong><a href="benchmarks.html">Benchmarks</a></strong> — lowering and generated text-input performance data</li>
</ul>
</div>
<div class="tabpanel" id="docs-panel-renderers" role="tabpanel" aria-labelledby="docs-tab-renderers" hidden>
<h3>Renderers</h3>
<p>Backend capability coverage for native, browser, terminal, libdraw, KRB, and constrained host work.</p>
<ul class="link-list">
<li><strong><a href="renderers.html">Renderer matrices</a></strong> — current backend and host capability coverage</li>
<li><strong><a href="matrices.html">Feature matrices</a></strong> — language, widget, and runtime coverage</li>
</ul>
</div>
<div class="tabpanel" id="docs-panel-platforms" role="tabpanel" aria-labelledby="docs-tab-platforms" hidden>
<h3>Targets</h3>
<p>Desktop, mobile, FreeBSD, Plan 9, embedded, and microcontroller-facing runtime notes.</p>
<ul class="link-list">
<li><strong><a href="renderers.html">Renderer matrices</a></strong> — platform-specific backend capabilities</li>
<li><strong><a href="showcase.html">Showcase</a></strong> — real projects using Kryon</li>
</ul>
</div>
</div>
</section>
</main>
<footer>
<div class="footer-bottom">
<p>&copy; 2026 Kryon Labs &middot; <a href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">Kryon source</a></p>
</div>
</footer>
<script>
(function() {
var toggle = document.querySelector(".menu-toggle");
var nav = document.getElementById("header-nav");
if (toggle && nav) {
toggle.addEventListener("click", function() {
var open = nav.classList.toggle("is-open");
toggle.setAttribute("aria-expanded", open ? "true" : "false");
});
}
document.querySelectorAll("[data-tabs]").forEach(function(group) {
var tabs = group.querySelectorAll("[role=tab]");
tabs.forEach(function(tab) {
tab.addEventListener("click", function() {
tabs.forEach(function(t) {
var selected = t === tab;
t.setAttribute("aria-selected", selected ? "true" : "false");
t.tabIndex = selected ? 0 : -1;
});
group.querySelectorAll(".tabpanel").forEach(function(panel) {
var active = panel.id === tab.getAttribute("aria-controls");
panel.classList.toggle("is-active", active);
if (active) panel.removeAttribute("hidden");
else panel.setAttribute("hidden", "");
});
});
});
});
})();
</script>
</body>
</html>
+1 -1
View File
@@ -1,6 +1,6 @@
(function() {
var keywords = /\b(return|if|else|while|for|int|float|void|const|static|typedef|struct|enum|include|define|draw|native)\b|#\b(module|output|import|enum|global|export|private|extern|intrinsic|type)\b/g;
var types = /\b(Color|Rectangle|Texture2D|Camera2D|UIPanelFrame|UITextField|UILabelTextField|Font)\b/g;
var types = /\b(Color|Rectangle|Texture2D|Camera2D|UIPanelFrame|Font)\b/g;
var functions = /\b([A-Za-z_][A-Za-z0-9_]*)\s*(?=\()/g;
var strings = /("([^"\\]|\\.)*"|'([^'\\]|\\.)*')/g;
var comments = /(\/\/[^\n]*|\/\*[\s\S]*?\*\/)/g;
Binary file not shown.

After

Width:  |  Height:  |  Size: 354 B

+101
View File
@@ -0,0 +1,101 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kryon Playground</title>
<meta name="description" content="Edit .kry files in the browser, compile with Kryon WASM tools, and preview the generated KRB cartridge from one place.">
<link rel="icon" type="image/png" sizes="16x16" href="icons/proj/kryon.png">
<link rel="stylesheet" href="styles.css">
<script src="theme.js"></script>
</head>
<body class="ide-page">
<header class="site-header">
<div class="site-header-inner">
<a class="brand" href="index.html">
<img src="icons/proj/kryon.png" alt="Kryon" width="22" height="22">
<span>KRYON</span>
</a>
<button class="menu-toggle" type="button" aria-label="Open site menu" aria-expanded="false" aria-controls="header-nav">Menu</button>
<nav class="header-nav" id="header-nav" aria-label="Primary">
<a href="/">Home</a>
<a href="docs.html">Docs</a>
<a href="language.html">Language</a>
<a href="renderers.html">Renderers</a>
<a href="showcase.html">Showcase</a>
<a href="api.html">API</a>
<a href="ide.html">Playground</a>
<a class="btn btn-primary" href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">GitHub</a>
</nav>
</div>
</header>
<main class="web-ide" data-kryon-web-ide>
<section class="ide-shell">
<div class="ide-toolbar">
<div>
<p class="section-eyebrow">Kryon Playground</p>
<h1>Write, compile, and preview .kry</h1>
</div>
<div class="ide-actions">
<button class="btn" type="button" data-action="load-sample">Sample</button>
<button class="btn btn-primary" type="button" data-action="compile">Run</button>
</div>
</div>
<div class="ide-grid">
<div class="ide-pane source-pane">
<div class="pane-title">
<span>app.kry</span>
<span data-status>Loading compiler...</span>
</div>
<textarea spellcheck="false" data-source>#import "kryon.h"
app "Kryon Web IDE" {
size 800 520
}
App :: () #ui {
Screen root: {
Background((Color){249, 246, 235, 255})
Rect(48, 42, 704, 390, (Color){255, 254, 249, 255})
Text("Hello from .kry", 76, 86, Text24, (Color){31, 83, 102, 255})
Text("This page runs k2kir and k2b as WebAssembly, then renders the KRB cartridge.", 76, 134, Text16, (Color){42, 59, 64, 255})
Rect(76, 188, 292, 80, (Color){35, 101, 125, 255})
Text("Portable preview", 104, 219, Text20, WHITE)
Button((ButtonProps){.bounds = {76, 308, 184, 44}, .label = "Get started"})
}
}</textarea>
</div>
<div class="ide-pane preview-pane">
<div class="pane-title">
<span>Live KRB Preview</span>
<span data-preview-status>waiting</span>
</div>
<canvas width="800" height="520" data-preview></canvas>
</div>
<div class="ide-pane artifact-pane">
<div class="artifact-tabs" role="tablist" aria-label="Generated artifacts">
<button type="button" class="is-active" data-tab="kry">.kry</button>
<button type="button" data-tab="kir">KIR</button>
<button type="button" data-tab="c">C</button>
<button type="button" data-tab="go">Go</button>
<button type="button" data-tab="js">JS</button>
<button type="button" data-tab="krb">KRB</button>
</div>
<pre class="artifact-output"><code data-artifact></code></pre>
</div>
</div>
</section>
</main>
<script src="ide-tools/k2kir.js"></script>
<script src="ide-tools/k2b.js"></script>
<script src="ide-tools/k2c.js"></script>
<script src="ide-tools/k2go.js"></script>
<script src="ide-tools/k2js.js"></script>
<script src="ide.js"></script>
</body>
</html>
+438
View File
@@ -0,0 +1,438 @@
(function() {
"use strict";
var source = document.querySelector("[data-source]");
var status = document.querySelector("[data-status]");
var previewStatus = document.querySelector("[data-preview-status]");
var canvas = document.querySelector("[data-preview]");
var artifact = document.querySelector("[data-artifact]");
var tabButtons = Array.prototype.slice.call(document.querySelectorAll("[data-tab]"));
var compileButton = document.querySelector("[data-action='compile']");
var sampleButton = document.querySelector("[data-action='load-sample']");
var menuToggle = document.querySelector(".menu-toggle");
var headerNav = document.getElementById("header-nav");
var k2kirMod = null;
var k2bMod = null;
var k2cMod = null;
var k2goMod = null;
var k2jsMod = null;
var activeTab = "kry";
var last = { kry: "", kir: "", krb: "", c: "", go: "", js: "", bytes: null };
var compileTimer = 0;
var sample = [
"#import \"kryon.h\"",
"",
"app \"Kryon Web IDE\" {",
" size 800 520",
"}",
"",
"App :: () #ui {",
" Screen root: {",
" Background((Color){249, 246, 235, 255})",
" Rect(48, 42, 704, 390, (Color){255, 254, 249, 255})",
" Text(\"Hello from .kry\", 76, 86, Text24, (Color){31, 83, 102, 255})",
" Text(\"This page runs k2kir and k2b as WebAssembly, then renders the KRB cartridge.\", 76, 134, Text16, (Color){42, 59, 64, 255})",
" Rect(76, 188, 292, 80, (Color){35, 101, 125, 255})",
" Text(\"Portable preview\", 104, 219, Text20, WHITE)",
" Button((ButtonProps){.bounds = {76, 308, 184, 44}, .label = \"Get started\"})",
" }",
"}"
].join("\n");
source.value = sample;
if (menuToggle && headerNav) {
menuToggle.addEventListener("click", function() {
var open = headerNav.classList.toggle("is-open");
menuToggle.setAttribute("aria-expanded", open ? "true" : "false");
});
}
function setStatus(text) {
if (status) status.textContent = text;
}
function setPreviewStatus(text) {
if (previewStatus) previewStatus.textContent = text;
}
function ensureDir(mod, path) {
var parts = path.split("/");
var cur = "";
for (var i = 0; i < parts.length; i++) {
if (!parts[i]) continue;
cur += "/" + parts[i];
try {
mod.FS.mkdir(cur);
} catch (e) {
if (!String(e).match(/File exists|ErrnoError/)) throw e;
}
}
}
function resetFs(mod) {
["/work", "/work/src", "/work/out"].forEach(function(path) {
try { mod.FS.rmdir(path); } catch (e) {}
});
ensureDir(mod, "/work/src");
ensureDir(mod, "/work/out");
}
function runTool(mod, args, reader) {
var rc;
if (!mod) return { ok: false, text: "Compiler module unavailable." };
try {
resetFs(mod);
mod.FS.writeFile("/work/src/app.kry", source.value);
rc = mod.callMain(args);
if (rc && rc !== 0) throw new Error("compiler exited with " + rc);
return reader(mod);
} catch (e) {
return { ok: false, text: String(e && e.stack ? e.stack : e) };
}
}
function readMaybe(mod, path, binary) {
try {
return mod.FS.readFile(path, binary ? { encoding: "binary" } : { encoding: "utf8" });
} catch (e) {
return binary ? new Uint8Array(0) : "";
}
}
function readFirst(mod, paths, binary) {
for (var i = 0; i < paths.length; i++) {
var value = readMaybe(mod, paths[i], binary);
if (binary ? value.length > 0 : value !== "") return value;
}
return binary ? new Uint8Array(0) : "";
}
function hex(bytes) {
var out = [];
for (var i = 0; i < bytes.length; i += 16) {
var line = ("00000000" + i.toString(16)).slice(-8) + " ";
for (var j = 0; j < 16; j++) {
line += i + j < bytes.length ? ("0" + bytes[i + j].toString(16)).slice(-2) + " " : " ";
}
out.push(line);
}
return out.join("\n");
}
function readU16(dv, off) {
return dv.getUint16(off, true);
}
function readI16(dv, off) {
return dv.getInt16(off, true);
}
function readU32(dv, off) {
return dv.getUint32(off, true);
}
function cstr(bytes, off, max) {
var end = off;
while (end < max && bytes[end] !== 0) end++;
return new TextDecoder().decode(bytes.slice(off, end));
}
function rgba(u32) {
if ((u32 & 0xffffff00) === 0x80000000) {
var slot = u32 & 0xff;
if (slot === 0) return "rgb(247,244,236)";
if (slot === 1) return "rgb(42,59,64)";
if (slot === 2) return "rgb(31,83,102)";
if (slot === 3) return "rgb(255,254,249)";
if (slot === 4) return "rgb(35,101,125)";
return "rgb(247,244,236)";
}
return "rgba(" + ((u32 >> 24) & 255) + "," + ((u32 >> 16) & 255) + "," + ((u32 >> 8) & 255) + "," + ((u32 & 255) / 255).toFixed(3) + ")";
}
function appSize() {
var m = source.value.match(/\bapp\b[\s\S]*?\{[\s\S]*?\bsize\s+([0-9]+)\s+([0-9]+)/);
var w = m ? parseInt(m[1], 10) : 800;
var h = m ? parseInt(m[2], 10) : 520;
if (!isFinite(w) || w <= 0) w = 800;
if (!isFinite(h) || h <= 0) h = 520;
return { width: Math.min(w, 4096), height: Math.min(h, 4096) };
}
function decodeKrb(bytes) {
if (!bytes || bytes.length < 32) throw new Error("KRB is empty");
var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
if (readU32(dv, 0) !== 0x0042524b) throw new Error("KRB magic mismatch");
var nodeCount = readU32(dv, 8);
var stringBytes = readU32(dv, 12);
var nodeOff = 32;
var strOff = nodeOff + nodeCount * 28;
var nodes = [];
for (var i = 0; i < nodeCount; i++) {
var off = nodeOff + i * 28;
nodes.push({
id: readU16(dv, off),
parent: readI16(dv, off + 2),
name: cstr(bytes, strOff + readU16(dv, off + 4), strOff + stringBytes),
type: bytes[off + 6],
flags: bytes[off + 7],
bind: readU16(dv, off + 8),
x: readI16(dv, off + 10),
y: readI16(dv, off + 12),
w: readI16(dv, off + 14),
h: readI16(dv, off + 16),
color: readU32(dv, off + 18),
text: cstr(bytes, strOff + readU16(dv, off + 22), strOff + stringBytes),
font: readU16(dv, off + 24) || 16,
style: bytes[off + 26]
});
}
return nodes;
}
function coord(v, full, scaled) {
return scaled ? Math.round(full * v / 10000) : v;
}
function drawRound(ctx, x, y, w, h, r) {
r = Math.max(0, Math.min(r, w / 2, h / 2));
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function fitCanvas(size) {
if (canvas.width !== size.width) canvas.width = size.width;
if (canvas.height !== size.height) canvas.height = size.height;
canvas.style.aspectRatio = size.width + " / " + size.height;
canvas.style.setProperty("--preview-aspect", String(size.width / size.height));
}
function drawText(ctx, text, x, y, font, color) {
ctx.fillStyle = color;
ctx.font = "600 " + Math.max(8, font) + "px system-ui, -apple-system, sans-serif";
ctx.textBaseline = "top";
ctx.fillText(text || "", x, y);
}
function drawButton(ctx, n, x, y, w, h) {
var fill = n.style === 2 ? "rgb(184,59,59)" : (n.style === 0 ? "rgb(35,101,125)" : "rgb(255,254,249)");
var label = n.style === 0 || n.style === 2 ? "rgb(255,255,255)" : "rgb(42,59,64)";
ctx.fillStyle = fill;
drawRound(ctx, x, y, w, h, 4);
ctx.fill();
ctx.strokeStyle = "rgba(31,83,102,0.55)";
ctx.lineWidth = 1;
ctx.stroke();
ctx.font = "700 " + Math.max(8, n.font || 16) + "px system-ui, -apple-system, sans-serif";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = label;
ctx.fillText(n.text || n.name || "Button", x + w / 2, y + h / 2);
ctx.textAlign = "start";
ctx.textBaseline = "top";
}
function render(bytes) {
var size = appSize();
var nodes = decodeKrb(bytes);
var ctx = canvas.getContext("2d");
fitCanvas(size);
ctx.clearRect(0, 0, size.width, size.height);
ctx.fillStyle = "#f3f1ea";
ctx.fillRect(0, 0, size.width, size.height);
nodes.forEach(function(n) {
var x = coord(n.x, size.width, n.flags & 4);
var y = coord(n.y, size.height, n.flags & 8);
var w = coord(n.w, size.width, n.flags & 16);
var h = coord(n.h, size.height, n.flags & 32);
var color = rgba(n.color);
switch (n.type) {
case 1:
ctx.fillStyle = color;
ctx.fillRect(0, 0, w || size.width, h || size.height);
break;
case 2:
drawText(ctx, n.text, x, y, n.font || 16, color);
break;
case 3:
ctx.fillStyle = color;
ctx.fillRect(x, y, w, h);
break;
case 4:
drawButton(ctx, n, x, y, w, h);
break;
case 7:
case 8:
case 13:
ctx.fillStyle = "rgb(255,254,249)";
ctx.fillRect(x, y, w, h);
ctx.strokeStyle = "rgba(31,83,102,0.55)";
ctx.strokeRect(x, y, w, h);
if (n.text) drawText(ctx, n.text, x + w + 6, y, n.font || 16, color);
break;
case 10:
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, Math.max(0, w), 0, Math.PI * 2);
ctx.fill();
break;
case 11:
ctx.strokeStyle = color;
ctx.lineWidth = Math.max(1, w - Math.max(0, h));
ctx.beginPath();
ctx.arc(x, y, Math.max(0, (w + h) / 2), 0, Math.PI * 2);
ctx.stroke();
ctx.lineWidth = 1;
break;
default:
break;
}
});
setPreviewStatus("canvas backend");
}
function showArtifact() {
artifact.textContent = last[activeTab] || "";
}
function compile() {
var passed = 0;
var failed = 0;
var result;
if (!k2kirMod || !k2bMod) return;
setStatus("compiling...");
last = { kry: source.value, kir: "", krb: "", c: "", go: "", js: "", bytes: null };
result = runTool(k2kirMod, ["--root", "/work", "-o", "/work/out", "/work/src/app.kry"], function(mod) {
return { ok: true, text: readFirst(mod, ["/work/out/app.kir", "/work/out/src/app.kir"], false) };
});
if (result.ok && result.text) { last.kir = result.text; passed++; } else { last.kir = result.text || "KIR output unavailable."; failed++; }
result = runTool(k2cMod, ["--no-main", "--root", "/work", "-o", "/work/out", "/work/src/app.kry"], function(mod) {
var files = [];
var appC = readFirst(mod, ["/work/out/src/app.c", "/work/out/app.c"], false);
var appH = readFirst(mod, ["/work/out/src/app.h", "/work/out/app.h"], false);
var projectC = readMaybe(mod, "/work/out/kryon_project.c", false);
if (appC) files.push("/* app.c */\n" + appC);
if (appH) files.push("/* app.h */\n" + appH);
if (projectC) files.push("/* kryon_project.c */\n" + projectC);
return { ok: files.length > 0, text: files.join("\n\n") || "C output unavailable." };
});
if (result.ok) { last.c = result.text; passed++; } else { last.c = result.text; failed++; }
result = runTool(k2goMod, ["--no-main", "--pkg", "kryexample", "--root", "/work", "-o", "/work/out", "/work/src/app.kry"], function(mod) {
return { ok: true, text: readFirst(mod, ["/work/out/app.go", "/work/out/src/app.go"], false) };
});
if (result.ok && result.text) { last.go = result.text; passed++; } else { last.go = result.text || "Go output unavailable."; failed++; }
result = runTool(k2jsMod, ["--no-main", "--root", "/work", "-o", "/work/out", "/work/src/app.kry"], function(mod) {
return { ok: true, text: readFirst(mod, ["/work/out/app.js", "/work/out/src/app.js"], false) };
});
if (result.ok && result.text) { last.js = result.text; passed++; } else { last.js = result.text || "JS output unavailable."; failed++; }
result = runTool(k2bMod, ["--no-main", "--root", "/work", "-o", "/work/out", "/work/src/app.kry"], function(mod) {
var bytes = readFirst(mod, ["/work/out/app.krb", "/work/out/src/app.krb"], true);
return { ok: bytes.length > 0, bytes: bytes, text: "KRB bytes: " + bytes.length + "\n\n" + hex(bytes) };
});
if (result.ok) {
last.bytes = result.bytes;
last.krb = result.text;
passed++;
try {
render(last.bytes);
} catch (e) {
setPreviewStatus(String(e && e.message ? e.message : e).slice(0, 80));
failed++;
}
} else {
last.krb = result.text || "KRB output unavailable.";
setPreviewStatus("no KRB preview");
failed++;
}
showArtifact();
setStatus(failed ? "compiled " + passed + "/5" : "compiled");
}
function scheduleCompile() {
window.clearTimeout(compileTimer);
compileTimer = window.setTimeout(compile, 260);
}
function loadInitialSource() {
var params = new URLSearchParams(window.location.search);
var src = params.get("src");
if (!src) {
source.value = sample;
return Promise.resolve();
}
setStatus("fetching source...");
return fetch(src).then(function(res) {
if (!res.ok) throw new Error("Could not fetch " + src + ": " + res.status);
return res.text();
}).then(function(text) {
source.value = text;
}).catch(function(err) {
source.value = sample;
artifact.textContent = String(err);
});
}
function boot() {
if (typeof createK2irModule !== "function" || typeof createK2bModule !== "function" ||
typeof createK2cModule !== "function" || typeof createK2gModule !== "function" ||
typeof createK2jsModule !== "function") {
setStatus("compiler unavailable");
artifact.textContent = "The web compiler assets were not built.";
return;
}
Promise.all([
createK2irModule({ noInitialRun: true }),
createK2bModule({ noInitialRun: true }),
createK2cModule({ noInitialRun: true }),
createK2gModule({ noInitialRun: true }),
createK2jsModule({ noInitialRun: true })
]).then(function(mods) {
k2kirMod = mods[0];
k2bMod = mods[1];
k2cMod = mods[2];
k2goMod = mods[3];
k2jsMod = mods[4];
return loadInitialSource();
}).then(function() {
setStatus("ready");
compile();
}).catch(function(err) {
setStatus("error");
artifact.textContent = String(err && err.stack ? err.stack : err);
});
}
tabButtons.forEach(function(btn) {
btn.addEventListener("click", function() {
activeTab = btn.getAttribute("data-tab");
tabButtons.forEach(function(b) { b.classList.toggle("is-active", b === btn); });
showArtifact();
});
});
source.addEventListener("input", scheduleCompile);
compileButton.addEventListener("click", compile);
sampleButton.addEventListener("click", function() {
source.value = sample;
compile();
});
boot();
})();
+154 -156
View File
@@ -3,178 +3,176 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kryon - Native Cross-Platform App and Game Development</title>
<meta name="description" content="Native cross-platform app and game development with .kry, human-readable C99 output, a full native widget toolkit, and an interactive AI-native IDE.">
<title>Kryon</title>
<meta name="description" content="Kryon is a language, runtime, and native UI framework for small app development.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://kryonlabs.com/">
<meta property="og:title" content="Kryon - Native Cross-Platform App and Game Development">
<meta property="og:description" content="Native cross-platform app and game development with .kry, human-readable C99 output, a full native widget toolkit, and an interactive AI-native IDE.">
<meta property="og:title" content="Kryon">
<meta property="og:description" content="A language, runtime, and native UI framework for small app development.">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:url" content="https://kryonlabs.com/">
<meta name="twitter:title" content="Kryon - Native Cross-Platform App and Game Development">
<meta name="twitter:description" content="Native cross-platform app and game development in .kry with readable C99 output.">
<meta name="twitter:title" content="Kryon">
<meta name="twitter:description" content="A language, runtime, and native UI framework for small app development.">
<meta name="twitter:site" content="@kryonlabs">
<meta name="twitter:creator" content="@kryonlabs">
<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="icon" type="image/png" sizes="16x16" href="icons/proj/kryon.png">
<link rel="apple-touch-icon" href="icons/proj/kryon.png">
<link rel="stylesheet" href="styles.css">
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "SoftwareApplication",
"name": "Kryon",
"description": "Native declarative UI and app runtime. Write .kry, inspect KIR, ship readable C99 or portable KRB cartridges.",
"url": "https://kryonlabs.com",
"applicationCategory": "DeveloperApplication",
"operatingSystem": "Linux, Windows, macOS, Android, Browser, FreeBSD",
"offers": {"@type": "Offer", "price": "0", "priceCurrency": "USD"},
"author": {"@type": "Organization", "name": "Kryon Labs", "url": "https://kryonlabs.com"}
}
</script>
<script src="theme.js"></script>
</head>
<body>
<div class="content">
<header class="hero">
<img class="hero-icon" src="icons/kryon.png" width="128" height="128" alt="Kryon">
<h1>KRYON</h1>
<p class="tagline">Native cross-platform app and game development</p>
<p class="tagline-detail">Write .kry &bull; Translate to readable C99 &bull; Build visually with an AI-native IDE</p>
</header>
<header class="site-header">
<div class="site-header-inner">
<a class="brand" href="/">
<img src="icons/proj/kryon.png" alt="Kryon" width="22" height="22">
<span>KRYON</span>
</a>
<button class="menu-toggle" type="button" aria-label="Open site menu" aria-expanded="false" aria-controls="header-nav">Menu</button>
<nav class="header-nav" id="header-nav" aria-label="Primary">
<a href="docs.html">Docs</a>
<a href="language.html">Language</a>
<a href="renderers.html">Renderers</a>
<a href="showcase.html">Showcase</a>
<a href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">GitHub</a>
<a class="btn btn-primary" href="ide.html">Playground</a>
</nav>
</div>
</header>
<nav class="site-nav" aria-label="Primary">
<a href="#about">About</a>
<a href="#goals">Goals</a>
<a href="#features">Features</a>
<a href="#philosophy">Philosophy</a>
<a href="#platforms">Platforms</a>
<a href="#start">Start</a>
<a href="api.html">API</a>
</nav>
<main>
<section id="about">
<h2>What is Kryon?</h2>
<p>Kryon is a native app and game development stack built around .kry source files, a small runtime, and clean translation to human-readable C99.</p>
<p>The Kryon IDE is built around the same source model: open a project or file path, edit .kry directly, see a live preview, and click a widget to jump back to the source line that generated it.</p>
</section>
<section id="goals">
<h2>Goals</h2>
<div class="goal-list">
<article class="goal">
<h3>Native Cross-Platform</h3>
<p>One source model for desktop, mobile, browser, and embedded targets, with platform behavior exposed as first-class Kryon features.</p>
</article>
<article class="goal">
<h3>Readable C99</h3>
<p>.kry translates to plain, inspectable C99 that can be built, debugged, and shipped by normal C toolchains.</p>
</article>
<article class="goal">
<h3>Full Native UI</h3>
<p>The widget toolkit should cover real product interfaces: layout, text, inputs, navigation, overlays, inspection, themes, and runtime assets.</p>
</article>
<article class="goal">
<h3>AI-Native IDE</h3>
<p>The IDE should make visual app and game development direct: live preview, source-aware inspection, diagnostics, and agent-assisted edits in one loop.</p>
</article>
<main id="top">
<section class="hero lab-hero">
<div class="hero-inner">
<span class="hero-eyebrow"><span class="dot"></span>Language and native UI framework</span>
<img class="hero-icon" src="icons/proj/kryon.png" width="84" height="84" alt="Kryon">
<h1>Kryon</h1>
<p class="hero-sub">A compact app language, runtime, and renderer stack for building small native interfaces across desktop, web, and embedded targets.</p>
<div class="hero-cta">
<a class="btn btn-primary" href="docs.html">Read docs</a>
<a class="btn" href="showcase.html">Open showcase</a>
</div>
</section>
</div>
</section>
<section id="features">
<h2>Core Features</h2>
<div class="grid">
<article class="feature">
<img src="icons/text.png" width="48" height="48" alt="">
<h3>Widget-Focused .kry</h3>
<p>Pages and reusable widgets stay in concise source files with explicit typed variables and direct compiler errors for unknown syntax.</p>
</article>
<article class="feature">
<img src="icons/c.png" width="48" height="48" alt="">
<h3>Clean C Output</h3>
<p>The compiler emits normal C and generated headers. Kry-to-Kry calls use compile-time modules, while C interop stays explicit.</p>
</article>
<article class="feature">
<img src="icons/globe.png" width="48" height="48" alt="">
<h3>Live Preview</h3>
<p>Hot reload rebuilds real .kry output, keeps the last good state during compilation, and shows diagnostics when the build fails.</p>
</article>
<article class="feature">
<img src="icons/wrench.png" width="48" height="48" alt="">
<h3>Source-Aware Inspection</h3>
<p>Preview widgets carry source metadata, so inspection clicks select the generated UI element and open the exact .kry line.</p>
</article>
<section class="replaces">
<div class="label">Development surface</div>
<div class="pills">
<span class="pill">.kry language</span>
<span class="pill">C runtime</span>
<span class="pill">KIR</span>
<span class="pill">KRB cartridges</span>
<span class="pill">renderer backends</span>
<span class="pill">app storage</span>
</div>
</section>
<section id="framework">
<p class="section-eyebrow">Framework</p>
<h2>Language, runtime, renderers</h2>
<p class="section-lead">Kryon keeps app code small while still exposing the lower-level surfaces needed for serious native development.</p>
<div class="why-grid">
<article class="why-card">
<h3><a href="language.html">Language</a></h3>
<p>Write declarative .kry interfaces, compile through KIR, and generate C, JavaScript, or portable runtime artifacts.</p>
</article>
<article class="why-card">
<h3><a href="docs.html">Framework docs</a></h3>
<p>Use the C runtime, app shell, storage, update, assets, windows, markdown, and automation APIs from one organized reference.</p>
</article>
<article class="why-card">
<h3><a href="renderers.html">Renderer backends</a></h3>
<p>Target raylib, Canvas, DOM, terminal cells, libdraw, and headless test backends from the same UI model.</p>
</article>
</div>
</section>
<section id="showcase">
<p class="section-eyebrow">Showcase</p>
<h2>Apps built with Kryon</h2>
<p class="section-lead">The homepage stays focused on Kryon itself. The showcase page is where first-party and community apps can be browsed with real screenshots and GitHub stars.</p>
<div class="hero-cta">
<a class="btn btn-primary" href="showcase.html">Browse showcase</a>
<a class="btn" href="https://github.com/kryonlabs/showcase/pulls/new?template=PULL_REQUEST_TEMPLATE.md" target="_blank" rel="noopener">Submit pull request</a>
</div>
</section>
<section id="links">
<p class="section-eyebrow">Development</p>
<h2>Source, docs, and related systems</h2>
<ul class="link-list">
<li><strong><a href="/api">API reference</a></strong> - generated C API documentation</li>
<li><strong><a href="ide.html">Playground</a></strong> - browser tools for trying Kryon source and artifacts</li>
<li><strong><a href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">Kryon source</a></strong> - compiler, runtime, docs, and release history</li>
<li><strong><a href="https://daochi.net" target="_blank" rel="noopener">Daochi</a></strong> - independent sync project used by apps that opt into it</li>
</ul>
</section>
</main>
<footer>
<div class="footer-inner">
<div class="footer-brand">
<img src="icons/proj/kryon.png" alt="Kryon Labs" width="20" height="20">
<span>KRYON</span>
</div>
<div class="footer-cols">
<div class="footer-col">
<h4>Related</h4>
<ul>
<li><a href="https://daochi.net">Daochi</a></li>
<li><a href="https://taijios.net">TaijiOS</a></li>
<li><a href="https://krait.kryonlabs.com">Krait</a></li>
</ul>
</div>
</section>
<section id="philosophy">
<h2>Philosophy</h2>
<ul class="philosophy-list">
<li><strong>Everything visible is a widget</strong> - source, bounds, state, and inspection all belong to the widget tree.</li>
<li><strong>Source stays primary</strong> - .kry files own screens and reusable UI pieces; C is the generated interop target.</li>
<li><strong>The IDE is source-aware</strong> - file browser, source editor, live preview, inspector, diagnostics, and search stay tied to .kry files.</li>
<li><strong>Default private API</strong> - only exported functions enter generated headers, keeping build boundaries small.</li>
<li><strong>Native first</strong> - direct C, raylib-style calls, and predictable runtime behavior across targets.</li>
</ul>
</section>
<section id="platforms">
<h2>Platforms</h2>
<p>Kryon targets the same interface source at the environments apps actually ship to.</p>
<div class="platform-grid">
<article class="platform">
<img src="platforms/tux.png" width="32" height="32" alt="">
<h3>Linux</h3>
<p>Native desktop builds.</p>
</article>
<article class="platform">
<img src="platforms/win.png" width="32" height="32" alt="">
<h3>Windows</h3>
<p>Native desktop and WinINet assets.</p>
</article>
<article class="platform">
<img src="platforms/macos.png" width="32" height="32" alt="">
<h3>macOS</h3>
<p>Native desktop builds.</p>
</article>
<article class="platform">
<img src="platforms/droid.png" width="32" height="32" alt="">
<h3>Android</h3>
<p>Mobile runtime support.</p>
</article>
<article class="platform">
<img src="language/wasm.png" width="32" height="32" alt="">
<h3>Browser</h3>
<p>WebAssembly runtime and previews.</p>
</article>
<article class="platform">
<img src="platforms/freebsd.png" width="32" height="32" alt="">
<h3>FreeBSD</h3>
<p>Native desktop and embedded targets.</p>
</article>
<div class="footer-col">
<h4>Kryon</h4>
<ul>
<li><a href="docs.html">Docs</a></li>
<li><a href="language.html">Language</a></li>
<li><a href="matrices.html">Matrices</a></li>
<li><a href="renderers.html">Renderers</a></li>
<li><a href="/api">API reference</a></li>
</ul>
</div>
</section>
<div class="footer-col">
<h4>Community</h4>
<ul>
<li><a href="showcase.html">Showcase</a></li>
<li><a href="https://github.com/kryonlabs" target="_blank" rel="noopener">GitHub</a></li>
<li><a href="https://t.me/kryonlabs_com" target="_blank" rel="noopener">Telegram</a></li>
</ul>
</div>
</div>
</div>
<div class="footer-bottom">
<p>&copy; 2026 Kryon Labs &middot; <a href="https://waozi.xyz" target="_blank" rel="noopener">Made by Waozi</a></p>
</div>
</footer>
<section id="start">
<h2>Get Started</h2>
<p>Build the runtime and tools:</p>
<pre><code>git clone https://github.com/kryonlabs/kryon.git
cd kryon
make
make install</code></pre>
<p>A simple .kry shape:</p>
<pre><code>#import "kryon.h"
<script>
(function() {
var toggle = document.querySelector(".menu-toggle");
var nav = document.getElementById("header-nav");
if (toggle && nav) {
toggle.addEventListener("click", function() {
var open = nav.classList.toggle("is-open");
toggle.setAttribute("aria-expanded", open ? "true" : "false");
});
}
AppHome :: (app: InbeApp*) {
y: int = ScaleUIPx(24)
WidgetText("Inner Breeze", ScaleUIPx(20), y, UI_TEXT_24, GetThemeText())
app_draw_bottom_nav(app)
}</code></pre>
<p>Open a project or a single .kry file in the IDE:</p>
<pre><code>kryon .
kryon path/to/app.kry</code></pre>
</section>
<section id="docs">
<h2>Documentation</h2>
<ul class="link-list">
<li><a href="api.html">API reference</a> - runtime and widget surface</li>
<li><a href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">Source repository</a> - code, issues, and releases</li>
</ul>
</section>
</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>
})();
</script>
</body>
</html>
+199
View File
@@ -0,0 +1,199 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kry Language Reference</title>
<meta name="description" content="Kry source language reference: declarations, statements, compile-time checks, KIR lowering, and backend behavior.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://kryonlabs.com/language.html">
<meta property="og:title" content="Kry Language Reference">
<meta property="og:description" content="The documented .kry to KIR to C, Go, JS, and KRB language contract.">
<meta name="theme-color" content="#f3f1ea">
<link rel="icon" type="image/png" sizes="16x16" href="icons/proj/kryon.png">
<link rel="apple-touch-icon" href="icons/proj/kryon.png">
<link rel="stylesheet" href="styles.css">
<script src="theme.js"></script>
</head>
<body>
<header class="site-header">
<div class="site-header-inner">
<a class="brand" href="/">
<img src="icons/proj/kryon.png" alt="Kryon" width="22" height="22">
<span>KRYON</span>
</a>
<button class="menu-toggle" type="button" aria-label="Open site menu" aria-expanded="false" aria-controls="header-nav">Menu</button>
<nav class="header-nav" id="header-nav" aria-label="Primary">
<a href="/">Home</a>
<a href="docs.html">Docs</a>
<a href="language.html">Language</a>
<a href="renderers.html">Renderers</a>
<a href="showcase.html">Showcase</a>
<a href="/api">API</a>
<a href="ide.html">Playground</a>
<a class="btn btn-primary" href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">GitHub</a>
</nav>
</div>
</header>
<main>
<section class="doc-hero">
<p class="section-eyebrow">Kry Source Language</p>
<h1>Language Reference</h1>
<p class="section-lead">Kry is C-close application code for Kryon. This page mirrors the canonical source contract in <code>docs/KRY_LANGUAGE_SPEC.md</code>: source lowers into KIR first, then the same KIR can produce readable C, Go bindings, browser-loadable JS, or portable KRB cartridges.</p>
<pre><code>.kry -> KIR -> C
.kry -> KIR -> Go
.kry -> KIR -> JS
.kry -> KIR -> KRB</code></pre>
</section>
<section>
<p class="section-eyebrow">Contract</p>
<h2>What Kry Guarantees</h2>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Rule</th><th>Meaning</th></tr></thead>
<tbody>
<tr><td>Single frontend</td><td><code>.kry</code> parses into KIR before every backend. Backend-specific behavior must be visible in KIR or reported as a diagnostic.</td></tr>
<tr><td>C-close expressions</td><td>Types, pointer expressions, calls, field access, and raw C escape lines stay familiar to C programmers.</td></tr>
<tr><td>Declarative UI shape</td><td><code>#ui</code> functions declare named node hierarchies; the runtime owns reconciliation, layout, input routing, focus, and update order.</td></tr>
<tr><td>Inspectable lowering</td><td><code>k2kir</code> prints imports, state, functions, statements, assertions, and simple structured expression trees for tooling.</td></tr>
<tr><td>Honest subsets</td><td>C is the full path. Go, JS, and KRB accept supported KIR and reject unsupported compile-time assertions instead of silently changing semantics.</td></tr>
</tbody>
</table>
</div>
</section>
<section>
<p class="section-eyebrow">Declarations</p>
<h2>Top-Level Forms</h2>
<pre><code>#import "kryon.h"
ui :: #import "src/ui/panel"
WEB :: #defined(PLATFORM_WEB)
ANSWER :: #run 6 * 7
#assert ANSWER == 42, "compile-time math failed"
state {
click_count: int = 0
}
Counter :: (viewport: Rectangle, app: App*) #ui {
Screen root: {
bounds = viewport
Column body: {
gap = 8
Text("Count", 0, 0, Text16, GetThemeText())
if Button((ButtonProps){.label = "Increment"}) {
app->click_count += 1
}
}
}
}</code></pre>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Form</th><th>Purpose</th></tr></thead>
<tbody>
<tr><td><code>#import "header.h"</code></td><td>Include a C header in generated native code.</td></tr>
<tr><td><code>name :: #import "module"</code></td><td>Import another Kry module.</td></tr>
<tr><td><code>name :: (...) -> Ret { ... }</code></td><td>Define a function. Module functions are source-prefixed in generated C unless exported.</td></tr>
<tr><td><code>name :: (...) #ui { ... }</code></td><td>Define a UI hierarchy function. Named nodes inside it get stable hierarchy paths.</td></tr>
<tr><td><code>#export</code>, <code>#private</code>, <code>#extern</code></td><td>Control ABI visibility and declarations that are implemented outside Kry.</td></tr>
<tr><td><code>#global</code></td><td>Create a file-level variable; combine with <code>#export</code> for public extern storage.</td></tr>
<tr><td><code>Type :: struct { ... }</code></td><td>Define a C-compatible struct type.</td></tr>
<tr><td><code>state { ... }</code></td><td>Declare persistent app state fields owned by the generated module.</td></tr>
</tbody>
</table>
</div>
</section>
<section>
<p class="section-eyebrow">Statements</p>
<h2>Function Body Forms</h2>
<ul class="link-list">
<li><strong>Locals:</strong> <code>name := expr</code>, <code>name: Type = expr</code>, or <code>name: Type</code>.</li>
<li><strong>Assignments:</strong> <code>name = expr</code> and compound operators such as <code>+=</code>, <code>%=</code>, and <code>&=</code>.</li>
<li><strong>UI nodes:</strong> <code>Screen root: { ... }</code>, <code>Column body: { ... }</code>, <code>Row actions: { ... }</code>, and <code>Stack layer: { ... }</code> declare hierarchy nodes.</li>
<li><strong>Calls:</strong> plain call statements remain available for leaf widgets and utility calls inside UI or normal functions.</li>
<li><strong>Control flow:</strong> <code>if</code>, <code>else if</code>, <code>else</code>, <code>while</code>, <code>for</code>, <code>switch</code>, <code>case</code>, <code>default</code>, labels, <code>goto</code>, <code>break</code>, <code>continue</code>, <code>guard</code>, <code>defer</code>, and <code>return</code>.</li>
<li><strong>Interop:</strong> <code>c line</code> emits raw C glue, and <code>unused expr</code> silences unused-value warnings.</li>
</ul>
</section>
<section>
<p class="section-eyebrow">Compile Time</p>
<h2>Constants, Guards, And Assertions</h2>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Feature</th><th>Status</th><th>Backend Behavior</th></tr></thead>
<tbody>
<tr><td><code>#defined(SYMBOL)</code></td><td class="ok">Available</td><td>Expands to a C preprocessor-style condition for guards and generated C.</td></tr>
<tr><td><code>NAME :: #run INTEGER_EXPR</code></td><td class="ok">Available</td><td>Evaluated by the Kry frontend as a small integer constant. It is not a general compile-time function system.</td></tr>
<tr><td><code>#assert CONDITION, "message"</code></td><td class="ok">Available</td><td>Ungarded constant-false assertions fail during Kry parsing. C emits <code>#if/#error</code>. Go, JS, and KRB require known true assertions.</td></tr>
<tr><td><code>#if</code>, <code>#else</code>, <code>#endif</code></td><td class="ok">Available</td><td>Retained in KIR as expanded guards so backends know the active platform conditions.</td></tr>
</tbody>
</table>
</div>
</section>
<section>
<p class="section-eyebrow">KIR</p>
<h2>Intermediate Representation</h2>
<p>KIR keeps raw source statement text for backend compatibility and adds structured metadata where the frontend can parse safely. Today that metadata covers simple identifiers, integer literals, string literals, calls, and binary expressions. More expression kinds can be added without changing the source pipeline.</p>
<pre><code>k2kir --root . -o build/ir src/app.kry
k2c --root . -o build/c src/app.kry
k2go --root . -o build/go src/app.kry
k2js --root . -o build/js src/app.kry
k2b --root . -o build/krb src/app.kry</code></pre>
</section>
<section>
<p class="section-eyebrow">Limits</p>
<h2>Known Language Boundaries</h2>
<ul class="link-list">
<li><strong>No hidden macro language:</strong> Kry keeps compile-time behavior small and explicit. <code>#run</code> currently folds integer expressions only.</li>
<li><strong>Backend subsets are real:</strong> C is broadest; Go, JS, and KRB intentionally support smaller surfaces and must diagnose unsupported KIR.</li>
<li><strong>Text system limits remain runtime limits:</strong> font fallback exists, but shaping, bidi, RTL mirroring, and IME preedit are not complete.</li>
<li><strong>KRB is portable by design:</strong> it carries a smaller widget and capability surface than native C.</li>
</ul>
</section>
<section>
<p class="section-eyebrow">Backend Contract</p>
<h2>Conformance Summary</h2>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Feature</th><th>KIR</th><th>C</th><th>Go</th><th>JS</th><th>KRB</th></tr></thead>
<tbody>
<tr><td><code>#run</code> integer constants</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td></tr>
<tr><td><code>#assert</code></td><td class="ok">Yes</td><td class="ok"><code>#if/#error</code></td><td class="part">Known true only</td><td class="part">Known true only</td><td class="part">Known true only</td></tr>
<tr><td>State block</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td></tr>
<tr><td>Raw C lines</td><td class="ok">Preserved</td><td class="ok">Yes</td><td class="no">No</td><td class="no">No</td><td class="no">No</td></tr>
<tr><td>Structured expression metadata</td><td class="part">Partial</td><td class="part">Metadata</td><td class="part">Metadata</td><td class="part">Metadata</td><td class="part">Metadata</td></tr>
</tbody>
</table>
</div>
</section>
</main>
<footer>
<div class="footer-bottom">
<p>&copy; 2026 Kryon Labs &middot; <a href="index.html">Home</a> &middot; <a href="matrices.html">Matrices</a> &middot; <a href="renderers.html">Renderers</a></p>
</div>
</footer>
<script src="highlight.js"></script>
<script>
(function() {
var toggle = document.querySelector(".menu-toggle");
var nav = document.getElementById("header-nav");
if (toggle && nav) {
toggle.addEventListener("click", function() {
var open = nav.classList.toggle("is-open");
toggle.setAttribute("aria-expanded", open ? "true" : "false");
});
}
})();
</script>
</body>
</html>
+93
View File
@@ -0,0 +1,93 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kryon Playground Examples</title>
<meta name="description" content="Kryon examples now live with the browser playground as one unified entry point.">
<meta http-equiv="refresh" content="0; url=ide.html">
<link rel="icon" type="image/png" sizes="16x16" href="icons/proj/kryon.png">
<link rel="stylesheet" href="styles.css">
<script src="theme.js"></script>
</head>
<body class="ide-page">
<header class="site-header">
<div class="site-header-inner">
<a class="brand" href="index.html">
<img src="icons/proj/kryon.png" alt="Kryon" width="22" height="22">
<span>KRYON</span>
</a>
<button class="menu-toggle" type="button" aria-label="Open site menu" aria-expanded="false" aria-controls="header-nav">Menu</button>
<nav class="header-nav" id="header-nav" aria-label="Primary">
<a href="/">Home</a>
<a href="docs.html">Docs</a>
<a href="language.html">Language</a>
<a href="renderers.html">Renderers</a>
<a href="showcase.html">Showcase</a>
<a href="/api">API</a>
<a href="ide.html">Playground</a>
<a class="btn btn-primary" href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">GitHub</a>
</nav>
</div>
</header>
<main class="web-ide live-examples" data-live-examples>
<section class="ide-shell">
<div class="ide-toolbar">
<div>
<p class="section-eyebrow">Playground Examples</p>
<h1>Examples now live in the Playground</h1>
</div>
<div class="ide-actions">
<a class="btn btn-primary" href="ide.html">Open Playground</a>
</div>
</div>
<div class="live-grid">
<aside class="ide-pane example-browser">
<div class="pane-title">
<span>Examples + widgets</span>
<span data-count>loading</span>
</div>
<div class="example-list" data-example-list></div>
</aside>
<div class="ide-pane source-pane">
<div class="pane-title">
<span data-source-title>source</span>
<span data-status>Loading compiler...</span>
</div>
<textarea spellcheck="false" data-source></textarea>
</div>
<div class="ide-pane preview-pane">
<div class="pane-title">
<span>Live canvas output</span>
<span data-preview-status>waiting</span>
</div>
<canvas width="800" height="600" data-preview></canvas>
</div>
<div class="ide-pane artifact-pane">
<div class="artifact-tabs" role="tablist" aria-label="Generated artifacts">
<button type="button" class="is-active" data-tab="kry">.kry</button>
<button type="button" data-tab="kir">KIR</button>
<button type="button" data-tab="c">C</button>
<button type="button" data-tab="go">Go</button>
<button type="button" data-tab="krb">KRB</button>
</div>
<pre class="artifact-output"><code data-artifact></code></pre>
</div>
</div>
</section>
</main>
<script src="ide-tools/k2kir.js"></script>
<script src="ide-tools/k2b.js"></script>
<script src="ide-tools/k2c.js"></script>
<script src="ide-tools/k2go.js"></script>
<script src="ide-tools/k2js.js"></script>
<script src="ide-tools/krb-web.js"></script>
<script src="live-examples.js"></script>
</body>
</html>
+481
View File
@@ -0,0 +1,481 @@
(function() {
"use strict";
var source = document.querySelector("[data-source]");
var sourceTitle = document.querySelector("[data-source-title]");
var status = document.querySelector("[data-status]");
var previewStatus = document.querySelector("[data-preview-status]");
var canvas = document.querySelector("[data-preview]");
var artifact = document.querySelector("[data-artifact]");
var list = document.querySelector("[data-example-list]");
var count = document.querySelector("[data-count]");
var tabButtons = Array.prototype.slice.call(document.querySelectorAll("[data-tab]"));
var compileButton = document.querySelector("[data-action='compile']");
var reloadButton = document.querySelector("[data-action='reload']");
var menuToggle = document.querySelector(".menu-toggle");
var headerNav = document.getElementById("header-nav");
var activeTab = new URLSearchParams(window.location.search).get("tab") || "kry";
var modules = {};
var playerMod = null;
var playerInputReady = false;
var items = [];
var current = null;
var compileTimer = 0;
var last = { kry: "", kir: "", c: "", go: "", krb: "", bytes: null };
var fallback = {
group: "Examples",
title: "Buttons",
name: "02_buttons.kry",
path: "examples/02_buttons.kry",
url: "examples-src/examples/02_buttons.kry"
};
if (menuToggle && headerNav) {
menuToggle.addEventListener("click", function() {
var open = headerNav.classList.toggle("is-open");
menuToggle.setAttribute("aria-expanded", open ? "true" : "false");
});
}
function setStatus(text) {
if (status) status.textContent = text;
}
function setPreviewStatus(text) {
if (previewStatus) previewStatus.textContent = text;
}
function ensureDir(mod, path) {
var parts = path.split("/");
var cur = "";
for (var i = 0; i < parts.length; i++) {
if (!parts[i]) continue;
cur += "/" + parts[i];
try {
mod.FS.mkdir(cur);
} catch (e) {
if (!String(e).match(/File exists|ErrnoError/)) throw e;
}
}
}
function rmTree(mod, path) {
var entries;
try {
entries = mod.FS.readdir(path);
} catch (e) {
return;
}
entries.forEach(function(name) {
var child;
if (name === "." || name === "..") return;
child = path + "/" + name;
try {
if (mod.FS.isDir(mod.FS.stat(child).mode)) {
rmTree(mod, child);
mod.FS.rmdir(child);
} else {
mod.FS.unlink(child);
}
} catch (e) {}
});
}
function resetFs(mod) {
rmTree(mod, "/work");
try { mod.FS.rmdir("/work"); } catch (e) {}
ensureDir(mod, "/work");
ensureDir(mod, "/work/out");
}
function writeSource(mod, path, text) {
var full = "/work/" + path;
var slash = full.lastIndexOf("/");
if (slash > 0) ensureDir(mod, full.slice(0, slash));
mod.FS.writeFile(full, text);
return full;
}
function readMaybe(mod, path, binary) {
try {
return mod.FS.readFile(path, binary ? { encoding: "binary" } : { encoding: "utf8" });
} catch (e) {
return binary ? new Uint8Array(0) : "";
}
}
function readFirst(mod, paths, binary) {
for (var i = 0; i < paths.length; i++) {
var value = readMaybe(mod, paths[i], binary);
if (binary ? value.length > 0 : value !== "") return value;
}
return binary ? new Uint8Array(0) : "";
}
function stem(path) {
var name = path.split("/").pop();
return name.replace(/\.[^.]+$/, "");
}
function dir(path) {
var slash = path.lastIndexOf("/");
return slash > 0 ? path.slice(0, slash) : "";
}
function outPath(path, ext) {
var d = dir(path);
return "/work/out/" + (d ? d + "/" : "") + stem(path) + ext;
}
function hex(bytes) {
var out = [];
for (var i = 0; i < bytes.length; i += 16) {
var line = ("00000000" + i.toString(16)).slice(-8) + " ";
for (var j = 0; j < 16; j++) {
line += i + j < bytes.length ? ("0" + bytes[i + j].toString(16)).slice(-2) + " " : " ";
}
out.push(line);
}
return out.join("\n");
}
function readU16(dv, off) { return dv.getUint16(off, true); }
function readI16(dv, off) { return dv.getInt16(off, true); }
function readU32(dv, off) { return dv.getUint32(off, true); }
function cstr(bytes, off, max) {
var end = off;
while (end < max && bytes[end] !== 0) end++;
return new TextDecoder().decode(bytes.slice(off, end));
}
function rgba(u32) {
if ((u32 & 0x80000000) !== 0) {
var slot = u32 & 0xff;
if (slot === 1) return "rgb(42,59,64)";
if (slot === 4) return "rgb(13,63,85)";
return "rgb(247,244,236)";
}
return "rgba(" + (u32 & 255) + "," + ((u32 >> 8) & 255) + "," + ((u32 >> 16) & 255) + "," + (((u32 >> 24) & 255) / 255).toFixed(3) + ")";
}
function decodeKrb(bytes) {
var dv;
var nodeCount;
var stringBytes;
var nodeOff = 32;
var nodes = [];
if (!bytes || bytes.length < 32) throw new Error("KRB is empty");
dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
if (readU32(dv, 0) !== 0x0042524b) throw new Error("KRB magic mismatch");
nodeCount = readU32(dv, 8);
stringBytes = readU32(dv, 12);
for (var i = 0; i < nodeCount; i++) {
var off = nodeOff + i * 28;
var strOff = nodeOff + nodeCount * 28;
nodes.push({
id: readU16(dv, off),
parent: readI16(dv, off + 2),
name: cstr(bytes, strOff + readU16(dv, off + 4), strOff + stringBytes),
type: bytes[off + 6],
flags: bytes[off + 7],
bind: readU16(dv, off + 8),
x: readI16(dv, off + 10),
y: readI16(dv, off + 12),
w: readI16(dv, off + 14),
h: readI16(dv, off + 16),
color: readU32(dv, off + 18),
text: cstr(bytes, strOff + readU16(dv, off + 22), strOff + stringBytes),
font: readU16(dv, off + 24) || 16,
style: bytes[off + 26]
});
}
return nodes;
}
function coord(v, full, scaled) {
return scaled ? Math.round(full * v / 10000) : v;
}
function drawRound(ctx, x, y, w, h, r) {
r = Math.max(0, Math.min(r, w / 2, h / 2));
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function sizeFromSource(text) {
var m = text.match(/\bsize\s+(\d+)\s+(\d+)/);
if (!m) return { w: 800, h: 600 };
return {
w: Math.max(240, Math.min(1600, parseInt(m[1], 10))),
h: Math.max(180, Math.min(1200, parseInt(m[2], 10)))
};
}
function attachPlayerInput() {
if (playerInputReady)
return;
playerInputReady = true;
function pos(e) {
var r = canvas.getBoundingClientRect();
return [
Math.round((e.clientX - r.left) * canvas.width / r.width),
Math.round((e.clientY - r.top) * canvas.height / r.height)
];
}
window.addEventListener("keydown", function(e) {
if (e.key === "Backspace" && playerMod && playerMod._krb_web_text) {
e.preventDefault();
playerMod._krb_web_text(8);
}
});
window.addEventListener("keypress", function(e) {
if (playerMod && playerMod._krb_web_text && e.charCode > 31)
playerMod._krb_web_text(e.charCode);
});
canvas.addEventListener("wheel", function(e) {
e.preventDefault();
if (playerMod && playerMod._krb_web_wheel)
playerMod._krb_web_wheel(Math.round(-e.deltaY / 2));
}, { passive: false });
canvas.addEventListener("mousemove", function(e) {
var p;
if (playerMod && playerMod._krb_web_mouse) {
p = pos(e);
playerMod._krb_web_mouse(p[0], p[1]);
}
});
canvas.addEventListener("mousedown", function(e) {
var p;
if (playerMod && playerMod._krb_web_button) {
p = pos(e);
playerMod._krb_web_mouse(p[0], p[1]);
playerMod._krb_web_button(0, 1);
}
});
canvas.addEventListener("mouseup", function(e) {
var p;
if (playerMod && playerMod._krb_web_button) {
p = pos(e);
playerMod._krb_web_mouse(p[0], p[1]);
playerMod._krb_web_button(0, 0);
}
});
}
function render(bytes) {
var rc;
if (!playerMod)
throw new Error("KRB web player unavailable");
canvas.width = 800;
canvas.height = 600;
try { playerMod.FS.unlink("/app.krb"); } catch (e) {}
playerMod.FS.writeFile("/app.krb", bytes);
rc = playerMod._krb_web_start();
if (rc && rc !== 0)
throw new Error("krb-web exited with " + rc);
attachPlayerInput();
setPreviewStatus("wasm canvas");
}
function runCompiler(key, args, readers) {
var mod = modules[key];
var full;
var rc;
if (!mod) return { ok: false, text: "Compiler module unavailable." };
resetFs(mod);
full = writeSource(mod, current.path, source.value);
args = args.concat([full]);
try {
rc = mod.callMain(args);
if (rc && rc !== 0) throw new Error(key + " exited with " + rc);
return readers(mod);
} catch (e) {
return { ok: false, text: String(e && e.stack ? e.stack : e) };
}
}
function showArtifact() {
artifact.textContent = last[activeTab] || "";
}
function compile() {
var passed = 0;
var failed = 0;
var result;
if (!current) return;
window.clearTimeout(compileTimer);
last = { kry: source.value, kir: "", c: "", go: "", krb: "", bytes: null };
setStatus("compiling...");
setPreviewStatus("rendering");
result = runCompiler("kir", ["--root", "/work", "-o", "/work/out"], function(mod) {
return { ok: true, text: readFirst(mod, [outPath(current.path, ".kir"), "/work/out/" + stem(current.path) + ".kir"], false) };
});
if (result.ok && result.text) { last.kir = result.text; passed++; } else { last.kir = result.text || "KIR output unavailable."; failed++; }
result = runCompiler("c", ["--no-main", "--root", "/work", "-o", "/work/out"], function(mod) {
var files = [];
var moduleC = readFirst(mod, [outPath(current.path, ".c"), "/work/out/" + stem(current.path) + ".c"], false);
var header = readFirst(mod, [outPath(current.path, ".h"), "/work/out/" + stem(current.path) + ".h"], false);
var projectC = readMaybe(mod, "/work/out/kryon_project.c", false);
if (moduleC) files.push("/* " + current.path.replace(/\.kry$/, ".c") + " */\n" + moduleC);
if (header) files.push("/* " + current.path.replace(/\.kry$/, ".h") + " */\n" + header);
if (projectC) files.push("/* kryon_project.c */\n" + projectC);
return { ok: files.length > 0, text: files.join("\n\n") || "C output unavailable." };
});
if (result.ok) { last.c = result.text; passed++; } else { last.c = result.text; failed++; }
result = runCompiler("go", ["--no-main", "--pkg", "kryexample", "--root", "/work", "-o", "/work/out"], function(mod) {
return { ok: true, text: readFirst(mod, ["/work/out/" + stem(current.path) + ".go", outPath(current.path, ".go")], false) };
});
if (result.ok && result.text) { last.go = result.text; passed++; } else { last.go = result.text || "Go output unavailable."; failed++; }
result = runCompiler("krb", ["--no-main", "--root", "/work", "-o", "/work/out"], function(mod) {
var bytes = readFirst(mod, [outPath(current.path, ".krb"), "/work/out/" + stem(current.path) + ".krb"], true);
return { ok: bytes.length > 0, bytes: bytes, text: "KRB bytes: " + bytes.length + "\n\n" + hex(bytes) };
});
if (result.ok) {
last.bytes = result.bytes;
last.krb = result.text;
passed++;
try {
render(last.bytes);
} catch (e) {
setPreviewStatus(String(e && e.message ? e.message : e).slice(0, 80));
failed++;
}
} else {
last.krb = result.text || "KRB output unavailable.";
setPreviewStatus("no KRB preview");
failed++;
}
showArtifact();
setStatus(failed ? "compiled " + passed + "/4" : "compiled");
}
function scheduleCompile() {
window.clearTimeout(compileTimer);
compileTimer = window.setTimeout(compile, 260);
}
function selectItem(item) {
current = item;
if (sourceTitle) sourceTitle.textContent = item.path;
Array.prototype.slice.call(list.querySelectorAll("button")).forEach(function(btn) {
btn.classList.toggle("is-active", btn.getAttribute("data-path") === item.path);
});
setStatus("fetching source...");
return fetch(item.url).then(function(res) {
if (!res.ok) throw new Error("Could not fetch " + item.url + ": " + res.status);
return res.text();
}).then(function(text) {
source.value = text;
compile();
}).catch(function(err) {
source.value = "#import \"kryon.h\"\n\n/* " + String(err) + " */\n";
last.kry = source.value;
showArtifact();
setStatus("source unavailable");
});
}
function renderList() {
var currentGroup = "";
list.innerHTML = "";
items.forEach(function(item) {
var heading;
var btn;
if (item.group !== currentGroup) {
currentGroup = item.group;
heading = document.createElement("div");
heading.className = "example-group";
heading.textContent = currentGroup;
list.appendChild(heading);
}
btn = document.createElement("button");
btn.type = "button";
btn.textContent = item.title;
btn.setAttribute("data-path", item.path);
btn.addEventListener("click", function() { selectItem(item); });
list.appendChild(btn);
});
if (count) count.textContent = String(items.length);
}
function loadManifest() {
return fetch("examples-manifest.json").then(function(res) {
if (!res.ok) throw new Error("No manifest");
return res.json();
}).then(function(data) {
items = data.items || [];
if (!items.length) items = [fallback];
}).catch(function() {
items = [fallback];
});
}
function boot() {
if (typeof createK2irModule !== "function" || typeof createK2bModule !== "function" ||
typeof createK2cModule !== "function" || typeof createK2gModule !== "function" ||
typeof createKrbWebModule !== "function") {
setStatus("compiler unavailable");
artifact.textContent = "The web compiler assets were not built.";
return;
}
Promise.all([
createK2irModule({ noInitialRun: true }),
createK2bModule({ noInitialRun: true }),
createK2cModule({ noInitialRun: true }),
createK2gModule({ noInitialRun: true }),
createKrbWebModule({ noInitialRun: true, canvas: canvas }),
loadManifest()
]).then(function(values) {
var query = new URLSearchParams(window.location.search);
var wanted = query.get("example");
modules.kir = values[0];
modules.krb = values[1];
modules.c = values[2];
modules.go = values[3];
playerMod = values[4];
renderList();
return selectItem(items.filter(function(item) {
return item.path === wanted || item.name === wanted;
})[0] || items[0]);
}).catch(function(err) {
setStatus("error");
artifact.textContent = String(err && err.stack ? err.stack : err);
});
}
tabButtons.forEach(function(btn) {
btn.classList.toggle("is-active", btn.getAttribute("data-tab") === activeTab);
btn.addEventListener("click", function() {
activeTab = btn.getAttribute("data-tab");
tabButtons.forEach(function(b) { b.classList.toggle("is-active", b === btn); });
showArtifact();
});
});
source.addEventListener("input", scheduleCompile);
compileButton.addEventListener("click", compile);
reloadButton.addEventListener("click", function() {
if (current) selectItem(current);
});
boot();
})();
+252
View File
@@ -0,0 +1,252 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kryon Widget and Language Matrices</title>
<meta name="description" content="Kryon widget, language, compiler, and runtime capability matrices.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://kryonlabs.com/matrices.html">
<meta property="og:title" content="Kryon Widget and Language Matrices">
<meta property="og:description" content="View Kryon's widget, language, compiler, and runtime coverage by target.">
<meta name="theme-color" content="#f3f1ea">
<link rel="icon" type="image/png" sizes="16x16" href="icons/proj/kryon.png">
<link rel="apple-touch-icon" href="icons/proj/kryon.png">
<link rel="stylesheet" href="styles.css">
<script src="theme.js"></script>
</head>
<body>
<header class="site-header">
<div class="site-header-inner">
<a class="brand" href="/">
<img src="icons/proj/kryon.png" alt="Kryon" width="22" height="22">
<span>KRYON</span>
</a>
<button class="menu-toggle" type="button" aria-label="Open site menu" aria-expanded="false" aria-controls="header-nav">Menu</button>
<nav class="header-nav" id="header-nav" aria-label="Primary">
<a href="/">Home</a>
<a href="docs.html">Docs</a>
<a href="language.html">Language</a>
<a href="renderers.html">Renderers</a>
<a href="showcase.html">Showcase</a>
<a href="/api">API</a>
<a href="ide.html">Playground</a>
<a class="btn btn-primary" href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">GitHub</a>
</nav>
</div>
</header>
<main>
<section class="doc-hero">
<p class="section-eyebrow">Capability Matrices</p>
<h1>Widgets and language support</h1>
<p class="section-lead">A compact view of what Kryon supports through C, <code>.kry</code> lowering, Go generation, hand-written Go, and KRB cartridges. See the <a href="language.html">language reference</a> for syntax and lowering rules.</p>
<div class="matrix-legend">
<span class="status ok">Available</span>
<span class="status part">Partial</span>
<span class="status no">Missing</span>
<span class="status na">Not applicable</span>
</div>
</section>
<section>
<p class="section-eyebrow">Automated</p>
<h2>Conformance Matrix</h2>
<p class="section-lead">Generated from checked-in <code>.kry</code> examples, generated-runtime parity fixtures, and renderer evidence. The JSON backing this view is refreshed by <code>tests/feature_matrix_docs_test.sh</code>; source-pipeline and KRB visual cells are verified by <code>make conformance-matrix-check</code>, with renderer-specific gates listed below.</p>
<div class="matrix-stat-grid" data-conformance-summary>
<p class="section-lead">Loading generated matrix...</p>
</div>
<h3>Pipelines</h3>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Pipeline</th><th>Path</th><th>Status</th><th>Evidence</th></tr></thead>
<tbody data-conformance-pipelines></tbody>
</table>
</div>
<h3>Renderers and Platforms</h3>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Renderer</th><th>Platform</th><th>Approach</th><th>Status</th><th>Evidence</th><th>Matrix Scope</th><th>Notes</th></tr></thead>
<tbody data-conformance-renderers></tbody>
</table>
</div>
<h3>Renderer Smoke Gates</h3>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Gate</th><th>Command</th><th>Scope</th></tr></thead>
<tbody data-conformance-renderer-checks></tbody>
</table>
</div>
<h3>Visual Comparisons</h3>
<p class="section-lead">Capture gates prove a renderer draws a nonblank frame. Comparison rows show whether that output is actually pixel-compared against another renderer.</p>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Pair</th><th>Mode</th><th>Status</th><th>Compared Sources</th><th>Known Gaps</th><th>Evidence</th><th>Scope</th></tr></thead>
<tbody data-conformance-visual-comparisons></tbody>
</table>
</div>
<h3>Runtime Parity Gates</h3>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Gate</th><th>Command</th><th>Scope</th></tr></thead>
<tbody data-conformance-runtime-checks></tbody>
</table>
</div>
<h3>Downstream Consumer Gates</h3>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Consumer</th><th>Command</th><th>Scope</th></tr></thead>
<tbody data-conformance-downstream-checks></tbody>
</table>
</div>
<h3>Source Cases</h3>
<p class="section-lead">Each source starts as <code>.kry</code>. Pipeline columns show lowering coverage; renderer columns show the strongest current evidence for that same source on each renderer/platform path.</p>
<div class="matrix-controls">
<input type="search" data-conformance-search placeholder="Filter sources or widgets" aria-label="Filter source cases">
<select data-conformance-type aria-label="Filter source type">
<option value="all">All source types</option>
<option value="example">Examples</option>
<option value="parity fixture">Parity fixtures</option>
</select>
</div>
<div class="table-wrap">
<table class="matrix-table source-matrix-table">
<thead><tr data-conformance-source-head><th>Source</th><th>Type</th><th>k2kir</th><th>k2c</th><th>k2go</th><th>k2js</th><th>k2b</th><th>Renderers</th><th>Widgets</th><th>State Evidence</th></tr></thead>
<tbody data-conformance-sources></tbody>
</table>
</div>
<h3>Widget Coverage</h3>
<div class="table-wrap compact-table-wrap">
<table class="matrix-table compact-matrix-table">
<thead><tr><th>Widget</th><th>Status</th><th>Sources</th><th>Source Cases</th><th>State Evidence</th></tr></thead>
<tbody data-conformance-widgets></tbody>
</table>
</div>
</section>
<section>
<p class="section-eyebrow">Language</p>
<h2>Pipeline Matrix</h2>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Target</th><th>Producer</th><th>Runtime</th><th>Status</th></tr></thead>
<tbody>
<tr><td>C</td><td><code>k2c</code></td><td><code>cc</code> + <code>libkryon.a</code></td><td class="ok">Production path; most complete</td></tr>
<tr><td>Go</td><td><code>k2go</code></td><td><code>go/kryon</code> native Go package</td><td class="ok">Declarative subset with executable CI gate</td></tr>
<tr><td>JS/Web</td><td><code>k2js</code></td><td><code>web/kryon-runtime.js</code> ESM recorder/presenter</td><td class="ok">Syntax, Node recorder snapshots, and generated runtime state parity gated</td></tr>
<tr><td>KRB cartridge</td><td><code>k2b</code></td><td><code>KrbLoad</code>/<code>KrbExec</code> on a <code>KryBackend</code></td><td class="part">Portable widget subset; byte-exact renderer tests</td></tr>
<tr><td>KIR</td><td><code>k2kir</code></td><td>Inspection artifact</td><td class="na">Debugging and tooling only</td></tr>
</tbody>
</table>
</div>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Feature</th><th>C</th><th>Go</th><th>KRB</th></tr></thead>
<tbody>
<tr><td>Theming</td><td class="ok">6 palettes, light/dark, scopes, vars</td><td class="ok">Theme control APIs</td><td class="part">Theme color slots</td></tr>
<tr><td>Style tokens</td><td class="ok">Radius, border, shadow, style presets</td><td class="ok">Get/set token API</td><td class="no">No token model</td></tr>
<tr><td>Text/fonts</td><td class="part">Fallback fonts; no shaping, bidi, or IME</td><td class="ok">Font registry and input queue</td><td class="part">font8x8 or KFA1 atlas</td></tr>
<tr><td>Input</td><td class="part">Pointer, keyboard, clipboard; no IME/gamepad nav</td><td class="ok">Key, mouse, char APIs</td><td class="part">Mouse, wheel, text-key queue</td></tr>
<tr><td>Accessibility</td><td class="part">Debug a11y structs; no screen-reader bridge</td><td class="no">Not exposed</td><td class="no">Not exposed</td></tr>
<tr><td>Dialogs/platform</td><td class="ok">Portal, GTK, shell pickers, notifications, tray, XDG</td><td class="ok">Tray and notify polling</td><td class="part">Host capability imports</td></tr>
</tbody>
</table>
</div>
</section>
<section>
<p class="section-eyebrow">Widgets</p>
<h2>Widget Matrix</h2>
<p class="section-lead">Columns: C is the public runtime API. <code>k2c</code> follows C because library calls compile as C-close statements. <code>k2go</code>, <code>k2js</code>, and KRB deliberately cover smaller subsets.</p>
<h3>Display</h3>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Widget</th><th>C</th><th>k2c</th><th>k2go</th><th>Go</th><th>KRB</th></tr></thead>
<tbody>
<tr><td>Background, Text, TextInRect</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Nodes</td></tr>
<tr><td>Paragraph, TextLines</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="no">Not lowered</td></tr>
<tr><td>Rect, Line, Bevel</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Nodes</td></tr>
<tr><td>IconTexture</td><td class="ok">114 icons</td><td class="ok">Yes</td><td class="ok">By icon type</td><td class="ok">Yes</td><td class="no">Not lowered</td></tr>
<tr><td>Image/Picture</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Picture props</td><td class="ok">Yes</td><td class="ok">Embedded asset or PNG</td></tr>
</tbody>
</table>
</div>
<h3>Input</h3>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Widget</th><th>C</th><th>k2c</th><th>k2go</th><th>Go</th><th>KRB</th></tr></thead>
<tbody>
<tr><td>Button</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">ButtonProps</td><td class="ok">Yes</td><td class="ok">Button control</td></tr>
<tr><td>IconButton</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="part">IconButton subset</td><td class="part">Subset</td><td class="no">Not lowered</td></tr>
<tr><td>Href / IconLink</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="part">Href only</td><td class="part">Href only</td><td class="no">Not lowered</td></tr>
<tr><td>TextField, TextArea</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="part">TextField only</td></tr>
<tr><td>Dropdown</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="part">No rich option arrays</td><td class="ok">Yes</td><td class="ok">Dropdown control</td></tr>
<tr><td>Slider, Toggle, Checkbox</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Controls</td></tr>
<tr><td>Radio, Progress, Spinbox, Combobox</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="part">Spinbox/combobox only</td></tr>
<tr><td>ColorPicker, InfoButton</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="no">Not exposed</td><td class="no">Not exposed</td><td class="no">Not lowered</td></tr>
</tbody>
</table>
</div>
<h3>Layout, Collections, Navigation</h3>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Family</th><th>C</th><th>k2c</th><th>k2go</th><th>Go</th><th>KRB</th></tr></thead>
<tbody>
<tr><td>Column, Row, Stack</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Structural nodes</td></tr>
<tr><td>Scroll container</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Scroll/EndScroll</td><td class="ok">Yes</td><td class="ok">Scroll node</td></tr>
<tr><td>Notebook, PanedView, Collapsible</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="no">Not lowered</td></tr>
<tr><td>Canvas helpers</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Canvas helpers</td><td class="ok">Yes</td><td class="no">Not lowered</td></tr>
<tr><td>ListBox, SourceView, TableView</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="no">Not lowered</td></tr>
<tr><td>TreeView, CascadingTreeView</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="no">Not exposed</td><td class="no">Not exposed</td><td class="no">Not lowered</td></tr>
<tr><td>TabBar, BottomNav, TopNav, Toolbar</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="part">Main controls only</td><td class="ok">Main controls</td><td class="part">NavButton as button</td></tr>
<tr><td>Modal, Toast, dialogs</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="part">Modal/toast/dialog subset</td><td class="part">Subset</td><td class="no">Not lowered</td></tr>
</tbody>
</table>
</div>
</section>
<section>
<p class="section-eyebrow">Caveats</p>
<h2>Known Gaps</h2>
<ul class="link-list">
<li><strong>Retained painting:</strong> the retained tree paints a smaller subset than immediate mode and routes retained input mainly for button/text-field paths.</li>
<li><strong>Text shaping:</strong> font fallback works, but HarfBuzz shaping, bidi, RTL mirroring, and IME preedit are not implemented yet.</li>
<li><strong>KRB:</strong> intentionally portable and smaller than the full C catalog; unsupported widget calls are reported per file by <code>k2b</code>.</li>
</ul>
</section>
</main>
<footer>
<div class="footer-bottom">
<p>&copy; 2026 Kryon Labs &middot; <a href="index.html">Home</a> &middot; <a href="renderers.html">Renderers</a> &middot; <a href="/api">API</a></p>
</div>
</footer>
<script src="highlight.js"></script>
<script src="conformance-matrix.js"></script>
<script>
(function() {
var toggle = document.querySelector(".menu-toggle");
var nav = document.getElementById("header-nav");
if (toggle && nav) {
toggle.addEventListener("click", function() {
var open = nav.classList.toggle("is-open");
toggle.setAttribute("aria-expanded", open ? "true" : "false");
});
}
})();
</script>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 472 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 734 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 759 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 217 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

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