Compare commits

Author SHA1 Message Date
nandiandClaude Opus 5.5 bcd7751f1a wasmhost: replace removed partial-application syntax (Str(_))
CI / test (pull_request) Failing after 19m24s
Current MoonBit (0.1.20261126) rejects f(_) partial application, so build-wasmhost.sh failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkMiWbNDLzKrZvtZWu
2026-11-26 11:12:06 +00:00
nandiandClaude Sonnet 5.5 7912a0b32b Emoji font: install it readable, and retry a failed load
CI / test (push) Failing after 44m48s
The fetch script downloaded through mktemp (0600) and the installer kept
that mode, so the session couldn't read the root-owned font and reported
it missing. The failure was also cached until the next session.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 00:12:06 -08:00
nandiandClaude Sonnet 5.5 44688453d7 Icons: load an absolute Icon= path that has no extension
CI / test (push) Failing after 31m49s
AppImage managers write icons as extensionless files, so those apps got the
generic icon. Any absolute path is now tried, and the loaders tell PNG and SVG
apart from the contents.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 23:01:20 -08:00
Claude 27252a97ab Emoji picker (Super+.): search, tabs, skin tones, recents, text-input-v3 insertion
CI / test (push) Canceled after 0s
Compositor-drawn Win+. style picker. The focused app keeps keyboard focus so
its text-input-v3 field stays enabled; the emoji goes in with commit_string,
or onto the clipboard with a visible notice when the app has no text field.
Shortcut lives in the shortcut table (rebindable in Settings > Shortcuts).

- compositor/wayland/text_input.mbt: zwp_text_input_manager_v3 (global 12)
- compositor/emoji: Emoji 18.0 + CLDR 49 data (Unicode License), search,
  picker model, CBDT/CBLC + GSUB reader for Noto Color Emoji
- Chandra's own pinned bitmap Noto Color Emoji (scripts/fetch-emoji-font.sh,
  just emoji-font); Fedora's COLRv1 copy can't be drawn. Missing font shows
  an error panel.
- raster WIT: emoji-font, emoji-has, emoji-image; served by wasmhost
- state.edn :emoji {:recent [...] :skin-tone n}
- tests incl. a fake text-input client; docs/emoji-picker.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkABDGJixotaqFv2X2
2026-11-26 07:00:22 +00:00
nandiandClaude Sonnet 5.5 738928352e Face unlock: let polkit's sandboxed PAM helper open cameras
CI / test (push) Canceled after 28m1s
polkit 126+ runs the password dialog's PAM stack in polkit-agent-helper@.service,
whose PrivateDevices=yes leaves no cameras in /dev, so the dialog reported "no
camera" while sudo and enrolling worked. Install a drop-in that allows only V4L2
devices and keeps the capability and syscall limits PrivateDevices= added.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 22:33:44 -08:00
Claude 2752b81e36 Session: wait for the document portal's mount before reopening apps; say when it's broken
CI / test (push) Canceled after 1m11s
V's session.log had kwi (a Flatpak) failing with "bwrap: Can't find source path
/run/user/1000/doc/by-app/org.kde.kwi". At login chandra-session restarts
xdg-desktop-portal, and xdg-document-portal stopped and started with it in the
same second (V's journal, 21:36:12); a Flatpak started in that gap, such as one
session restore reopens, finds no FUSE mount to bind into its sandbox.

When flatpak is installed, chandra-session now asks the document portal for its
mount point (which also starts it), waits up to 5 s for the FUSE mount and
checks it answers. If it doesn't, the reason goes to the log and into
CHANDRA_SESSION_ERRORS, which the shell shows as an error notice once the desktop
is up (DesktopShell::show_session_errors). A missing dbus-send is reported too.

Tested: the snippet against a real xdg-document-portal on a dbus-run-session bus
(mounted after 0 waits) and with an unreachable bus (error text); the notice in
compositor/host/launch_test.mbt and headless with build/wasmhost.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiGJWeuHiTgtoyB4kb
2026-11-26 06:29:54 +00:00
nandiandClaude Sonnet 5.5 70b24ffe47 Private bus: don't take over the session's document portal mount
CI / test (push) Canceled after 24m10s
A nested compositor's private D-Bus kept the session's XDG_RUNTIME_DIR, so
an xdg-document-portal activated on it mounted over $XDG_RUNTIME_DIR/doc and
removed the mount when the bus exited. The session's portal kept running
without it, and flatpak apps stopped starting.

The bus now has its own config that starts the document portal with a runtime
directory per compositor. scripts/test-private-bus.sh covers it. The KDE
colors test gets its own runtime directory for the same reason.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 22:06:51 -08:00
Claude 50149e6b99 Launches that fail say why: command, exit status and what it printed
CI / test (push) Canceled after 17m11s
V: "kwi not starting from app menu or dock". Kwi is a Flatpak, and bwrap died
before it opened a window ("Can't find source path /run/user/1000/doc/by-app/
org.kde.kwi"); Chandra forked apps and forgot them, so the failure only reached
the session log and the click did nothing visible.

Every app the Applications menu, the dock, Super+1..9 and session restore start
now runs under a small monitor (sys spawn-watch, compositor/sys/sys_stub.c): it
copies the app's output to the session log as before, keeps its last 2 KiB,
and reports how sh -c CMD exited on a socket the main loop wakes on. The shell
(compositor/shell/launch.mbt) shows a red error notice for 15 s, and logs it,
when the app exits non-zero or by a signal within 30 s, or exits 0 without ever
opening a window here (after a 2 s grace for single-instance hand-offs): the
first line says what happened, then the command and the last lines it printed,
repeats folded ("(3 times)"). Status 127/126 say "command not found" / "not
executable". Launched apps no longer inherit the compositor's fds.

chandra-ctl launch ID starts a desktop app exactly as the dock does.

Tests: compositor/host/launch_test.mbt (bwrap-style failure incl. drawn notice,
127, SIGSEGV, exit 0 without a window, an app that keeps running), unit tests
in launch.mbt. Checked end to end with build/wasmhost + compositor.wasm
headless and a Flatpak-style kwi desktop file: chandra-ctl launch org.kde.kwi
shows the notice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiGJWeuHiTgtoyB4kb
2026-11-26 05:48:39 +00:00
Claude 77fcc4db1c Screenshot editor: annotate, blur, pixelate, redact and crop before saving
CI / test (push) Canceled after 12m58s
Every screenshot now opens in an editor after KDE Spectacle's annotation mode:
Arrow, Line, Rectangle, Ellipse, Pen, Highlighter, Text, Number markers, Blur,
Pixelate, Redact and Crop, 8 colours, 3 sizes, undo/redo. Enter saves and
copies, Ctrl+C copies only, Esc discards.

- Drawn by the compositor (shot_editor.mbt), keyboard owned by it while up.
- Annotations are drawn into the picture's pixels at full size (annotate.mbt),
  so what is shown is what is saved. Blur = 6x6 block average + 3 box-blur
  passes; redact is opaque; both touch only their box (pixel tests).
- The picture goes to the renderer as <=2 MB strips: one 8 MB image-pixels
  call exhausts wasmtime's hostcall fuel and killed the wasm host.
- Frame callbacks are held while the overlay/editor freeze the screen, so apps
  behind stop drawing (0% CPU vs 52% with a full-screen animating app).
- wasmhost: error buffer 16 KB so trap causes aren't cut off; image-pixels
  limit 1024 -> 16384 a side (both hosts).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hh3TaFJh7nhCxAjV4Q
2026-11-26 05:37:03 +00:00
Claude 76a23f7816 Drag and drop: files can be dragged between windows and within one
CI / test (push) Canceled after 4m0s
The compositor ignored wl_data_device.start_drag, so no drag ever reached a
window: Dolphin, GNOME Files, Chrome tabs and text could not be dropped
anywhere, not even inside the window they started in.

Now (compositor/wayland/dnd.mbt, compositor/host/dnd.mbt):
- start_drag while a button is held on the client turns the pointer into the
  drag (the origin gets wl_pointer.leave); a request that arrives after the
  release is cancelled at once.
- The surface under the pointer (windows, subsurfaces, menus) gets
  data_offer + offer + source_actions + enter, then motion and leave; a drag
  without a source stays inside its own client.
- accept -> source.target, set_actions -> copy/move/ask agreed and sent as
  offer.action and source.action (version 3), version 1/2 clients copy.
- Release drops when the target accepted a type and an action: drop,
  dnd_drop_performed, and finish -> dnd_finished; otherwise cancelled + leave.
  Escape cancels. The window dropped on becomes active, so Dolphin's
  Copy/Move Here menu opens as a menu of a focused window.
- The drag icon is drawn under the pointer at its hotspot (attach offsets and
  wl_surface.offset), above windows and menus.
- A source, icon or client going away ends or updates the drag.

Tests: compositor/host/dnd_test.mbt (fail on the previous commit). Checked
headless with real Dolphin 23.08 (Qt 5.15) and GNOME Files 46 on both the
native build and the wasm build: Files -> Dolphin, Dolphin -> Files,
Dolphin -> Dolphin (Move/Copy/Link menu) and a move into a folder inside Files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjWb2dWbR1K7qoMgWP
2026-11-26 05:31:33 +00:00
Claude 80af76fb15 Password dialog rebuilt: a separate polkit agent, one state machine, explicit errors
CI / test (push) Canceled after 21m14s
The first version ran polkit registration, polkit-agent-helper-1, the PAM
conversation and the drawing inside the compositor's frame loop, with
overlapping state in two layers. A helper that quit before asking was taken
for a wrong password and restarted in a loop that wiped the field (typing
seemed dead), a refused registration quietly started a third-party agent,
and the dialog and the Face unlock window each grabbed the keyboard.

Now:
- chandra-polkit-agent (compositor/authagent, /usr/local/lib/chandra) does
  polkit and PAM. Each request runs one state machine (polkit/machine.mbt:
  starting, asking, checking, failed, done). A check that quits or can't
  start is Failed with the reason and waits for Try again; only a wrong
  password starts the next check by itself. It logs each step to stderr
  (the session log), never the typed text.
- The compositor starts it on a socket pair and only draws what it says
  (host/auth.mbt, auth_draw.mbt; line protocol in polkit/wire.mbt). One
  input owner (grab_input): the dialog, else the Face unlock window.
- No silent fallback: if the agent can't run, polkit refuses it, polkit
  doesn't answer in 10 s, or it dies, a notice on screen says why (a crash
  after it ran restarts it, up to 3 times, and says so). The third-party
  agent runs only when the Settings switch is off.
- chandra-ctl auth-demo [password|face|face-ok|die|slow|users] shows the
  real dialog with a pretend check (password "demo"), no root needed;
  chandra-ctl auth-status says whether the agent is registered.
- just install builds and installs the agent (just auth-agent).

Tests: polkit_test (link, machine, view, helper Gone) and auth_test end to
end through handle_input: the agent loop in-process against a mock polkit
on a private dbus-daemon plus a mock helper, and the real agent program
spawned by the compositor (demo, and registered with the mock polkit).
Typing on a real xkb keymap, wrong password, cancel, withdrawal, helper
quitting early or missing, polkit refusing, agent not starting or crashing,
demo modes, Face unlock Apply. 170/170 host and 20/20 polkit tests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgkRPrAzXECBUGmNEE
2026-11-26 05:09:49 +00:00
Claude 2c33c4a847 Text selection in terminals: drags stay with their window, middle-click paste works
CI / test (push) Canceled after 4m14s
V: "kwi is having problems selecting text". Two compositor gaps:

- No implicit pointer grab. A drag that started in a window lost it as soon as the pointer
  crossed its edge (onto the frame, the panel, a divider or another window): the client got
  wl_pointer.leave mid-drag (Qt then forgets the held button), and the release went to the
  other window or nowhere, so the terminal's selection never ended and kept following the
  pointer. Selecting past the top/bottom edge to scroll, which Kwi and Konsole autoscroll on,
  could not work. Now a press forwarded to a client grabs the pointer: motion (in that
  surface's coordinates, also outside it), the wheel and every button go to it until the last
  button is up; then the pointer goes to whatever is under it. Anything that takes the pointer
  (a window move or resize, the overview, a screenshot) ends the grab as before.
- No primary selection. zwp_primary_selection_device_manager_v1 was not offered, so Qt's
  QClipboard::supportsSelection() was false: selected text was never put on the primary
  selection and a middle click pasted nothing. Now offered (v1), with the offer sent to the
  focused client like the clipboard.

Checked headless with Konsole (Qt 5 Wayland): a selection dragged out of the window keeps
extending, is set as the primary selection on release, and a middle click in another Konsole
window pastes it. Tests in selection_test.mbt (both grab tests fail without the fix).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5himKXPLcfCZN6BXByd
2026-11-26 05:07:25 +00:00
Claude 516180196f Face unlock: say why a camera can't be used, list the cameras, pick one
CI / test (push) Canceled after 21m7s
"no camera at PATH" now says why (not there or a broken link, permission
denied, not a V4L2 device, a metadata node rather than the picture node,
OpenCV couldn't start it or it gives no picture: another app using it) and
lists the cameras found (VIDIOC_QUERYCAP on /dev/v4l/by-id/* and /dev/video*).
New commands: `chandra-face cameras`, `chandra-face set-camera PATH` (root,
edits device in face.conf after checking it is a capture node). The Face
unlock window shows the cameras found with a Use button (one password), then
opens again. just install prints NOT READY with the reason when the
configured camera can't be used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhiJfJNAYqWzQiuKMf
2026-11-26 04:47:06 +00:00
Claude ff6f733810 chandra-ctl windows: how Chandra sees each window, and what the pointer is over
CI / test (push) Canceled after 7m7s
For "this window won't resize" reports (V's Gajim still not resizing on real hardware,
while a libadwaita window built like Gajim's resizes headless on both hosts): one line per
window with its frame kind (client-frame / chandra-frame), layout state (floating, tiled,
maximized, fullscreen), box, buffer, the client's shadow per side, min/max size and title,
then the pointer position and what it's over (a resize grip and which edge, a window, a
title bar, a tiling divider, the panel, the desktop).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiu4r7mEXBdKY6cgv6
2026-11-26 04:39:45 +00:00
Claude db442879f5 Subsurfaces are drawn and get the pointer: Chrome's toolbar bubbles work
CI / test (push) Canceled after 14m47s
Chrome draws the bubbles of its toolbar buttons (bookmark star, downloads, extensions) as
wl_subsurfaces of the window, not xdg_popups. Chandra accepted wl_subcompositor.get_subsurface
but never drew a subsurface or sent it input, so those buttons seemed to do nothing (the
bookmark was even added, with no bubble). Menus (xdg_popup) were unaffected.

- Server: subsurface state (parent, position) per child surface; a child commit or
  set_position reports SubsurfaceCommitted(window, child, x, y, buffer) with the position
  added up to the window's surface, and a null buffer or destroy reports SubsurfaceUnmapped.
- Host: HostWindow.subs, drawn above the window as undecorated scene nodes (no change to any
  renderer); the pointer enters the topmost subsurface under it (ptr_sub) with its own
  coordinates, so clicks reach the bubble.

Checked headless with Chromium 158 on Ozone Wayland, in both frame modes: the star bubble
opens and its Remove button works. Test in csd_test.mbt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkfW5ttNd831XmdsC5
2026-11-26 04:19:53 +00:00
Claude 41c6ec1135 Remove the Rust host (host-wasm)
CI / test (push) Canceled after 0s
The MoonBit host (wasmhost/, build/wasmhost) is the only host now. Gone:
host-wasm/ (Rust on the wasmtime crate, ~5,700 lines incl. Cargo.lock),
the run-rust, run-drm-rust and host-wasm recipes, and `just install --rust`
(both the recipe and session/install.py now stop with an error naming the
removal instead of quietly ignoring the flag). remote-build.sh builds and
pulls build/wasmhost. README, wasmhost/README and docs no longer describe a
second host, apart from short history notes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiBxpbLoeUM9xfZayq
2026-11-26 04:19:19 +00:00
Claude 024f18ce61 Screen recordings keep up with animations: every drawn frame, up to 60 fps, with its real time
CI / test (push) Canceled after 0s
A recording of an animation looked choppy because frames barely reached ffmpeg: each 8 MB
1080p frame went out only as far as the socket buffer took it on each main loop pass, so a
new frame could be taken only every few hundred ms (V's recording changed picture ~12 times a
second; headless, 2 a second). Frames were also stamped when ffmpeg read them, not when drawn,
and every grab forced a full redraw.

Now:
- Both hosts (wasmhost raster_stub.c, host-wasm main.rs) copy a frame into a 3-slot queue and
  a writer thread sends it, so a frame never waits on the main loop. A full queue (ffmpeg
  behind) means that frame is not taken; the next one is, with its own time.
- The stream is uncompressed RGBA in Matroska (recorder.mbt mkv_stream_header /
  mkv_frame_header; the hosts write the same 42-byte cluster header), each frame stamped
  with the time it was drawn. ffmpeg makes constant 60 fps H.264 from it, under nice -n 10.
- A frame is taken when the desktop draws a changed frame (app.mbt draw_frame,
  compose_frame), at most 60 a second, or when the pointer moves. A still screen sends
  nothing; the REC pill redraws only its own rectangle when its seconds turn.
- ffmpeg going away mid-recording says so in the notification.
- Tests: the cluster header bytes, ffprobe reading the stream with each frame's own time,
  and the recording test now checks a 60 fps file as long as the recording ran. The
  recording tests fail with a clear message when ffmpeg/ffprobe are missing instead of
  returning early; CI installs ffmpeg.

Headless 1080p, one window redrawing at 60 fps (rec-bench.sh in project files
recorder-smooth/): distinct frames in the video 2.1/s -> 58.9/s (MoonBit host), 59.1/s
(Rust host); overview open/close 1.8/s -> 38.7/s (its previews refresh at 5-10/s live).
Compositor kept drawing 57 fps while recording; still screen: compositor 8% CPU.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjEUQq16Te1LPYMinT
2026-11-26 04:14:28 +00:00
Claude 14acc5d42e Window frames in the style of V's Flatkit Aurorae theme, the classic frame as a setting
CI / test (push) Canceled after 52s
The default frame now follows codegod100/kde aurorae (Flatkit / Flatkit Dark): the kit's
neutral title bar, a 1px outline with 10px top corners, a hairline under the title, a soft
16px shadow all round, a centred title and 24px flat buttons with hover and pressed fills
(close turns red). 38px title bar, 1px border. Maximized: no shadow, square corners.

- scene: WindowStyle (frame sizes, button layout, hit test) and build_window_decoration;
  the shadow is part of the decoration ops, so the three rasterisers lost their own offset
  shadow and redraw 18px around a changed window.
- host: the frame size follows the style (work area, wm title-bar room, CSD client boxes,
  hit zones, screenshots); title-bar buttons track hover, show pressed, act on release.
- Settings > Session > Flat window frames (off: the old Breeze-like frame), saved as
  :window-style :breeze; an unknown value is logged.
- docs/window-frames.md; tests for both styles' pixels, button states and switching.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hmKDDLLES2aBrrnPxT
2026-11-26 04:09:38 +00:00
Claude 2c2ce3f913 Face unlock window steps aside while Apply asks for the password
CI / test (push) Canceled after 3m23s
After Apply the window kept the keyboard and the pointer and its dimmed card
covered the screen, so a password dialog that isn't Chandra's own (another
polkit agent's window) couldn't be reached. While Apply waits, the window now
shows only a note at the top and takes no input. A refused or cancelled
password brings it back with the snaps and marks kept (chandra-face camera
restarts the camera instead of exiting) and says so.

Test: snaps, Enter, the password dialog gets typing (Space no longer snaps
underneath) and the Authenticate click, then the root step finishes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhiJfJNAYqWzQiuKMf
2026-11-26 04:05:11 +00:00
Claude f2b2618104 ci: cancel superseded runs (one CI run per ref)
CI / test (push) Failing after 7m59s
Three overlapping runs on 2026-11-26 starved the shared runner node of memory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hm8CvtJYQBG6kVhtbZ
2026-11-26 03:55:37 +00:00
Claude 2960005139 Gamerig Library: its own smooth gradient backdrop under the glass by default
CI / test (push) Successful in 7m13s
The desktop wallpaper's logo showing through the cards looked like a glitch. Background
now offers Gradient (default: 4 px bands with faint amber and blue glows), Wallpaper and Solid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgvjzw8hHirxRsXSsE
2026-11-26 03:29:54 +00:00
Claude 02c831576a Smoother on Xorg and Live Starfield: draw one frame ahead, cache a backdrop's unchanging start
CI / test (push) Successful in 2m33s
Tested on a Vast GTX 1650 rig (8-core Xeon E5-2620 v4, NVIDIA Xorg, --x11 --fullscreen):
GPU detection says hardware (nvidia), CHANDRA_RENDER=software switches.

- Frame pacing: at most one frame is drawn ahead of the output instead of waiting until the
  output is ready. Waiting serialised drawing with the X server's copy of the last frame; overview
  on Xorg went from 24-27 fps to 41-48 fps (before the first round: 16-17 fps).
- MoonBit host: a backdrop whose ops change every frame but begin the same (a desktop module:
  Live Starfield's sky and nebulae under moving stars) keeps that common start as cached pixels
  and draws only the rest over a copy of it. Starfield raster 13 -> 1.7 ms a frame and CPU 46% ->
  11% in the cloud; it no longer clears, redraws and re-saves the whole backdrop every frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkTQp5uN5FtwpzrXUA
2026-11-26 03:15:55 +00:00
Claude 1154437050 Gamerig Library: fit the screen without scrolling, draw over the wallpaper
CI / test (push) Successful in 2m32s
The grid picks the roomiest card density that fits (fewer description and hint lines, narrower
cards, then name and buttons only) before it would scroll. The module now draws over the
desktop wallpaper with glassy panels and cards; Background setting Wallpaper (default) or Solid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgvjzw8hHirxRsXSsE
2026-11-26 03:14:18 +00:00
Claude f556df2f4b Gamerig Library: gamerig's game library as a Chandra desktop module
CI / test (push) Successful in 2m25s
- New desktop module gamerig-library (components/gamerig-library, logic in lib/gamelib): the
  layout of gamerig's web library (desktop/ui) in draw ops. Top bar with the Gamerig mark, app
  count and search; sidebar with categories and counts, running apps (switch to, stop) and rig
  status (GPU, display, audio); card grid with featured games two columns wide, icon tiles,
  category and status badges, description, install hint, Launch / Big Picture / Switch to / Stop.
  Typing filters, arrows + Enter launch, the wheel scrolls. Colours: follow desktop, dark, light.
- New game-library capability: tables 26-28 (status, games, launch modes), request 45, in the
  wasmer/wasmtime stub, the MoonBit wasmhost and the Rust host-wasm.
- compositor/shell/gamelib.mbt polls GET $GAMERIG_DESKTOP_API/api/state (default
  http://127.0.0.1:8091) every 2 s with curl on a socket and POSTs launch/stop/focus; a file://
  base reads a state file (tests).
- --desktop NAME picks what fills the desktop at start. scripts/gamerig-kiosk.sh now runs a
  hybrid kiosk with the library as the desktop (CHANDRA_KIOSK_MODE=strict for the old one).
- Tests: lib/gamelib, compositor/host/gamelib_test.mbt, a host-wasm test; docs/gamerig-library.md
  with a screenshot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgvjzw8hHirxRsXSsE
2026-11-26 02:57:07 +00:00
Claude fa932f9ac0 GTK windows (Gajim, GNOME apps) resize from their shadow and all four edges
CI / test (push) Successful in 3m44s
GTK draws no border, only a shadow, and resizes only from a press in that
shadow, which Chandra never hands to the client. Chandra's own zones were
~4px wide around the visible edge and there was none on the top edge, so
Gajim (GTK 4) looked unresizable. Client-decorated windows now get zones
that reach up to 12px into the shadow (GTK's own handle size, at least 6px)
plus 3px over their edge, with 16px corners, top edge included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiu4r7mEXBdKY6cgv6
2026-11-26 02:48:22 +00:00
Claude b4f7149c72 Kiosk: --kiosk-hybrid keeps the desktop and locks only leaving the session
CI / test (push) Successful in 3m49s
Panel, launcher, dock, desktop module and shortcuts stay; Log out and power
actions are refused while locked. Admin escape and chandra-ctl kiosk work as
in the strict kiosk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgvjzw8hHirxRsXSsE
2026-11-26 02:38:02 +00:00
Claude f0c39757d7 GTK 3 windows get Chandra's frame: org_kde_kwin_server_decoration
CI / test (push) Successful in 12m52s
GTK 3 has no xdg-decoration support, so every GTK 3 window without its own
header bar (Webby, Nemo-style apps) drew GTK's fallback title bar: a centered
title, only a close button, and a dark border inside Chandra's CSD box.
GTK 3 asks for server-side decoration through KWin's
org_kde_kwin_server_decoration instead. Chandra now advertises it with
default mode Server; request_mode(Client) (GTK 3 apps with a header bar)
keeps their own frame.

The Settings portal also answers org.gnome.desktop.wm.preferences
button-layout "appmenu:minimize,maximize,close", so apps that still draw
their own title bar show the same three buttons as Chandra's frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hghaEWWsCBgEq6iZHj
2026-11-26 02:37:48 +00:00
Claude 63ce79fa7c Drop pkg.generated.mbti files the test run left in the last commit
CI / test (push) Successful in 12m25s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhiJfJNAYqWzQiuKMf
2026-11-26 02:36:40 +00:00
Claude 9f7489cfea Face unlock window: live camera preview, Snap, thumbnails, one password on Apply
CI / test (push) Failing after 12m30s
Settings > Session "Add or remove faces…" (and "Remove…" on a face) opens a
compositor-drawn Face unlock window instead of running root steps one by one:

- chandra-face camera runs as the user (no password): it streams a small live
  picture with the face box and a cropped thumbnail per snap; the snaps'
  embeddings stay in that process, nothing is written to disk.
- Click a snap to drop it; mark saved faces Remove/Keep.
- Apply saves the snaps as one face and removes the marked ones in one root
  `chandra-face apply` (JSON on stdin, validated) through run0/pkexec: one
  password prompt.
- New raster host function image-pixels (host-wasm, wasmhost, native) for the
  window's pictures.

Tests: camera session and apply in face/test_face.py; the window end to end
against a fake tool in compositor/host/face_test.mbt. Docs explain why the
change itself still needs root.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhiJfJNAYqWzQiuKMf
2026-11-26 02:36:29 +00:00
Claude 0a9787ae36 Chrome's own frame: honor zxdg_toplevel_decoration_v1.set_mode(client_side)
CI / test (push) Successful in 2m18s
Chrome with "Use system title bar and borders" off, and its installed web apps (PWAs), ask
for client-side decoration. Chandra always answered server-side, and Chrome kept drawing its
own title bar and shadow anyway (window geometry 10px in), so Chandra's title bar showed above
Chrome's with Chrome's shadow as a gap. Now a client asking for client_side gets it and is
framed like a GTK window (ToplevelFrame client_side); unset_mode or server_side keep Chandra's
frame. Checked with Chromium 158 on Ozone Wayland, headless. Test in csd_test.mbt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkfW5ttNd831XmdsC5
2026-11-26 02:27:05 +00:00
Claude 81cb8f9a1c docs: gamerig kiosk revisited on Xorg: Chandra as an X client, go
CI / test (push) Successful in 2m38s
Chandra runs as gamerig's library window on its NVIDIA Xorg; games, Selkies
and server.py stay as they are, so dmabuf/Xwayland are no longer needed. Gap
list, size (Chandra package 12 MiB gz measured), staged plan, test status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgvjzw8hHirxRsXSsE
2026-11-26 02:24:36 +00:00
Claude d521d0d840 Kiosk mode: --kiosk CMD runs one fullscreen app, locked down, restarted when it exits
CI / test (push) Successful in 4m10s
No panel, no compositor shortcuts or desktop menus, the focused window
fullscreen (dialogs float), CMD restarted with backoff. Ctrl+Alt+Shift+Escape
or chandra-ctl kiosk lock|unlock|status for admin work. --app-id sets the X11
WM_CLASS / Wayland app id of Chandra's own window. scripts/gamerig-kiosk.sh
runs Chandra as a gamerig rig's library window on its NVIDIA Xorg.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgvjzw8hHirxRsXSsE
2026-11-26 02:22:03 +00:00
Claude 4920f505e5 dock test: don't expect LibreOffice's catalog name (CI has no .desktop for it)
CI / test (push) Successful in 2m18s
The menu title is the app's catalog name, which is just the id on a machine
without libreoffice-writer.desktop. The window rows check is enough.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiPCFHRxaJQvwex6ry
2026-11-26 02:19:19 +00:00
Claude e184e29600 X11 backend: ignore a stale _NET_SUPPORTING_WM_CHECK; tested on NVIDIA Xorg
CI / test (push) Failing after 2m3s
A window manager that was killed leaves the property on the root window,
so Chandra opened a 1280x720 window instead of taking the screen (seen on
a Vast.ai NVIDIA rig after pkill -9 openbox). Check that the window it
names exists and points at itself, as EWMH says. docs/x11.md records the
NVIDIA test (GTX 1650, driver 595.91.07).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhLFs4VtHV26G1iyeo
2026-11-26 01:59:17 +00:00
Claude ae48cc5bf4 Applications menu and Icon Desktop: show each app's .desktop icon
CI / test (push) Failing after 2m56s
The launcher's rows drew a letter circle and the Icon Desktop fell back to
letter tiles for every app that wasn't in the dock: the shell only published
icons for windows' and dock apps. publish_icons now also covers the rows the
open Applications menu lists (only those, so opening it looks up a handful of
icons) and every catalog app when the desktop module imports icons. Lookups
are the dock's (theme chain, absolute Icon= paths, PNG on the native host,
SVG too on the wasm host, generic app icon, then the letter tile) and cached
per id; an unchanged icons table is no longer re-sent every frame.

launcher-widget imports icons; the JS host has an icons stub (always 0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkhaM5djqPXPQNs7QR
2026-11-26 01:56:01 +00:00
Claude 71f0b858d6 Smoother animations without a GPU: faster rasteriser, frame pacing, software/hardware mode
CI / test (push) Failing after 3m2s
Measured headless at 1920x1080 with CHANDRA_FRAME_TRACE (new: one log line per drawn frame):
- Overview open: 46 -> 62 fps, worst frame gap 69 -> 36 ms, raster 14 -> 5 ms a frame.
- Live Starfield: 19 -> 30 fps (its target), raster 49 -> 13 ms, CPU 97% -> 46%.

Rasteriser (MoonBit host; circles and previews also in the Rust host):
- Blending works on two channels at a time in 16-bit lanes with an exact /255: same pixels,
  about 3x quicker on big translucent fills (the overview's dim, the starfield's nebulae).
- Filled circles are drawn as row spans, rings skip their empty middle (a sqrt per pixel of the
  bounding box before). Same pixels; a Rust test checks it against the old loop.
- Window previews gliding in the overview are sampled straight from the preview at each frame's
  size instead of filtered and cached at a size used once; the MoonBit host also gets the
  one-large-size cache and 4096 px draw limit the Rust host had (it kept every size and didn't
  draw previews past 1024 px).
- Image scaling sums each output row's columns once, with 32-bit sums and division.

Frame pacing: frames are drawn only when the output can take them (no page flip in flight on
KMS; the previous frame shown nested and on X11), with a frame every 250 ms for an output that
never gets ready. The KMS loop runs at 125 Hz, so animations used to rasterise frames that were
never shown.

Software or hardware mode (compositor/shell/render_mode.mbt, docs/rendering.md): detected from
the DRM render nodes' drivers (and NVIDIA's proprietary driver, LIBGL_ALWAYS_SOFTWARE),
overridden by CHANDRA_RENDER=software|hardware or Settings > Session "Lighter animations"
(state.edn :render, saved only when it differs from what was detected). Software mode remakes
changing previews every 200 ms instead of 100 ms and caps desktop modules at ~30 fps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkTQp5uN5FtwpzrXUA
2026-11-26 01:55:50 +00:00
nandiandClaude Sonnet 5.5 1aabccba5d Face unlock: point at the webcam by its stable by-id path, not /dev/video0 (OBS virtual camera)
CI / test (push) Failing after 3m0s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjM4nPcLCbqchiA2V3
2026-11-25 17:54:26 -08:00
Claude 01bd8281d5 Dock: plain icons always come before the task pills
CI / test (push) Failing after 2m33s
With window titles on, a pinned app that was running drew as a pill in its
pin slot, so idle pinned icons ended up between pills. Now the dock shows
the pinned apps that aren't running first, then every task: running pinned
apps in pin order, then the other running apps. The divider sits between
the two groups. Squeezing the pills to icons keeps the order; with titles
off the plain pinned order stays. Move left / right in the menu follow the
pin list, not the shown position.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiPCFHRxaJQvwex6ry
2026-11-26 01:53:43 +00:00
Claude 5403777451 Session: replace a Qt platform theme whose plugin isn't installed
CI / test (push) Successful in 2m10s
QT_QPA_PLATFORMTHEME=gnome left in the environment without QGnomePlatform
made Qt load no platform theme, so KF6 apps got a light Breeze palette
while the Breeze style and Dolphin's view read the dark kdeglobals colors:
Dolphin's rows alternated near-black (with dark text) and light.
chandra-session now keeps a preset theme only if its plugin exists for Qt 6
or 5, else picks kde / xdgdesktopportal as before. Reproduced and checked
with Dolphin 26.08 / Qt 6.11 / KF 6.32 headless.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hivwxSsQ56aGGv4cFQ
2026-11-26 01:43:02 +00:00
Claude 3e35c4dfa5 One install recipe: just install installs everything
CI / test (push) Successful in 2m25s
just install now builds as you, then asks for root once and installs the
whole thing: the login session (wasm compositor on the MoonBit host,
modules, chandra-ctl, KDE colors, portal) and face unlock (helper, PAM
module, config, models). The alternatives are flags instead of recipes:
--link (was install-dev), --rust (install-rust), --native
(install-native), --pam (install-face --pam), --no-face, --no-models.
The PAM module is compiled as you into build/, so root only copies it;
without a compiler or libpam headers face unlock is skipped with a warning.
just uninstall removes face unlock too (--purge: enrolled faces).

Removed: install-dev, install-rust, install-native, install-face,
uninstall-face and the old install-session* / uninstall-session aliases.
New docs/install.md; README, docs and installer hints updated. Also drops
a committed __pycache__ file and ignores __pycache__/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkA52AocBmJHipFRqb
2026-11-26 01:38:58 +00:00
Claude e6be3825d0 X11 backend: run Chandra on Xorg (NVIDIA's proprietary driver)
CI / test (push) Successful in 2m28s
--x11 shows the desktop on the X server in $DISPLAY: a resizable window
under a window manager (--fullscreen asks it for fullscreen), or the whole
screen when no window manager runs, following xrandr resizes.

compositor/x11 is a pure X11 wire-protocol client (no libX11/xcb), so it
runs in the wasm compositor on both hosts and in the native build. Frames
go through MIT-SHM 1.2 (ShmAttachFd of the host frame memfd, paced by
ShmCompletion), with a core PutImage fallback. The keymap given to clients
is the X server's own (xkbcomp -xkb $DISPLAY -); X auto-repeat is dropped,
modifier/lock state comes from X's modifier map; MIT-MAGIC-COOKIE-1 auth.

chandra-session --x11 (and the new "Chandra (X11)" xsessions entry) runs
it as the login session; --login-session gives an X11 session what --drm
implied (power actions, polkit agent, system theme). just run-x11.
Docs: docs/x11.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhLFs4VtHV26G1iyeo
2026-11-26 01:37:49 +00:00
Claude 90fdda2455 Client-drawn window frames: GTK apps (GNOME Files) get no second title bar
CI / test (push) Successful in 2m57s
GTK never asks for server-side decoration (it has no xdg-decoration support), so it draws its
own header bar plus a transparent shadow margin around it, and says where the real window is
with xdg_surface.set_window_geometry. Chandra drew its Breeze frame around every window anyway
and blitted the whole buffer from the frame's corner: a second title bar on top, and the
content shifted down/right by the shadow (a see-through gap), with the right/bottom cut off.

- The server reports per window who draws the frame (ToplevelFrame: client-side when the
  client never made a zxdg_toplevel_decoration_v1, plus the window-geometry offset).
- A client-decorated window gets no Chandra frame and fills the frame's whole box
  (HostWindow::client_rect): it is configured for that size, drawn with its buffer shifted by
  the geometry offset (its own shadow drawn around it), and pointer coordinates and popup
  placement use the same origin. Tiling, title-bar hit areas and resize zones are unchanged.
- xdg_toplevel.move / resize (dragging a header bar, a CSD border) start Chandra's move and
  resize drags; they were ignored before.
- Tiled windows get the tiled_left/right/top/bottom states, so GTK drops its shadow and
  rounded corners there.

Checked with real Nautilus 46 and gtk4-demo on the headless native compositor. Tests:
compositor/host/csd_test.mbt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkfW5ttNd831XmdsC5
2026-11-26 01:35:31 +00:00
Claude b097116ded Face unlock: Python, OpenCV and numpy from a root-owned pixi environment
CI / test (push) Successful in 2m41s
- face/pixi.toml + pixi.lock (python 3.12, numpy, opencv-python-headless). `just install-face`
  passes the pixi on your PATH; install.py runs `pixi install --frozen` as root into
  /usr/local/lib/chandra/face-env (not the checkout's .pixi: the PAM module runs this Python as
  root, so it must not be user-writable), writes the helper's shebang for it and builds the PAM
  module with it as the default python. No python3-opencv needed; uninstall removes the env.
- The PAM module now also refuses a Python that isn't root's; group-writable is accepted only
  for group root (conda/pixi files are 0775 root:root), in the module and chandra-face's checks.
- Elevation re-runs on the same interpreter (sys.executable). "OpenCV is missing: run just
  install-face" instead of naming the distro package. Dropped a stray __pycache__.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhiJfJNAYqWzQiuKMf
2026-11-26 01:34:45 +00:00
Claude fa634956cc auth dialog: keep typed text when the polkit helper ends before asking
CI / test (push) Successful in 2m1s
If polkit-agent-helper-1 exited (or the socket service refused) before
sending a PAM prompt, the dialog counted it as a wrong password, wiped the
field and restarted the helper immediately, in a tight loop, so typing
seemed to do nothing. Now such an early end keeps what was typed, shows
why, and retries after 1s/2s/4s (then on Enter). Every helper event and
route is logged as "chandra: polkit helper ..." (never the typed text).

Adds an end-to-end test that types through handle_input with a real
xkbcommon keymap, including Shift, across a helper that dies at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgkRPrAzXECBUGmNEE
2026-11-26 01:31:59 +00:00
Claude ac2d0fa205 Face unlock: say that the Settings rows need the new session (just install + log in again)
CI / test (push) Successful in 2m1s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhiJfJNAYqWzQiuKMf
2026-11-26 01:25:54 +00:00
Claude 932fca627e Face unlock: a Howdy-style PAM module, shown in the password dialog and set up in Settings
CI / test (push) Successful in 2m6s
- face/pam_chandra_face.so (`-auth sufficient`): runs `chandra-face compare` as root with a clean
  environment, forwards what it says as PAM_TEXT_INFO / PAM_ERROR_MSG, and maps its exit status
  to success / auth error / unavailable, so the password always still works. Skips remote
  sessions (PAM_RHOST, SSH_CONNECTION), a closed lid and users without faces; refuses a helper
  that isn't root's; kills one that hangs (timeout + 6 s).
- face/chandra-face (Python + OpenCV): YuNet finds the face, SFace embeds it, cosine similarity
  against the enrolled embeddings (threshold 0.42, two matching frames, dark IR warm-up frames
  skipped, optional require_ir). enroll / list / remove / clear / test / status / pam
  enable|disable / fetch-models (sha256-pinned opencv_zoo models). Embeddings only, in
  /var/lib/chandra-face/USER/faces.json (root, 0600); labels in faces.list (0644). Store, config
  and models must be root's and not writable by others. Root commands re-run through run0 (or
  pkexec), so polkit asks first. Settings in /etc/chandra/face.conf.
- `just install-face [--pam]`, `just uninstall-face [--purge]` (face/install.py; uninstall takes
  the module out of every PAM service first). `pam enable` inserts before the first auth or
  @include line (Debian's sudo has only @include common-auth), keeping a .bak.
- Password dialog: a face row ("Looking for your face…" with a sweeping ring, "Face
  recognized", or why not, "Type your password instead"); typing and Enter during the scan go in
  when PAM asks for the password. Howdy's pam_howdy.so messages are understood too.
- Settings > Session > Face unlock: "Use my face for passwords" (polkit-1 + sudo), the enrolled
  faces (Remove takes a second click), "Add a face…", and the tool's progress. New `face-unlock`
  capability: tables 24 (status) and 25 (faces), request 44, in the wasmer/wasmtime stub, the Rust
  host, the MoonBit wasmhost and chandra:host/plasmoids. compositor/shell/face.mbt runs the tool
  on a socket so the compositor never waits.
- Tests: face/test_face.py (fake camera of PGM frames + fake recognizer; --pam builds the module
  and runs it through pamtester), dialog states and message parsing (polkit_test), the dialog via
  a mock helper (auth_test, shots 14/15), Settings against a fake chandra-face (face_test).
  scripts/test.sh runs them (compositor/polkit was missing from its native list), CI installs
  libpam0g-dev + pamtester. Also regenerated two stale desktop-module bindings (doc comments).
- docs/face-unlock.md, including the limits of 2D face recognition.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhiJfJNAYqWzQiuKMf
2026-11-26 01:19:29 +00:00
Claude 0f71779819 Desktop modules: a wasm module can fill the desktop, with Icon Desktop and Live Starfield
CI / test (push) Failing after 30s
A module that exports chandra:desktop/desktop-module (wit/desktop.wit) owns the desktop behind
the windows instead of a box in the panel: same sandbox, draw ops and capabilities, drawn at the
output's full size and re-rendered on resize. It gets pointer and scroll events only on the empty
desktop (windows, panel, popups and menus always win; a drag stays with the module until
release), keys only while the desktop has focus, and can draw over the wallpaper or replace it.
Its tick() asks for animation frames only while something moves; the main loop sleeps until the
next one (wake_timeout), and frames pause while a window covers the desktop, so an idle desktop
module costs nothing.

Settings > Desktop gets "On the desktop": Wallpaper only, Clock card (default) or any installed
desktop module, saved in state.edn as :desktop, loaded at login and reloaded by chandra-ctl
reload. Right-click the empty desktop for Module settings and System settings. Hidden settings
(empty label) are persisted by the shell, which is how Icon Desktop keeps icon positions.

Samples: Icon Desktop (click to launch, drag to arrange, keyboard navigation, count and size
settings) and Live Starfield (pointer steers, click or Space warps, wheel sets speed). Served by
all hosts: compositor/wasm (native + MoonBit wasmhost) and Rust host-wasm. Docs in
docs/desktop-modules.md; tests in compositor/host/desktop_test.mbt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgf1SwPMHVfLUbJKsB
2026-11-26 00:30:32 +00:00
Claude 30f5e88639 Overview (Exposé): every window side by side when the launcher opens, or alone on Super+W
CI / test (push) Successful in 1m35s
Opening the launcher (Super tap or its panel button) now also shows every window of the
workspace scaled down beside it, over the dimmed wallpaper, like GNOME's Activities overview:
a natural layout (rows, one scale, aspect ratios kept, never enlarged), minimized windows
dimmed, windows gliding in and out over 220 ms. Hover lights a window and shows a close
button; click brings it forward and closes the overview and launcher; middle-click closes the
window; Escape or a click on empty space closes it. Typing in the launcher's search fades the
windows whose title and app id don't match.

- compositor/host/overview.mbt: layout, area beside the launcher, hit testing, easing,
  input and draw ops; previews reuse the Alt+Tab thumbnails (10 fps refresh, nothing redrawn
  once settled).
- New shortcut "overview" (Super+W) in the shortcut table, rebindable in Settings > Shortcuts.
- chandra-ctl / control socket: "shortcut ID" runs any shortcut by id.
- Both renderers keep only one large scaled copy per image (a gliding preview is drawn at a
  new size every frame) and draw images up to 4096 px.
- Tests: layout packing and aspect ratio, balance, hit testing, animation, Super tap + click,
  Super+W + Escape/empty click, search filter, middle click, inspector, control command;
  screenshots of 1/4/9 windows in dark and light.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgo3PfGPY8wwv21ZZS
2026-11-26 00:24:16 +00:00
Claude acf2daa399 CI: green again (moon update, wasmer + native deps, stale tests)
CI / test (push) Successful in 1m34s
CI has failed on every push since Nov 25. In order:

- `moon check` died resolving jqlssg/moonedn: the workflow never ran
  `moon update`, so the registry index was missing.
- The wasm-target `moon test` tried to instantiate compositor/{host,network,
  portal}, which import chandra:host/* on wasm and only run under the native
  host. scripts/test.sh now runs the wasm tests for everything outside
  compositor/, and compositor/network + compositor/portal join the native run.
- The JS (jco) host didn't know the launcher's new `session` and `power`
  imports; it now has in-memory versions and the configs grant them. Its tests
  expect the Digital Clock's 12-hour default ("2:07 PM").
- The native compositor links -lwasmer and kms needs libseat etc.:
  setup-toolchain.sh fetches the wasmer C API (WASMER_VERSION=6.1.0) into
  .tools/wasmer, test.sh puts it on the C paths, and the workflow apt-installs
  libseat/libdrm/libinput/libudev/libxkbcommon dev packages.
- Stale compositor tests: moon-disc has no source in the tree, so tests use
  network / clock-binary instead (the wasm test skips moon-disc with a notice
  when it isn't built); the in-tree layout module is a Tile | Float toggle, not
  a popup; the clock lists the calendar's two settings; the settings popup is
  390 wide, so the Panel-tab buttons moved right.

Locally scripts/test.sh passes end to end: 59 wasm, 15 host, 144 native tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiRjHvKRKCJHaGFekY
2026-11-26 00:19:52 +00:00
Claude 0feea23a06 Password dialog: Chandra is its own polkit agent, drawn in the shell layer
CI / test (push) Failing after 18s
run0, pkexec and other polkit prompts used whatever third-party agent was
installed: a plain toolkit window saying "start transient unit
'run-p15802-i1990.service'". The compositor now registers as the session's
polkit authentication agent and asks in its own dialog:

- a centered card over a dimmed screen, above all windows and client menus,
  themed (dark/light follow the Dark mode switch), keyboard-first: Enter,
  Esc, Tab order, Alt+R show/hide, Alt+D details, Ctrl+U clear
- for run0 it shows the command it will run ("gparted /dev/sda", as root)
  from run0's command line (pid from polkit's details or the unit name),
  pkexec's command from its details, polkit's message otherwise; Details
  lists the requester, target user, unit and action id
- account picker when several admins can answer (group members expanded)
- the PAM conversation through polkit-agent-helper-1: polkit 126's socket
  first, else the setuid helper on a socket pair (new sys spawn-socket on the
  native, Rust and MoonBit hosts); password, echo-on prompts, info (fingerprint)
  and errors (faillock) shown as they come; wrong password shakes and retries;
  spinner while PAM checks; Caps Lock warning
- typing through the clients' xkb keymap (groups, Shift, AltGr, Caps Lock),
  US layout when there is none
- no client has keyboard focus or input while it is up; the password is
  wiped after sending and never logged

Settings > Session > "Chandra password dialog" (state.edn :auth-agent
:system when off) switches back to the third-party agent, which
chandra-session now finds and the compositor starts (also when polkit
refuses our agent). Tests: polkit_test (keymaps, helper protocol, run0
parsing, dialog states, the socket-pair route) and auth_test (mock polkit
Authority on a private dbus-daemon, mock helper; CHANDRA_AUTH_SHOTS writes
a PNG per state). Docs: docs/auth-dialog.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgkRPrAzXECBUGmNEE
2026-11-26 00:17:04 +00:00
Claude 2a67bc83d4 docs: feasibility of Chandra as the gamerig kiosk shell
CI / test (push) Failing after 17s
What gamerig's rig-side shell does today (headless NVIDIA Xorg, Openbox,
WebKit library window, Selkies X11 capture/input), what Chandra has, the gap
list with effort and risk, size estimate, staged plan with a dmabuf go/no-go
spike first, and the physical thin-client reading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgvjzw8hHirxRsXSsE
2026-11-26 00:11:43 +00:00
Claude 6253371cb3 Dock and task manager are one module: titled window pills, pins, Super+1..9
CI / test (push) Failing after 30s
The panel had a task list and, beside it, a dock showing the same running
apps again. They are now one module, the dock, in the task list's place:

- Pinned apps, then running ones; an app with windows is a pill with its
  window's title (or name and window count) while there is room, an icon
  when the panel is crowded ("Show window titles" in Dock settings).
- Its right-click menu has the task list's window commands (Minimize /
  Restore, Maximize) for a single window, or the app's windows by title.
- It stretches like the task list did; new panels get it instead of
  tasks. A saved panel's "tasks" becomes the dock (one dock, where the
  task list was); pins are the dock's own setting, so they carry over.
- An empty dock shows a "+ Add apps" tile that opens the Applications
  menu, where right-clicking an app offers Open and Pin to dock (adding a
  dock to the panel if there is none).
- Super+1 .. Super+9 open the dock's first nine apps like a click
  (shortcut "dock-apps", rebindable in Settings > Shortcuts).
- "New window" / "Open" only for apps the catalog can start.

The tasks component, lib/panel's pill geometry and the taskbar-widget
world are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiPCFHRxaJQvwex6ry
2026-11-26 00:08:05 +00:00
Claude 42aa770452 Dark mode for KDE/Qt apps: write kdeglobals colors and set QT_QPA_PLATFORMTHEME
CI / test (push) Failing after 17s
KWrite stayed light with the Dark mode switch on. KDE apps read their colors
from the [Colors:*] groups of kdeglobals, not from the scheme's name, and the
switch only set [General] ColorScheme with kwriteconfig. Qt 6 apps also had no
platform theme under XDG_CURRENT_DESKTOP=chandra, so Qt reported an unknown
(light) color scheme whatever the portal said, and KDE Frameworks 6 apps
picked Breeze Light.

- session/chandra-kde-colors dark|light copies the scheme's color groups into
  kdeglobals (counterpart of the current scheme, else Breeze, else Chandra's
  own ChandraDark/ChandraLight) and emits KGlobalSettings.notifyChange so
  running apps repaint. The compositor calls it from the switch.
- chandra-session sets QT_QPA_PLATFORMTHEME to kde (plasma-integration) or
  xdgdesktopportal when unset, and passes it to the activation environment.
- install.py installs the script and the two color schemes.
- scripts/test-kde-colors.sh tests the rewriting, and that a running KWrite
  turns dark live; docs/dark-mode.md explains it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjmk6mgq6Gg5vgKfMp
2026-11-25 22:33:29 +00:00
Claude 114f0b4e04 Icons: follow the icon theme spec so KDE apps in the dock get real icons
CI / test (push) Failing after 19s
Pinned KDE apps (Konsole, Dolphin, Kate, KWrite, System Settings) showed
letter tiles because their Icon= names a theme icon (utilities-terminal,
system-file-manager, preferences-system) that only breeze has, and breeze
keeps icons in <context>/<size> (apps/48), which the hard-coded
<size>x<size>/apps lookup never looked in.

The lookup now reads each theme's index.theme (Directories, sizes, Type,
Scale), picks the closest directory as the spec says, searches the user's
theme (kdeglobals [Icons] Theme, GTK settings.ini, $CHANDRA_ICON_THEME) and
its Inherits chain, then hicolor, then breeze and Adwaita. It also tries the
desktop id and its last dotted part, and falls back to the theme's generic
application-x-executable icon before the letter tile. Misses are logged.

The dock's first pins are now the installed default browser, file manager,
terminal and editor (Settings > Apps) instead of the catalog's first five.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkNwArmSLRGcuxUMhw
2026-11-25 22:33:03 +00:00
Claude da56f59cf7 Shell: test that module settings menus have no blank rows
CI / test (push) Failing after 18s
The dock keeps its pinned apps as a setting with an empty label; the settings menu must skip it
(c45e0ef) rather than draw an unlabeled row. Cover config_rows directly and with the dock's real
settings, on the wasm target (no wasmer needed). No other module declares an empty label or choice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkqAzaoEVwZmqjUx99
2026-11-25 22:25:24 +00:00
Claude 4437a3a576 Rename just install-session to just install
CI / test (push) Failing after 16s
install-session(-dev/-rust/-native) become install(-dev/-rust/-native) and
uninstall-session becomes uninstall, so installing is just `just install`.
The old names stay as hidden recipes that print a one-line note and run the
new one. Docs, scripts and comments now point at the new names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hj5zRiffcgWaggHdjv
2026-11-25 22:17:05 +00:00
Claude c45e0ef431 Dock: pinned and running apps with real icons, window dots, hover names and a per-app menu
CI / test (push) Failing after 17s
The dock showed the first eight catalog apps as letter tiles, and that list reshuffled after
every launch (the catalog puts recent apps first). Now:

- Pinned apps first, in the order you set, then the other running apps after a thin divider
  (like macOS). Windows find their app by desktop id, case, the last dotted part, or the app's
  name (xterm -> debian-xterm.desktop "XTerm"); windows without an app id stay out.
- Real icons from the icon theme (the `icons` capability, as in the task manager), with the
  letter tile as fallback. The shell publishes icons for pinned apps that aren't running too.
- A dot under an icon per open window (up to three), a longer accent bar when the app has focus.
- Click: start the app if it isn't running, otherwise bring its newest window forward
  (restoring it if minimized); click a focused app again to step through its windows.
- Hover: the icon grows (neighbours a little) on a light highlight, and the shell draws the app's
  name in a label above it.
- Right-click an icon (drawn by the shell, like the task manager's window menu): Open / New
  window, Pin to dock / Unpin from dock, Move left / Move right, Quit or Close N windows, and
  Dock settings.
- Dock settings (module-config): Icon size (Small/Medium/Large), Magnify icons under the
  pointer, Show running apps that aren't pinned. The pinned list is a hidden setting (empty
  label: the shell's settings menu skips it), saved in state.edn's :module-config. Until it is
  set the dock pins the catalog's first five, and the shell saves that once so launches don't
  move them.
- The panel sizes the dock from its current items (a module's preferred width is read once).

Plumbing: new WIT world dock-widget (app-catalog, app-launch, windows, icons, exports
module-config); no new interfaces, so both hosts load it as is. lib/dock holds the items,
layout, hit-testing, drawing and pin edits, shared by the module and compositor/shell/dock.mbt.
The shell's Launch handling moved into launch_catalog_app so the menu can use it.
Also: DesktopShell::pointer_move delivered every hover move twice (a duplicated block).

Tests: lib/dock (settings round trip, app matching, item order, hit-testing with the divider,
clicks and window cycling, drawing, pin edits), compositor/host input_test (the dock in a real
compositor: saved default pins, growing for running apps, hover label, the menu's rows and
actions, settings menu without the pinned row, focusing by click), dock_test (screenshots in
_build/dock_hover.png and dock_menu.png).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkmB8pJF5ckPeecFxL
2026-11-25 22:15:01 +00:00
nandiandClaude Sonnet 5.5 0ce0de0356 Document keyring unlock: the login PAM stack must pass the password to the secret service (oo7 or gnome-keyring)
CI / test (push) Failing after 30s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 14:01:29 -08:00
nandiandClaude Sonnet 5.5 326dd06f30 install-session: install libseat for the copied host (its RUNPATH only resolves inside the checkout)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 13:47:35 -08:00
Claude bb7c9b947f Settings > Apps: choose the default browser, email, files, terminal, editor, viewers and players
CI / test (push) Failing after 45s
- A sixth Settings tab, Apps (key 6, SettingsTab::Apps; the popup is 390 px wide for it): Web
  browser, Email, File manager, Terminal, Text editor, Image viewer, Video player, Music player,
  PDF and documents, Archive manager. Each row shows the current default with its real icon (the
  icon-theme lookup the task manager uses; a letter tile when there is none). Click a row to list
  the installed apps that can take it, click one to make it the default. A chosen app that has
  been uninstalled since is named in red under its row ("gthumb is not installed any more").
- Installed apps come from the .desktop files in the XDG data dirs (and flatpak's exports), with
  MimeType= and Categories= (desktop_entry_keys, now shared with the launcher's parse_desktop).
  A kind lists the shown apps that handle one of its MIME types; the terminal lists
  TerminalEmulator apps; browsers are only offered as browsers.
- Reading follows the mimeapps.list spec: $XDG_CONFIG_HOME/[chandra-]mimeapps.list, then
  $XDG_CONFIG_DIRS (/etc/xdg), then $XDG_DATA_HOME and $XDG_DATA_DIRS applications/; the first
  installed [Default Applications] entry wins, else [Added Associations], else mimeinfo.cache
  (minus [Removed Associations]), else the first installed app that handles the type. A hidden
  (NoDisplay) default still counts and its name is shown.
- Setting writes [Default Applications] in ~/.config/mimeapps.list for each of the kind's MIME
  types the app handles (always the main one: http/https/text/html for browsers, mailto,
  inode/directory, text/plain, image/png..., video/mp4..., audio/mpeg..., application/pdf...,
  application/zip...), as xdg-mime default / xdg-settings do, without running them. Every other
  section, entry, comment and blank line is kept; the app leaves those types' [Removed
  Associations]; a chandra-mimeapps.list that already names one of those types is updated too.
- The terminal has no MIME type: state.edn :terminal "kitty" (desktop id), also written first in
  ~/.config/xdg-terminals.list (xdg-terminal-exec). Terminal=true apps from the launcher (and
  session restore) now start in it (foot -e, kgx/gnome-terminal/ptyxis --, kitty <cmd>, wezterm
  start --) instead of always foot; with no choice: xdg-terminals.list, then foot, then any
  installed terminal. Terminal apps are listed when any terminal emulator is installed, not only
  foot.
- New `default-apps` capability (categories, apps, set-default, refresh): host tables 11 (sss:
  name current missing) and 12 (issii: category id name icon current), request 19 (category *
  1000 + app, -1 rescans) in the wasmer/wasmtime stub, host-wasm and the MoonBit wasmhost
  (chandra:host/plasmoids default-app(s32)). Nothing is scanned until the tab opens (refresh).
- Tests with a temporary XDG tree: categories and current defaults (user file, system file,
  Added Associations, mimeinfo.cache, missing apps, hidden defaults), writing that keeps other
  entries, desktop-specific files, the terminal list and commands, the Apps tab end to end, and
  the :terminal round trip through state.edn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgywj7RPmFdFhpzGZj
2026-11-25 21:27:30 +00:00
Claude 442f9477b4 CPU, round two: cheaper client captures, content-only redraws, damage-limited KMS and nested output
CI / test (push) Failing after 19s
Measured on the MoonBit host, 1080p, cloud container (two runs each, before -> after):
- full-screen (tiled) client redrawing at 60 fps: 43/39% -> 31/35%
- 800x600 floating client at 60 fps: 15.5/13.2% -> 10.4/11.9%
- client inside the nested window: nested 18% -> 12%, outer 17% -> 11.6%
- Alt+Tab open over two animating clients: 36.6% -> 25.4%
- idle (headless / nested): 0.2-0.6% -> 0.1-0.3%

wasmhost raster:
- capture keeps client pools mapped (keyed by dev/inode/size, dropped after 1 s unused) and
  reuses released surface buffers, swizzling a word at a time: 3.2 -> 2.1 ms per 1080p commit.
- a window whose only change is a new buffer damages just its client area, and the topmost
  opaque buffer that covers the damage is drawn first (no backdrop copy, desktop card, lower
  windows or its own decoration under it): submit 3.2 -> 0.8 ms per full-screen frame.
- the framebuffer tracks what changed since each output took it. The nested window's frames
  are a ring of three mapped memfds, each updated only where the screen changed, instead of
  a new memfd with a full 8 MB conversion and write every frame.
- KMS: present copies only the rows the back buffer is missing (this frame's change and the
  last one's), and kms_stub.c is compiled with -O2 (its stub-cc-flags dropped moon's default,
  so the per-frame copy ran unoptimised).
- images re-filled under the same handle (Alt+Tab previews) damage where the panel draws them:
  before, a live preview only repainted where it overlapped the window that redrew.

compositor:
- Alt+Tab previews of a window that keeps redrawing are remade at most every 100 ms (scaling a
  1080p buffer takes ~2 ms); the loop keeps its pace while one is pending.
- set-tokens is sent to the host only when the theme changes (it was 9 calls a frame).
- /proc is sampled only when a module imports `system`; a machine without a battery looks for
  one every 30 s instead of probing eight sysfs paths every second.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkh3qygSXtftCTVhSZ
2026-11-25 21:16:41 +00:00
Claude 99c6c66726 Launcher: Reload session, and Log out moves in from its own module
CI / test (push) Failing after 17s
The Application Launcher's menu now ends in a session row: Reload, Log out, Suspend, Restart,
Power off. Log out, Restart and Power off take a second click on the same button (a status line
says "Click Log out again to confirm"); Reload and Suspend act at once.

- Reload calls the new session.reload, which reaches the shell as the ReloadSession request
  (native stub: request 8 with n 1; host plasmoids.wit: reload-session; host-wasm: Req::ReloadSession)
  and runs DesktopShell::reload_modules(""): every panel module again from disk, in place, with
  its settings. Windows and apps keep running. The compositor redraws the whole frame after it.
- Suspend / Restart / Power off use the power capability, the same calls as Settings > Power.
- The standalone logout module is gone (component, world, components.txt). Saved panels drop
  "logout", or get the launcher in its place when they had none; panel.edn is rewritten without
  it. A stale logout.wasm is hidden from Settings > Panel (retired_modules).
- Tests: lib/launcher session row, shell migrate_panel, host input tests for Log out and Reload,
  host-wasm launcher session row; control_test uses inspector.wasm instead of logout.wasm.
- README and docs/reloading.md describe the session row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjKUnSS3D92ThigvJf
2026-11-25 21:01:17 +00:00
Claude 68164ff75e Reload panel modules from outside the session: control socket, chandra-ctl, SIGUSR1
CI / test (push) Failing after 16s
Until now a module reload was only reachable by clicking Settings > Panel inside the session.
Now:

- The compositor listens on $XDG_RUNTIME_DIR/chandra/<wayland socket name>.sock (the login
  session's is wayland-moon-0.sock) with a line protocol: ping, list, reload [NAME], help.
  Replies end with an "ok ..." or "error ..." line. It lives in compositor/host/control.mbt,
  runs from ChandraCompositor::step, and its fds join the idle loop's wait set, so an idle
  desktop still sleeps (measured ~0.4% CPU on wasmhost, ~0.1% on host-wasm) and wakes for a
  command. A path another live compositor answers on is left alone.
- DesktopShell::reload_modules(name) reloads every loaded module (or those whose module id,
  stem, slot or path is NAME) in place via replace_slot: same panel position, saved
  :module-config applied, a module that fails to load stays as it was and the error is
  reported to the caller and shown as a notice. The catalog is rescanned.
- SIGUSR1 to the host reloads every module (result in the log and the notice): new WIT
  function sys.take-sigusr1, implemented in compositor/sys (native build and wasmhost) and
  host-wasm; the handler has no SA_RESTART so it interrupts the idle poll.
- session/chandra-ctl (installed to /usr/local/bin), `just reload [NAME]`, docs/reloading.md,
  README.
- Tests: compositor/host/control_test.mbt (protocol, reload all / by name / by slot, order
  and settings kept, failing module kept, busy socket). Checked headless on both hosts with
  chandra-ctl and kill -USR1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjLJtvYcgW48okL6qQ
2026-11-25 20:57:40 +00:00
Claude 0fc2598d27 Delta drew in a 640x480 corner of a full-size window: ask again when a client keeps another size
CI / test (push) Failing after 17s
GPUI apps (Delta, Zed) answer a configure that takes the maximized state away by going back to
their old floating size, whatever size it asks for. Unmaximized into a tiled slot (or a layout
change while maximized), Delta kept drawing 640x480 and Chandra padded it out with the bottom
right colour to the whole frame, so only the sidebar and toolbar showed.

The server now tracks each toplevel's last configure and the serial the client acked. When a
client commits a buffer of another size after acking the latest configure, the same configure
is sent once more (GPUI, no longer maximized then, takes it). A client that still keeps its own
size gets a ToplevelSizeChosen: a floating window's frame follows it, a tiled, maximized or
fullscreen window keeps the compositor's size. Sizes take set_window_geometry and
set_buffer_scale into account.

CHANDRA_DEBUG_CONFIGURE=1 logs configures, acks and committed buffer sizes to stderr.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiKUmCPZNFNiGwd8EW
2026-11-25 20:55:58 +00:00
Claude a215dd6bf7 Clock calendar: left click slides out a month calendar
CI / test (push) Failing after 17s
Left-clicking the Digital Clock (or the Binary Clock) opens a calendar flyout that
slides up out of the panel; Escape, a click elsewhere or another click on the clock
slides it back in.

- lib/clock/calendar.mbt: month maths (leap years, weekday, ISO week numbers), a
  six-week grid, the flyout's state, drawing and hit testing. Header with the time
  (in the clock's own 12/24-hour format) and the long date; month and year with
  previous / Today / next buttons; weekday names; today circled in the accent colour,
  other months' days muted. Keys: Escape closes, t today, p/n previous/next month.
- Module settings (right click): "Week starts on" Sunday/Monday and "Show week
  numbers", for both clocks (saved per module like the other settings).
- compositor/shell/slide.mbt: popups of the clock modules slide (200 ms, ease-out in,
  ease-in out), clipped to their final place so they come out of the panel edge; the
  popup takes input at its final place at once. A popup below the panel would slide
  the other way. Theme comes from the module's tokens, so dark/light follow.
- CPU: has_timed_work() is true only while a slide runs, so the main loop only keeps
  the frame pace for those 200 ms; an open calendar redraws only when its minute or
  month changes.
- Tests: lib/clock calendar tests (wasm), compositor/host/calendar_test.mbt (open,
  slide finishes, month buttons, Escape / click outside / toggle, settings, binary
  clock). Host failures are the 5 known input_test ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjahaLE5XqnCWoEwKv
2026-11-25 20:47:06 +00:00
nandiandClaude Sonnet 5.5 10659e7655 docs: what a running session can reload after an install (panel modules yes, host/compositor no)
CI / test (push) Failing after 17s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjq2YbDd5zJXXKWqSR
2026-11-25 12:43:04 -08:00
Claude 34885bfdda Settings > Shortcuts: rebind the compositor's keyboard shortcuts
CI / test (push) Failing after 18s
- One shortcut table (compositor/shell/shortcuts.mbt): named actions with their default combos,
  the same as before: Super tap launcher, Super+D, Alt+Tab, Super+Shift+S, Super+Shift+Print,
  Print, Super+Print, Super+Ctrl+Print, Super+Shift+R, Super+Alt+R, Super+Ctrl+R. Combos are
  "Super+Ctrl+Alt+Shift+Key" text (parse/print, aliases like Meta, PrtSc, Return); "Super" alone
  is a Super tap. Two shortcuts on one combo conflict and the one listed first wins.
- The compositor looks every non-modifier key press up in the table (compositor/host/
  shortcuts.mbt) instead of the hardcoded checks in showdesktop/screenshot/recorder; the switcher
  reads its combo from it (hold the combo's modifiers, its key steps, Shift reverses, releasing a
  held modifier switches). Matching is now exact on Super/Ctrl/Alt/Shift (caps/num lock ignored),
  so e.g. Super+Shift+D or Ctrl+Print no longer fire Super+D / Print.
- Settings gets a fifth tab, Shortcuts (key 5, SettingsTab::Shortcuts): every shortcut and its
  combo. Click a row (or Enter) and press the new keys: the compositor captures the combo before
  anything else sees it (Escape cancels, Backspace unbinds, a Super tap binds "Super"; window
  switching keeps waiting until the combo has a modifier). Changed rows get a Reset button
  (Backspace/Delete on the highlighted row too), plus "Reset all to defaults"; conflicting combos
  show in red with a line saying which shortcut wins. The popup is 360 px wide for the fifth tab.
- New `shortcuts` capability (shortcuts, capture, cancel-capture, reset, reset-all), served from
  host table 10 and request 18 by the wasmer/wasmtime stub, host-wasm and the MoonBit wasmhost
  (chandra:host/plasmoids `shortcut(s32)`).
- Changes are kept in state.edn as :shortcuts {:show-desktop "Super+Ctrl+D" ...} (only the ones
  that differ; "" unbinds), applied at startup and live.
- There were no window-management or tiling key shortcuts to move into the table.
- Tests: combo parsing/printing, defaults, conflicts, switcher constraint, save/restore pairs,
  rebinding through the compositor, capture (Escape/Backspace/Super tap), the Shortcuts tab
  (capture, conflict line, Reset, Reset all) and the state.edn round trip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjypNwGHE9WeFvnWLA
2026-11-25 20:41:22 +00:00
Claude 8ecdef17d4 Settings > Panel: a cleaner module selector with reordering
CI / test (push) Failing after 17s
The Panel tab was one flat list: every panel module with an "x" that removed
it on any click, then every module on disk again with cryptic "x1" counts and
a Browse row that looked selected.

- "In the panel, left to right": the modules in panel order, each with
  move up / move down / remove buttons. Clicking the row itself does nothing,
  so a stray click no longer removes a module. Backspace/Delete removes the
  highlighted one, PageUp/PageDown move it.
- "Add to the panel": grouped (Apps and windows, System, Clocks, Other),
  each with a one-line description and an Add button. A module already in the
  panel is left out, except clocks, which offer "Add another". With nothing
  left: "Everything is in the panel".
- "Browse for a module file..." is a secondary outlined button.
- Section headings are larger and full contrast; the popup is 320 wide and
  now fits a 720-high screen with the default panel.

Reordering goes through a new modules.move-instance(slot, delta) capability
call, plumbed through both hosts: wasmer stub request 17, host-wasm, the
plasmoids host WIT (move-instance(instance-move)) and wasmhost. The shell's
move_slot clamps to the ends and saves panel.edn, so the saved format is
unchanged. DesktopShell::slot_popup_texts lets tests find popup rows by text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhRDWZf5WcmrNwnFe3
2026-11-25 20:35:54 +00:00
Claude c1936299cb README: describe Chandra as it is now
CI / test (push) Failing after 17s
Rewrite the M0-era README for the current project: the rename from
moon-plasma, the MoonBit wasmhost as the default host (Rust host-wasm as
fallback), the just recipes, shortcuts (Super+D, screenshots, recording),
panel modules and Settings, config/state paths, CHANDRA_* variables, and
known gaps. Add a headless desktop frame (docs/screenshots/desktop.png).
TOOLCHAIN.md and ARCHITECTURE.md get notes that they describe M0 and point
to the README for the current state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhZBVRuyDznwycdo4s
2026-11-25 20:31:19 +00:00
Claude 005e11e7bf Chrome follows the Dark mode switch: Chandra serves the portal's color-scheme
CI / test (push) Failing after 17s
Chrome (and Firefox, Electron, GTK 4, Qt 6) read dark/light from xdg-desktop-portal's Settings
interface. With XDG_CURRENT_DESKTOP=chandra and no chandra-portals.conf, xdg-desktop-portal found
no Settings backend (gtk/gnome are UseIn=gnome, kde is UseIn=KDE) and exported no Settings
interface at all, so the gsettings color-scheme a790901 sets never reached Chrome.

- compositor/portal: the compositor is an org.freedesktop.impl.portal.Settings backend
  (org.freedesktop.impl.portal.desktop.chandra on the session bus): Read/ReadAll of
  org.freedesktop.appearance color-scheme (1 dark, 2 light), SettingChanged when the switch flips,
  version property, introspection. Login session only; the main loop wakes on its socket.
- compositor/network/dbus.mbt: serve calls (on_call, reply, reply_error), emit and receive
  signals, sender field, session bus address.
- session/chandra.portal + chandra-portals.conf, installed to /usr/share/xdg-desktop-portal by
  install.py: Settings from chandra first, then gtk/kde/gnome; other portals from gtk/kde/gnome.
- chandra-session restarts a running xdg-desktop-portal so it reads the config for this desktop.
- scripts/test-portal-dbus.sh: end to end behind the real xdg-desktop-portal on a private bus
  (ReadOne gives 1, flipping gives SettingChanged 2). docs/dark-mode.md: how to check it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhkztRQM7vcSuHX4bB
2026-11-25 20:30:30 +00:00
Claude c7a6c8376e Merge the 12-hour clock into the Digital Clock
CI / test (push) Failing after 18s
clock-digital12 and clock-digital had become the same module (same lib/clock
code, same right-click settings), differing only in the starting format. Keep
one: the Digital Clock now starts in 12-hour mode with AM/PM, and its
"Time format" setting switches to 24-hour.

- components/clock-digital12 is gone (and from scripts/components.txt);
  lib/clock drops digital12_info/digital12_config.
- The default panel loads clock-digital.
- "clock-digital12" stays an alias (find_module, slot_of, saved panels) and is
  never listed in the module picker, even if an old .wasm is still installed.
- panel.edn gets :version 2. A version-1 panel is migrated once: the old
  12-hour clock becomes the Digital Clock with its settings (state.edn
  :module-config) moved over in 12-hour mode; a panel that had the old
  24-hour Digital Clock keeps 24-hour. The file is rewritten afterwards.
- Tests updated, plus a migration test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgnZsS91fwCreut8FL
2026-11-25 20:29:12 +00:00
Claude 9c0a794c2d run0: install via scripts/as-root, chandra-root for GUI apps as root, session refuses root
CI / test (push) Failing after 16s
- scripts/as-root runs a command as root with run0 (systemd PID 1 + run0 present), else sudo,
  doas or pkexec; resolves the program to an absolute path since run0 doesn't inherit PATH.
  The install-session recipes use it and pass install.py by absolute path.
- session/chandra-root (installed to /usr/local/bin): run a graphical app as root inside
  Chandra, passing WAYLAND_DISPLAY (absolute) and the Wayland toolkit variables through
  run0 --setenv (or sudo/doas/pkexec env).
- chandra-session: refuses to run as root (CHANDRA_ALLOW_ROOT=1 overrides), fills in HOME and
  XDG_RUNTIME_DIR when started without a login environment, logs when the logind session has
  no seat (run0 --user / su / ssh), and starts an installed polkit agent once the socket is up
  so run0/pkexec from the launcher can prompt (CHANDRA_POLKIT_AGENT picks one or 'none').
- install.py: checks for root before --remove too; installs chandra-root.
- docs/run0.md: invocations for installing, starting from a TTY, apps as root, polkit agents.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkq6Hq7AXG85g5HyJU
2026-11-25 20:13:55 +00:00
Claude f844ac66ff Task manager: right-click a window's pill for Minimize/Restore, Maximize, Quit
CI / test (push) Failing after 16s
- Right-clicking a pill in the task manager opens that window's menu (titled with the window's
  title): Minimize (Restore when minimized), Maximize (Restore size when maximized) and Quit,
  which asks the app to close the window (xdg_toplevel close, like the title-bar close button).
  Empty task-bar space keeps the module's own menu (Module settings, Replace with, Remove widget).
- Modules only get left clicks, so the shell draws the menu and hit-tests the pills itself: the
  pill geometry moved to lib/panel/tasks.mbt, shared by the tasks module and the shell. No WIT
  change, so every host works as before.
- New menu row kind 6 and ShellAction::Window(id, WindowCommand); the compositor runs it through
  the same WM requests as the title-bar buttons. WinInfo carries `maximized`.
- Tests: native end-to-end (menu rows, minimize/restore, maximize/restore size, Quit sends close,
  empty space keeps the module menu) and lib/panel pill geometry tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiX13fXK1eMboRe5oQ
2026-11-25 20:13:38 +00:00
Claude f33f84c35b Make the MoonBit host the default: just run, run-drm and install-session use build/wasmhost
CI / test (push) Failing after 17s
The Rust host stays as a fallback: just run-rust, run-drm-rust, install-session-rust
(session/install.py --rust-host). build-wasmhost.sh fetches the wasmtime C API when it is
missing and replaces build/wasmhost by renaming, so a running dev session keeps its copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiNfjrw2edja7LiRLB
2026-11-25 20:10:51 +00:00
Claude 2774516abf wasmhost: SVG icons with clip paths and masks (nanosvg drew them as black boxes)
CI / test (push) Failing after 18s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiNfjrw2edja7LiRLB
2026-11-25 20:09:39 +00:00
nandiandClaude Sonnet 5.5 b4b9ba0e10 remote-build: pull artifacts with sprite file pull; a tar stream over exec breaks on reconnect
CI / test (push) Failing after 18s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hk4tUnZsmzjbobxkwy
2026-11-25 12:06:47 -08:00
Claude caa12058fd Screenshots, recording and --gfx-out keep the screen's pixels on the host
CI / test (push) Failing after 17s
New chandra:host/raster functions, on both hosts: write-frame-png (--gfx-out),
grab-recording-frame / send-recording-frame (the recorder streams frames from the
host to ffmpeg) and snapshot-frame / snapshot-png / snapshot-pixels (screenshots
freeze, crop and encode the screen there; the magnifier and the notification's
thumbnail read small scaled copies). The wasm compositor sets them up through
frame_recorder and frame_shots; the native compositor keeps its pixel path.

Moving whole frames as list<u8> is cheap for the Rust host but costs about
0.4 s a 720p frame through the wasmtime C API. A full-screen screenshot now takes
45 ms on the MoonBit host (was 472) and 8 ms on the Rust host (was 112);
recording runs at 30 fps on both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiNfjrw2edja7LiRLB
2026-11-25 20:03:34 +00:00
nandiandClaude Sonnet 5.5 3b15248124 Remote build on a sprites.dev sprite: just remote-build
CI / test (push) Failing after 17s
Syncs the tree to a sprite at the same absolute path (host-wasm/build.rs bakes the
checkout's .pixi lib dir into the host's rpath), builds host, compositor.wasm and the
panel modules there, and pulls the artifacts back.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hk4tUnZsmzjbobxkwy
2026-11-25 12:03:04 -08:00
Claude 1f4b686087 Network module: Wi-Fi and wired status, connect to Wi-Fi networks, Wi-Fi and airplane switches
CI / test (push) Failing after 18s
- New `network` panel module (in the default panel, before the battery and the clock): signal bars and the
  Wi-Fi network's name, a plug when wired, crossed-out bars offline or in airplane mode. Its
  popup shows the status and the last action's outcome ("Couldn't connect to X: wrong
  password?"), switches for Wi-Fi and airplane mode, and the networks in range (strongest
  access point per name, the one in use first). Click a saved or open network to connect, a new
  secured one to type its password in a field under it (Enter or Connect), the one in use to
  disconnect, or "Forget" on a saved one. Opening the popup asks for a scan.
- compositor/network: NetworkManager over D-Bus through a small D-Bus client of our own
  (wire format, EXTERNAL auth, async calls) on the existing @sys socket calls, so neither host
  needed new imports. One ObjectManager.GetManagedObjects + GetAll every 2 s; GetSettings once
  per saved connection; RequestScan, Device.Disconnect, WirelessEnabled / WwanEnabled,
  ActivateConnection (saved), AddAndActivateConnection (new: open, WPA/WPA2 PSK, WPA3 SAE) and
  Settings.Connection.Delete. Without NetworkManager it falls back to read-only status from
  /proc/net/dev, /proc/net/wireless and /sys/class/net (no network names there), and looks for
  NetworkManager again every 30 s.
- New `network` capability (wit/capabilities.wit): status, wifi-networks, scan, connect,
  disconnect, forget, set-wifi-enabled, set-airplane-mode. Served from host tables 8/9 and a
  `network(network-request)` request by the wasmer/wasmtime stub (compositor/wasm), host-wasm
  and the MoonBit wasmhost. The stub's build_list learned bool fields; request strings are
  wiped after use (Wi-Fi passwords).
- Running out of module instances now says "too many modules loaded".
- Deferred: VPN, hotspot, hidden networks, WEP and 802.1X (enterprise) networks, IP settings,
  mobile broadband beyond the airplane switch, D-Bus signals (state is polled).
- Tests: D-Bus wire format (incl. the well-known Hello bytes), NetworkManager objects -> status
  and list, security settings, /proc parsing; the module through the shell against a fake
  backend (list, connect/forget/disconnect, password entry, switches, read-only); a host-wasm
  test; and scripts/test-network-dbus.sh, which runs the backend against python-dbusmock's
  NetworkManager on a private bus.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hizqNXcNDuef3gxa7D
2026-11-25 20:02:36 +00:00
Claude 88915842c2 Battery panel module: charge, charging state, time left, low-battery warning
CI / test (push) Failing after 18s
- New `battery` panel module (components/battery, logic in lib/battery): a battery icon filled to
  the charge with the percentage and time remaining ("73% 2:05"; time to full while charging).
  The fill turns green when charging or full, amber at 20 % and below, and at 10 % the whole
  button turns red and a "Battery low" popup opens by itself, once per discharge spell. A click
  opens the details (charge, state, time left in words). Without a battery it shows a plug.
- Right-click "Module settings": Show percentage, Show time remaining, and Without a battery
  (Show a plug / Show nothing). Saved per module in state.edn like the clocks' settings.
- New `battery` capability (wit/capabilities.wit: read -> status {percent, charge-state,
  secs-left}). Served by the wasmer stub (host ints 7-9), host-wasm and wasmhost (publish-battery).
- Host side (compositor/shell/battery.mbt): reads /sys/class/power_supply, every battery
  together (energy_* / power_now, or charge_* / current_now; capacity when that is all there
  is; device-scope batteries like mice are skipped). The `system` snapshot the Power tab uses
  now reads the battery through the same code. Time left follows a running average of the
  rate, starting over when the state changes.
- A fresh panel gets the battery module before the clock only on a machine with a battery.
- wasm_stub: MAX_INST 512 -> 2048. The host test binary creates ~70 compositors without
  unloading their modules; at 512 the last tests' panels came up half empty.
- Tests: sysfs reading against a fake power supply (energy and charge units, two packs,
  charging, full, capacity only, no battery), the running average, the module in the panel
  (text, settings, click, the critical warning, the plug), the rendering logic, and a
  host-wasm test of the module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hky51dmaUqiYW746Gz
2026-11-25 19:53:42 +00:00
Claude 05fe70a2f6 wasmhost: WASMHOST_PROFILE=1 times each host function (encode / handler / decode)
CI / test (push) Failing after 18s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiNfjrw2edja7LiRLB
2026-11-25 19:51:28 +00:00
Claude 9431254de0 wasmhost: login-session display (DRM/KMS) through compositor/kms
CI / test (push) Failing after 17s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiNfjrw2edja7LiRLB
2026-11-25 19:48:38 +00:00
Claude f52a5ff40e wasmhost: panel modules, through compositor/wasm on libwasmtime's wasm.h
CI / test (push) Failing after 17s
The native compositor's module runtime (compositor/wasm) only uses the standard
wasm.h API, which libwasmtime implements as well as libwasmer, so the MoonBit host
serves chandra:host/plasmoids with it: the same capabilities, tables and requests
as the native build, from the same code. The nested window (--window) works too:
a wasmhost compositor runs inside another one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiNfjrw2edja7LiRLB
2026-11-25 19:45:55 +00:00
Claude 2f4ce827c3 MoonBit host for the compositor component on prebuilt libwasmtime (sys, font, raster)
CI / test (push) Failing after 17s
wasmhost/ runs build/compositor.wasm with wasmtime linked as the upstream C API
library (fetched by setup-toolchain.sh) instead of compiling it: a cold build is
about 4 s against about 2 min for host-wasm. sys and font reuse the native
compositor's packages; the rasteriser is a port of host-wasm/src/raster.rs with the
pixel work in C, SVG through nanosvg. Panel modules, --drm and --window come next;
host-wasm stays the working host until then.

wit: sys.append-file. The C API moves list<u8> as one dynamic value per byte and
wasmtime caps what one call may copy, so the component writes files over 1 MiB as
write-file plus appends (host-wasm implements it too).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiNfjrw2edja7LiRLB
2026-11-25 19:42:20 +00:00
Claude 2636373a4f Power settings: screen off and suspend when idle, battery, suspend / restart / power off
CI / test (push) Failing after 18s
- Settings gets a Power tab (fourth; key 4 or SettingsTab::Power): the battery when there is
  one (the system capability), "Turn screen off after" (Never, 1 min ... 1 hour; default 10 min)
  and "Suspend after" (Never, 5 min ... 2 hours; default never), a click stepping through the
  choices, and Suspend / Restart / Power off now. Restart and Power off need a second click.
- New `power` capability (screen-off-minutes, suspend-minutes and setters, suspend, power-off,
  reboot), served by the wasmer stub (host ints 5/6, requests 13-15) and host-wasm
  (publish-power, set-screen-off / set-suspend-after / power-action).
- The timeouts are kept in state.edn as :power {:screen-off N :suspend N} when not the defaults.
- Login session only (compositor/host/power.mbt): input restarts the idle time; power_tick,
  run every pass of the main loop (an idle loop still wakes about once a second), turns the
  screen off through DPMS and back on at the next input, and suspends once per idle spell.
  Monotonic time stops in suspend, so a resumed machine waits for input and a new idle spell.
  Suspend, restart and power off run `systemctl <verb> || loginctl <verb>` (logind, so its
  inhibitors and polkit rules apply); a nested window only shows a notice.
- Display: chandra:host/display set-power and Kms::set_power; the shared C shim sets the
  connector's legacy DPMS property, shows no frames while off (frame_ready false, so the idle
  loop still sleeps), redoes the modeset when turned on, and keeps the screen off across a VT
  switch.
- components/screenshot bindings regenerated (they were stale: the module didn't build).
- Tests: idle timer sequence, the Power tab driving the shell (timeouts, two-click power off),
  the state.edn round trip, a host-wasm test of the tab, and logind commands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgxf6exeYrDGcy4WW3
2026-11-25 19:37:21 +00:00
Claude ba82d3c59b Idle desktop sleeps instead of redrawing; only changed parts of the screen are redrawn
CI / test (push) Failing after 15s
Measured headless and nested at 1080p (host-wasm), against main:
- Idle: ~9.4% CPU per compositor -> ~0.35%. Idle frames cost ~1.3 ms, and the loop
  woke 60-125 times a second to find nothing had changed.
- One 800x600 floating client animating at 60 fps: 33% -> 16% CPU; raster per frame
  ~4.5 ms -> ~0.9 ms. A full-screen tiled client: 65% -> 54% (its cost is now mostly
  copying the 8 MB buffer out of the client's shared memory).

Changes:
- shell: the wallpaper and desktop card ops (~1900, the moon disc is drawn per pixel)
  are kept and reused until what they are drawn from changes (size, theme, wallpaper,
  card position, date, hour:minute). This was ~75% of an idle frame.
- FrameSig compares the background by identity first instead of op by op.
- Host tables (windows, layouts, ...) are only sent to the host when their bytes change.
- Main loop: a pass with no input, no changed frame and nothing waiting to be shown
  blocks in the new sys.wait-readable on the Wayland socket and clients (plus the
  nested host connection; the login session's seat, DRM and libinput fds are added by
  the host) until just before the wall clock's next second, then polls every 5 ms
  until it turns, so clocks still tick on time. Recording, pending screenshots and
  toasts keep the frame pace (ChandraCompositor::has_timed_work).
- Host raster: works out what changed from the last frame. When only windows changed
  (a client drew, a window moved, focus moved) it redraws just their footprint
  (decoration and shadow included, old and new place), copying back only that part
  of the cached backdrop; anything else still redraws everything. A test checks the
  partial redraw is pixel-identical to a full one for a client redraw, a move and a
  focus change with stacking swapped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hku78wdzXtY9QsR9NW
2026-11-25 19:21:39 +00:00
Claude 2d9f4e34c5 host-wasm: incremental release builds (edit rebuild 6.5 s -> 3 s)
CI / test (push) Failing after 16s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiNfjrw2edja7LiRLB
2026-11-25 19:19:32 +00:00
Claude c32a31ffd7 Clock: AM/PM in 12-hour mode, and the default panel clock now has source
CI / test (push) Failing after 16s
clock-digital12 (the default panel's clock) was a prebuilt wasm with no source.
It is now a component built from lib/clock like the Digital Clock, starting in
12-hour mode with AM/PM, and it gets the same right-click Module settings.
Both digital clocks get a "Show AM/PM" switch, offered in 12-hour mode (on by
default).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhrQpz9texRcAtgECq
2026-11-25 19:14:46 +00:00
Claude 51b914f6cf Alt+Tab switcher: show a preview of each window
CI / test (push) Failing after 19s
The switcher is now a grid of cards: a scaled-down picture of each window's
last frame over its app icon and title, the selected card lit. Cards wrap
into rows and shrink to fit small screens.

- Previews keep the buffer's aspect ratio and are never enlarged.
- Minimized windows show the last frame they drew, dimmed, marked
  "minimized". A window with no buffer yet shows its app icon (or its
  initial) on a plain tile.
- Cheap: nothing is scaled while the switcher is closed. A preview is made
  when the switcher opens and again only when that window commits a new
  buffer (or its shown size changes), into the same image handle; handles
  of closed windows are reused. The native scaler samples at most 3x3
  points per preview pixel, so big windows cost about the same as small.
- Both hosts: native scales the wl_shm snapshot in the software renderer
  (renderer.shm_thumbnail + set_image); the wasm compositor asks the host
  with the new chandra:host/raster thumbnail(surface, w, h, reuse), which
  scales the captured surface natively, so no pixels cross the boundary.
- Frames the screenshot overlay held back mark previews stale too.

Tests: switcher_test (preview pixels, aspect, no-buffer, stale and
remade into the same handle, minimized), renderer shm_thumbnail/set_image,
host-wasm thumbnail scaling and handle reuse. Pre-existing failures on
main are unchanged (6 panel-module host tests, the screenshot panel
module test, host-wasm translucent_surfaces_blend).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjDvAsSQUdTTUGA3n5
2026-11-25 19:14:30 +00:00
Claude 8f88d93d9f Apps drawing with Vulkan on wl_shm (Delta, Zed) show every frame
CI / test (push) Failing after 16s
Delta is a GPUI app: it draws with Vulkan, and without linux-dmabuf Mesa's WSI
presents through wl_shm, making one wl_shm_pool per swapchain image. libwayland
flushes those create_pool requests with all their fds in one sendmsg (vkcube on
lavapipe sends 4), but both hosts kept only the first SCM_RIGHTS fd and closed
the rest. Every pool but the first had no memory, so only one swapchain image
ever reached the screen: stale, frozen or flickering windows.

- recvmsg keeps every fd (up to 32), in order: natively through recvmsg_fds,
  and in the wasm host through a new chandra:host/sys take-fd import.
- A commit consumes the attached buffer. A bare commit (GPUI commits after
  ack_configure) used to re-show and re-release the old buffer, which the
  client may already be drawing its next frame into.
- ARGB8888 client buffers are blended as premultiplied alpha, as wl_shm
  defines, in both rasterisers (translucent edges were darkened).
- wl_seat.name and wl_output.scale/done are only sent to clients that bound
  version 2 or later (vkcube binds v1 and aborted on them).

Regression test: a client flushes three pools with their fds in one message,
then commits a bare frame; it fails on the old code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hm8wb1UKxQxf8o6gpz
2026-11-25 19:09:18 +00:00
Claude 85f6ff42f4 Screenshot module after Spectacle (Super+Shift+S), with a screen recorder
CI / test (push) Failing after 16s
- Super+Shift+S (or Super+Shift+Print) freezes the screen under a selection overlay, like
  Spectacle's Rectangular Region: drag a rectangle (size readout under it, magnifier while
  drawing), drag inside to move it, drag its handles to resize, or click a window to select it.
  Enter or a double-click takes it, Escape or right-click cancels; F full screen, W active window,
  arrows nudge (Shift+arrows resize). Print takes the full screen, Super+Print the active window,
  Super+Ctrl+Print the window under the pointer.
- Saved as ~/Pictures/Screenshots/Screenshot_YYYYMMDD_HHMMSS.png (XDG_PICTURES_DIR honoured),
  put on the clipboard as image/png (compositor-owned wl_data selection, written to the paste
  pipe without blocking), and confirmed by a notification with a thumbnail.
- Screen recording: Super+Shift+R picks a region on the same overlay, Super+Alt+R the screen,
  Super+Ctrl+R a window; the same shortcut or the REC pill (top centre) stops. Raw frames
  (<= 30 fps, wall-clock stamped) stream into ffmpeg over a unix socket; it writes H.264 MP4 to
  ~/Videos/Screencasts/Screencast_*.mp4. The pointer is drawn in unless switched off.
- renderer: encode_png_compressed (per-row filters + LZ77/fixed-Huffman deflate): a 1280x720
  desktop is ~90 KB instead of 3.7 MB.
- New 'screenshot' capability and 'screenshot' panel module (in the default panel): Spectacle's
  modes and the recording modes with their shortcuts, and a pointer switch; the button becomes
  Stop while recording. Served by both hosts (wasmer stub request 12 / host int 4; host-wasm
  publish-screenshot and a screenshot request). Panel requests wait for a frame without the
  module's popup.
- sys: pwrite with a negative offset is a non-blocking write (pipes, sockets), SIGPIPE ignored.
- Tests: native overlay, shortcuts, window pick, module, recording (with ffmpeg); host-wasm
  module test; renderer compression test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjMGSLc5tHuzjsxGVa
2026-11-25 19:07:23 +00:00
Claude b33373d801 Right-click menus inside apps: keep them open and on screen
CI / test (push) Failing after 15s
Chrome's context menu opened and closed at once: when a client created an
xdg_popup the compositor moved keyboard focus to it straight away, and the
wl_keyboard.leave on the window made Chrome dismiss the menu. Popups now
only take the keyboard when they ask for a grab (xdg_popup.grab, as Qt
menus do) and once they have a buffer; Chrome's grab-less menus leave
focus on the window.

Also:
- honour xdg_positioner constraint adjustment (flip, slide, resize) so the
  configure tells the client where its menu really is, instead of the host
  silently nudging it on screen (Chrome then took the button release as a
  click on a menu item);
- answer xdg_popup.reposition with repositioned + configure (it was ignored,
  so clients waiting for it stalled);
- place popups by their window geometry, so Chrome's client-drawn menu
  shadow no longer shifts the menu right and down.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hikqzveCoytgF4Uyvh
2026-11-25 19:03:04 +00:00
Claude 3454619162 Double-click a window's title bar to maximize or restore it
CI / test (push) Failing after 16s
Two left presses on the same title bar within 400ms and 4px of each other
toggle maximize, like the title-bar button. A press that turned into a drag
never starts a double-click. A tiled window now floats only once the pointer
actually moves, so clicking or double-clicking its title bar leaves it in
(and restores it to) its tile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjF2tD2UuaXLzFzrvV
2026-11-25 19:00:40 +00:00
Claude 4fc4a963b4 Module settings in each module's right-click menu, and System settings
CI / test (push) Failing after 15s
- New optional WIT export `chandra:desktop/module-config` (wit/plasmoid.wit): config-items (key,
  label, choices, current value; no choices = an on/off switch) and set-config. Hosts look it up
  by name, so modules without it (or prebuilt ones like Pulse) load as before.
- Right-click a panel module: "Module settings..." (or a greyed "No module settings"), then
  "System settings..." (the settings module, Session tab), then Replace with... and Remove widget.
  The "Modules..." row is gone; right-clicking empty panel space offers "System settings..." on the
  Panel tab instead. Module settings open in the same menu: on/off rows with a check box, choices
  under a heading with the current one ticked; clicking applies at once and the menu stays open.
- Choices are saved per module id in state.edn as :module-config {"clock-digital" {"format"
  "12-hour"}} (module_config.mbt; not an owned key, so save_state keeps it) and handed back through
  set-config whenever the module is loaded. Other instances of the module follow a change.
- Both hosts: wasmer stub (optional exports 8-10, canonical-ABI decoding in wasm_native.mbt) and
  host-wasm (chandra:host/plasmoids config-items/set-config, bound with a separate `configurable`
  world so the export stays optional).
- Adopted by the digital clock (Time format 24-hour/12-hour, Show date) and the binary clock (Show
  seconds); clock-widget now exports module-config.
- Tests: native menu end-to-end (open, pick 12-hour, heading inert, reload keeps it), state.edn
  round trip, EDN unit test, wasmer and host-wasm module-config tests, lib/clock settings test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjuApkJR4sVRYDpDLy
2026-11-25 18:58:43 +00:00
Claude a7909014b8 Dark mode sets the system preference for apps: GTK, browsers, Qt and KDE
CI / test (push) Failing after 16s
In the login session (--drm) the settings module's Dark mode switch, and the saved choice at
startup, now also set what other programs follow (compositor/host/system_theme.mbt):

- gsettings org.gnome.desktop.interface color-scheme prefer-dark|default: the portal's
  org.freedesktop.appearance color-scheme, followed by Chrome/Chromium, Electron, Firefox,
  GTK 4 / libadwaita and Qt 6.5+;
- gtk-theme Adwaita <-> Adwaita-dark for GTK 3 (only when it is one of those two);
- gtk-application-prefer-dark-theme in gtk-3.0 and gtk-4.0 settings.ini;
- KDE color scheme BreezeDark|BreezeLight via plasma-apply-colorscheme, else kwriteconfig6/5
  (kdeglobals [General] ColorScheme);
- qt6ct/qt5ct: a *-light / *-dark color file is swapped for its counterpart when it exists.

Missing tools are skipped. Nested windows and tests leave the system alone
(ChandraCompositor::sync_system_theme, set from --drm).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgxf6exeYrDGcy4WW3
2026-11-25 18:57:46 +00:00
Claude f2e870c251 Task manager: draw each app's real icon from its .desktop file
CI / test (push) Failing after 16s
Each pill now shows the icon the app's .desktop file names (Icon=), looked up in the
freedesktop icon themes, instead of the letter tile. The tile stays as the fallback for
windows with no app id, no desktop file or no icon the host can read.

- WIT: a new `icons` capability (`app-icon(app-id) -> u32`, a handle, never a path or pixels)
  and an `image(image-op)` draw op (appended, so existing modules keep their ABI).
  taskbar-widget and plasmoid-host import `icons`. Host raster gains `load-image(path)` and a
  `draw-image` op; the plasmoids host gets an icons table (6: app id, handle).
- Compositor (shell/icons.mbt): window app id -> desktop file (resolve_app_id, so StartupWMClass
  and last-dotted-part matches work) -> Icon= -> theme lookup (XDG data dirs, ~/.icons,
  flatpak exports; hicolor, Adwaita, breeze; 48/64/32 px PNG first, then scalable SVG when the
  host can draw it, then other sizes, then /usr/share/pixmaps). Absolute Icon= paths are used as
  they are. Results are cached per app id; the table is published only when a module imports
  `icons`.
- wasm host (host-wasm): PNG via the png crate, SVG via resvg (rendered sharp at each size),
  PNGs area-averaged to the drawn size; loads cached by path.
- Native build: a small PNG decoder (compositor/renderer/png.mbt: inflate + filters, 1-16 bit,
  palettes with tRNS) and the Image op in the software renderer. SVG-only icons fall back to the
  tile there. The wasmer stub serves `icons.app-icon` from the same table.
- Tests: PNG decoder fixtures (all filters, fixed/dynamic/stored blocks, palette), image scaling
  and drawing, icon lookup order, Icon= parsing, task module icon-or-tile (native and wasmtime),
  host raster PNG+SVG loading and drawing. Checked end to end with the wasm host: foot's
  hicolor icon shows on its pill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhmtDt52EjaW8jevGU
2026-11-25 18:52:58 +00:00
Claude 0e6a1257e1 Settings module: Session, Desktop and Panel tabs; the module manager moves in
CI / test (push) Failing after 15s
- The settings popup gets a tab bar, split by where things live: Session (the switches), Desktop
  (what is drawn on the desktop: the wallpaper list under a "Wallpaper" heading) and Panel (what
  the module manager showed: modules in the panel to remove, modules to add, Browse...).
  Left/Right or 1/2/3 switch tabs; it reopens on the tab it was left on. Modules can't be placed
  on the desktop yet (every wasm module lives in the panel; the desktop card is built in), so
  the Desktop tab has no module section until they can.
- The standalone module-manager module and its world are removed; the settings module imports
  `modules`. Saved panels listing "module-manager" get the settings module in its place.
- DesktopShell::open_settings(SettingsTab) opens the settings module on a tab (loading it into the
  panel if needed), for the panel menu and "System settings" entries; the wasm picker
  ("Modules..." in the panel menu) is open_settings(Panel).
- Tests: the native picker test drives the Panel tab, the wallpaper and switch tests go through
  the tabs, an open_settings test; the wasm and host-wasm module tests use the settings module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgxf6exeYrDGcy4WW3
2026-11-25 18:50:57 +00:00
Claude ee019ecbaa Settings module: the wallpaper chooser moves in, and a Dark mode switch
CI / test (push) Failing after 16s
- The session settings module becomes the panel's "Settings" button. Its popup lists the session
  switches, then a "Wallpaper" heading and the wallpapers (current one ticked); a click on a
  wallpaper shows it at once, as the old chooser did. Up/Down skip the heading.
- The standalone wallpaper module and its world are removed. A saved panel.edn that lists
  "wallpaper" gets the settings module in its place (or just drops it when Settings is there).
- New "Dark mode" setting (on by default). Off swaps the compositor to the Moon Day palette
  (ThemeTokens::moon_day, the values of config/themes/moon-day.json) for the shell, panel modules,
  window decorations and the switcher; on goes back to the configured theme. Saved in state.edn
  as :theme :light (absent or :dark: dark) and applied at startup by restore_state.
- Tests: the native wallpaper test drives the settings module, the settings test flips Dark mode
  and checks the theme, the state.edn round trip covers :theme, panel migration unit test, and
  the host-wasm test covers the switches and the wallpaper rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgxf6exeYrDGcy4WW3
2026-11-25 18:46:25 +00:00
Claude a0b878af23 Session settings panel module: switch session restore and window placement on or off
CI / test (push) Failing after 16s
- New 'session-settings' capability (wit/capabilities.wit: settings, is-on, set-setting) and
  'session-settings' panel module: a "Session" button whose popup lists the session settings,
  each with an on/off switch. Clicking a row flips it at once (the list stays open); Up/Down move
  the highlight, Enter or Space flips it, Escape or a click elsewhere closes. In the default
  panel, between Wallpaper and Log out.
- Two settings to start with, kept in state.edn and written only when off (absent means on):
  "Reopen windows at login" (:restore-session, the key session restore already read) and
  "Remember window positions" (:remember-windows; when off, floating windows aren't placed where
  their app was left and new places aren't recorded, but the saved ones are kept).
- Served by both hosts: wasmer stub (native; settings table 6, bit mask in host int 3,
  requests 10/11) and host-wasm (publish-session-settings, set-session-setting request).
- Tests: native end-to-end (open, click both rows, keyboard, Escape), a state.edn round trip
  that checks both settings take effect, and a host-wasm module test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgxf6exeYrDGcy4WW3
2026-11-25 18:43:27 +00:00
Claude c169489d44 Desktop Pulse: drop the task icons
CI / test (push) Failing after 31s
Pulse no longer draws a chip (a lettered tile) per open window at the end
of its row, and clicking there no longer raises a window. Its machine
stats are unchanged.

Pulse's source is not in the tree, so this patches the prebuilt
component: the chip loop in render now runs zero times (its bound, the
window count, is replaced with 0). The task manager and dock icons are
untouched.

The Pulse test now checks that clicking where the chips were focuses
nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhrN6hviAdUbcZrRTM
2026-11-25 18:43:09 +00:00
nandiandClaude Haiku 5.5 d4d099a0e4 host-wasm: find pixi's libseat at runtime
CI / test (push) Failing after 16s
The login session starts chandra-host without the pixi environment, so the
dynamic loader could not find libseat.so.1 and the session died before DRM.
Record the pixi env's lib directory as an rpath on the host binary. Only the
host gets it, so apps the compositor starts don't inherit it.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-25 10:37:54 -08:00
Claude 9a25d70f77 Task manager: show an app icon on each window's pill
CI / test (push) Failing after 18s
Each pill now starts with the app's icon: the same coloured tile with a
letter that the dock draws for that app id, so an app looks the same in
both. The app id comes from windows.all (the task-bar rows carry only
titles); windows without one fall back to a title-keyed tile. Pills
narrower than 72px show just the centred icon.

The tile drawing moves into lib/dock (app_icon, app_glyph) and the dock
uses it too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hm1XqzhrA4N8FyhuRa
2026-11-25 18:31:41 +00:00
Claude 46780c399b Restore the session on login: reopen the windows the last session ended with
CI / test (push) Failing after 20s
- state.edn gets :session [{:app "foot"} {:app "org.gnome.Nautilus" :minimized true}]: the open
  windows by app id, in opening order, with whether each was minimized or maximized. Dialogs
  (xdg_toplevel.set_parent, now tracked by the Wayland server) are left out.
- Written at the end of a session (logout, or the display/window going away) and, against
  crashes, whenever the set of windows changes and then holds for 3 s; that delay also keeps a
  shutdown, where apps die a moment before the compositor, from saving an empty desktop.
- At start (both the native binary and the wasm compositor) each saved app is launched through
  its .desktop file: the app id is matched to the desktop file id, StartupWMClass (now parsed),
  case-insensitively, or by its last dotted part. Restored apps don't count as recent launches.
  A launched app stays in the session until its window shows up (30 s at most), and that window
  gets its minimized/maximized state back; placement is the existing layout mode and per-app
  floating geometry.
- --no-restore, or :restore-session false in state.edn, starts with an empty desktop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjkHnYqipToGkWFC9P
2026-11-25 18:31:31 +00:00
nandiandClaude Haiku 5.5 f7f90e1c41 build: run builds panel modules through a pixi task
CI / test (push) Failing after 15s
Add a pixi `modules` task that runs scripts/build-modules.sh. The justfile
`modules` recipe calls it, and `run` now depends on `modules` so the panel
has its wasm modules when the compositor starts.

Drop pulse, clock-digital12, moon-disc and moon-text from components.txt.
They had no source in any branch, so the build skipped them every time.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-25 10:22:11 -08:00
nandiandClaude Haiku 5.5 ab01688778 build: manage system deps with pixi
CI / test (push) Failing after 28s
Add seatd (libseat headers and library) to the pixi workspace, so the
host-wasm build no longer needs a system libseat. Set channel priority
to disabled so the solver can resolve seatd's libsystemd0 dependency.

Activation env points CPATH, LIBRARY_PATH and LD_LIBRARY_PATH at the
pixi prefix. The justfile runs every recipe through `pixi run`, so a
plain `just run` builds and launches against the pixi environment.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-25 10:18:25 -08:00
Claude c78afbd29e docs: point to renamed repo experiments/chandra
CI / test (push) Failing after 16s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hinfszxuytSmkHXNjS
2026-11-25 17:25:31 +00:00
VandClaude Opus 5.5 af774d76fe Rename the project to Chandra
CI / test (push) Failing after 16s
moon-plasma / moonplasma / MoonPlasma / Moon Plasma become chandra / Chandra
everywhere: the WIT package (chandra:desktop, chandra:host, chandra:wm), the
MoonBit module (chandra/desktop) and generated bindings, the Rust host,
identifiers (ChandraCompositor), the session script (chandra-session) and
desktop entry (chandra.desktop), config and data paths
($XDG_CONFIG_HOME/chandra, share/chandra/modules), env vars (CHANDRA_*),
UI strings, docs and tests. The test fixture components are rebuilt against
the renamed WIT.

Saved panel.edn and state.edn are still read from the old
$XDG_CONFIG_HOME/moon-plasma until the first save writes the new copy.

The remote repository keeps its experiments/moon-plasma name for now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hi3L9oVBoRd373Qr4n
2026-11-25 17:12:57 +00:00
Claude 5dfe34027b Wallpaper chooser panel module, and four new wallpapers
CI / test (push) Failing after 17s
- New 'wallpaper' capability (wit/capabilities.wit: wallpapers, current-wallpaper, set-wallpaper)
  and 'wallpaper' panel module: a button whose popup lists the wallpapers with the current one
  ticked. Clicking a row switches the desktop at once (the list stays open to compare); Enter
  picks the highlighted row, Escape or a click elsewhere closes. In the default panel, before
  Log out.
- lib/shell: render_wallpaper(screen, tokens, index) with Plasma glow (the old background),
  Aurora, Starfield, Dusk and Solid, all draw ops; the themed ones follow a theme swap.
- The shell draws the chosen one (the renderer's wallpaper cache redraws it on change) and
  saves it in state.edn as :wallpaper (:aurora, ...); unknown names fall back to the default.
- Served by both hosts: wasmer stub (native) and host-wasm (publish-wallpaper, wallpapers
  table 5, set-wallpaper request).
- Tests: lib/shell wallpaper test, host-wasm module test, native end-to-end test (open, pick,
  Escape) and a state.edn round trip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhM8CTYpe2XVYTFQGn
2026-11-25 17:08:39 +00:00
Claude 7248e0ca6e Nested window: follow the host's size instead of being cropped
The --window backend pinned its xdg_toplevel to a fixed size (min == max ==
1280x720 or --size) and ignored xdg_toplevel.configure. Whenever the host gave
the window less room than that (a tiling host, a maximized/snapped window, a
screen smaller than the default once its own panels and title bar are taken
off), the host cropped the 1280x720 buffer and the right/bottom of the desktop,
panel included, was cut off. Fullscreen only looked right when the screen
happened to be at least that big.

- nested: drop the max size (min 640x400), read the configure size and, on
  xdg_wm_base v4, configure_bounds to fit the first size on screen; report a
  new size through take_resize.
- compositor: MoonPlasmaCompositor::resize recomputes the work area, tells
  clients the new wl_output mode, reflows every workspace and pulls floating
  windows back inside (WmState::fit_work_area), and forces a full redraw.
- both main loops (wasm component and native) resize before presenting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkYa7dkDnotDeMSdX7
2026-11-25 17:07:33 +00:00
Claude 0f4c84b966 Super+D shows the desktop: minimize every window, again to bring them back
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hktZQ73WicBDmBgP57
2026-11-25 17:07:33 +00:00
Claude 11d7e4d276 Login session: keep the real session bus so the PAM-unlocked GNOME keyring works
As a login session, launched apps were put on a private dbus-daemon bus (meant
only to stop single-instance apps forwarding to a host session when nested).
That bus has no org.freedesktop.secrets, so apps D-Bus-activated a second,
locked gnome-keyring-daemon on it: unlock prompts / "create default keyring"
dialogs, even though pam_gnome_keyring had already unlocked the login keyring.
The session script also wrapped everything in dbus-run-session whenever
DBUS_SESSION_BUS_ADDRESS was unset, splitting off from systemd's user bus.

- host-wasm + native sys stub: start the private bus only when nested
  (WAYLAND_DISPLAY or DISPLAY set); under --drm apps use the session bus.
- moon-plasma-session: use $XDG_RUNTIME_DIR/bus when it exists, fall back to
  re-running itself under dbus-run-session; push WAYLAND_DISPLAY and
  XDG_* into the D-Bus/systemd activation environment so gcr-prompter can show
  unlock prompts; run gnome-keyring-daemon --start --components=secrets.
- justfile run-drm(-native): update the activation environment too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhWvZgm7r2v8NpS2g4
2026-11-25 17:07:33 +00:00
Claude d0d375c071 Mouse wheel scrolls windows: forward scroll to Wayland clients
The wheel used to reach only the Interface Explorer dialog; clients never got
wl_pointer.axis, and the login-session (KMS/libinput) backend dropped scroll events.

- libinput axis events (wheel, touchpad, trackpoint) are queued as EV_AXIS and
  surface as InputEvent::Scroll(axis, value, discrete) in both the native and
  wasm (moonplasma:host/display seat-event.scroll) backends.
- The nested backend keeps horizontal scroll and the host's axis_discrete notches.
- The compositor sends axis_source(wheel) + axis_discrete/axis_value120 + axis +
  frame to the popup or window under the pointer; the explorer still takes the
  wheel while inspect mode is on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjdz1uQ1y3GgazdKrR
2026-11-25 17:07:33 +00:00
nandiandClaude Sonnet 5.5 63e63c65e0 raster: don't zero the framebuffer when the cached backdrop is about to overwrite it
CI / test (push) Failing after 18s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 04:40:31 -08:00
nandiandClaude Sonnet 5.5 c6e31b4a8f Draw in the host: the wasm compositor sends draw ops, the host rasterises natively
CI / test (push) Failing after 29s
The wasm software renderer cost ~10-20 ns/pixel, so any changed frame took ~100+ ms at 1080p and
the desktop swung between idle and very slow. The compositor still builds the scene (windows,
decorations, panel, wallpaper) but a new moonplasma:host/raster interface turns it into pixels
in the host:
- host-wasm/src/raster.rs: a port of compositor/renderer (same blend arithmetic: fills, strokes,
  lines, circles, text, clips, shadows, surface blits), a wallpaper+desktop-card cache, and captured
  client surfaces (copied out of the shared memory once at commit, converted to RGBA, solid ones
  blit as row copies). 9 unit tests; a full frame matches the native software renderer except for
  text antialiasing (0.3% of pixels).
- compositor/raster sends a SceneGraph as ops; compositor.compose_scene() returns it only when
  something changed. The login session shows the host framebuffer directly (display.present-frame),
  the nested window gets it as a memfd (raster.export-memfd), --gfx-out reads it (read-frame).
- Client buffers never enter wasm: snapshot_shm_buffer captures in the host and keeps an id.
- Loop pacing sleeps the rest of the frame budget instead of a fixed 16/8 ms.
Full-screen terminal flooding output at 1080p: ~2 fps / 94% CPU -> ~57 fps; idle ~9%.
The native build keeps the software renderer.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 04:39:40 -08:00
nandiandClaude Sonnet 5.5 66bf293085 Faster busy-client frames: read only the buffer's bytes, cache the wallpaper, cheaper strokes
CI / test (push) Failing after 18s
Profiling a full-screen terminal at 1080p (about 2 fps):
- snapshot_shm_buffer asked the host to copy the pool from byte 0 to the end of the buffer; foot
  puts its buffers deep in a ~135 MB pool, so every commit moved ~135 MB (~185 ms). New
  sys.mmap-read-at(fd, offset, len) copies just the buffer: step 200 ms -> 5 ms per frame.
- The wallpaper (gradient + discs) is rendered once and copied back each frame while unchanged;
  it is split from the desktop card, which changes every second.
- stroke_rounded_rect walked every pixel of the window to draw a 1px outline; it now only
  draws the border strips (exact per-pixel path kept for the corner bands).
- Window shadows only blend the strips that stick out from under the window.
Rasteriser: ~256 ms -> ~93 ms per full-screen frame. Tests compare strokes and fills with the
old per-pixel code, and check the wallpaper cache.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 04:01:25 -08:00
nandiandClaude Sonnet 5.5 70ad87f2d2 Task manager panel module and Alt+Tab window switcher
CI / test (push) Failing after 18s
- components/tasks: the 'tasks' module the panel and components.txt already named but whose source
  was missing. One pill per window in opening order (stable, not stacking order), focused lit,
  minimized dimmed, hover, titles shortened, pills shrink to fit; click focuses/restores.
  Tests that loaded it (task list, title-bar minimize/restore) pass again.
- compositor/host/switcher.mbt: hold Alt, press Tab: most-recently-used window list with the
  previous window selected; Tab/Shift+Tab/arrows move, releasing Alt switches (restoring a
  minimized window), Escape cancels. Tab is not forwarded to clients.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 03:39:19 -08:00
nandiandClaude Sonnet 5.5 095bbc5906 Stop redrawing an unchanged desktop; faster fills and blits; --profile
CI / test (push) Failing after 31s
Profiling the wasm compositor at 1080p idle: ~90 ms per frame in the software rasteriser, run
every loop iteration (92% of a core, stuttery). Now:
- compose_frame compares what the frame is made from (shell ops, decorations, popups, client
  damage) with the last one and returns the previous pixels when nothing changed; the DRM and
  nested loops only present a changed frame (held until the display is ready).
- fill_rounded_rect fills spans (circle test only in the corner bands) and blit_shm_surface
  copies rows without per-pixel calls; tests check both against the old per-pixel code.
- snapshot_shm_buffer sliced buffers byte by byte; now a slice copy.
- --profile prints per-3s step / shell / raster timings.
Idle CPU at 1080p: 92% -> ~10%.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 03:35:06 -08:00
nandiandClaude Sonnet 5.5 235f17cd70 Remember window positions in state.edn, per app
CI / test (push) Failing after 37s
:windows {"app.id" {:x :y :w :h}} is written when a floating window is dragged or resized and
read at startup; an app opening later gets its last place (floating, clamped on screen).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 03:14:58 -08:00
nandiandClaude Sonnet 5.5 4b99b0063e Clicking a window raises it: go through the WM's Activate so stacking order changes
CI / test (push) Failing after 34s
Window clicks, title-bar drags, resize grabs and focus handoff after close emitted Focus/Raise
directly; Raise only marked damage, so the WM's floating order never changed and a focused
window could stay drawn under another. They now use handle_request(Activate) (activate_window).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 03:11:58 -08:00
nandiandClaude Sonnet 5.5 69a163bc08 Persist the desktop card position in state.edn
CI / test (push) Failing after 16s
:desktop-card {:x N :y N} is written when the card is dropped (and kept on later saves),
and restored at startup; the existing clamp keeps it on screen if the resolution changed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 02:59:38 -08:00
nandiandClaude Sonnet 5.5 61796b9f69 Ignore the generated package interfaces that were never committed
CI / test (push) Failing after 33s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 02:53:51 -08:00
nandiandClaude Sonnet 5.5 b50e79acaa Save the layout mode and recent apps as EDN (state.edn) and restore them at startup
CI / test (push) Failing after 30s
state.edn sits next to panel.edn in $XDG_CONFIG_HOME/moon-plasma: {:layout :tiling|:monocle|:floating
:recent [...]}. It is written whenever the layout changes (the Tile | Float switcher, or anything else)
or an app is launched, and read at startup by both the native and wasm compositors. Saving merges
into the existing file, so keys this build doesn't know survive; unreadable files are ignored. Uses
jqlssg/moonedn for reading and writing. The launcher's recents used to live in a plain-text file under
~/.cache; they are migrated once when there is no state.edn yet. The Interface Explorer toggle is
deliberately not restored (while on, clicks don't reach windows).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 02:52:07 -08:00
nandiandClaude Sonnet 5.5 0ba975da67 Logout button for the session, and a dev install that symlinks into the checkout
CI / test (push) Failing after 28s
- New 'session' capability (wit/capabilities.wit) and 'logout' panel module: a button whose popup
  asks 'Log out | Cancel' (Enter confirms, Escape cancels). Confirming makes the compositor exit,
  which ends the login session; works in the wasm host and the native build. In the default panel.
- session/install.py --link (just install-session-dev): symlink the host, component, modules,
  fonts and config into this checkout, so after one root install a rebuild is just
  'just compositor-wasm host-wasm modules' for the next login. Plain installs still copy.
- Tests: host runtime test for the module, native end-to-end test (click, cancel, confirm).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 02:44:44 -08:00
nandiandClaude Sonnet 5.5 c03d4c6c17 The wasm compositor as a login session: DRM/KMS + libinput through the host
CI / test (push) Failing after 1m13s
New moonplasma:host/display import (open, poll, present, cursor, input events, close). The
wasmtime host implements it by compiling the compositor's own kms shim (libseat + DRM/KMS +
libinput + xkbcommon) via build.rs (feature drm, default on), so the native and wasm backends
share one implementation. compositor/kms gets a wasm backend with the same API, and the shared
app loop gains --drm.

- session: install.py installs the host, compositor.wasm, fonts, config, wit and modules and the
  display-manager entry (--native keeps the old native session); the launcher starts the host
  when installed. just run-drm / install-session use the wasm compositor; *-native keep the old.
- compositor.wasm moves to build/ (out of build/components, where the module catalog scans).

Verified: component builds with the new import, host instantiates it and renders frames, installed
layout (fonts/modules/theme from the share dir) renders correctly in a sandbox, native build and
tests unchanged. NOT exercised on a real login VT.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 02:38:19 -08:00
nandiandClaude Sonnet 5.5 95b7275b3a Spike: compositor session state as EDN (jqlssg/moonedn)
CI / test (push) Failing after 16s
compositor/session round-trips a toy snapshot of server state (counters, clients, toplevels) through
EDN and edits one field by path: groundwork for persisting compositor state across a component swap.
Adds the jqlssg/moonedn dependency. Builds and passes on native and wasm.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 02:18:36 -08:00
nandiandClaude Sonnet 5.5 e769566d8f Panel modules in the wasm compositor: the host runs them (moonplasma:host/plasmoids)
CI / test (push) Failing after 46s
A component can't embed a second wasm runtime, so the compositor drives panel modules through a
host import and the wasmtime host instantiates them: load, render, popup, on-event, plus the data
they read (apps, windows, layouts, modules, system) and the requests they make (launch, focus
window, set layout, load/unload, browse), with a zenity file chooser for 'Add widget'.

- wit/worlds.wit: world plasmoid-host, every capability a module can import + the plasmoid export.
  The host instantiates any module against it; a module imports the subset it uses.
- wit/host/plasmoids.wit + generated MoonBit bindings; compositor/wasm gets a wasm backend
  (wasm_host.mbt) with the same public API as the native wasmer one.
- host-wasm/src/plasmoid.rs: typed component bindings, one Store per module, shared host data.
  Tests load the built launcher/layout modules and drive them (typed filter, Enter, launch request).
- scripts/gen-native-stubs.py keeps a package's imports when it rewrites moon.pkg.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 02:09:57 -08:00
nandiandClaude Sonnet 5.5 5c3bebc7fd Real fonts in the wasm compositor: the host rasterises glyphs (Allo Variable, Adwaita Mono)
CI / test (push) Failing after 27s
New moonplasma:host/font import (load a TTF into a slot, rasterise a glyph). compositor/font now
shares its loading/caching/install logic and has two backends: stb_truetype through C (native) and
the host import (wasm). The Rust host draws glyphs with ab_glyph's outlines on an integer pixel grid,
using stb_truetype's em-size scaling, so text matches the native build.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 01:50:01 -08:00
nandiandClaude Sonnet 5.5 0b9af11232 Focus and raise windows through the WM's Activate request
CI / test (push) Failing after 16s
A click on a window and a task-list click now go through WmState::handle_request(Activate)
instead of emitting Focus/Raise directly, so the window manager's own focus and stacking state
stays in step with what the compositor shows. Also refreshes scene's generated interface
(SceneGraph.popups).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 01:46:25 -08:00
nandiandClaude Sonnet 5.5 4ff933ce54 just run now runs the wasm compositor; the native one is just run-native
CI / test (push) Failing after 18s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 01:43:55 -08:00
nandiandClaude Sonnet 5.5 6aba9b6a4f Compile the compositor to a wasm component, run by a small wasmtime host
CI / test (push) Failing after 22s
The whole compositor (Wayland server, window manager, scene, rasteriser, shell) now builds as
build/components/compositor.wasm: a component that imports only moonplasma:host/sys
(wit/host/sys.wit: sockets + SCM_RIGHTS, memfd, poll, spawn, files, clock) and exports run().
host-wasm/ is the native side: a wasmtime program implementing that interface with libc.

- compositor/sys: per-target backends (sys_native.mbt over the C shim, sys_wasm.mbt over the WIT
  imports) behind one API; wayland/nested/host/shell/scene/renderer/gfx build for wasm unchanged.
- compositor/app: the entry point (arg parsing + main loop) as a library for both targets;
  --serve keeps refreshing a PNG so a live compositor can be inspected without a display.
- compositor/font, compositor/wasm: wasm-side placeholders (bitmap font; no panel modules yet,
  since a component can't embed a second wasm runtime: that becomes a host import).
- scripts/gen-native-stubs.py: native stand-ins for wasm-only generated imports.
- just compositor-wasm / host-wasm / run-wasm.

Verified: foot connects to the component's socket and renders into it; native build and
tests unchanged (16/23, the same 7 need unbuilt panel modules).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 01:41:31 -08:00
nandiandClaude Sonnet 5.5 92d2b29889 just build no longer builds tcc: use $TCC, an already-built vendored tcc, or tcc on PATH
CI / test (push) Failing after 35s
scripts/tcc/tcc resolves the compiler (and errors with how to get one if none exists);
tcc-build stays as an optional recipe. bench no longer depends on it either.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 01:27:00 -08:00
nandiandClaude Sonnet 5.5 1bbdf58372 justfile: add clean (keeps the built tinycc) and clean-all
CI / test (push) Failing after 10m34s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 01:24:31 -08:00
nandiandClaude Sonnet 5.5 a0872c9b40 just bench: time the native build (cold / warm / one-file edit), tcc vs system cc
CI / test (push) Failing after 11m6s
scripts/bench-build.sh copies the sources to a temp dir with its own target dir, so it
never touches _build/ or files being edited. just bench [runs] ["tcc cc cc-release"].

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 01:13:05 -08:00
nandi 69a1a0738c Merge commits a9417fbccf
CI / test (push) Failing after 28s
2026-11-25 01:04:11 -08:00
nandiandClaude Sonnet 5.5 a9417fbccf Resize floating windows by dragging their corners and side edges
CI / test (push) Failing after 15s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 00:44:34 -08:00
nandiandClaude Sonnet 5.5 8a3ea16b1c Drag windows by their title bar
CI / test (push) Failing after 17s
A press on a title bar (outside the buttons) focuses the window, floats it if it was
tiled (WmState::float_window) and starts a move drag; motion moves it, release ends it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 00:42:38 -08:00
nandiandClaude Sonnet 5.5 306a7c121e Clipboard: implement wl_data_device selection (copy/paste between clients)
The data-device manager was accepted but ignored. Now set_selection is tracked,
the focused client is offered the selection (data_offer/offer/selection) on focus
change and on update, receive() forwards the fd to the owner as source.send, and
the selection is cleared when its owner goes away. Drag-and-drop is still unsupported.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 00:41:44 -08:00
nandiandClaude Sonnet 5.5 f05677178a Panel hover events for modules; spawned apps get default SIGCHLD and keep the real bus for flatpak
CI / test (push) Failing after 16s
- shell: the module under the pointer gets PointerMove, the one it left gets PointerLeave
  (hover feedback, e.g. the dock's magnifying tiles)
- sys: reset SIGCHLD to SIG_DFL in the child before exec (SIG_IGN is inherited and breaks
  apps that wait() on helpers, e.g. terminals); flatpak run keeps the real session bus
- inspector: drop the redundant 'scroll for more' hint next to the scrollbar

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 00:41:07 -08:00
nandiandClaude Sonnet 5.5 95a21a0b84 Add layout module: Tile | Float toggle widget for the panel
CI / test (push) Failing after 1m5s
Two-segment switch over the layout-control capability: click flips tiling <-> floating
(monocle goes to floating). Includes generated bindings and an updated wasm test.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 00:39:32 -08:00
nandiandClaude Sonnet 5.5 82cac8a915 wl_shm: keep a buffer valid after its pool is destroyed
CI / test (push) Failing after 18s
Qt Quick apps (kwi) render through Mesa's software EGL path, which creates a pool,
creates one buffer and destroys the pool at once. We closed the fd and dropped the
pool, so every snapshot returned None and the window stayed blank. The pool now lives
until its last buffer is destroyed (re-keyed so recycled client ids can't collide).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 00:24:33 -08:00
nandiandClaude Sonnet 5.5 df1f37ee78 Inspector popup: show module file name and clip the note to the popup width
CI / test (push) Failing after 28s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 00:16:27 -08:00
nandiandClaude Sonnet 5.5 6fc921b431 Add dock module: dock-style quick launcher with magnifying app tiles
CI / test (push) Failing after 23s
- lib/dock: tile layout, hit-testing, magnification, per-app colours (tested)
- components/dock: plasmoid module (imports only app-catalog + app-launch)
- shell: panel widgets now get pointer-move / pointer-leave while hovered

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 00:14:29 -08:00
nandi 79321790a1 Merge branch 'main' of https://git.site.latha.org/experiments/moon-plasma
CI / test (push) Failing after 20s
2026-11-25 00:10:16 -08:00
nandiandClaude Sonnet 5.5 bf07af2c43 Add the inspector panel module (Interface Explorer toggle): source and bindings
components.txt listed it but no source existed, so the panel had no Interface
Explorer button. Panel button that toggles the shell's inspect mode via the
inspector capability.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 00:10:11 -08:00
nandiandClaude Sonnet 5.5 bc1e3dfdbd xdg_popup support: right-click menus in client apps (Konsole etc.)
CI / test (push) Failing after 37s
- server: xdg_positioner state, get_popup placement + configure, popup commits,
  popup_done; popups share the toplevel table so pointer/keyboard routing is reused
- compositor: popups drawn above windows and panel, input goes to the popup under the
  pointer, keyboard focus follows the popup, a click outside dismisses them
- test: a client opens a popup, clicks inside it, and is told to dismiss it

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 00:03:49 -08:00
nandi 3b2e19ace5 Merge commits bca69d8c90
CI / test (push) Failing after 54s
2026-11-24 23:47:09 -08:00
nandiandClaude Sonnet 5.5 200b02d0f1 Add the module-manager panel module (source, bindings)
CI / test (push) Failing after 15s
components.txt listed it but no source existed, so just modules skipped it and the
picker said 'Module manager not found'. Panel button + popup: loaded instances
(click to unload), available modules (click to load), Browse...

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 23:42:50 -08:00
nandiandClaude Sonnet 5.5 bca69d8c90 Desktop card: click and drag it around the wallpaper
Press on the card (when no window covers it) to grab it; it follows the pointer,
clamped to the screen, with a hand cursor on hover and grabbing while dragged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 23:41:31 -08:00
nandiandClaude Sonnet 5.5 8724805a72 Right-click Replace only offers modules of the same kind (same WIT world)
CI / test (push) Failing after 16s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 23:41:07 -08:00
nandiandClaude Sonnet 5.5 783618b89f build-modules: skip modules whose source isn't in the tree instead of failing
CI / test (push) Failing after 29s
just run depends on just modules; a component listed in components.txt without a
built core module (pulse, tasks, layout, ...) aborted the whole build. It now warns
and carries on, so the panel loads whichever modules do exist.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 23:38:40 -08:00
nandiandClaude Sonnet 5.5 0145981c6a Wasm panel modules, widget host, merged plasmoid host design, and shell/UI work
Panel and wasm host
- The panel is built from wasm plasmoid modules (compositor/wasm: wasmer-backed host).
  Modules get capabilities by importing host interfaces; the host publishes data tables
  and serves a request queue (launch, focus window, set layout, inspector, load/unload
  modules). New WIT: windows, layout-control, inspector, modules, system.
- Merged two competing host designs: generic tables + requests are the base; the
  `system` snapshot and the id-stable `windows.all/focus` (Desktop Pulse) run on top of it.
- Panel widgets: load a .wasm from a path or file chooser, reorder by dragging,
  right-click replace/remove/add, saved to panel.edn.
- Desktop widget, system sampler (sysinfo), app catalog/humanised names, Interface
  Explorer (inspector), real font rendering (compositor/font, assets/fonts).

Compositor
- Drag the divider between tiled windows; lower tiled rows leave room for the title bar.
- Title-bar buttons, 12-hour clock, truncated titles, task-list/layout menus.
- DRM/KMS session, tcc debug builds (vendored tinycc incl. conftest.c), justfile
  recipes (modules, run, test), pixi.toml.

Known gaps
- The sources for the pulse, tasks, layout, inspector, module-manager, moon-* and
  clock-digital12 modules are not in the tree yet, so `just modules` stops at pulse and
  the host tests that load those modules fail until they land.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 23:38:05 -08:00
nandiandClaude Sonnet 5.5 080377fd79 Wayland: decode UTF-8 strings from clients (titles like 'Session Chooser — Kate' showed as mojibake)
CI / test (push) Failing after 38s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 22:08:34 -08:00
nandiandClaude Sonnet 5.5 50442a7e30 Vendor tinycc's conftest.c (ignored by tinycc's own .gitignore, so ./configure failed)
CI / test (push) Failing after 39s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 21:20:28 -08:00
nandiandClaude Sonnet 5.5 b2557aca52 DRM/KMS + libinput backend and a Moon Plasma login session
compositor/kms: libseat (device access, VT switching), DRM dumb buffers with page
flips and a hardware cursor, libinput keyboard/pointer, xkbcommon keymap and
modifiers. --drm runs the compositor on the real display at the monitor's native
mode. session/ holds the display-manager entry, launcher script and installer
(just install-session). Untested on hardware: refuses to start inside another
session.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 20:59:54 -08:00
nandiandClaude Sonnet 5.5 5b32cf9808 Interface Explorer: compact dialog (14 rows) with mouse-wheel scrolling and scrollbar
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 20:58:06 -08:00
nandiandClaude Sonnet 5.5 7a37039673 Vendor tinycc and build the compositor in debug with it (just build/run)
CI / test (push) Successful in 38s
moon adds -DMOONBIT_NATIVE_NO_SYS_HEADER whenever the C compiler is tcc, which
compiles the system runtime out and breaks linking a standalone exe; the
scripts/tcc/tcc wrapper drops that flag. just tcc-build builds third_party/tinycc
into _build/tcc; build-release keeps the optimised system-cc build.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 20:53:51 -08:00
nandi 49e91b4c01 Merge branch 'main' of https://git.site.latha.org/experiments/moon-plasma
CI / test (push) Successful in 39s
2026-11-24 20:21:54 -08:00
nandiandClaude Sonnet 5.5 57d5376211 Fix launcher search: key_name returned code-unit numbers instead of characters
String indexing yields a UTF-16 code unit, so 'a' became "97" and the launcher
rejected it. Convert to Char first; the input test now types into the search.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 20:21:46 -08:00
nandiandClaude Sonnet 5.5 7154312919 Drag the divider between tiled windows to resize them
CI / test (push) Successful in 37s
- lib/wm: split handles, drag_split, vertical rows now leave room for the lower
  window's title bar (fixes overlapping title bars)
- compositor: pointer press/move/release on a divider resizes the split, with an
  ew/ns-resize cursor; button releases are only forwarded after a forwarded press

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 20:12:13 -08:00
nandiandClaude Sonnet 5.5 ee698c9846 Decorations: truncate window titles so they never draw over the title-bar buttons
CI / test (push) Successful in 25s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 20:08:58 -08:00
nandiandClaude Sonnet 5.5 9e7687bea8 Panel: truncate task-button titles to fit their pill
CI / test (push) Successful in 38s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 20:06:53 -08:00
nandiandClaude Sonnet 5.5 9b31a7c476 Renderer: add punctuation glyphs (~ @ ( ) etc.) to the bitmap font
CI / test (push) Successful in 25s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 19:53:50 -08:00
nandiandClaude Sonnet 5.5 abdc5de8e3 Reserve title-bar height at the top of the work area so tiled windows' title bars aren't cut off
CI / test (push) Successful in 28s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 19:52:29 -08:00
nandiandClaude Sonnet 5.5 59ea224d38 12-hour clock and hover-dependent cursor
CI / test (push) Successful in 45s
- timefmt.hhmm12 + render_digital(hour12=); compositor panel shows '7:51 PM'
  (wasm clock component keeps 24h by default)
- wp_cursor_shape_v1: server lets clients pick their cursor; nested window
  forwards the shape to the host. Launcher button/entries show a hand, the
  search field a text cursor, client windows what the client asked for.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 19:51:16 -08:00
nandiandClaude Sonnet 5.5 a63f65806d Make the desktop interactive: pointer/keyboard routing, launcher popup, app launching
CI / test (push) Successful in 25s
- server: wl_pointer/wl_keyboard events (enter/leave/motion/button/key/modifiers),
  host keymap shared with client keyboards
- nested: receives host pointer + keyboard + keymap, queues InputEvents
- host: routes input to the launcher popup or the window under the pointer;
  click-to-focus moves keyboard focus
- shell: launcher button opens lib/launcher popup; entries start real apps
  (foot, konsole, dolphin, firefox, kate, systemsettings if installed) with
  WAYLAND_DISPLAY pointed at the compositor
- sys: has_exe + spawn
- e2e test for input delivery and the launcher popup

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 19:11:15 -08:00
nandiandClaude Sonnet 5.5 a1b85474f8 Nested window backend: run the compositor in a window on the host Wayland session
CI / test (push) Successful in 26s
The compositor opens an xdg_toplevel on $WAYLAND_DISPLAY, presents frames via
wl_shm with frame-callback pacing and forwards host pointer input to the gfx
surface. just run now uses it (release build); run-headless keeps the old mode.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 19:06:51 -08:00
nandiandClaude Sonnet 5.5 a265eebf02 justfile: add view recipe (one-frame PNG snapshot)
CI / test (push) Successful in 42s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 19:04:24 -08:00
Antigravity 7caadb3f7f feat(gfx): integrate wasi-gfx for loading and presenting GUI
CI / test (push) Successful in 24s
2026-11-25 02:54:03 +00:00
nandiandClaude Sonnet 5.5 ccb809bdc3 Add justfile with build, run, client, test, frame, ci recipes
CI / test (push) Successful in 24s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 18:51:22 -08:00
nandiandClaude Sonnet 5.5 769ab829c8 Load the real desktop shell (lib/shell, panel, launcher, clock) into the native compositor
CI / test (push) Successful in 34s
Replaces the hardcoded build_shell_ops with compositor/shell, which drives the
same pure lib/* logic the wasm components wrap and adapts it to scene ops.
Adds a wall-clock FFI and native stubs for the wasm-only theme bindings.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 18:48:34 -08:00
nandiandClaude Sonnet 5.5 3cb8417699 Compositor: advertise wl_subcompositor and wl_data_device_manager so real clients (foot) load
CI / test (push) Successful in 59s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 18:40:24 -08:00
Antigravity ae4f3fa93c Replace Rust host-native with 100% pure-MoonBit Wayland compositor
CI / test (push) Successful in 36s
2026-11-25 01:18:46 +00:00
Antigravity 17a8a46cfd Spike Wayland compositor, hybrid MoonBit WM, SSD decorations, and wasmtime native host 2026-11-25 00:42:01 +00:00
nandi 880ecd4102 M0: WIT package, MoonBit components, JS host, docs, CI (#1)
CI / test (push) Successful in 19s
2026-11-24 23:51:26 +00:00
875 changed files with 195095 additions and 538 deletions

No files matched your search

+16 -1
View File
@@ -6,6 +6,13 @@ on:
pull_request: pull_request:
branches: [main] branches: [main]
# Several quick pushes to main used to start several full builds at once; on the shared
# runner that starved the cluster node of memory (2026-11-26 freeze). Keep one run per ref
# and cancel the older one.
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs: jobs:
test: test:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -20,8 +27,16 @@ jobs:
run: | run: |
curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash
echo "$HOME/.moon/bin" >> "$GITHUB_PATH" echo "$HOME/.moon/bin" >> "$GITHUB_PATH"
# Fetch the package registry index, or registry deps (jqlssg/moonedn) aren't found.
"$HOME/.moon/bin/moon" update
- name: Install wasm-tools, wit-bindgen, wasmtime - name: Install native compositor build dependencies
run: |
apt-get update -q
apt-get install -y -q --no-install-recommends libseat-dev libdrm-dev libinput-dev libudev-dev libxkbcommon-dev \
libpam0g-dev pamtester ffmpeg
- name: Install wasm-tools, wit-bindgen, wasmtime, wasmer C API
run: scripts/setup-toolchain.sh run: scripts/setup-toolchain.sh
- name: Install host dependencies (jco) - name: Install host dependencies (jco)
+9
View File
@@ -5,3 +5,12 @@ node_modules/
.context/ .context/
.mooncakes/ .mooncakes/
*.log *.log
host-native/target/
.pixi/
# moon rewrites these for whichever target was built last, so they differ run to run. A few
# (app, gfx, renderer, scene) were committed early and stay tracked; the rest are not.
compositor/*/pkg.generated.mbti
wasmhost/*/pkg.generated.mbti
__pycache__/
assets/fonts/NotoColorEmoji.ttf
+209 -58
View File
@@ -1,88 +1,239 @@
# moon-plasma # Chandra
A modular, KDE-Plasma-inspired desktop environment where **every part is a A modular, KDE-Plasma-inspired Wayland desktop where **every part is a WebAssembly component**
WebAssembly component** (Component Model, WIT interfaces) written in (Component Model, WIT interfaces) written in [MoonBit](https://www.moonbitlang.com), on top of a
[MoonBit](https://www.moonbitlang.com), on top of a deliberately tiny trusted host. deliberately small host. The compositor itself (Wayland server, window manager, scene, shell) is a
component, and so is every panel module: the clock, the dock (task manager), the launcher, the settings.
![launcher open](docs/screenshots/m0-2-launcher-open.png) Chandra was called moon-plasma until 2026-11-25. The code, the WIT packages (`chandra:*`), the
session (`chandra-session`) and the paths (`~/.config/chandra`) all use the new name; an old
`~/.config/moon-plasma/panel.edn` and `state.edn` are still read when the new ones don't exist yet.
*Headless-Chromium capture of the M0 browser host: the shell, the launcher and the clock Repository: <https://git.site.latha.org/experiments/chandra>
are three separate MoonBit components.*
![Chandra desktop](docs/screenshots/desktop.png)
*A frame rendered headless by `build/wasmhost --gfx-out`: the wallpaper, the desktop card and every
panel button are drawn by wasm components.*
## Vision ## Vision
Plasma's strength is its decomposition (shell, widgets, window manager, runner, Plasma's strength is its decomposition (shell, widgets, window manager, runner, settings modules,
settings modules, notifications, tray). moon-plasma keeps that decomposition and notifications, tray). Chandra keeps that decomposition and makes each seam a **typed WIT
makes each seam a **typed WIT interface** with **deny-by-default capabilities**: interface** with **deny-by-default capabilities**:
* the **host** only owns engine/lifecycle, devices, the capability broker and the * the **host** only owns the wasm engine, devices (sockets, files, DRM/KMS, libinput), the
render-list rasteriser; capability broker and the rasteriser;
* **everything else is a component**: swap the clock for another implementation, * **everything else is a component**: swap the clock for another implementation, swap the shell,
swap the whole shell, change the theme, without rebuilding the rest; change the theme, without rebuilding the rest;
* components draw by returning a **render-list** (`list<draw-op>`), never pixels; * components draw by returning a **render list** (`list<draw-op>`), never pixels;
* components can't touch anything their imports + the desktop config don't grant. * components can't touch anything their imports and the desktop config don't grant.
Read [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) (Plasma→component mapping, host Design: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) (Plasma to component mapping, permissions,
decision, rendering, input, permissions, versioning, roadmap M0–M8) and versioning) and [docs/compositor-design.md](docs/compositor-design.md) (the compositor and its
[docs/TOOLCHAIN.md](docs/TOOLCHAIN.md) (what works today, exact versions). hosts). Toolchain notes: [docs/TOOLCHAIN.md](docs/TOOLCHAIN.md). Dark mode and the portal: [docs/dark-mode.md](docs/dark-mode.md). Running as root and run0:
[docs/run0.md](docs/run0.md). Kiosk mode (`--kiosk CMD`, one fullscreen app, locked down): [docs/kiosk.md](docs/kiosk.md). Picking up a new build without logging out (`just reload`, `chandra-ctl reload`): [docs/reloading.md](docs/reloading.md). Chandra as the kiosk shell of the gamerig streaming rigs (feasibility, gaps, plan): [docs/kiosk-gamerig.md](docs/kiosk-gamerig.md).
## Status: M0 (proof of concept) ## How it runs
Works today: ```
build/compositor.wasm the compositor, a wasm component (components/compositor, code in compositor/)
build/wasmhost the host that runs it: MoonBit, linked to the prebuilt wasmtime C API
build/components/*.wasm panel modules, loaded by the host and drawn by the compositor
```
* WIT package `moonplasma:desktop@0.1.0` (`wit/`): worlds `widget`, `clock-widget`, The **MoonBit host** ([wasmhost/](wasmhost/README.md)) is the only host. It links
`launcher-widget`, `panel`, `shell`. `libwasmtime` from the upstream C API release instead of compiling wasmtime, so a cold build takes
* Four MoonBit components, each an independently built `.wasm` component of 24–33 KB: about 4 seconds. (An earlier host in Rust on the wasmtime crate, `host-wasm/`, was removed on
`clock-digital`, `clock-binary` (drop-in replacement), `launcher` (kickoff-like with 2026-11-26.) A **native build** of the same
keyboard search), `shell` (desktop background + bottom panel layout + theme tokens). compositor code (no wasm, `just run-native`) is used by the test suite.
* Host (`host/`): Node + browser, jco-transpiled components, capability grants,
popup/focus input routing, hot-swap, fault isolation, Canvas2D + ASCII renderers.
* Tests: 16 MoonBit unit tests (pure logic), 13 host integration tests that
instantiate the real components, WIT conformance (`wasm-tools component targets`),
generated-bindings freshness check, `wasmtime compile` of every component.
Stubbed / not done (see ARCHITECTURE §10): no window manager/compositor, search runner, The compositor runs **nested**, as a window on your current Wayland session, as a **login
notifications, settings, tray, session, shortcuts, clipboard, files; `launch` only logs; session** on DRM/KMS with libinput (`--drm`, through libseat/logind), or **on an X server**
host does input hit-testing; fixed-advance text metrics, no real fonts/icons; native (`--x11`: a window under an X window manager, or the whole screen without one), for NVIDIA's
wasmtime host is M3; no CPU/fuel limits under jco. proprietary driver on Xorg ([docs/x11.md](docs/x11.md)).
## Quickstart ## Quickstart
Requirements: Linux x86_64, Node ≥ 20, [MoonBit](https://www.moonbitlang.com/download). Requirements: Linux x86_64, [MoonBit](https://www.moonbitlang.com/download),
[pixi](https://pixi.sh) (it provides `just`, tcc and seatd/libseat), and the dev headers for
libdrm, libinput, libudev and libxkbcommon (on Debian/Ubuntu:
`apt install libdrm-dev libinput-dev libudev-dev libxkbcommon-dev libseat-dev`).
Screen recording needs `ffmpeg` on `PATH`.
```bash ```bash
export PATH="$HOME/.moon/bin:$PATH" export PATH="$HOME/.moon/bin:$PATH"
scripts/setup-toolchain.sh # wasm-tools, wit-bindgen, wasmtime -> ./.tools (no root) moon update # fetch mooncakes dependencies
(cd host && npm ci) # jco scripts/setup-toolchain.sh # wasm-tools, wit-bindgen, wasmtime + its C API -> ./.tools (no root)
scripts/build.sh # MoonBit -> components -> build/components, build/jco
scripts/test.sh # everything CI runs
node host/src/cli.mjs --time 2026-11-24T14:07:00 --click-launcher # terminal render just run # build compositor.wasm, wasmhost and the modules; open in a window
node host/serve.mjs 8080 # browser host: http://127.0.0.1:8080/ just client # start foot inside it (or: just client konsole)
node host/serve.mjs & # then try ?config=desktop.binary-clock.json or ?theme=moon-day
``` ```
Swap the clock **without rebuilding anything else**: | Recipe | What it does |
|---|---|
| `just run` | Nested in a window on your Wayland session, MoonBit host |
| `just run-drm` | As a login session on the real screen (from a text console, as yourself) |
| `just run-x11` | On the X server in `$DISPLAY` (NVIDIA on Xorg; the whole screen when no window manager runs) |
| `just install` | Install everything: the "Chandra" display-manager session, "Chandra (X11)" for Xorg, and face unlock (asks for root once). `--link` symlinks into this checkout (later just rebuild), `--native` picks the native compositor, `--pam` turns face unlock on, `--no-face` skips it |
| `just uninstall` | Remove it all again (`--purge` also deletes enrolled faces) |
| `just reload` | Reload the running session's panel modules from disk (`chandra-ctl reload [NAME]`) |
| `just run-native`, `run-drm-native` | The native (non-wasm) build |
| `just compositor-wasm`, `wasmhost`, `modules` | Build one piece |
| `just test` | Native compositor tests and lib tests |
| `just frame` | Render one composed frame to `_build/e2e_frame.png` |
| `just remote-build` | Build on a sprites.dev sprite (`CHANDRA_SPRITE`) and pull the artifacts back |
```bash `build/wasmhost build/compositor.wasm --socket PATH` takes `--window` (nested), `--drm` (login
node host/src/cli.mjs --config config/desktop.binary-clock.json session), `--x11` (on Xorg; `--fullscreen` under a window manager, `--login-session` to act as the
scripts/build.sh clock-binary # builds just that component desktop session), `--theme PATH`, `--no-restore`, `--profile`, `--size WxH` and `--gfx-out frame.png`
# in the browser console: await moonPlasma.swap('clock', 'clock-binary') (render to a PNG, headless; add `--serve` to keep refreshing it). `WASMHOST_PROFILE=1` prints the
``` time spent in each host function every 5 seconds; `WASMHOST_TRACE=1` logs every host call.
No GPU? Chandra detects it and asks less of the CPU; `CHANDRA_RENDER=software|hardware` or
Settings > Session > Lighter animations overrides it, and `CHANDRA_FRAME_TRACE=1` logs frame times
([docs/rendering.md](docs/rendering.md)).
Screenshots: see the end of [docs/TOOLCHAIN.md](docs/TOOLCHAIN.md). `CHANDRA_DEBUG_CONFIGURE=1` (any host) logs each window's configures, acks and committed buffer
sizes, for an app that draws at the wrong size.
The installed session logs to `~/.local/state/chandra/session.log`. Start it as yourself, never
as root: `chandra-session` refuses to run as root (`CHANDRA_ALLOW_ROOT=1` overrides). Installing
goes through `scripts/as-root`, which prefers run0 and falls back to sudo, doas or pkexec
(`CHANDRA_AS_ROOT` picks one). What it installs and its flags: [docs/install.md](docs/install.md). To run a graphical app as root inside Chandra, use
`chandra-root gparted`. Details, including polkit agents (`CHANDRA_POLKIT_AGENT`), are in
[docs/run0.md](docs/run0.md).
Face unlock, in the style of Howdy, comes with `just install`: then Settings > Session > Face unlock to
add a face and use it for the password dialog and sudo (a PAM module; the password always still
works). See [docs/face-unlock.md](docs/face-unlock.md), including what 2D face recognition can't
protect against.
## What works
**Windows**
* Wayland clients (xdg-shell, wl_shm buffers, clipboard), tiling or floating (the Tile | Float
panel toggle).
* Drag a window by its title bar, resize floating windows from corners and edges, double-click
the title bar to maximize or restore. Clicking a window raises it.
* App right-click menus (xdg_popup) stay open and on screen; apps that draw with Vulkan on wl_shm
(Zed, Delta) show every frame; buffers stay valid after their pool is destroyed.
* The mouse wheel scrolls windows.
* Window positions are remembered per app, and on login the session reopens the windows the last
one ended with (switch it off in Settings, or start with `--no-restore`).
**Shortcuts** (the defaults; rebind any of them in Settings > Shortcuts: click one and press the
new keys)
| Keys | Action |
|---|---|
| Super (tap) | Open the application launcher, with an overview of every window beside it (typing filters both) |
| Super+W | Overview alone: every window side by side; click one to bring it forward, middle-click to close it |
| Alt+Tab | Window switcher, with a live preview of each window |
| Super+D | Show the desktop (minimize every window); again to bring them back |
| Super+1 .. Super+9 | Open the dock's first nine apps (or bring their windows forward) |
| Super+Shift+S | Screenshot: select a region or click a window (F full screen, W active window) |
| Print / Super+Print / Super+Ctrl+Print | Screenshot of the full screen / active window / window under the pointer |
| Super+Shift+R | Record a region or window (Enter starts) |
| Super+Alt+R / Super+Ctrl+R | Record the whole screen / the window under the pointer |
| Super+. | Emoji picker: type to search, arrows and Enter to insert into the app you're typing in ([docs/emoji-picker.md](docs/emoji-picker.md)) |
Every screenshot opens in the screenshot editor first: annotate it (arrow, line, rectangle,
ellipse, pen, highlighter, text, numbered markers), hide parts of it (blur, pixelate, redact) or
crop it, then Enter saves and copies it, Ctrl+C only copies it and Esc discards it. See
[docs/screenshot-editor.md](docs/screenshot-editor.md).
Screenshots go to `~/Pictures/Screenshots/` and the clipboard; recordings (H.264 MP4, via
`ffmpeg`) go to `~/Videos/Screencasts/`. A red REC pill shows while recording; click it or press
a recording shortcut again to stop.
**Panel modules** (each one a separate `.wasm` component in `components/`)
* **Launcher** (application menu with search). Its menu ends in a session row: **Reload**
(reload every panel module from disk, keeping the panel and module settings; windows and apps
keep running), **Log out**, **Suspend**, **Restart** and **Power off**. Log out, Restart and
Power off ask for a second click.
* **Dock**, the panel's task manager: the pinned apps that aren't running as plain icons, then
after a divider every running app (pinned ones in pin order first), with their theme icons and
a dot per open window (lit when the app has focus). An app with windows is a pill with its window's title (or its name and window count) while there is room,
just its icon when the panel gets crowded. Click to start an app or bring its newest window
forward (restoring it if minimized); click a focused app again to step through its windows.
**Super+1** .. **Super+9** do the same for the first nine. Right-click an app for Open / New
window, Pin or Unpin, Move left / right, its window's Minimize and Maximize (or a list of its
windows), Quit, and Dock settings (icon size, magnification, running apps, window titles).
Pin apps from there or by right-clicking them in the Launcher's menu; an empty dock shows a "+"
that opens it. Pins live in state.edn. (It replaced the separate Task Manager: a saved panel
with the old `tasks` module gets the dock in its place.)
* **Network**: Wi-Fi and wired status, connect to Wi-Fi networks (with passwords), Wi-Fi and
airplane switches, through NetworkManager over D-Bus (read-only sysfs status without it).
* **Battery**: charge, charging state, time left, low-battery warning (only added on machines
with a battery).
* **Clocks**: the Digital Clock (12-hour with AM/PM by default, 24-hour in its Module settings)
and a binary clock.
* **Screenshot**, **Layout** (Tile | Float), **Inspector** (interface explorer).
* **Settings**: tabs for Session (reopen windows at login, remember window positions, dark
mode), Desktop (what fills the desktop, wallpapers), Panel (add, remove and replace modules), Power (screen off and
suspend when idle, battery, suspend / restart / power off), Shortcuts and Apps (the default web
browser, email, file manager, terminal, text editor, image viewer, video and music player, PDF
viewer and archive manager, chosen from the installed apps; written to
`~/.config/mimeapps.list`, so xdg-open and other apps follow it). Dark mode also sets the system
preference for apps: GTK, Qt and KDE settings, and in the login session Chandra serves
xdg-desktop-portal's Settings color-scheme itself, so Chrome, Firefox and Electron apps follow
the switch live (see [docs/dark-mode.md](docs/dark-mode.md)).
**Desktop modules**: a module can fill the desktop itself, behind the windows, instead of sitting
in the panel. Choose one in Settings > Desktop (*Wallpaper only*, *Clock card*, or any installed
desktop module); right-click the empty desktop for its settings. Three ship: **Icon Desktop** (app
icons you click to launch and drag to arrange, positions remembered), **Live Starfield** (an
animated starfield you steer with the pointer) and **Gamerig Library** (gamerig's game library
for a streaming rig, [docs/gamerig-library.md](docs/gamerig-library.md)). See
[docs/desktop-modules.md](docs/desktop-modules.md) to write one.
Right-click any module for **Module settings** (its own options, such as the clock's format,
saved in `state.edn`), **System settings**, Replace with and Remove widget. Right-clicking empty
panel space opens System settings on the Panel tab.
**Performance**: an idle desktop sleeps instead of redrawing (about 0.35 % CPU, down from about
9 %), only changed parts of the screen are redrawn, and screenshots, recording and `--gfx-out`
keep pixels on the host rather than copying them through the component.
## Configuration and state
* `~/.config/chandra/panel.edn`: the panel's modules, in order.
* `~/.config/chandra/state.edn`: layout mode, recent apps, window positions, the windows to
reopen, wallpaper, theme, power timeouts, the terminal terminal apps run in (`:terminal`, also
put first in `~/.config/xdg-terminals.list`), per-module settings (`:module-config`), what fills the desktop (`:desktop`), and the
Settings switches (`:restore-session false`, `:remember-windows false`, `:theme :light`).
* Themes: `config/themes/moon-night.json` (default) and `moon-day.json`.
## Known gaps
* 5 to 6 compositor tests fail on main in a cloud container and are not regressions
(`input_test`, plus `screenshot_test` when the screenshot module isn't built). Build the panel
modules first and run with `CHANDRA_TEST_CONFIG=1`, or more tests fail.
* The DRM/KMS login session and real-hardware paths (power actions, battery, NetworkManager on a
real machine) are not exercised by CI; they have been built and unit-tested, not run on
hardware in automation.
* Not done yet: lock screen, notifications daemon, system tray, virtual desktops, multi-monitor
configuration, idle-inhibit (a playing video doesn't keep the screen on), lid and power-button
actions (logind's defaults apply), VPN and enterprise Wi-Fi.
* Desktop Pulse (`compositor/wasm/testdata/pulse.component.wasm`) and the `moon-disc` panel
module have no source in the tree, so `scripts/build-modules.sh` skips moon-disc and a fresh
panel shows a "Module 'moon-disc' not found" notice (remove it in Settings, Panel tab).
## Layout ## Layout
``` ```
wit/ the WIT package (host-agnostic API) wit/ WIT packages: chandra:desktop (components) and chandra:host (wit/host, what hosts serve)
interface/ world/ generated shared MoonBit bindings (wit-bindgen; committed) compositor/ the compositor in MoonBit: wayland/, shell/, scene/, raster/, kms/, network/, portal/, host/, ...
components/<n>/gen/ generated export bindings + hand-written thin stub.mbt components/<n>/ one wasm component each: compositor, shell, panel modules (gen/ bindings + thin stub.mbt)
lib/ pure, unit-tested logic (ui helpers, panel layout, launcher state machine, ...) lib/ pure, unit-tested logic (panel layout, clock, launcher, battery, task pills, ...)
host/ JS host: src/desktop.mjs (core), loaders, renderers, tests, web/ (browser) wasmhost/ the host (MoonBit + wasmtime C API)
config/ desktop configs (grants!), themes, static app list host/ the original M0 browser/Node host (jco), kept for the component demos
scripts/ setup-toolchain, gen-bindings, build, test, screenshot session/ chandra-session, chandra-root, chandra-ctl, chandra.desktop, chandra.portal, install.py
docs/ ARCHITECTURE, TOOLCHAIN, screenshots config/ desktop configs, themes, app list
scripts/ setup-toolchain, build-*, gen-bindings, as-root, remote-build, test
docs/ ARCHITECTURE, compositor-design, TOOLCHAIN, run0, dark-mode, reloading, screenshots
``` ```
## License ## License
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+96
View File
@@ -0,0 +1,96 @@
Copyright (c) 2016, The Inter Project Authors (https://github.com/rsms/inter)
Copyright (c) 2015-2025, Renzhi Li (aka. Belleve Invis, belleve@typeof.net)
Copyright (c) 2025, Jamie Gravendeel (https://jamie.garden)
Copyright (c) 2025, Florian Müllner
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+95
View File
@@ -0,0 +1,95 @@
Noto Color Emoji (assets/fonts/NotoColorEmoji.ttf, fetched by scripts/fetch-emoji-font.sh from
https://github.com/googlefonts/noto-emoji, v2.051): Copyright 2013-2025 Google LLC.
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font
creation efforts of academic and linguistic communities, and to
provide a free and open framework in which fonts may be shared and
improved in partnership with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply to
any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software
components as distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to,
deleting, or substituting -- in part or in whole -- any of the
components of the Original Version, by changing formats or by porting
the Font Software to a new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed,
modify, redistribute, and sell modified and unmodified copies of the
Font Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components, in
Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the
corresponding Copyright Holder. This restriction only applies to the
primary font name as presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created using
the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+274
View File
@@ -0,0 +1,274 @@
// #region subtask
///|
priv struct SubTask {
handle : Int
state : SubTaskState
}
///|
priv enum SubTaskState {
Starting = 0
Started = 1
Returned = 2
Cancelled_before_started = 3
Cancelled_before_returned = 4
}
///|
fn SubTaskState::from(int : Int) -> SubTaskState {
match int {
0 => Starting
1 => Started
2 => Returned
3 => Cancelled_before_started
4 => Cancelled_before_returned
_ => panic()
}
}
///|
fn SubTask::from(code : Int) -> SubTask {
{ handle: code >> 4, state: SubTaskState::from(code & 0xf) }
}
///|
/// The baseline intrinsic cooperatively waits in the component model and
/// returns only after the subtask reaches a terminal state.
fn SubTask::cancel(self : SubTask) -> SubTaskState {
SubTaskState::from(subtask_cancel(self.handle))
}
// #endregion
// #region events
///|
priv enum EventCode {
None = 0
SubTask = 1
StreamRead = 2
StreamWrite = 3
FutureRead = 4
FutureWrite = 5
TaskCancelled = 6
}
///|
fn EventCode::from(int : Int) -> EventCode {
match int {
0 => None
1 => SubTask
2 => StreamRead
3 => StreamWrite
4 => FutureRead
5 => FutureWrite
6 => TaskCancelled
_ => panic()
}
}
///|
priv enum Events {
None
Subtask(Int, SubTaskState)
StreamRead(Int, StreamResult)
StreamWrite(Int, StreamResult)
FutureRead(Int, FutureReadResult)
FutureWrite(Int, FutureWriteResult)
TaskCancelled
}
///|
fn Events::new(code : EventCode, i : Int, j : Int) -> Events {
match code {
None => None
SubTask => Subtask(i, SubTaskState::from(j))
StreamRead => StreamRead(i, StreamResult::from(j))
StreamWrite => StreamWrite(i, StreamResult::from(j))
FutureRead => FutureRead(i, FutureReadResult::from(j))
FutureWrite => FutureWrite(i, FutureWriteResult::from(j))
TaskCancelled => TaskCancelled
}
}
// #endregion
// #region waitable set
///|
#borrow(array)
extern "wasm" fn int_array2ptr(array : FixedArray[Int]) -> Int =
#|(func (param i32) (result i32) local.get 0)
///|
struct WaitableSet(Int) derive(Eq, Hash)
///|
#deprecated
pub extend WaitableSet with Eq::{not_equal, equal}
///|
#deprecated
pub extend WaitableSet with Hash::{hash, hash_combine}
///|
fn WaitableSet::new() -> WaitableSet {
WaitableSet(waitable_set_new())
}
///|
fn WaitableSet::drop(self : Self) -> Unit {
waitable_set_drop(self.0)
}
///|
fn WaitableSet::poll(self : Self) -> (Events, Int) {
let payload : FixedArray[Int] = FixedArray::make(2, 0)
let event = waitable_set_poll(self.0, int_array2ptr(payload))
(Events::new(EventCode::from(event), payload[0], payload[1]), payload[0])
}
// #endregion
// #region Future
///|
priv enum FutureReadResult {
Completed = 0
Cancelled = 2
}
///|
fn FutureReadResult::from(int : Int) -> FutureReadResult {
match int {
0 => Completed
2 => Cancelled
_ => panic()
}
}
///|
priv enum FutureWriteResult {
Completed = 0
Dropped = 1
Cancelled = 2
}
///|
fn FutureWriteResult::from(int : Int) -> FutureWriteResult {
match int {
0 => Completed
1 => Dropped
2 => Cancelled
_ => panic()
}
}
// #endregion
// #region Stream
///|
priv struct StreamResult {
progress : Int
copy_result : CopyResult
}
///|
fn StreamResult::from(int : Int) -> StreamResult {
let progress = int >> 4
let copy_result = CopyResult::from(int & 0xf)
{ progress, copy_result }
}
///|
priv enum CopyResult {
Completed = 0
Dropped = 1
Cancelled = 2
}
///|
fn CopyResult::from(int : Int) -> CopyResult {
match int {
0 => Completed
1 => Dropped
2 => Cancelled
_ => panic()
}
}
// #endregion
// #region callback code
///|
/// Code to let the runtime know what to do in the callback
priv enum CallbackCode {
Completed
Yield
Wait(WaitableSet)
}
///|
fn CallbackCode::encode(self : Self) -> Int {
match self {
Completed => 0
Yield => 1
Wait(id) => 2 | (id.0 << 4)
}
}
// #endregion
// #region Component async primitives
///|
fn subtask_cancel(id : Int) -> Int = "$root" "[subtask-cancel]"
///|
fn subtask_drop(id : Int) = "$root" "[subtask-drop]"
///|
fn tls_set(tls : Int) = "$root" "[context-set-0]"
///|
fn tls_get() -> Int = "$root" "[context-get-0]"
///|
fn task_cancel() = "[export]$root" "[task-cancel]"
///|
fn waitable_set_new() -> Int = "$root" "[waitable-set-new]"
///|
fn waitable_set_drop(set : Int) = "$root" "[waitable-set-drop]"
///|
/// This poll is deliberately non-cancellable. Component-task cancellation is
/// delivered by the stackless callback instead of being consumed here.
fn waitable_set_poll(set : Int, payload : Int) -> Int = "$root" "[waitable-set-poll]"
///|
fn task_wakeup_stream_new() -> Int64 = "$root" "[stream-new-unit]"
///|
fn task_wakeup_stream_read(handle : Int, ptr : Int, len : Int) -> Int = "$root" "[async-lower][stream-read-unit]"
///|
fn task_wakeup_stream_write(handle : Int, ptr : Int, len : Int) -> Int = "$root" "[async-lower][stream-write-unit]"
///|
fn task_wakeup_stream_cancel_read(handle : Int) -> Int = "$root" "[stream-cancel-read-unit]"
///|
fn task_wakeup_stream_drop_readable(handle : Int) = "$root" "[stream-drop-readable-unit]"
///|
fn task_wakeup_stream_drop_writable(handle : Int) = "$root" "[stream-drop-writable-unit]"
///|
fn waitable_join(waitable : Int, set : Int) = "$root" "[waitable-join]"
// #endregion
+73
View File
@@ -0,0 +1,73 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
priv struct CondVarWaiter {
// Once a signal is assigned, cancellation must not lose it before the
// waiter resumes. This matches moonbitlang/async's condition variable.
mut woken : Bool
mut coro : Coroutine?
}
///|
/// A condition variable for synchronization between tasks.
pub struct CondVar {
priv waiters : @deque.Deque[CondVarWaiter]
}
///|
/// Create a new condition variable.
#alias(new, deprecated)
pub fn CondVar::CondVar() -> CondVar {
{ waiters: Deque([]) }
}
///|
/// Wait until the condition variable is signaled.
pub async fn CondVar::wait(self : CondVar) -> Unit noraise {
let waiter = { woken: false, coro: Some(current_coroutine()) }
self.waiters.push_back(waiter)
match suspend_check_cancel() {
Continue => ()
Cancelled if waiter.woken => ()
Cancelled => {
waiter.coro = None
raise_cancellation_signal()
}
}
}
///|
/// Wake the first waiting task. Does nothing when no task is waiting.
pub fn CondVar::signal(self : CondVar) -> Unit {
while self.waiters.pop_front() is Some(waiter) {
if waiter.coro is Some(coro) {
waiter.woken = true
coro.wake()
break
}
}
}
///|
/// Wake all waiting tasks. Does nothing when no task is waiting.
pub fn CondVar::broadcast(self : CondVar) -> Unit {
for waiter in self.waiters {
if waiter.coro is Some(coro) {
waiter.woken = true
coro.wake()
}
}
self.waiters.clear()
}
+218
View File
@@ -0,0 +1,218 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
priv enum SuspendResult {
Continue
Cancelled
}
///|
priv enum State {
Done
Fail(Error)
Cancelled
Running
Suspend((SuspendResult) -> Unit)
}
///|
struct Coroutine {
coro_id : Int
lane : TaskLane
mut state : State
mut shielded : Bool
mut cancelled : Bool
mut ready : Bool
mut spawner : ((async () -> Unit) -> Unit)?
downstream : Set[Coroutine]
}
///|
impl Eq for Coroutine with fn equal(c1, c2) {
c1.coro_id == c2.coro_id
}
///|
impl Hash for Coroutine with fn hash_combine(self, hasher) {
Hash::hash_combine(self.coro_id, hasher)
}
///|
fn Coroutine::wake(self : Coroutine) -> Unit {
if !self.ready {
self.ready = true
enqueue(self)
signal_component_task(self.lane)
}
}
///|
pub fn is_being_cancelled() -> Bool {
let coro = current_coroutine()
coro.cancelled && !coro.shielded
}
///|
pub async fn check_cancellation() -> Unit noraise {
if is_being_cancelled() {
raise_cancellation_signal()
}
}
///|
fn Coroutine::cancel(self : Coroutine) -> Unit {
match self.state {
Done | Fail(_) | Cancelled => return
Running | Suspend(_) => ()
}
self.cancelled = true
if !self.shielded {
self.wake()
}
}
///|
async fn suspend_check_cancel() -> SuspendResult noraise {
guard! scheduler.curr_coro is Some(coro)
if coro.cancelled && !coro.shielded {
return Cancelled
}
coro.lane.blocking += 1
defer {
coro.lane.blocking -= 1
}
async_suspend(fn(cont) {
guard! coro.state is Running
coro.state = Suspend(cont)
})
}
///|
async fn suspend() -> Unit noraise {
match suspend_check_cancel() {
Continue => ()
Cancelled => raise_cancellation_signal()
}
}
///|
fn spawn_owned(
f : async () -> Unit,
lane : TaskLane,
inherited_spawner : ((async () -> Unit) -> Unit)?,
) -> Coroutine {
scheduler.coro_id += 1
let coro = {
state: Running,
ready: true,
shielded: false,
downstream: Set([]),
coro_id: scheduler.coro_id,
lane,
cancelled: false,
spawner: inherited_spawner,
}
fn run(_) {
run_async(() => {
// Even a task cancelled before its first turn enters its body, so entry
// defers run. Cancellation is delivered at its first suspension/check.
try capture_cancellation(f, handler=() => coro.state = Cancelled) catch {
err => coro.state = Fail(err)
} noraise {
_ if coro.state is Running => coro.state = Done
_ => ()
}
for coro in coro.downstream {
coro.wake()
}
coro.downstream.clear()
})
}
coro.state = Suspend(run)
enqueue(coro)
coro
}
///|
fn spawn(f : async () -> Unit) -> Coroutine {
match scheduler.curr_coro {
Some(parent) => spawn_owned(f, parent.lane, parent.spawner)
None => {
let waitable_set = current_waitableset()
let task_state = component_task_state(waitable_set).unwrap()
spawn_owned(f, task_state.lane, None)
}
}
}
///|
fn Coroutine::unwrap(self : Coroutine) -> SuspendResult raise {
match self.state {
Done => Continue
Cancelled => Cancelled
Fail(err) => raise err
Running | Suspend(_) => panic()
}
}
///|
async fn Coroutine::wait(target : Coroutine) -> SuspendResult {
guard! scheduler.curr_coro is Some(coro)
guard! !physical_equal(coro, target)
match target.state {
Done => return Continue
Cancelled => return Cancelled
Fail(err) => raise err
Running | Suspend(_) => ()
}
target.downstream.add(coro)
defer target.downstream.remove(coro)
suspend()
target.unwrap()
}
///|
fn Coroutine::check_error(coro : Coroutine) -> Unit raise {
match coro.state {
Fail(err) => raise err
Done | Cancelled | Running | Suspend(_) => ()
}
}
///|
pub async fn[X] protect_from_cancel(f : async () -> X) -> X nocancel {
guard! scheduler.curr_coro is Some(coro)
// The shield prevents delivery; capture_cancellation expresses that invariant
// in the effect type without changing normal error propagation.
capture_cancellation(handler=() => panic(), () => {
if coro.shielded {
f()
} else {
coro.shielded = true
defer {
coro.shielded = false
}
f()
}
})
}
///|
/// Observe cancellation without clearing the task's sticky cancelled state.
/// Returns None on cancellation, Some on success, and propagates normal errors.
pub async fn[X] handle_cancellation(f : async () -> X) -> X? {
capture_cancellation(handler=() => None, () => Some(f()))
}
+658
View File
@@ -0,0 +1,658 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
/// State owned by one P3 component task. `task.state` is the sole completion
/// source; `owned_coroutines` contains only runtime bridge coroutines.
priv struct ComponentTaskState {
lane : TaskLane
subscribers : Map[Int, Subscriber]
task : Coroutine
owned_coroutines : @set.Set[Coroutine]
mut resolution : TaskResolution
mut cancellation_pending : Bool
}
///|
priv struct TaskWakeup {
reader : Int
writer : Int
mut reading : Bool
mut signaled : Bool
}
///|
priv struct Subscriber {
mut event : Events?
coro : @set.Set[Coroutine]
}
///|
priv enum TaskResolution {
Pending
FlushPending
Resolved
}
///|
fn current_waitableset() -> WaitableSet {
WaitableSet(tls_get())
}
///|
fn component_task_state(waitable_set : WaitableSet) -> ComponentTaskState? {
component_tasks.get(waitable_set)
}
///|
fn finish_waitableset(
waitable_set : WaitableSet,
task_state : ComponentTaskState,
) -> Unit {
guard task_state.owned_coroutines.is_empty() else { panic() }
guard task_state.lane.blocking == 0 && task_state.lane.run_later.is_empty() else {
panic()
}
drop_task_wakeup(task_state)
guard task_state.subscribers.is_empty() else { panic() }
component_tasks.remove(waitable_set)
waitable_set.drop()
tls_set(0)
}
///|
fn acknowledge_cancellation(task_state : ComponentTaskState) -> Unit {
guard task_state.cancellation_pending else { return }
match task_state.task.state {
Done => () // The generated wrapper already called task.return.
Fail(_) | Cancelled =>
if task_state.resolution is Pending {
task_cancel()
task_state.resolution = Resolved
}
Running | Suspend(_) => return
}
task_state.cancellation_pending = false
}
///|
fn notify_subscriber(
task_state : ComponentTaskState,
waitable_id : Int,
event : Events,
) -> Unit {
if task_state.lane.wakeup is Some(wakeup) && wakeup.reader == waitable_id {
guard! event is StreamRead(i, { progress: 1, copy_result: Completed }) &&
i == waitable_id
wakeup.reading = false
wakeup.signaled = false
task_state.subscribers.remove(waitable_id)
waitable_join(waitable_id, 0)
return
}
guard! task_state.subscribers.get(waitable_id) is Some(subscriber)
subscriber.event = Some(event)
subscriber.coro.each(Coroutine::wake)
// Keep the delivered event discoverable until its waiter consumes it. A
// local cancellation can race with the wakeup, and cancelling an already
// terminal canonical operation would trap.
waitable_join(waitable_id, 0)
}
///|
fn next_callback(
waitable_set : WaitableSet,
task_state : ComponentTaskState,
) -> Int {
if task_state.resolution is FlushPending {
task_state.resolution = Resolved
reschedule(task_state.lane)
}
acknowledge_cancellation(task_state)
if task_state.task.state is (Done | Fail(_) | Cancelled) &&
no_more_work(task_state.lane) {
let resolution = task_state.resolution
finish_waitableset(waitable_set, task_state)
guard! resolution is Resolved
return CallbackCode::Completed.encode()
}
if has_immediately_ready_task(task_state.lane) {
if !task_state.subscribers.is_empty() {
let (event, waitable_id) = waitable_set.poll()
match event {
None => ()
TaskCancelled => panic()
_ => notify_subscriber(task_state, waitable_id, event)
}
}
tls_set(waitable_set.0)
return CallbackCode::Yield.encode()
}
tls_set(waitable_set.0)
arm_task_wakeup(waitable_set, task_state)
CallbackCode::Wait(waitable_set.0).encode()
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn with_waitableset(f : async () -> Unit) -> Int {
let waitable_set = WaitableSet::new()
let lane = { blocking: 0, run_later: Deque([]), wakeup: None }
tls_set(waitable_set.0)
let task = spawn_owned(f, lane, None)
let task_state = {
lane,
subscribers: Map([]),
task,
owned_coroutines: Set([]),
resolution: Pending,
cancellation_pending: false,
}
component_tasks.set(waitable_set, task_state)
reschedule(lane)
next_callback(waitable_set, task_state)
}
///|
/// Record that the generated export wrapper has resolved the component-model
/// task. One additional fair scheduling round lets the enclosing MoonBit task
/// group observe its body completing without draining runnable background work.
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn task_returned() -> Unit {
let waitable_set = current_waitableset()
guard! component_task_state(waitable_set) is Some(task_state)
guard! task_state.resolution is Pending
task_state.resolution = FlushPending
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn cb(event : Int, waitable_id : Int, code : Int) -> Int {
let waitable_set = current_waitableset()
guard component_task_state(waitable_set) is Some(task_state) else { panic() }
let events = Events::new(EventCode::from(event), waitable_id, code)
let preserve_task_wakeup = match events {
StreamRead(i, _) =>
match task_state.lane.wakeup {
Some(wakeup) => wakeup.reader == i
None => false
}
_ => false
}
cancel_task_wakeup_read(task_state, preserve=preserve_task_wakeup)
match events {
None => {
reschedule(task_state.lane)
next_callback(waitable_set, task_state)
}
TaskCancelled => {
task_state.cancellation_pending = true
task_state.task.cancel()
task_state.owned_coroutines.each(Coroutine::cancel)
reschedule(task_state.lane)
next_callback(waitable_set, task_state)
}
_ => {
notify_subscriber(task_state, waitable_id, events)
reschedule(task_state.lane)
next_callback(waitable_set, task_state)
}
}
}
///|
let component_tasks : Map[WaitableSet, ComponentTaskState] = Map([])
///|
/// Spawn a coroutine owned by the current component-model async task.
///
/// This is intended for runtime bridge work such as lowering local futures and
/// streams to component-model handles. The coroutine does not participate in
/// `TaskGroup` structured concurrency, but it is cancelled when the current
/// component-model task is cancelled and keeps the waitable-set alive until it
/// terminates.
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn spawn_component_task_current(f : async () -> Unit) -> Unit {
let waitable_set = current_waitableset()
guard! component_task_state(waitable_set) is Some(task_state)
let coro = spawn_owned(
async fn() -> Unit {
let coro = current_coroutine()
defer task_state.owned_coroutines.remove(coro)
f()
},
task_state.lane,
Some(spawn_component_task_current),
)
task_state.owned_coroutines.add(coro)
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn has_component_task_scope() -> Bool {
let waitable_set = current_waitableset()
component_task_state(waitable_set) is Some(_)
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn current_component_task_token() -> Int {
current_waitableset().0
}
///|
fn detach_waitable(task_state : ComponentTaskState, waitable_id : Int) -> Unit {
if task_state.subscribers.get(waitable_id) is Some(subscriber) {
subscriber.coro.clear()
task_state.subscribers.remove(waitable_id)
}
waitable_join(waitable_id, 0)
}
///|
fn task_wakeup(lane : TaskLane) -> TaskWakeup {
match lane.wakeup {
Some(wakeup) => wakeup
None => {
let pair = task_wakeup_stream_new()
let wakeup = {
reader: pair.to_int(),
writer: (pair >> 32).to_int(),
reading: false,
signaled: false,
}
lane.wakeup = Some(wakeup)
wakeup
}
}
}
///|
fn arm_task_wakeup(
waitable_set : WaitableSet,
task_state : ComponentTaskState,
) -> Unit {
let wakeup = task_wakeup(task_state.lane)
if wakeup.reading {
return
}
let result = task_wakeup_stream_read(wakeup.reader, 0, 1)
guard! result == -1
let subscribers = task_state.subscribers
guard! subscribers.get(wakeup.reader) is None
subscribers.set(wakeup.reader, { event: None, coro: Set([]) })
waitable_join(wakeup.reader, waitable_set.0)
wakeup.reading = true
wakeup.signaled = false
}
///|
fn signal_component_task(lane : TaskLane) -> Unit {
guard lane.wakeup is Some(wakeup) else { return }
if !wakeup.reading || wakeup.signaled {
return
}
let result = StreamResult::from(task_wakeup_stream_write(wakeup.writer, 0, 1))
guard! result.progress == 1 && result.copy_result is Completed
wakeup.signaled = true
}
///|
fn cancel_task_wakeup_read(
task_state : ComponentTaskState,
preserve~ : Bool,
) -> Unit {
guard task_state.lane.wakeup is Some(wakeup) else { return }
if !wakeup.reading || preserve {
return
}
waitable_join(wakeup.reader, 0)
task_state.subscribers.remove(wakeup.reader)
ignore(task_wakeup_stream_cancel_read(wakeup.reader))
wakeup.reading = false
wakeup.signaled = false
}
///|
fn drop_task_wakeup(task_state : ComponentTaskState) -> Unit {
guard task_state.lane.wakeup is Some(wakeup) else { return }
if wakeup.reading {
waitable_join(wakeup.reader, 0)
task_state.subscribers.remove(wakeup.reader)
ignore(task_wakeup_stream_cancel_read(wakeup.reader))
}
task_wakeup_stream_drop_readable(wakeup.reader)
task_wakeup_stream_drop_writable(wakeup.writer)
task_state.lane.wakeup = None
}
///|
fn cancel_waitable_event(
owner_task : Int,
waitable_id : Int,
cancel : () -> Events,
) -> Events {
let waitable_set = WaitableSet(owner_task)
guard! component_task_state(waitable_set) is Some(task_state)
guard! task_state.subscribers.get(waitable_id) is Some(subscriber)
// Baseline cancel-read is synchronous and traps while its endpoint belongs
// to a waitable set. Detach before invoking the generated intrinsic.
waitable_join(waitable_id, 0)
let event = match subscriber.event {
Some(event) => event
None => cancel()
}
subscriber.event = Some(event)
subscriber.coro.each(Coroutine::wake)
task_state.subscribers.remove(waitable_id)
event
}
///|
/// Complete an operation immediately or suspend until its terminal waitable
/// event arrives. This is the single owner of subscription registration and
/// detachment for future and stream copy operations.
async fn waitable_event(waitable_id : Int, immediate : Events?) -> Events {
let waitable_set = current_waitableset()
let task_state = component_task_state(waitable_set).unwrap()
let subscribers = task_state.subscribers
match immediate {
Some(event) => {
if subscribers.get(waitable_id) is Some(subscriber) {
subscriber.event = Some(event)
subscriber.coro.each(Coroutine::wake)
subscriber.coro.clear()
waitable_join(waitable_id, 0)
}
subscribers.remove(waitable_id)
event
}
None => {
let subscriber = if subscribers.get(waitable_id) is Some(subscriber) {
subscriber
} else {
let subscriber = { event: None, coro: Set([]) }
subscribers.set(waitable_id, subscriber)
subscriber
}
guard! subscriber.event is None
waitable_join(waitable_id, waitable_set.0)
let coro = current_coroutine()
subscriber.coro.add(coro)
defer subscriber.coro.remove(coro)
let event = match suspend_check_cancel() {
Continue => subscriber.event.unwrap()
Cancelled =>
match subscriber.event {
// Completion owns the canonical buffer once its event is
// delivered, even if local cancellation wakes the same coroutine.
Some(event) => event
None => raise_cancellation_signal()
}
}
subscribers.remove(waitable_id)
event
}
}
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub async fn suspend_for_subtask(
val : Int,
settle_lowered_arguments : (Bool) -> Unit,
drop_returned_result : () -> Unit,
) -> Unit {
let task = SubTask::from(val)
let mut cleaned = false
// Once the subtask leaves Starting, canonical arguments are either
// transferred or rejected. Generated code owns the corresponding action.
fn settle_arguments(state : SubTaskState) -> Unit {
if !cleaned && !(state is Starting) {
cleaned = true
settle_lowered_arguments(state is Cancelled_before_started)
}
}
// Immediate completion without a handle.
if task.handle == 0 {
settle_arguments(task.state)
match task.state {
Returned => return
Cancelled_before_started => raise SubTaskCancelled(before_started=true)
Cancelled_before_returned => raise SubTaskCancelled(before_started=false)
_ => panic()
}
}
defer subtask_drop(task.handle)
// Initial state, return if finished
settle_arguments(task.state)
match task.state {
Returned => return
Cancelled_before_started => raise SubTaskCancelled(before_started=true)
Cancelled_before_returned => raise SubTaskCancelled(before_started=false)
_ => ()
}
// A subtask can report intermediate states, so register the same subscriber
// again after each callback until a terminal state arrives.
let waitable_set = current_waitableset()
let task_state = component_task_state(waitable_set).unwrap()
let set = @set.Set([])
let subscriber = { event: None, coro: set }
let coro = current_coroutine()
set.add(coro)
defer {
set.remove(coro)
detach_waitable(task_state, task.handle)
}
for ;; {
let subscribers = task_state.subscribers
guard! subscribers.get(task.handle) is None
subscribers.set(task.handle, subscriber)
waitable_join(task.handle, waitable_set.0)
if suspend_check_cancel() is Cancelled {
protect_from_cancel(() => {
detach_waitable(task_state, task.handle)
// Consume a delivered terminal event before requesting cancellation:
// cancelling an already terminal canonical operation traps.
if subscriber.event is Some(Subtask(i, state)) {
guard! i == task.handle
settle_arguments(state)
match state {
Returned => {
drop_returned_result()
return
}
Cancelled_before_started | Cancelled_before_returned => return
Starting | Started => subscriber.event = None
}
}
let state = task.cancel()
settle_arguments(state)
match state {
Returned => drop_returned_result()
Cancelled_before_started | Cancelled_before_returned => ()
Starting | Started => panic()
}
})
raise_cancellation_signal()
}
task_state.subscribers.remove(task.handle)
// Subsequent state, return if finished
if subscriber.event is Some(Subtask(i, state)) {
guard! i == task.handle
settle_arguments(state)
match state {
Returned => return
Cancelled_before_started => raise SubTaskCancelled(before_started=true)
Cancelled_before_returned =>
raise SubTaskCancelled(before_started=false)
_ => subscriber.event = None
}
}
}
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub async fn suspend_for_future_read(idx : Int, val : Int) -> Unit {
let event = if val == -1 {
waitable_event(idx, None)
} else {
let result = FutureReadResult::from(val)
waitable_event(idx, Some(FutureRead(idx, result)))
}
guard! event is FutureRead(i, result) && i == idx
match result {
Completed => return
Cancelled => raise FutureReadError::Cancelled
}
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn cancel_future_read(
owner_task : Int,
idx : Int,
cancel : () -> Int,
) -> Bool {
let event = cancel_waitable_event(owner_task, idx, () => {
FutureRead(idx, FutureReadResult::from(cancel()))
})
guard! event is FutureRead(i, result) && i == idx
match result {
Completed => true
Cancelled => false
}
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn cancel_stream_read(
owner_task : Int,
idx : Int,
cancel : () -> Int,
) -> Int {
let event = cancel_waitable_event(owner_task, idx, () => {
StreamRead(idx, StreamResult::from(cancel()))
})
guard! event is StreamRead(i, result) && i == idx
result.progress
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn cancel_stream_write(idx : Int, cancel : () -> Int) -> Int {
let event = cancel_waitable_event(current_component_task_token(), idx, () => {
StreamWrite(idx, StreamResult::from(cancel()))
})
guard! event is StreamWrite(i, result) && i == idx
result.progress
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub async fn suspend_for_future_write_terminal(idx : Int, val : Int) -> Bool? {
let event = if val == -1 {
waitable_event(idx, None)
} else {
let result = FutureWriteResult::from(val)
waitable_event(idx, Some(FutureWrite(idx, result)))
}
guard! event is FutureWrite(i, result) && i == idx
match result {
Completed => Some(true)
Dropped => Some(false)
Cancelled => None
}
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub async fn suspend_for_stream_read(idx : Int, val : Int) -> (Int, Bool) {
let event = if val == -1 {
waitable_event(idx, None)
} else {
let result = StreamResult::from(val)
waitable_event(idx, Some(StreamRead(idx, result)))
}
guard! event is StreamRead(i, { progress, copy_result }) && i == idx
match copy_result {
Completed => return (progress, false)
Dropped => return (progress, true)
Cancelled =>
if progress > 0 {
return (progress, false)
} else {
raise StreamReadCancelled
}
}
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub async fn suspend_for_stream_write(idx : Int, val : Int) -> (Int, Bool) {
let event = if val == -1 {
waitable_event(idx, None)
} else {
let result = StreamResult::from(val)
waitable_event(idx, Some(StreamWrite(idx, result)))
}
guard! event is StreamWrite(i, { progress, copy_result }) && i == idx
match copy_result {
Completed => return (progress, false)
Dropped => return (progress, true)
Cancelled => return (progress, false)
}
}
///|
pub suberror OpCancelled {
SubTaskCancelled(before_started~ : Bool)
StreamReadCancelled
}
///|
pub(all) suberror FutureReadError {
Cancelled
Dropped
}
///|
#internal(wit_bindgen, "generated binding code only")
pub(all) suberror EndpointBusy {
Read
Write
}
+44
View File
@@ -0,0 +1,44 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
/// A mutex for synchronization between tasks.
#valtype
pub struct Mutex {
priv semaphore : Semaphore
}
///|
/// Create a mutex in the released state.
pub fn Mutex::Mutex() -> Mutex {
{ semaphore: Semaphore(1) }
}
///|
/// Acquire the mutex in FIFO order.
pub async fn Mutex::acquire(self : Mutex) -> Unit noraise {
self.semaphore.acquire()
}
///|
/// Try to acquire the mutex without waiting.
pub fn Mutex::try_acquire(self : Mutex) -> Bool {
self.semaphore.try_acquire()
}
///|
/// Release the mutex. The mutex must already be acquired.
pub fn Mutex::release(self : Mutex) -> Unit {
self.semaphore.release()
}
+31
View File
@@ -0,0 +1,31 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
async fn[T] async_suspend(cb : ((T) -> Unit) -> Unit) -> T noraise + nocancel = "%async.suspend"
///|
fn run_async(f : async () -> Unit noraise + nocancel) = "%async.run"
///|
/// Deliver cancellation from the runtime, or resume it after boundary cleanup.
#internal(wit_bindgen, "runtime and generated binding code only")
#doc(hidden)
pub async fn[X] raise_cancellation_signal() -> X noraise = "%async.raise_cancellation_signal"
///|
async fn[X] capture_cancellation(
f : async () -> X,
handler~ : async () -> X nocancel,
) -> X nocancel = "%async.capture_cancellation"
+211
View File
@@ -0,0 +1,211 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
priv enum PromiseState[X] {
Pending
Completed(X)
Failed(Error)
Closed
ReaderDropped
Consumed
}
///|
priv struct PromiseCell[X] {
mut state : PromiseState[X]
ready : Semaphore
cleanup : ((X) -> Unit)?
mut reading : Bool
}
///|
/// The local producer side of a one-shot `Future[X]`.
///
/// This is a MoonBit coordination value, not a component-model future writable
/// endpoint. Conversion to a component future remains generated at an FFI site.
pub struct Promise[X] {
priv cell : Ref[PromiseCell[X]]
}
///|
pub(all) suberror PromiseClosed derive(Debug)
///|
#deprecated
pub extend PromiseClosed with Debug::{to_repr}
///|
fn[X] new_future_promise(cleanup : ((X) -> Unit)?) -> (Future[X], Promise[X]) {
let cell : Ref[PromiseCell[X]] = {
val: {
state: Pending,
ready: Semaphore(1, initial_value=0),
cleanup,
reading: false,
},
}
({ inner: Promised(cell) }, { cell, })
}
///|
/// Create a local one-shot Future/Promise pair.
pub fn[X] Future::new() -> (Future[X], Promise[X]) {
new_future_promise(None)
}
///|
/// Create a local one-shot Future/Promise pair with value-discard cleanup.
///
/// The cleanup callback runs when the promise completed successfully but the
/// future is dropped before consuming the value.
pub fn[X] Future::new_with_cleanup(
cleanup : (X) -> Unit,
) -> (Future[X], Promise[X]) {
new_future_promise(Some(cleanup))
}
///|
/// Complete the paired future with `value`.
///
/// `true` means the future accepted ownership. `false` means its reader was
/// already dropped and the caller retains ownership of `value`.
pub fn[X] Promise::complete(self : Promise[X], value : X) -> Bool {
match self.cell.val.state {
Pending => {
self.cell.val.state = Completed(value)
self.cell.val.ready.release()
true
}
ReaderDropped => false
Completed(_) | Failed(_) | Closed | Consumed =>
abort("promise already settled")
}
}
///|
/// Complete the paired future with an error raised by `Future::get`.
pub fn[X] Promise::fail(self : Promise[X], error : Error) -> Bool {
match self.cell.val.state {
Pending => {
self.cell.val.state = Failed(error)
self.cell.val.ready.release()
true
}
ReaderDropped => false
Completed(_) | Failed(_) | Closed | Consumed =>
abort("promise already settled")
}
}
///|
/// Close the paired future without producing a value.
///
/// A local waiter observes `PromiseClosed`. An outgoing component future still
/// cannot represent this terminal state and follows the bridge's no-value
/// failure policy if it has already crossed an FFI boundary.
pub fn[X] Promise::close(self : Promise[X]) -> Bool {
match self.cell.val.state {
Pending => {
self.cell.val.state = Closed
self.cell.val.ready.release()
true
}
ReaderDropped => false
Completed(_) | Failed(_) | Closed | Consumed =>
abort("promise already settled")
}
}
///|
fn[X] consume_promised_future(cell : Ref[PromiseCell[X]]) -> X raise {
match cell.val.state {
Completed(value) => {
cell.val.state = Consumed
value
}
Failed(error) => {
cell.val.state = Consumed
raise error
}
Closed => {
cell.val.state = Consumed
raise PromiseClosed
}
Pending => panic()
ReaderDropped => raise FutureReadError::Dropped
Consumed => abort("future already consumed")
}
}
///|
async fn[X] promised_future_get(cell : Ref[PromiseCell[X]]) -> X {
if cell.val.reading {
abort("future read already in progress")
}
match cell.val.state {
Pending => {
cell.val.reading = true
{
errdefer {
cell.val.reading = false
if cell.val.state is Pending {
cell.val.state = ReaderDropped
}
}
cell.val.ready.acquire()
}
cell.val.reading = false
consume_promised_future(cell)
}
Completed(_) | Failed(_) | Closed => consume_promised_future(cell)
ReaderDropped => consume_promised_future(cell)
Consumed => abort("future already consumed")
}
}
///|
fn[X] promised_future_drop(
cell : Ref[PromiseCell[X]],
fallback_cleanup : ((X) -> Unit)?,
) -> Unit {
if cell.val.reading {
match cell.val.state {
Pending => {
cell.val.state = ReaderDropped
cell.val.ready.release()
}
// Once settlement assigned a result, the waiting reader owns it.
Completed(_) | Failed(_) | Closed => ()
ReaderDropped | Consumed => ()
}
return
}
match cell.val.state {
Pending => cell.val.state = ReaderDropped
Completed(value) => {
cell.val.state = Consumed
match cell.val.cleanup {
Some(cleanup) => cleanup(value)
None =>
match fallback_cleanup {
Some(cleanup) => cleanup(value)
None => ()
}
}
}
Failed(_) | Closed => cell.val.state = Consumed
ReaderDropped | Consumed => ()
}
}
+74
View File
@@ -0,0 +1,74 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
priv struct Scheduler {
mut coro_id : Int
mut curr_coro : Coroutine?
}
///|
/// The per-component-task part of the scheduler. Coroutines retain this lane,
/// not `ComponentTaskState`, so a retired task cannot be kept alive by an RC
/// cycle through its registry entry or subscribers.
priv struct TaskLane {
mut blocking : Int
run_later : @deque.Deque[Coroutine]
mut wakeup : TaskWakeup?
}
///|
let scheduler : Scheduler = { coro_id: 0, curr_coro: None }
///|
fn current_coroutine() -> Coroutine {
scheduler.curr_coro.unwrap()
}
///|
fn enqueue(coro : Coroutine) -> Unit {
coro.lane.run_later.push_back(coro)
}
///|
fn has_immediately_ready_task(lane : TaskLane) -> Bool {
!lane.run_later.is_empty()
}
///|
fn no_more_work(lane : TaskLane) -> Bool {
lane.blocking == 0 && lane.run_later.is_empty()
}
///|
/// Run one fair scheduling round for a component task. Coroutines woken or
/// spawned during this round are left for the next round so the component
/// event loop gets a chance to poll completed waitables.
fn reschedule(lane : TaskLane) -> Unit {
let count = lane.run_later.length()
for _ in 0..<count {
guard lane.run_later.pop_front() is Some(coro) else { break }
coro.ready = false
guard coro.state is Suspend(cont) else { }
coro.state = Running
let last_coro = scheduler.curr_coro
scheduler.curr_coro = Some(coro)
if coro.cancelled && !coro.shielded {
cont(Cancelled)
} else {
cont(Continue)
}
scheduler.curr_coro = last_coro
}
}
+95
View File
@@ -0,0 +1,95 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
priv struct SemaphoreWaiter {
// Once a permit is assigned, cancellation must not lose it before the
// waiter resumes. This matches moonbitlang/async's semaphore semantics.
mut acquired : Bool
mut coro : Coroutine?
}
///|
pub struct Semaphore {
size : Int
priv mut value : Int
priv waiters : @deque.Deque[SemaphoreWaiter]
}
///|
/// Create a semaphore with at most `size` permits.
///
/// The initial number of available permits is `initial_value`, or `size` when
/// omitted.
#alias(new, deprecated)
pub fn Semaphore::Semaphore(
size : Int,
initial_value? : Int = size,
) -> Semaphore {
if size <= 0 {
abort("size of semaphore must be positive")
}
guard! initial_value >= 0 && initial_value <= size
{ value: initial_value, size, waiters: Deque([]) }
}
///|
/// Release one permit. Waiting coroutines acquire permits in FIFO order.
///
/// Each call must correspond one-to-one with a successful `acquire`. Calling
/// `release` without owning a permit is invalid.
pub fn Semaphore::release(self : Semaphore) -> Unit {
if self.value >= self.size {
abort("semaphore: too many release")
}
while self.waiters.pop_front() is Some(waiter) {
if waiter.coro is Some(coro) {
waiter.acquired = true
coro.wake()
break
}
} nobreak {
self.value += 1
}
}
///|
/// Acquire one permit, suspending in FIFO order when none is available.
pub async fn Semaphore::acquire(self : Semaphore) -> Unit noraise {
if self.value > 0 {
self.value -= 1
} else {
let waiter = { coro: Some(current_coroutine()), acquired: false }
self.waiters.push_back(waiter)
match suspend_check_cancel() {
Continue => ()
Cancelled if waiter.acquired => ()
Cancelled => {
waiter.coro = None
raise_cancellation_signal()
}
}
}
}
///|
/// Try to acquire one permit without suspending.
pub fn Semaphore::try_acquire(self : Semaphore) -> Bool {
if self.value > 0 {
self.value -= 1
true
} else {
false
}
}
+61
View File
@@ -0,0 +1,61 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
/// `Task[X]` represents a running task with result type `X`,
/// it can be used to wait and retrieve the result value of the task.
pub struct Task[X] {
priv value : Ref[X?]
priv coro : Coroutine
}
///|
/// An observed task terminated by cancellation. This is an ordinary error in
/// the waiter, distinct from cancellation of the waiter itself.
pub suberror TaskCancelled derive(Debug)
///|
#deprecated
pub extend TaskCancelled with Debug::{to_repr}
///|
/// Wait for a task and retrieve its result value.
/// If the task fails, `wait` will also fail with the same error.
///
/// If the target task was cancelled, `wait` raises `TaskCancelled`.
/// Cancellation of the current task propagates as a cancellation signal.
pub async fn[X] Task::wait(self : Task[X]) -> X {
match self.coro.wait() {
Continue => self.value.val.unwrap()
Cancelled => raise TaskCancelled::TaskCancelled
}
}
///|
/// Try to obtain the result of the task.
/// If the task already terminated, its result value will be returned.
/// If the task already failed, `try_wait` will fail immediately.
/// If the task is still running, `try_wait` returns `None`.
/// `try_wait` is a synchoronous function: it never blocks.
pub fn[X] Task::try_wait(self : Task[X]) -> X? raise {
self.coro.check_error()
self.value.val
}
///|
/// Cancel a running task. Cancelling a terminated task has no effect.
/// Subsequent attempt to wait for a cancelled task will receive error.
pub fn[X] Task::cancel(self : Task[X]) -> Unit {
self.coro.cancel()
}
+269
View File
@@ -0,0 +1,269 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
priv enum TaskGroupState {
Done
Fail(Error)
Cancelled
Running
}
///|
priv struct GroupDeferBlock(async () -> Unit nocancel)
///|
/// A `TaskGroup` can be used to spawn children tasks that run in parallel.
/// Task groups implements *structured concurrency*:
/// a task group will only return after all its children task terminates.
///
/// Task groups also handles *error propagation*:
/// by default, if any child task raises error,
/// the whole task group will also raise that error,
/// and all other remaining child tasks will be cancelled.
///
/// The type parameter `X` in `TaskGroup[X]` is the result type of the group,
/// see `with_task_group` for more detail.
pub struct TaskGroup[X] {
priv children : Set[Coroutine]
priv parent : Coroutine
priv mut waiting : Int
priv mut state : TaskGroupState
priv mut result : X?
priv group_defer : Array[GroupDeferBlock]
}
///|
fn[X] TaskGroup::spawn_coroutine(
self : TaskGroup[X],
f : async () -> Unit,
no_wait~ : Bool,
allow_failure~ : Bool,
) -> Coroutine {
guard self.state is Running || !self.children.is_empty() else {
abort("trying to spawn from a terminated task group")
}
if !no_wait {
self.waiting += 1
}
async fn worker() {
let coro = current_coroutine()
defer {
self.children.remove(coro)
if !no_wait {
self.waiting -= 1
if self.waiting == 0 && self.state is Running {
for child in self.children {
child.cancel()
}
self.state = Done
}
}
if self.children.is_empty() {
self.parent.wake()
}
}
f() catch {
err if allow_failure => raise err
err => {
if self.state is Running {
for child in self.children {
child.cancel()
}
self.state = Fail(err)
} else {
self.state = Fail(err)
}
raise err
}
}
}
let coro = spawn(worker)
self.children.add(coro)
if !(self.state is Running) {
coro.cancel()
}
coro
}
///|
/// Spawn a child task in a task group, and run it asynchronously in the background.
///
/// Unless `no_wait` (`false` by default) is `true`,
/// the task group will wait for this task to complete before normal exit.
/// No matter what the value of `no_wait` is,
/// `with_task_group` will only return after all child tasks terminate.
/// The task will be cancelled automatically if it is still running
/// when the task group wishes to terminate.
///
/// Unless `allow_failure` (`false` by default) is `true`,
/// the whole task group will also fail if the spawned task fails,
/// other tasks in the group will be cancelled in this case.
///
/// Cancelled tasks are not considered failing. A normal error raised during
/// cancellation cleanup is still considered a failure.
///
/// A task spawned while the group is cancelling still starts, but begins in a
/// cancelled state so its entry cleanup can run. Spawning after the group has
/// terminated or from a group defer is invalid and aborts.
///
/// It is undefined whether the child task will start running immediately
/// before `spawn_bg` returns.
pub fn[X] TaskGroup::spawn_bg(
self : TaskGroup[X],
f : async () -> Unit,
no_wait? : Bool = false,
allow_failure? : Bool = false,
) -> Unit {
ignore(self.spawn_coroutine(f, no_wait~, allow_failure~))
}
///|
/// Spawn a child task in a task group, compute a result asynchronously.
/// A task handle will be returned, the result value of the task can be waited
/// and retrieved using `.wait()`, or cancelled using `.cancel()`.
///
/// Unless `no_wait` (`false` by default) is `true`,
/// the task group will wait for this task to complete before normal exit.
/// No matter what the value of `no_wait` is,
/// `with_task_group` will only return after all child tasks terminate.
/// The task will be cancelled automatically if it is still running
/// when the task group wishes to terminate.
///
/// Unless `allow_failure` (`false` by default) is `true`,
/// the whole task group will also fail if the spawned task fails,
/// other tasks in the group will be cancelled in this case.
///
/// Cancelled tasks are not considered failing. A normal error raised during
/// cancellation cleanup is still considered a failure.
///
/// A task spawned while the group is cancelling still starts, but begins in a
/// cancelled state so its entry cleanup can run. Spawning after the group has
/// terminated or from a group defer is invalid and aborts.
///
/// It is undefined whether the child task will start running immediately
/// before `spawn` returns.
pub fn[G, X] TaskGroup::spawn(
self : TaskGroup[G],
f : async () -> X,
no_wait? : Bool = false,
allow_failure? : Bool = false,
) -> Task[X] {
let value = @ref.new(Option::None)
let coro = self.spawn_coroutine(
() => value.val = Some(f()),
no_wait~,
allow_failure~,
)
{ value, coro }
}
///|
/// Attach a defer block, represented as a cleanup function, to a task group.
/// The cleanup function runs after every child task has terminated. Spawning a
/// new child from a group defer is invalid and aborts.
/// Group scoped defer blocks are executed in FILO order, just like normal `defer`.
/// `with_task_group` will only exit after all group defer blocks terminate.
///
/// Group defer blocks must be `nocancel`. Use `protect_from_cancel` when
/// running cancellable operations in a group defer.
/// It is highly recommended to add a hard timeout to async defer block in this case,
/// to avoid infinite hanging due to blocked operation.
pub fn[X] TaskGroup::add_defer(
self : TaskGroup[X],
block : async () -> Unit nocancel,
) -> Unit {
guard self.state is Running else {
abort("trying to attach defer to a terminated task group")
}
self.group_defer.push(GroupDeferBlock(block))
}
///|
/// `with_task_group(f)` creates a new task group and run `f` with the new group.
/// `f` itself will be run in a child task of the new group.
/// `with_task_group` exits after all the whole group terminates,
/// which means all child tasks in the group have terminated, including `f`.
///
/// If all children task terminate successfully,
/// `with_task_group` will return the result of `f`.
pub async fn[X] with_task_group(f : async (TaskGroup[X]) -> X) -> X {
let tg = {
children: Set([]),
parent: current_coroutine(),
waiting: 0,
state: Running,
result: None,
group_defer: [],
}
let curr = current_coroutine()
let prev = curr.spawner
curr.spawner = Some(fn(child) { tg.spawn_bg(child) })
defer {
curr.spawner = prev
}
tg.spawn_bg(() => {
let value = f(tg)
if tg.result is None {
tg.result = Some(value)
}
})
match suspend_check_cancel() {
Continue => ()
Cancelled => {
if tg.state is Running {
tg.state = Cancelled
}
if !tg.children.is_empty() {
for child in tg.children {
child.cancel()
}
protect_from_cancel(() => suspend())
}
}
}
guard! tg.children.is_empty()
while tg.group_defer.pop() is Some(defer_block) {
defer_block() catch {
err => if tg.state is Done { tg.state = Fail(err) }
}
}
match tg.state {
Done => tg.result.unwrap()
Fail(err) => raise err
Cancelled => raise_cancellation_signal()
Running => panic()
}
}
///|
/// Force a task group to terminate immediately with the given result value.
/// All child tasks in the group, including potentially the current one,
/// will be cancelled.
pub async fn[X] TaskGroup::return_immediately(
self : TaskGroup[X],
value : X,
) -> Unit noraise {
if self.result is None {
self.result = Some(value)
}
if self.state is Running {
self.state = Done
for child in self.children {
child.cancel()
}
}
check_cancellation()
}
+964
View File
@@ -0,0 +1,964 @@
///|
pub struct Sink[X] {
priv write : async (ArrayView[X]) -> Int
priv close : async () -> Unit
priv is_open : () -> Bool
priv has_cleanup : () -> Bool
priv cleanup : ((X) -> Unit)?
priv write_window_size : Int
}
///|
let default_sink_write_window_size : Int = 64
///|
/// The write callback must either raise before consuming any value or return
/// the number consumed. It must not raise after partial consumption because
/// `ArrayView` cannot carry an ownership offset through an exception.
/// The close callback must be idempotent.
#internal(wit_bindgen, "generated binding code only")
pub fn[X] Sink::from_callbacks(
write : async (ArrayView[X]) -> Int,
close : async () -> Unit,
is_open : () -> Bool,
cleanup : ((X) -> Unit)?,
write_window_size : Int,
) -> Sink[X] {
guard! write_window_size > 0
{
write,
close,
is_open,
has_cleanup: () => cleanup is Some(_),
cleanup,
write_window_size,
}
}
///|
/// Consumes up to one bounded window and returns the number of values consumed.
///
/// Consumption includes values accepted by the peer and values recursively
/// cleaned after the peer closes. Check `is_open()` to distinguish those cases.
pub async fn[X] Sink::write(self : Sink[X], data : ArrayView[X]) -> Int {
if data.length() == 0 {
return 0
}
let length = if data.length() < self.write_window_size {
data.length()
} else {
self.write_window_size
}
// The callback may suspend, so it must not retain the caller's borrowed view.
let buffer = FixedArray::from_array(data[:length])
let written = (self.write)(buffer[:])
guard! written >= 0 && written <= length
if !(self.is_open)() && written < length && (self.has_cleanup)() {
self.cleanup_unaccepted(buffer[:], written)
return length
}
written
}
///|
/// Writes one bounded window from an immutable byte view.
///
/// This is the byte-stream counterpart of `write(ArrayView[T])`. MoonBit keeps
/// `BytesView` and `ArrayView[Byte]` as distinct types, so byte strings need a
/// separate entry point until the language provides a shared read-only view.
pub async fn Sink::write_bytes(self : Sink[Byte], data : BytesView) -> Int {
if data.length() == 0 {
return 0
}
let length = if data.length() < self.write_window_size {
data.length()
} else {
self.write_window_size
}
let buffer = data[:length].to_fixedarray()
let written = (self.write)(buffer[:])
guard! written >= 0 && written <= length
if !(self.is_open)() && written < length && (self.has_cleanup)() {
self.cleanup_unaccepted(buffer[:], written)
return length
}
written
}
///|
/// Returns whether the sink can still accept values from its peer.
pub fn[X] Sink::is_open(self : Sink[X]) -> Bool {
(self.is_open)()
}
///|
fn[X] Sink::cleanup_unaccepted(
self : Sink[X],
data : ArrayView[X],
offset : Int,
) -> Unit {
match self.cleanup {
Some(cleanup) =>
for i in offset..<data.length() {
cleanup(data[i])
}
None => ()
}
}
///|
fn Sink::cleanup_unaccepted_bytes(
self : Sink[Byte],
data : BytesView,
offset : Int,
) -> Unit {
match self.cleanup {
Some(cleanup) =>
for i in offset..<data.length() {
cleanup(data[i])
}
None => ()
}
}
///|
/// Writes the entire slice to the sink unless the sink closes first.
///
/// Returns `true` if all items were written while the sink remained open and
/// `false` if the endpoint closed during the operation. When the sink has a
/// cleanup callback, every item was either accepted or cleaned and must not be
/// retried. Producers of explicitly managed resources must use such a sink.
pub async fn[X] Sink::write_all(self : Sink[X], data : ArrayView[X]) -> Bool {
let mut offset = 0
for ;; {
if offset >= data.length() {
return true
}
let written = {
errdefer self.cleanup_unaccepted(data, offset)
self.write(data[offset:])
}
offset = offset + written
if !self.is_open() {
self.cleanup_unaccepted(data, offset)
return false
}
guard! written > 0
}
}
///|
/// Writes the entire byte view unless the sink closes first.
pub async fn Sink::write_all_bytes(self : Sink[Byte], data : BytesView) -> Bool {
let mut offset = 0
for ;; {
if offset >= data.length() {
return true
}
let written = {
errdefer self.cleanup_unaccepted_bytes(data, offset)
self.write_bytes(data[offset:])
}
offset = offset + written
if !self.is_open() {
self.cleanup_unaccepted_bytes(data, offset)
return false
}
guard! written > 0
}
}
///|
/// Closes the writable end of the stream.
///
/// Closing is idempotent. A peer waiting for values observes the end of the
/// stream after any values already accepted by the sink have been read.
pub async fn[X] Sink::close(self : Sink[X]) -> Unit {
(self.close)()
}
///|
priv struct LocalFutureState[X] {
mut value : X?
mut closed : Bool
cleanup : ((X) -> Unit)?
}
///|
fn[X] local_future_close(
state : Ref[LocalFutureState[X]],
fallback_cleanup : ((X) -> Unit)?,
) -> Unit {
if state.val.closed {
return
}
match state.val.value {
Some(value) => {
state.val.value = None
match state.val.cleanup {
Some(cleanup) => cleanup(value)
None =>
match fallback_cleanup {
Some(cleanup) => cleanup(value)
None => ()
}
}
}
None => ()
}
state.val.closed = true
}
///|
fn[X] local_future_get(state : Ref[LocalFutureState[X]]) -> X raise {
match state.val.value {
Some(value) => {
state.val.value = None
state.val.closed = true
value
}
None => raise FutureReadError::Dropped
}
}
///|
priv struct StreamPipeReader[X] {
max : Int
mut value : FixedArray[X]?
mut ended : Bool
mut coro : Coroutine?
}
///|
priv struct StreamPipeWriter[X] {
mut value : FixedArray[X]?
mut accepted : Int
mut coro : Coroutine?
}
///|
priv struct StreamPipe[X] {
capacity : Int
chunks : @deque.Deque[FixedArray[X]]
mut buffered : Int
mut writer_closed : Bool
mut reader_dropped : Bool
mut cleanup : ((X) -> Unit)?
mut head : FixedArray[X]?
mut head_pos : Int
readers : @deque.Deque[StreamPipeReader[X]]
writers : @deque.Deque[StreamPipeWriter[X]]
}
///|
fn[X] wake_stream_pipe_reader(
reader : StreamPipeReader[X],
value : FixedArray[X]?,
ended : Bool,
) -> Unit {
match reader.coro {
Some(coro) => {
reader.value = value
reader.ended = ended
reader.coro = None
coro.wake()
}
None => ()
}
}
///|
fn[X] wake_stream_pipe_writer(
writer : StreamPipeWriter[X],
accepted : Int,
) -> Unit {
match writer.coro {
Some(coro) => {
writer.accepted = accepted
writer.value = None
writer.coro = None
coro.wake()
}
None => writer.value = None
}
}
///|
fn[X] take_stream_pipe_reader(
pipe : Ref[StreamPipe[X]],
) -> StreamPipeReader[X]? {
while pipe.val.readers.pop_front() is Some(reader) {
if reader.coro is Some(_) {
return Some(reader)
}
}
None
}
///|
fn[X] take_stream_pipe_writer(
pipe : Ref[StreamPipe[X]],
) -> StreamPipeWriter[X]? {
while pipe.val.writers.pop_front() is Some(writer) {
if writer.coro is Some(_) && writer.value is Some(_) {
return Some(writer)
}
}
None
}
///|
fn[X] fill_stream_pipe_from_writers(pipe : Ref[StreamPipe[X]]) -> Unit {
if pipe.val.capacity <= 0 || pipe.val.writer_closed || pipe.val.reader_dropped {
return
}
for ;; {
let available = pipe.val.capacity - pipe.val.buffered
if available <= 0 {
return
}
guard take_stream_pipe_writer(pipe) is Some(writer) else { return }
guard writer.value is Some(data) else { continue }
let take = if available < data.length() { available } else { data.length() }
let chunk = FixedArray::from_array(data[:take])
pipe.val.chunks.push_back(chunk)
pipe.val.buffered = pipe.val.buffered + take
wake_stream_pipe_writer(writer, take)
}
}
///|
fn[X] stream_pipe_drop_reader(pipe : Ref[StreamPipe[X]]) -> Unit {
stream_pipe_drop_reader_with_cleanup(pipe, pipe.val.cleanup)
}
///|
fn[X] stream_pipe_drop_reader_with_cleanup(
pipe : Ref[StreamPipe[X]],
cleanup : ((X) -> Unit)?,
) -> Unit {
if pipe.val.reader_dropped {
return
}
match cleanup {
Some(cleanup) => {
match pipe.val.head {
Some(head) =>
for i in pipe.val.head_pos..<head.length() {
cleanup(head[i])
}
None => ()
}
while pipe.val.chunks.pop_front() is Some(chunk) {
for value in chunk {
cleanup(value)
}
}
}
None => ()
}
pipe.val.head = None
pipe.val.head_pos = 0
pipe.val.chunks.clear()
pipe.val.buffered = 0
pipe.val.reader_dropped = true
while pipe.val.readers.pop_front() is Some(reader) {
wake_stream_pipe_reader(reader, None, true)
}
while pipe.val.writers.pop_front() is Some(writer) {
let consumed = match (cleanup, writer.value) {
(Some(cleanup), Some(data)) => {
for value in data {
cleanup(value)
}
data.length()
}
_ => 0
}
wake_stream_pipe_writer(writer, consumed)
}
}
///|
fn[X] stream_pipe_reject_reader(
pipe : Ref[StreamPipe[X]],
fallback : (X) -> Unit,
) -> Unit {
if pipe.val.cleanup is None {
pipe.val.cleanup = Some(fallback)
}
stream_pipe_drop_reader(pipe)
}
///|
fn[X] stream_pipe_close_writer(pipe : Ref[StreamPipe[X]]) -> Unit {
if pipe.val.writer_closed {
return
}
pipe.val.writer_closed = true
while pipe.val.writers.pop_front() is Some(writer) {
wake_stream_pipe_writer(writer, 0)
}
if pipe.val.buffered == 0 {
while pipe.val.readers.pop_front() is Some(reader) {
wake_stream_pipe_reader(reader, None, true)
}
}
}
///|
async fn[X] stream_pipe_write(
pipe : Ref[StreamPipe[X]],
data : ArrayView[X],
) -> Int {
if data.length() == 0 || pipe.val.writer_closed || pipe.val.reader_dropped {
return 0
}
match take_stream_pipe_reader(pipe) {
Some(reader) => {
let take = if reader.max < data.length() {
reader.max
} else {
data.length()
}
let chunk = FixedArray::from_array(data[:take])
wake_stream_pipe_reader(reader, Some(chunk), false)
return take
}
None => ()
}
if pipe.val.capacity > 0 && pipe.val.buffered < pipe.val.capacity {
let available = pipe.val.capacity - pipe.val.buffered
let take = if available < data.length() { available } else { data.length() }
let chunk = FixedArray::from_array(data[:take])
pipe.val.chunks.push_back(chunk)
pipe.val.buffered = pipe.val.buffered + take
return take
}
let writer = StreamPipeWriter::{
value: Some(FixedArray::from_array(data)),
accepted: 0,
coro: Some(current_coroutine()),
}
pipe.val.writers.push_back(writer)
match suspend_check_cancel() {
Continue => ()
Cancelled if writer.coro is None => return writer.accepted
Cancelled => {
writer.coro = None
writer.value = None
raise_cancellation_signal()
}
}
writer.value = None
writer.accepted
}
///|
async fn[X] stream_pipe_read(
pipe : Ref[StreamPipe[X]],
count : Int,
) -> FixedArray[X]? {
if count <= 0 {
return Some([])
}
for ;; {
if pipe.val.reader_dropped {
return None
}
match pipe.val.head {
Some(head) => {
let available = head.length() - pipe.val.head_pos
let take = if count < available { count } else { available }
let result = FixedArray::from_array(
head[pipe.val.head_pos:pipe.val.head_pos + take],
)
pipe.val.head_pos = pipe.val.head_pos + take
pipe.val.buffered = pipe.val.buffered - take
if pipe.val.head_pos >= head.length() {
pipe.val.head = None
pipe.val.head_pos = 0
}
fill_stream_pipe_from_writers(pipe)
return Some(result)
}
None => ()
}
if pipe.val.chunks.pop_front() is Some(chunk) {
pipe.val.head = Some(chunk)
pipe.val.head_pos = 0
continue
}
match take_stream_pipe_writer(pipe) {
Some(writer) => {
guard writer.value is Some(data) else { continue }
let take = if count < data.length() { count } else { data.length() }
let result = FixedArray::from_array(data[:take])
wake_stream_pipe_writer(writer, take)
return Some(result)
}
None => ()
}
if pipe.val.writer_closed {
return None
}
let reader = StreamPipeReader::{
max: count,
value: None,
ended: false,
coro: Some(current_coroutine()),
}
pipe.val.readers.push_back(reader)
if suspend_check_cancel() is Cancelled {
reader.coro = None
match reader.value {
Some(value) => return Some(value)
None if reader.ended => return None
None => raise_cancellation_signal()
}
}
match reader.value {
Some(value) => return Some(value)
None if reader.ended => return None
None => ()
}
}
}
///|
priv struct FutureSource[X] {
get : async () -> X
close : async () -> Unit
close_sync : () -> Unit
}
///|
priv struct FutureProducerState[X] {
mut producer : (async () -> X)?
mut on_unstarted_drop : (() -> Unit)?
}
///|
priv enum FutureState[X] {
Source(FutureSource[X])
Local(Ref[LocalFutureState[X]])
Pending(Ref[FutureProducerState[X]])
Promised(Ref[PromiseCell[X]])
}
///|
pub struct Future[X] {
priv inner : FutureState[X]
}
///|
pub fn[X] Future::ready_with_cleanup(
value : X,
cleanup : (X) -> Unit,
) -> Future[X] {
let state : Ref[LocalFutureState[X]] = {
val: { value: Some(value), closed: false, cleanup: Some(cleanup) },
}
{ inner: Local(state) }
}
///|
pub fn[X] Future::ready(value : X) -> Future[X] {
let state : Ref[LocalFutureState[X]] = {
val: { value: Some(value), closed: false, cleanup: None },
}
{ inner: Local(state) }
}
///|
/// Creates a lazy future from an async producer.
///
/// `on_unstarted_drop`, when present, releases resources captured by a producer
/// that is discarded before its first `get`. Once the producer starts, it owns
/// its runtime cleanup and this callback is never invoked.
pub fn[X] Future::from(
producer : async () -> X,
on_unstarted_drop? : () -> Unit,
) -> Future[X] {
{ inner: Pending({ val: { producer: Some(producer), on_unstarted_drop } }) }
}
///|
#internal(wit_bindgen, "generated binding code only")
pub fn[X] Future::from_source(
get : async () -> X,
close : async () -> Unit,
close_sync : () -> Unit,
) -> Future[X] {
{ inner: Source({ get, close, close_sync }) }
}
///|
/// Waits for and consumes the future's single value.
///
/// A `Future` is a one-shot value. Calling `get` again, or calling it after the
/// readable end has been dropped, fails instead of replaying the value.
pub async fn[X] Future::get(self : Future[X]) -> X {
match self.inner {
Source(source) => (source.get)()
Local(state) => local_future_get(state)
Pending(state) =>
match state.val.producer {
Some(producer) => {
state.val.producer = None
state.val.on_unstarted_drop = None
producer()
}
None => raise FutureReadError::Dropped
}
Promised(cell) => promised_future_get(cell)
}
}
///|
/// Releases the readable end without consuming its value.
///
/// If the value is already locally available, its registered cleanup callback
/// runs. An unstarted lazy producer is discarded and runs
/// `on_unstarted_drop`, when provided.
pub async fn[X] Future::drop(self : Future[X]) -> Unit noraise {
match self.inner {
Source(source) => (source.close)() catch { _ => () }
Local(state) => local_future_close(state, None)
Pending(state) => {
let cleanup = state.val.on_unstarted_drop
state.val.producer = None
state.val.on_unstarted_drop = None
match cleanup {
Some(cleanup) => cleanup()
None => ()
}
}
Promised(cell) => promised_future_drop(cell, None)
}
}
///|
#internal(wit_bindgen, "generated binding code only")
pub fn[X] Future::drop_sync(self : Future[X]) -> Unit {
match self.inner {
Source(source) => (source.close_sync)()
Local(state) => local_future_close(state, None)
Pending(state) => {
let cleanup = state.val.on_unstarted_drop
state.val.producer = None
state.val.on_unstarted_drop = None
match cleanup {
Some(cleanup) => cleanup()
None => ()
}
}
Promised(cell) => promised_future_drop(cell, None)
}
}
///|
/// Rejects a future that was prepared for a component-model transfer but was
/// never transferred. A locally available value uses its registered cleanup,
/// falling back to the generated canonical-ABI cleanup. An unstarted producer
/// is discarded without running it.
#internal(wit_bindgen, "generated binding code only")
pub async fn[X] Future::reject(
self : Future[X],
cleanup : (X) -> Unit,
) -> Unit noraise {
match self.inner {
Source(source) => (source.close)() catch { _ => () }
Local(state) => local_future_close(state, Some(cleanup))
Pending(state) => {
let cleanup = state.val.on_unstarted_drop
state.val.producer = None
state.val.on_unstarted_drop = None
match cleanup {
Some(cleanup) => cleanup()
None => ()
}
}
Promised(cell) => promised_future_drop(cell, Some(cleanup))
}
}
///|
priv struct StreamProducerState[X] {
mut producer : (async (Sink[X]) -> Unit)?
mut cleanup : ((X) -> Unit)?
mut on_unstarted_drop : (() -> Unit)?
mut pipe : Ref[StreamPipe[X]]?
}
///|
priv struct StreamSource[X] {
read : async (Int) -> FixedArray[X]?
close : async () -> Unit
close_sync : () -> Unit
}
///|
priv enum StreamState[X] {
Source(StreamSource[X])
Local(Ref[StreamPipe[X]])
Outgoing(Ref[StreamProducerState[X]])
}
///|
pub struct Stream[X] {
priv inner : StreamState[X]
}
///|
fn[X] new_stream_pipe(
capacity : Int,
cleanup : ((X) -> Unit)?,
) -> Ref[StreamPipe[X]] {
if capacity < 0 {
abort("stream capacity must not be negative")
}
{
val: {
capacity,
chunks: Deque([]),
buffered: 0,
writer_closed: false,
reader_dropped: false,
cleanup,
head: None,
head_pos: 0,
readers: Deque([]),
writers: Deque([]),
},
}
}
///|
fn[X] stream_pipe_sink(pipe : Ref[StreamPipe[X]]) -> Sink[X] {
{
write: (data : ArrayView[X]) => stream_pipe_write(pipe, data),
close: () => stream_pipe_close_writer(pipe),
is_open: () => !pipe.val.writer_closed && !pipe.val.reader_dropped,
has_cleanup: () => pipe.val.cleanup is Some(_),
cleanup: Some(fn(value) {
match pipe.val.cleanup {
Some(cleanup) => cleanup(value)
None => ()
}
}),
write_window_size: default_sink_write_window_size,
}
}
///|
fn[X] new_local_stream(
capacity : Int,
cleanup : ((X) -> Unit)?,
) -> (Stream[X], Sink[X]) {
let pipe = new_stream_pipe(capacity, cleanup)
let stream = Stream::{ inner: Local(pipe) }
let sink = stream_pipe_sink(pipe)
(stream, sink)
}
///|
fn spawn_stream_producer(task : async () -> Unit) -> Unit {
let current = current_coroutine()
match current.spawner {
Some(spawner) => spawner(task)
None => ignore(spawn(task))
}
}
///|
fn[X] materialize_stream_producer(
state : Ref[StreamProducerState[X]],
) -> Ref[StreamPipe[X]] {
match state.val.pipe {
Some(pipe) => pipe
None => {
let pipe = new_stream_pipe(0, state.val.cleanup)
state.val.cleanup = None
state.val.pipe = Some(pipe)
match state.val.producer {
Some(producer) => {
state.val.producer = None
state.val.on_unstarted_drop = None
let sink = stream_pipe_sink(pipe)
spawn_stream_producer(async fn() {
defer stream_pipe_close_writer(pipe)
producer(sink) catch {
_ => ()
}
})
}
None => stream_pipe_close_writer(pipe)
}
pipe
}
}
}
///|
pub fn[X] Stream::new(capacity? : Int = 0) -> (Stream[X], Sink[X]) {
new_local_stream(capacity, None)
}
///|
/// Creates a local stream whose unread values are cleaned up when its readable
/// end is dropped.
pub fn[X] Stream::new_with_cleanup(
cleanup : (X) -> Unit,
capacity? : Int = 0,
) -> (Stream[X], Sink[X]) {
new_local_stream(capacity, Some(cleanup))
}
///|
/// Creates a lazy stream from an async producer.
///
/// `cleanup`, when present, releases buffered or pending values if the readable
/// end is dropped after the producer starts. Producers of explicitly managed
/// resources should provide it.
///
/// `on_unstarted_drop`, when present, releases resources captured by a producer
/// that is discarded before its first read or before a prepared component
/// transfer commits. Once the producer starts, it owns its runtime cleanup and
/// this callback is never invoked.
pub fn[X] Stream::produce(
producer : async (Sink[X]) -> Unit,
cleanup? : (X) -> Unit,
on_unstarted_drop? : () -> Unit,
) -> Stream[X] {
{
inner: Outgoing({
val: { producer: Some(producer), cleanup, on_unstarted_drop, pipe: None },
}),
}
}
///|
#internal(wit_bindgen, "generated binding code only")
pub fn[X] Stream::from_source(
read : async (Int) -> FixedArray[X]?,
close : async () -> Unit,
close_sync : () -> Unit,
) -> Stream[X] {
{ inner: Source({ read, close, close_sync }) }
}
///|
/// Reads at most `count` values from the stream.
///
/// `Some(values)` contains the next owned chunk and may be empty when the peer
/// reports no progress. `None` means the writable end has closed and no
/// buffered values remain. A non-positive count returns an empty chunk without
/// waiting.
pub async fn[X] Stream::read(self : Stream[X], count : Int) -> FixedArray[X]? {
match self.inner {
Source(source) => (source.read)(count)
Local(pipe) => stream_pipe_read(pipe, count)
Outgoing(state) =>
stream_pipe_read(materialize_stream_producer(state), count)
}
}
///|
/// Releases the readable end and discards unread values.
///
/// Registered cleanup callbacks run for locally buffered values. An unstarted
/// lazy producer is discarded and runs `on_unstarted_drop`, when provided.
pub async fn[X] Stream::drop(self : Stream[X]) -> Unit noraise {
match self.inner {
Source(source) => (source.close)() catch { _ => () }
Local(pipe) => stream_pipe_drop_reader(pipe)
Outgoing(state) =>
match state.val.pipe {
Some(pipe) => stream_pipe_drop_reader(pipe)
None => {
let cleanup = state.val.on_unstarted_drop
state.val.producer = None
state.val.cleanup = None
state.val.on_unstarted_drop = None
match cleanup {
Some(cleanup) => cleanup()
None => ()
}
}
}
}
}
///|
#internal(wit_bindgen, "generated binding code only")
pub fn[X] Stream::drop_sync(self : Stream[X]) -> Unit {
match self.inner {
Source(source) => (source.close_sync)()
Local(pipe) => stream_pipe_drop_reader(pipe)
Outgoing(state) =>
match state.val.pipe {
Some(pipe) => stream_pipe_drop_reader(pipe)
None => {
let cleanup = state.val.on_unstarted_drop
state.val.producer = None
state.val.cleanup = None
state.val.on_unstarted_drop = None
match cleanup {
Some(cleanup) => cleanup()
None => ()
}
}
}
}
}
///|
#internal(wit_bindgen, "generated binding code only")
pub fn[X] Stream::take_producer(self : Stream[X]) -> (async (Sink[X]) -> Unit)? {
match self.inner {
Outgoing(state) =>
match state.val.pipe {
Some(_) => None
None => {
let producer = state.val.producer
state.val.producer = None
state.val.cleanup = None
state.val.on_unstarted_drop = None
producer
}
}
Source(_) | Local(_) => None
}
}
///|
/// Rejects a stream that was prepared for a component-model transfer but was
/// never transferred. Component sources are closed immediately and buffered
/// local values are cleaned synchronously. An unstarted producer is discarded
/// without running it; its optional `on_unstarted_drop` callback owns cleanup of
/// captured resources.
#internal(wit_bindgen, "generated binding code only")
pub async fn[X] Stream::reject(
self : Stream[X],
cleanup : (X) -> Unit,
) -> Unit noraise {
match self.inner {
Source(source) => (source.close)() catch { _ => () }
Local(pipe) => stream_pipe_reject_reader(pipe, cleanup)
Outgoing(state) =>
match state.val.pipe {
Some(pipe) => stream_pipe_reject_reader(pipe, cleanup)
None => {
let cleanup = state.val.on_unstarted_drop
state.val.producer = None
state.val.cleanup = None
state.val.on_unstarted_drop = None
match cleanup {
Some(cleanup) => cleanup()
None => ()
}
}
}
}
}
+8
View File
@@ -0,0 +1,8 @@
import {
"moonbitlang/core/deque" @deque,
"moonbitlang/core/ref" @ref,
"moonbitlang/core/set" @set,
}
warnings = "-44"
supported_targets = "wasm"
+148
View File
@@ -0,0 +1,148 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/async-core"
import {
"moonbitlang/core/debug",
}
// Values
pub async fn check_cancellation() -> Unit noraise
pub async fn[X] handle_cancellation(async () -> X) -> X?
pub fn is_being_cancelled() -> Bool
pub async fn[X] protect_from_cancel(async () -> X) -> X nocancel
pub async fn[X] with_task_group(async (TaskGroup[X]) -> X) -> X
// Errors
pub(all) suberror EndpointBusy {
Read
Write
}
pub(all) suberror FutureReadError {
Cancelled
Dropped
}
pub suberror OpCancelled {
SubTaskCancelled(before_started~ : Bool)
StreamReadCancelled
}
#derive(@debug.Debug)
pub(all) suberror PromiseClosed
#deprecated
pub fn PromiseClosed::to_repr(Self) -> @debug.Repr
#derive(@debug.Debug)
pub suberror TaskCancelled
#deprecated
pub fn TaskCancelled::to_repr(Self) -> @debug.Repr
// Types and methods
pub struct CondVar {
// private fields
}
#alias(new, deprecated)
pub fn CondVar::CondVar() -> Self
pub fn CondVar::broadcast(Self) -> Unit
pub fn CondVar::signal(Self) -> Unit
pub async fn CondVar::wait(Self) -> Unit noraise
type Coroutine
pub struct Future[X] {
// private fields
}
pub async fn[X] Future::drop(Self[X]) -> Unit noraise
pub fn[X] Future::drop_sync(Self[X]) -> Unit
pub fn[X] Future::from(async () -> X, on_unstarted_drop? : () -> Unit) -> Self[X]
pub fn[X] Future::from_source(async () -> X, async () -> Unit, () -> Unit) -> Self[X]
pub async fn[X] Future::get(Self[X]) -> X
pub fn[X] Future::new() -> (Self[X], Promise[X])
pub fn[X] Future::new_with_cleanup((X) -> Unit) -> (Self[X], Promise[X])
pub fn[X] Future::ready(X) -> Self[X]
pub fn[X] Future::ready_with_cleanup(X, (X) -> Unit) -> Self[X]
pub async fn[X] Future::reject(Self[X], (X) -> Unit) -> Unit noraise
pub struct Mutex {
// private fields
}
pub fn Mutex::Mutex() -> Self
pub async fn Mutex::acquire(Self) -> Unit noraise
pub fn Mutex::release(Self) -> Unit
pub fn Mutex::try_acquire(Self) -> Bool
pub struct Promise[X] {
// private fields
}
pub fn[X] Promise::close(Self[X]) -> Bool
pub fn[X] Promise::complete(Self[X], X) -> Bool
pub fn[X] Promise::fail(Self[X], Error) -> Bool
pub struct Semaphore {
size : Int32
// private fields
}
#alias(new, deprecated)
pub fn Semaphore::Semaphore(Int32, initial_value? : Int32) -> Self
pub async fn Semaphore::acquire(Self) -> Unit noraise
pub fn Semaphore::release(Self) -> Unit
pub fn Semaphore::try_acquire(Self) -> Bool
pub struct Sink[X] {
// private fields
}
pub async fn[X] Sink::close(Self[X]) -> Unit
pub fn[X] Sink::from_callbacks(async (ArrayView[X]) -> Int32, async () -> Unit, () -> Bool, ((X) -> Unit)?, Int32) -> Self[X]
pub fn[X] Sink::is_open(Self[X]) -> Bool
pub async fn[X] Sink::write(Self[X], ArrayView[X]) -> Int32
pub async fn[X] Sink::write_all(Self[X], ArrayView[X]) -> Bool
pub async fn Sink::write_all_bytes(Self[Byte], BytesView) -> Bool
pub async fn Sink::write_bytes(Self[Byte], BytesView) -> Int32
pub struct Stream[X] {
// private fields
}
pub async fn[X] Stream::drop(Self[X]) -> Unit noraise
pub fn[X] Stream::drop_sync(Self[X]) -> Unit
pub fn[X] Stream::from_source(async (Int32) -> FixedArray[X]?, async () -> Unit, () -> Unit) -> Self[X]
pub fn[X] Stream::new(capacity? : Int32) -> (Self[X], Sink[X])
pub fn[X] Stream::new_with_cleanup((X) -> Unit, capacity? : Int32) -> (Self[X], Sink[X])
pub fn[X] Stream::produce(async (Sink[X]) -> Unit, cleanup? : (X) -> Unit, on_unstarted_drop? : () -> Unit) -> Self[X]
pub async fn[X] Stream::read(Self[X], Int32) -> FixedArray[X]?
pub async fn[X] Stream::reject(Self[X], (X) -> Unit) -> Unit noraise
pub fn[X] Stream::take_producer(Self[X]) -> (async (Sink[X]) -> Unit)?
pub struct Task[X] {
// private fields
}
pub fn[X] Task::cancel(Self[X]) -> Unit
pub fn[X] Task::try_wait(Self[X]) -> X? raise
pub async fn[X] Task::wait(Self[X]) -> X
pub struct TaskGroup[X] {
// private fields
}
pub fn[X] TaskGroup::add_defer(Self[X], async () -> Unit nocancel) -> Unit
pub async fn[X] TaskGroup::return_immediately(Self[X], X) -> Unit noraise
pub fn[G, X] TaskGroup::spawn(Self[G], async () -> X, no_wait? : Bool, allow_failure? : Bool) -> Task[X]
pub fn[X] TaskGroup::spawn_bg(Self[X], async () -> Unit, no_wait? : Bool, allow_failure? : Bool) -> Unit
#derive(Eq, Hash)
type WaitableSet
#deprecated
pub fn WaitableSet::equal(Self, Self) -> Bool
#deprecated
pub fn WaitableSet::hash(Self) -> Int32
#deprecated
pub fn WaitableSet::hash_combine(Self, Hasher) -> Unit
#deprecated
pub fn WaitableSet::not_equal(Self, Self) -> Bool
// Type aliases
// Traits
+1
View File
@@ -0,0 +1 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
+100
View File
@@ -0,0 +1,100 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
pub fn mbt_ffi_cabi_realloc(
src_offset : Int,
src_size : Int,
_dst_alignment : Int,
dst_size : Int,
) -> Int {
// malloc
if src_offset == 0 && src_size == 0 {
return mbt_ffi_malloc(dst_size)
}
// free
if dst_size == 0 {
mbt_ffi_free(src_offset)
return 0
}
// realloc
let dst = mbt_ffi_malloc(dst_size)
mbt_ffi_copy(dst, src_offset, if src_size < dst_size { src_size } else { dst_size })
mbt_ffi_free(src_offset)
dst
}
///|
extern "wasm" fn mbt_ffi_copy(dest : Int, src : Int, len : Int) =
#|(func (param i32) (param i32) (param i32) local.get 0 local.get 1 local.get 2 memory.copy)
///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#|(func (param i32) (result i32) (local i32)
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
#| local.tee 1 i32.const 0 call $moonbit.init_array8
#| local.get 1)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///|
#doc(hidden)
pub fn wasmExportPopup() -> Int {
@plasmoid.wasmExportPopup()
}
///|
#doc(hidden)
pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
@plasmoid.wasmExportOnEvent(p0, p1, p2, p3)
}
///|
#doc(hidden)
pub fn wasmExportConfigItems() -> Int {
@module-config.wasmExportConfigItems()
}
///|
#doc(hidden)
pub fn wasmExportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
@module-config.wasmExportSetConfig(p0, p1, p2, p3)
}
///|
#doc(hidden)
pub fn wasmExportInfo() -> Int {
@plasmoid.wasmExportInfo()
}
///|
#doc(hidden)
pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportRenderPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportInfoPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportConfigItemsPostReturn(p0 : Int) -> Unit {
@module-config.wasmExportConfigItemsPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int {
@plasmoid.wasmExportRender(p0, p1)
}
///|
#doc(hidden)
pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportPopupPostReturn(p0)
}
@@ -0,0 +1,5 @@
Optional: a module's own settings. A module that exports this gets a "Module settings" entry in
its right-click menu, listing the items below; the shell draws the menu (the same for every
module), remembers each choice per module in state.edn (`:module-config`), and hands the saved
values back through `set-config` right after the module is loaded. A module without it simply
has no settings: the export is looked up by name, so older modules keep loading.
@@ -0,0 +1,114 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
#doc(hidden)
pub fn wasmExportConfigItems() -> Int {
let (result) : (Array[ConfigItem]) = config_items();
let return_area = mbt_ffi_malloc(8)
let address3 = mbt_ffi_malloc((result).length() * 32);
for index4 = 0; index4 < (result).length(); index4 = index4 + 1 {
let iter_elem : ConfigItem = (result)[(index4)]
let iter_base = address3 + (index4 * 32);
let ptr = mbt_ffi_str2ptr((iter_elem).key)
mbt_ffi_store32((iter_base) + 4, (iter_elem).key.length())
mbt_ffi_store32((iter_base) + 0, ptr)
let ptr0 = mbt_ffi_str2ptr((iter_elem).label)
mbt_ffi_store32((iter_base) + 12, (iter_elem).label.length())
mbt_ffi_store32((iter_base) + 8, ptr0)
let address = mbt_ffi_malloc(((iter_elem).choices).length() * 8);
for index = 0; index < ((iter_elem).choices).length(); index = index + 1 {
let iter_elem : String = ((iter_elem).choices)[(index)]
let iter_base = address + (index * 8);
let ptr1 = mbt_ffi_str2ptr(iter_elem)
mbt_ffi_store32((iter_base) + 4, iter_elem.length())
mbt_ffi_store32((iter_base) + 0, ptr1)
}
mbt_ffi_store32((iter_base) + 20, ((iter_elem).choices).length())
mbt_ffi_store32((iter_base) + 16, address)
let ptr2 = mbt_ffi_str2ptr((iter_elem).value)
mbt_ffi_store32((iter_base) + 28, (iter_elem).value.length())
mbt_ffi_store32((iter_base) + 24, ptr2)
}
mbt_ffi_store32((return_area) + 4, (result).length())
mbt_ffi_store32((return_area) + 0, address3)
let ret = return_area
return ret
}
///|
#doc(hidden)
pub fn wasmExportConfigItemsPostReturn(p0 : Int) -> Unit {
for index0 = 0; index0 < (mbt_ffi_load32((p0) + 4)); index0 = index0 + 1 {
let iter_base = (mbt_ffi_load32((p0) + 0)) + (index0 * 32)
mbt_ffi_free(mbt_ffi_load32((iter_base) + 0))
mbt_ffi_free(mbt_ffi_load32((iter_base) + 8))
for index = 0; index < (mbt_ffi_load32((iter_base) + 20)); index = index + 1 {
let iter_base = (mbt_ffi_load32((iter_base) + 16)) + (index * 8)
mbt_ffi_free(mbt_ffi_load32((iter_base) + 0))
}
mbt_ffi_free(mbt_ffi_load32((iter_base) + 16))
mbt_ffi_free(mbt_ffi_load32((iter_base) + 24))
}
mbt_ffi_free(mbt_ffi_load32((p0) + 0))
}
///|
#doc(hidden)
pub fn wasmExportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
let result = mbt_ffi_ptr2str(p0, p1)
let result0 = mbt_ffi_ptr2str(p2, p3)
let (result1) : (Bool) = set_config(result, result0);
let ret = (if result1 { 1 } else { 0 })
return ret
}
///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#|(func (param i32) (result i32) (local i32)
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
#| local.tee 1 i32.const 0 call $moonbit.init_array8
#| local.get 1)
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) local.get 0)
///|
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
///|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
@@ -0,0 +1,5 @@
import {
"chandra/desktop/lib/battery" @logic,
}
warnings = "-44"
@@ -0,0 +1,21 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/battery/gen/interface/chandra/desktop/module-config"
// Values
pub fn config_items() -> Array[ConfigItem]
pub fn set_config(String, String) -> Bool
// Errors
// Types and methods
pub(all) struct ConfigItem {
key : String
label : String
choices : Array[String]
value : String
}
// Type aliases
// Traits
@@ -0,0 +1,12 @@
///| The battery module's right-click settings (percentage, time remaining, what shows without a
/// battery); the logic is in lib/battery.
///|
pub fn config_items() -> Array[ConfigItem] {
@logic.config.items().map(e => { key: e.key, label: e.label, choices: e.choices, value: e.value })
}
///|
pub fn set_config(key : String, value : String) -> Bool {
@logic.config.set(key, value)
}
@@ -0,0 +1,11 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
pub(all) struct ConfigItem {
key : String; label : String; choices : Array[String]; value : String
}
///|
declare pub fn config_items() -> Array[ConfigItem]
///|
/// Set `key` to `value` (unknown keys and values are ignored). True when the widget should redraw.
declare pub fn set_config(key : String, value : String) -> Bool
@@ -130,6 +130,16 @@ pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int {
PopClip => { PopClip => {
mbt_ffi_store8((iter_base) + 0, (6)) mbt_ffi_store8((iter_base) + 0, (6))
()
}
Image(payload6) => {
mbt_ffi_store8((iter_base) + 0, (7))
mbt_ffi_store32((iter_base) + 4, ((payload6).rect).x)
mbt_ffi_store32((iter_base) + 8, ((payload6).rect).y)
mbt_ffi_store32((iter_base) + 12, (((payload6).rect).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, (((payload6).rect).h).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 20, ((payload6).image).reinterpret_as_int())
() ()
} }
} }
@@ -160,6 +170,7 @@ pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
} }
5 => () 5 => ()
6 => () 6 => ()
7 => ()
_ => panic() _ => panic()
} }
@@ -278,6 +289,16 @@ pub fn wasmExportPopup() -> Int {
PopClip => { PopClip => {
mbt_ffi_store8((iter_base) + 0, (6)) mbt_ffi_store8((iter_base) + 0, (6))
()
}
Image(payload8) => {
mbt_ffi_store8((iter_base) + 0, (7))
mbt_ffi_store32((iter_base) + 4, ((payload8).rect).x)
mbt_ffi_store32((iter_base) + 8, ((payload8).rect).y)
mbt_ffi_store32((iter_base) + 12, (((payload8).rect).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, (((payload8).rect).h).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 20, ((payload8).image).reinterpret_as_int())
() ()
} }
} }
@@ -316,6 +337,7 @@ pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
} }
5 => () 5 => ()
6 => () 6 => ()
7 => ()
_ => panic() _ => panic()
} }
@@ -369,16 +391,28 @@ pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
} }
///| ///|
extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) (result i32) local.get 0 i32.load8_u) #|(func (param i32) local.get 0 call $moonbit.decref)
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) local.get 0)
///| ///|
extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) = extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8) #|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8)
///| ///|
extern "wasm" fn mbt_ffi_free(position : Int) = extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) local.get 0 call $moonbit.decref) #|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
///|
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
///| ///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
@@ -388,22 +422,10 @@ extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#| local.get 1) #| local.get 1)
///| ///|
#owned(str) extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int =
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = #|(func (param i32) (result i32) local.get 0 i32.load8_u)
#|(func (param i32) (result i32) local.get 0)
///|
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
///| ///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load) #|(func (param i32) (result i32) local.get 0 i32.load)
///|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
@@ -0,0 +1,8 @@
import {
"chandra/desktop/interface/chandra/desktop/types" @types,
"chandra/desktop/interface/chandra/desktop/theme" @theme,
"chandra/desktop/interface/chandra/desktop/battery" @battery,
"chandra/desktop/lib/battery" @logic,
}
warnings = "-44"
@@ -1,8 +1,8 @@
// Generated using `moon info`, DON'T EDIT IT // Generated using `moon info`, DON'T EDIT IT
package "moonplasma/desktop/components/launcher/gen/interface/moonplasma/desktop/plasmoid" package "chandra/desktop/components/battery/gen/interface/chandra/desktop/plasmoid"
import { import {
"moonplasma/desktop/interface/moonplasma/desktop/types", "chandra/desktop/interface/chandra/desktop/types",
} }
// Values // Values
@@ -0,0 +1,82 @@
///| Implementation of `chandra:desktop/plasmoid` for the battery module: charge as an icon and
/// percentage, charging state and time remaining, turning amber when low and red when critical.
/// A click opens the details; a critical battery opens them by itself once per discharge spell.
/// All drawing is in lib/battery; this file only adapts the `battery` capability.
///|
let open_ : Ref[Bool] = { val: false }
///| The open popup is the low-battery warning (not a click).
let warning : Ref[Bool] = { val: false }
///|
let low : @logic.LowWarning = @logic.LowWarning::new()
///| The host's reading, sampled about once a second.
fn reading() -> @logic.Reading {
let s = @battery.read()
{ percent: s.percent, state: s.state.ordinal(), secs_left: s.secs_left.reinterpret_as_int() }
}
///|
pub fn info() -> PlasmoidInfo {
let (id, name, w, h, min_w) = @logic.info()
{
id,
name,
preferred: { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() },
min_width: min_w.reinterpret_as_uint(),
stretch: false,
}
}
///|
pub fn render(size : @types.Size) -> Array[@types.DrawOp] {
let r = reading()
if low.update(r) {
open_.val = true
warning.val = true
}
@logic.render(size, @theme.get_tokens(), r, @logic.config, open=open_.val && !warning.val)
}
///|
pub fn popup() -> PopupSurface? {
if !open_.val {
return None
}
let (w, h, ops) = @logic.render_popup(@theme.get_tokens(), reading(), warning=warning.val)
Some({ size: { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() }, ops })
}
///|
fn close() -> Unit {
open_.val = false
warning.val = false
}
///|
pub fn on_event(target : Surface, event : @types.InputEvent) -> Bool {
match (target, event) {
(WIDGET, PointerDown(_)) => {
if open_.val {
close()
} else {
open_.val = true
}
true
}
(POPUP, PointerDown(_)) => {
close()
true
}
(_, FocusLost) | (_, KeyDown("Escape")) =>
if open_.val {
close()
true
} else {
false
}
_ => false
}
}
+30
View File
@@ -0,0 +1,30 @@
import {
"chandra/desktop/components/battery/gen/interface/chandra/desktop/module-config" @module-config,
"chandra/desktop/components/battery/gen/interface/chandra/desktop/plasmoid" @plasmoid,
}
warnings = "-44"
pkgtype(kind: "foreign_library")
options(
link: {
"wasm": {
"export-memory-name": "memory",
"heap-start-address": 16,
"exports": [
"mbt_ffi_cabi_realloc:cabi_realloc",
"wasmExportConfigItems:chandra:desktop/module-config@0.1.0#config-items",
"wasmExportConfigItemsPostReturn:cabi_post_chandra:desktop/module-config@0.1.0#config-items",
"wasmExportInfo:chandra:desktop/plasmoid@0.1.0#info",
"wasmExportInfoPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#info",
"wasmExportOnEvent:chandra:desktop/plasmoid@0.1.0#on-event",
"wasmExportPopup:chandra:desktop/plasmoid@0.1.0#popup",
"wasmExportPopupPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#popup",
"wasmExportRender:chandra:desktop/plasmoid@0.1.0#render",
"wasmExportRenderPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#render",
"wasmExportSetConfig:chandra:desktop/module-config@0.1.0#set-config"
],
},
},
)
+13
View File
@@ -0,0 +1,13 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/battery/gen"
// Values
pub fn mbt_ffi_cabi_realloc(Int32, Int32, Int32, Int32) -> Int32
// Errors
// Types and methods
// Type aliases
// Traits
+32 -14
View File
@@ -50,24 +50,30 @@ pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int {
@plasmoid.wasmExportRender(p0, p1) @plasmoid.wasmExportRender(p0, p1)
} }
///|
#doc(hidden)
pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportInfoPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportRenderPostReturn(p0)
}
///| ///|
#doc(hidden) #doc(hidden)
pub fn wasmExportPopup() -> Int { pub fn wasmExportPopup() -> Int {
@plasmoid.wasmExportPopup() @plasmoid.wasmExportPopup()
} }
///|
#doc(hidden)
pub fn wasmExportConfigItems() -> Int {
@module-config.wasmExportConfigItems()
}
///|
#doc(hidden)
pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
@plasmoid.wasmExportOnEvent(p0, p1, p2, p3)
}
///|
#doc(hidden)
pub fn wasmExportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
@module-config.wasmExportSetConfig(p0, p1, p2, p3)
}
///| ///|
#doc(hidden) #doc(hidden)
pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit { pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
@@ -76,7 +82,19 @@ pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
///| ///|
#doc(hidden) #doc(hidden)
pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportOnEvent(p0, p1, p2, p3) @plasmoid.wasmExportInfoPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportConfigItemsPostReturn(p0 : Int) -> Unit {
@module-config.wasmExportConfigItemsPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportRenderPostReturn(p0)
} }
@@ -0,0 +1,5 @@
Optional: a module's own settings. A module that exports this gets a "Module settings" entry in
its right-click menu, listing the items below; the shell draws the menu (the same for every
module), remembers each choice per module in state.edn (`:module-config`), and hands the saved
values back through `set-config` right after the module is loaded. A module without it simply
has no settings: the export is looked up by name, so older modules keep loading.
@@ -0,0 +1,114 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
#doc(hidden)
pub fn wasmExportConfigItems() -> Int {
let (result) : (Array[ConfigItem]) = config_items();
let return_area = mbt_ffi_malloc(8)
let address3 = mbt_ffi_malloc((result).length() * 32);
for index4 = 0; index4 < (result).length(); index4 = index4 + 1 {
let iter_elem : ConfigItem = (result)[(index4)]
let iter_base = address3 + (index4 * 32);
let ptr = mbt_ffi_str2ptr((iter_elem).key)
mbt_ffi_store32((iter_base) + 4, (iter_elem).key.length())
mbt_ffi_store32((iter_base) + 0, ptr)
let ptr0 = mbt_ffi_str2ptr((iter_elem).label)
mbt_ffi_store32((iter_base) + 12, (iter_elem).label.length())
mbt_ffi_store32((iter_base) + 8, ptr0)
let address = mbt_ffi_malloc(((iter_elem).choices).length() * 8);
for index = 0; index < ((iter_elem).choices).length(); index = index + 1 {
let iter_elem : String = ((iter_elem).choices)[(index)]
let iter_base = address + (index * 8);
let ptr1 = mbt_ffi_str2ptr(iter_elem)
mbt_ffi_store32((iter_base) + 4, iter_elem.length())
mbt_ffi_store32((iter_base) + 0, ptr1)
}
mbt_ffi_store32((iter_base) + 20, ((iter_elem).choices).length())
mbt_ffi_store32((iter_base) + 16, address)
let ptr2 = mbt_ffi_str2ptr((iter_elem).value)
mbt_ffi_store32((iter_base) + 28, (iter_elem).value.length())
mbt_ffi_store32((iter_base) + 24, ptr2)
}
mbt_ffi_store32((return_area) + 4, (result).length())
mbt_ffi_store32((return_area) + 0, address3)
let ret = return_area
return ret
}
///|
#doc(hidden)
pub fn wasmExportConfigItemsPostReturn(p0 : Int) -> Unit {
for index0 = 0; index0 < (mbt_ffi_load32((p0) + 4)); index0 = index0 + 1 {
let iter_base = (mbt_ffi_load32((p0) + 0)) + (index0 * 32)
mbt_ffi_free(mbt_ffi_load32((iter_base) + 0))
mbt_ffi_free(mbt_ffi_load32((iter_base) + 8))
for index = 0; index < (mbt_ffi_load32((iter_base) + 20)); index = index + 1 {
let iter_base = (mbt_ffi_load32((iter_base) + 16)) + (index * 8)
mbt_ffi_free(mbt_ffi_load32((iter_base) + 0))
}
mbt_ffi_free(mbt_ffi_load32((iter_base) + 16))
mbt_ffi_free(mbt_ffi_load32((iter_base) + 24))
}
mbt_ffi_free(mbt_ffi_load32((p0) + 0))
}
///|
#doc(hidden)
pub fn wasmExportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
let result = mbt_ffi_ptr2str(p0, p1)
let result0 = mbt_ffi_ptr2str(p2, p3)
let (result1) : (Bool) = set_config(result, result0);
let ret = (if result1 { 1 } else { 0 })
return ret
}
///|
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) local.get 0)
///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#|(func (param i32) (result i32) (local i32)
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
#| local.tee 1 i32.const 0 call $moonbit.init_array8
#| local.get 1)
///|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
@@ -0,0 +1,5 @@
import {
"chandra/desktop/lib/clock" @logic,
}
warnings = "-44"
@@ -0,0 +1,21 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/clock-binary/gen/interface/chandra/desktop/module-config"
// Values
pub fn config_items() -> Array[ConfigItem]
pub fn set_config(String, String) -> Bool
// Errors
// Types and methods
pub(all) struct ConfigItem {
key : String
label : String
choices : Array[String]
value : String
}
// Type aliases
// Traits
@@ -0,0 +1,16 @@
///| The binary clock's right-click settings (seconds columns); the logic is in lib/clock.
///|
pub fn config_items() -> Array[ConfigItem] {
@logic.binary_config.binary_items().map(e => {
key: e.key,
label: e.label,
choices: e.choices,
value: e.value,
})
}
///|
pub fn set_config(key : String, value : String) -> Bool {
@logic.binary_config.set(key, value)
}
@@ -0,0 +1,11 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
pub(all) struct ConfigItem {
key : String; label : String; choices : Array[String]; value : String
}
///|
declare pub fn config_items() -> Array[ConfigItem]
///|
/// Set `key` to `value` (unknown keys and values are ignored). True when the widget should redraw.
declare pub fn set_config(key : String, value : String) -> Bool
@@ -130,6 +130,16 @@ pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int {
PopClip => { PopClip => {
mbt_ffi_store8((iter_base) + 0, (6)) mbt_ffi_store8((iter_base) + 0, (6))
()
}
Image(payload6) => {
mbt_ffi_store8((iter_base) + 0, (7))
mbt_ffi_store32((iter_base) + 4, ((payload6).rect).x)
mbt_ffi_store32((iter_base) + 8, ((payload6).rect).y)
mbt_ffi_store32((iter_base) + 12, (((payload6).rect).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, (((payload6).rect).h).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 20, ((payload6).image).reinterpret_as_int())
() ()
} }
} }
@@ -160,6 +170,7 @@ pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
} }
5 => () 5 => ()
6 => () 6 => ()
7 => ()
_ => panic() _ => panic()
} }
@@ -278,6 +289,16 @@ pub fn wasmExportPopup() -> Int {
PopClip => { PopClip => {
mbt_ffi_store8((iter_base) + 0, (6)) mbt_ffi_store8((iter_base) + 0, (6))
()
}
Image(payload8) => {
mbt_ffi_store8((iter_base) + 0, (7))
mbt_ffi_store32((iter_base) + 4, ((payload8).rect).x)
mbt_ffi_store32((iter_base) + 8, ((payload8).rect).y)
mbt_ffi_store32((iter_base) + 12, (((payload8).rect).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, (((payload8).rect).h).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 20, ((payload8).image).reinterpret_as_int())
() ()
} }
} }
@@ -316,6 +337,7 @@ pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
} }
5 => () 5 => ()
6 => () 6 => ()
7 => ()
_ => panic() _ => panic()
} }
@@ -368,10 +390,25 @@ pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
} }
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///| ///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load) #|(func (param i32) (result i32) local.get 0 i32.load)
///|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
///|
extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8)
///| ///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#|(func (param i32) (result i32) (local i32) #|(func (param i32) (result i32) (local i32)
@@ -379,31 +416,16 @@ extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#| local.tee 1 i32.const 0 call $moonbit.init_array8 #| local.tee 1 i32.const 0 call $moonbit.init_array8
#| local.get 1) #| local.get 1)
///|
extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load8_u)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///|
extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8)
///|
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
///| ///|
#owned(str) #owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) local.get 0) #|(func (param i32) (result i32) local.get 0)
///| ///|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int =
#|(func (param i32) (param i32) (result i32) #|(func (param i32) (result i32) local.get 0 i32.load8_u)
#| local.get 0
#| local.get 1 call $moonbit.init_array16 ///|
#| local.get 0) extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
@@ -0,0 +1,8 @@
import {
"chandra/desktop/interface/chandra/desktop/types" @types,
"chandra/desktop/interface/chandra/desktop/theme" @theme,
"chandra/desktop/interface/chandra/desktop/clock" @clock,
"chandra/desktop/lib/clock" @logic,
}
warnings = "-44"
@@ -1,8 +1,8 @@
// Generated using `moon info`, DON'T EDIT IT // Generated using `moon info`, DON'T EDIT IT
package "moonplasma/desktop/components/clock-binary/gen/interface/moonplasma/desktop/plasmoid" package "chandra/desktop/components/clock-binary/gen/interface/chandra/desktop/plasmoid"
import { import {
"moonplasma/desktop/interface/moonplasma/desktop/types", "chandra/desktop/interface/chandra/desktop/types",
} }
// Values // Values
@@ -0,0 +1,35 @@
///| Implementation of `chandra:desktop/plasmoid` for the binary clock.
/// All logic lives in lib/clock; this file only adapts host capabilities.
///|
pub fn info() -> PlasmoidInfo {
let (id, name, w, h, min_w) = @logic.binary_info()
{
id,
name,
preferred: { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() },
min_width: min_w.reinterpret_as_uint(),
stretch: false,
}
}
///|
pub fn render(size : @types.Size) -> Array[@types.DrawOp] {
@logic.render_binary(size, @theme.get_tokens(), @clock.now(), seconds=@logic.binary_config.seconds)
}
///| The calendar flyout (left click opens it; the shell slides it out of the panel).
pub fn popup() -> PopupSurface? {
let cal = @logic.binary_config.cal
if !cal.open {
return None
}
let (w, h) = cal.size()
let ops = cal.render(@theme.get_tokens(), @clock.now())
Some({ size: { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() }, ops })
}
///|
pub fn on_event(target : Surface, event : @types.InputEvent) -> Bool {
@logic.binary_config.cal.handle(target is POPUP, event, @clock.now())
}
@@ -1,8 +0,0 @@
import {
"moonplasma/desktop/interface/moonplasma/desktop/types" @types,
"moonplasma/desktop/interface/moonplasma/desktop/theme" @theme,
"moonplasma/desktop/interface/moonplasma/desktop/clock" @clock,
"moonplasma/desktop/lib/clock" @logic,
}
warnings = "-44"
@@ -1,29 +0,0 @@
///| Implementation of `moonplasma:desktop/plasmoid` for the binary clock.
/// All logic lives in lib/clock; this file only adapts host capabilities.
///|
pub fn info() -> PlasmoidInfo {
let (id, name, w, h, min_w) = @logic.binary_info()
{
id,
name,
preferred: { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() },
min_width: min_w.reinterpret_as_uint(),
stretch: false,
}
}
///|
pub fn render(size : @types.Size) -> Array[@types.DrawOp] {
@logic.render_binary(size, @theme.get_tokens(), @clock.now())
}
///|
pub fn popup() -> PopupSurface? {
None
}
///|
pub fn on_event(_target : Surface, _event : @types.InputEvent) -> Bool {
false
}
+12 -8
View File
@@ -1,5 +1,6 @@
import { import {
"moonplasma/desktop/components/clock-binary/gen/interface/moonplasma/desktop/plasmoid" @plasmoid, "chandra/desktop/components/clock-binary/gen/interface/chandra/desktop/module-config" @module-config,
"chandra/desktop/components/clock-binary/gen/interface/chandra/desktop/plasmoid" @plasmoid,
} }
warnings = "-44" warnings = "-44"
@@ -13,13 +14,16 @@ options(
"heap-start-address": 16, "heap-start-address": 16,
"exports": [ "exports": [
"mbt_ffi_cabi_realloc:cabi_realloc", "mbt_ffi_cabi_realloc:cabi_realloc",
"wasmExportInfo:moonplasma:desktop/plasmoid@0.1.0#info", "wasmExportConfigItems:chandra:desktop/module-config@0.1.0#config-items",
"wasmExportInfoPostReturn:cabi_post_moonplasma:desktop/plasmoid@0.1.0#info", "wasmExportConfigItemsPostReturn:cabi_post_chandra:desktop/module-config@0.1.0#config-items",
"wasmExportOnEvent:moonplasma:desktop/plasmoid@0.1.0#on-event", "wasmExportInfo:chandra:desktop/plasmoid@0.1.0#info",
"wasmExportPopup:moonplasma:desktop/plasmoid@0.1.0#popup", "wasmExportInfoPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#info",
"wasmExportPopupPostReturn:cabi_post_moonplasma:desktop/plasmoid@0.1.0#popup", "wasmExportOnEvent:chandra:desktop/plasmoid@0.1.0#on-event",
"wasmExportRender:moonplasma:desktop/plasmoid@0.1.0#render", "wasmExportPopup:chandra:desktop/plasmoid@0.1.0#popup",
"wasmExportRenderPostReturn:cabi_post_moonplasma:desktop/plasmoid@0.1.0#render" "wasmExportPopupPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#popup",
"wasmExportRender:chandra:desktop/plasmoid@0.1.0#render",
"wasmExportRenderPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#render",
"wasmExportSetConfig:chandra:desktop/module-config@0.1.0#set-config"
], ],
}, },
}, },
@@ -1,5 +1,5 @@
// Generated using `moon info`, DON'T EDIT IT // Generated using `moon info`, DON'T EDIT IT
package "moonplasma/desktop/components/clock-binary/gen" package "chandra/desktop/components/clock-binary/gen"
// Values // Values
pub fn mbt_ffi_cabi_realloc(Int32, Int32, Int32, Int32) -> Int32 pub fn mbt_ffi_cabi_realloc(Int32, Int32, Int32, Int32) -> Int32
+28 -10
View File
@@ -44,6 +44,18 @@ pub fn wasmExportInfo() -> Int {
@plasmoid.wasmExportInfo() @plasmoid.wasmExportInfo()
} }
///|
#doc(hidden)
pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
@plasmoid.wasmExportOnEvent(p0, p1, p2, p3)
}
///|
#doc(hidden)
pub fn wasmExportConfigItems() -> Int {
@module-config.wasmExportConfigItems()
}
///| ///|
#doc(hidden) #doc(hidden)
pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit { pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
@@ -52,14 +64,8 @@ pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
///| ///|
#doc(hidden) #doc(hidden)
pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit { pub fn wasmExportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
@plasmoid.wasmExportInfoPostReturn(p0) @module-config.wasmExportSetConfig(p0, p1, p2, p3)
}
///|
#doc(hidden)
pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportPopupPostReturn(p0)
} }
///| ///|
@@ -68,6 +74,12 @@ pub fn wasmExportPopup() -> Int {
@plasmoid.wasmExportPopup() @plasmoid.wasmExportPopup()
} }
///|
#doc(hidden)
pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportInfoPostReturn(p0)
}
///| ///|
#doc(hidden) #doc(hidden)
pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int { pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int {
@@ -76,7 +88,13 @@ pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int {
///| ///|
#doc(hidden) #doc(hidden)
pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportOnEvent(p0, p1, p2, p3) @plasmoid.wasmExportPopupPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportConfigItemsPostReturn(p0 : Int) -> Unit {
@module-config.wasmExportConfigItemsPostReturn(p0)
} }
@@ -0,0 +1,5 @@
Optional: a module's own settings. A module that exports this gets a "Module settings" entry in
its right-click menu, listing the items below; the shell draws the menu (the same for every
module), remembers each choice per module in state.edn (`:module-config`), and hands the saved
values back through `set-config` right after the module is loaded. A module without it simply
has no settings: the export is looked up by name, so older modules keep loading.
@@ -0,0 +1,114 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
#doc(hidden)
pub fn wasmExportConfigItems() -> Int {
let (result) : (Array[ConfigItem]) = config_items();
let return_area = mbt_ffi_malloc(8)
let address3 = mbt_ffi_malloc((result).length() * 32);
for index4 = 0; index4 < (result).length(); index4 = index4 + 1 {
let iter_elem : ConfigItem = (result)[(index4)]
let iter_base = address3 + (index4 * 32);
let ptr = mbt_ffi_str2ptr((iter_elem).key)
mbt_ffi_store32((iter_base) + 4, (iter_elem).key.length())
mbt_ffi_store32((iter_base) + 0, ptr)
let ptr0 = mbt_ffi_str2ptr((iter_elem).label)
mbt_ffi_store32((iter_base) + 12, (iter_elem).label.length())
mbt_ffi_store32((iter_base) + 8, ptr0)
let address = mbt_ffi_malloc(((iter_elem).choices).length() * 8);
for index = 0; index < ((iter_elem).choices).length(); index = index + 1 {
let iter_elem : String = ((iter_elem).choices)[(index)]
let iter_base = address + (index * 8);
let ptr1 = mbt_ffi_str2ptr(iter_elem)
mbt_ffi_store32((iter_base) + 4, iter_elem.length())
mbt_ffi_store32((iter_base) + 0, ptr1)
}
mbt_ffi_store32((iter_base) + 20, ((iter_elem).choices).length())
mbt_ffi_store32((iter_base) + 16, address)
let ptr2 = mbt_ffi_str2ptr((iter_elem).value)
mbt_ffi_store32((iter_base) + 28, (iter_elem).value.length())
mbt_ffi_store32((iter_base) + 24, ptr2)
}
mbt_ffi_store32((return_area) + 4, (result).length())
mbt_ffi_store32((return_area) + 0, address3)
let ret = return_area
return ret
}
///|
#doc(hidden)
pub fn wasmExportConfigItemsPostReturn(p0 : Int) -> Unit {
for index0 = 0; index0 < (mbt_ffi_load32((p0) + 4)); index0 = index0 + 1 {
let iter_base = (mbt_ffi_load32((p0) + 0)) + (index0 * 32)
mbt_ffi_free(mbt_ffi_load32((iter_base) + 0))
mbt_ffi_free(mbt_ffi_load32((iter_base) + 8))
for index = 0; index < (mbt_ffi_load32((iter_base) + 20)); index = index + 1 {
let iter_base = (mbt_ffi_load32((iter_base) + 16)) + (index * 8)
mbt_ffi_free(mbt_ffi_load32((iter_base) + 0))
}
mbt_ffi_free(mbt_ffi_load32((iter_base) + 16))
mbt_ffi_free(mbt_ffi_load32((iter_base) + 24))
}
mbt_ffi_free(mbt_ffi_load32((p0) + 0))
}
///|
#doc(hidden)
pub fn wasmExportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
let result = mbt_ffi_ptr2str(p0, p1)
let result0 = mbt_ffi_ptr2str(p2, p3)
let (result1) : (Bool) = set_config(result, result0);
let ret = (if result1 { 1 } else { 0 })
return ret
}
///|
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#|(func (param i32) (result i32) (local i32)
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
#| local.tee 1 i32.const 0 call $moonbit.init_array8
#| local.get 1)
///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) local.get 0)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
@@ -0,0 +1,5 @@
import {
"chandra/desktop/lib/clock" @logic,
}
warnings = "-44"
@@ -0,0 +1,21 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/clock-digital/gen/interface/chandra/desktop/module-config"
// Values
pub fn config_items() -> Array[ConfigItem]
pub fn set_config(String, String) -> Bool
// Errors
// Types and methods
pub(all) struct ConfigItem {
key : String
label : String
choices : Array[String]
value : String
}
// Type aliases
// Traits
@@ -0,0 +1,16 @@
///| The digital clock's right-click settings (time format, AM/PM, date line); the logic is in lib/clock.
///|
pub fn config_items() -> Array[ConfigItem] {
@logic.digital_config.digital_items().map(e => {
key: e.key,
label: e.label,
choices: e.choices,
value: e.value,
})
}
///|
pub fn set_config(key : String, value : String) -> Bool {
@logic.digital_config.set(key, value)
}
@@ -0,0 +1,11 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
pub(all) struct ConfigItem {
key : String; label : String; choices : Array[String]; value : String
}
///|
declare pub fn config_items() -> Array[ConfigItem]
///|
/// Set `key` to `value` (unknown keys and values are ignored). True when the widget should redraw.
declare pub fn set_config(key : String, value : String) -> Bool
@@ -130,6 +130,16 @@ pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int {
PopClip => { PopClip => {
mbt_ffi_store8((iter_base) + 0, (6)) mbt_ffi_store8((iter_base) + 0, (6))
()
}
Image(payload6) => {
mbt_ffi_store8((iter_base) + 0, (7))
mbt_ffi_store32((iter_base) + 4, ((payload6).rect).x)
mbt_ffi_store32((iter_base) + 8, ((payload6).rect).y)
mbt_ffi_store32((iter_base) + 12, (((payload6).rect).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, (((payload6).rect).h).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 20, ((payload6).image).reinterpret_as_int())
() ()
} }
} }
@@ -160,6 +170,7 @@ pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
} }
5 => () 5 => ()
6 => () 6 => ()
7 => ()
_ => panic() _ => panic()
} }
@@ -278,6 +289,16 @@ pub fn wasmExportPopup() -> Int {
PopClip => { PopClip => {
mbt_ffi_store8((iter_base) + 0, (6)) mbt_ffi_store8((iter_base) + 0, (6))
()
}
Image(payload8) => {
mbt_ffi_store8((iter_base) + 0, (7))
mbt_ffi_store32((iter_base) + 4, ((payload8).rect).x)
mbt_ffi_store32((iter_base) + 8, ((payload8).rect).y)
mbt_ffi_store32((iter_base) + 12, (((payload8).rect).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, (((payload8).rect).h).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 20, ((payload8).image).reinterpret_as_int())
() ()
} }
} }
@@ -316,6 +337,7 @@ pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
} }
5 => () 5 => ()
6 => () 6 => ()
7 => ()
_ => panic() _ => panic()
} }
@@ -368,18 +390,6 @@ pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
} }
///|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) local.get 0)
///| ///|
extern "wasm" fn mbt_ffi_free(position : Int) = extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref) #|(func (param i32) local.get 0 call $moonbit.decref)
@@ -389,8 +399,8 @@ extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load) #|(func (param i32) (result i32) local.get 0 i32.load)
///| ///|
extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) = extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8) #|(func (param i32) (result i32) local.get 0 i32.load8_u)
///| ///|
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) = extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
@@ -404,6 +414,18 @@ extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#| local.get 1) #| local.get 1)
///| ///|
extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) =
#|(func (param i32) (result i32) local.get 0 i32.load8_u) #|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8)
///|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) local.get 0)
@@ -0,0 +1,8 @@
import {
"chandra/desktop/interface/chandra/desktop/types" @types,
"chandra/desktop/interface/chandra/desktop/theme" @theme,
"chandra/desktop/interface/chandra/desktop/clock" @clock,
"chandra/desktop/lib/clock" @logic,
}
warnings = "-44"
@@ -1,8 +1,8 @@
// Generated using `moon info`, DON'T EDIT IT // Generated using `moon info`, DON'T EDIT IT
package "moonplasma/desktop/components/clock-digital/gen/interface/moonplasma/desktop/plasmoid" package "chandra/desktop/components/clock-digital/gen/interface/chandra/desktop/plasmoid"
import { import {
"moonplasma/desktop/interface/moonplasma/desktop/types", "chandra/desktop/interface/chandra/desktop/types",
} }
// Values // Values
@@ -0,0 +1,36 @@
///| Implementation of `chandra:desktop/plasmoid` for the digital clock.
/// All logic lives in lib/clock; this file only adapts host capabilities.
///|
pub fn info() -> PlasmoidInfo {
let (id, name, w, h, min_w) = @logic.digital_info()
{
id,
name,
preferred: { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() },
min_width: min_w.reinterpret_as_uint(),
stretch: false,
}
}
///|
pub fn render(size : @types.Size) -> Array[@types.DrawOp] {
let c = @logic.digital_config
@logic.render_digital(size, @theme.get_tokens(), @clock.now(), hour12=c.hour12, show_date=c.show_date, ampm=c.ampm)
}
///| The calendar flyout (left click opens it; the shell slides it out of the panel).
pub fn popup() -> PopupSurface? {
let c = @logic.digital_config
if !c.cal.open {
return None
}
let (w, h) = c.cal.size()
let ops = c.cal.render(@theme.get_tokens(), @clock.now(), hour12=c.hour12, ampm=c.ampm)
Some({ size: { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() }, ops })
}
///|
pub fn on_event(target : Surface, event : @types.InputEvent) -> Bool {
@logic.digital_config.cal.handle(target is POPUP, event, @clock.now())
}
@@ -1,8 +0,0 @@
import {
"moonplasma/desktop/interface/moonplasma/desktop/types" @types,
"moonplasma/desktop/interface/moonplasma/desktop/theme" @theme,
"moonplasma/desktop/interface/moonplasma/desktop/clock" @clock,
"moonplasma/desktop/lib/clock" @logic,
}
warnings = "-44"
@@ -1,29 +0,0 @@
///| Implementation of `moonplasma:desktop/plasmoid` for the digital clock.
/// All logic lives in lib/clock; this file only adapts host capabilities.
///|
pub fn info() -> PlasmoidInfo {
let (id, name, w, h, min_w) = @logic.digital_info()
{
id,
name,
preferred: { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() },
min_width: min_w.reinterpret_as_uint(),
stretch: false,
}
}
///|
pub fn render(size : @types.Size) -> Array[@types.DrawOp] {
@logic.render_digital(size, @theme.get_tokens(), @clock.now())
}
///|
pub fn popup() -> PopupSurface? {
None
}
///|
pub fn on_event(_target : Surface, _event : @types.InputEvent) -> Bool {
false
}
+12 -8
View File
@@ -1,5 +1,6 @@
import { import {
"moonplasma/desktop/components/clock-digital/gen/interface/moonplasma/desktop/plasmoid" @plasmoid, "chandra/desktop/components/clock-digital/gen/interface/chandra/desktop/module-config" @module-config,
"chandra/desktop/components/clock-digital/gen/interface/chandra/desktop/plasmoid" @plasmoid,
} }
warnings = "-44" warnings = "-44"
@@ -13,13 +14,16 @@ options(
"heap-start-address": 16, "heap-start-address": 16,
"exports": [ "exports": [
"mbt_ffi_cabi_realloc:cabi_realloc", "mbt_ffi_cabi_realloc:cabi_realloc",
"wasmExportInfo:moonplasma:desktop/plasmoid@0.1.0#info", "wasmExportConfigItems:chandra:desktop/module-config@0.1.0#config-items",
"wasmExportInfoPostReturn:cabi_post_moonplasma:desktop/plasmoid@0.1.0#info", "wasmExportConfigItemsPostReturn:cabi_post_chandra:desktop/module-config@0.1.0#config-items",
"wasmExportOnEvent:moonplasma:desktop/plasmoid@0.1.0#on-event", "wasmExportInfo:chandra:desktop/plasmoid@0.1.0#info",
"wasmExportPopup:moonplasma:desktop/plasmoid@0.1.0#popup", "wasmExportInfoPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#info",
"wasmExportPopupPostReturn:cabi_post_moonplasma:desktop/plasmoid@0.1.0#popup", "wasmExportOnEvent:chandra:desktop/plasmoid@0.1.0#on-event",
"wasmExportRender:moonplasma:desktop/plasmoid@0.1.0#render", "wasmExportPopup:chandra:desktop/plasmoid@0.1.0#popup",
"wasmExportRenderPostReturn:cabi_post_moonplasma:desktop/plasmoid@0.1.0#render" "wasmExportPopupPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#popup",
"wasmExportRender:chandra:desktop/plasmoid@0.1.0#render",
"wasmExportRenderPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#render",
"wasmExportSetConfig:chandra:desktop/module-config@0.1.0#set-config"
], ],
}, },
}, },
@@ -1,5 +1,5 @@
// Generated using `moon info`, DON'T EDIT IT // Generated using `moon info`, DON'T EDIT IT
package "moonplasma/desktop/components/clock-digital/gen" package "chandra/desktop/components/clock-digital/gen"
// Values // Values
pub fn mbt_ffi_cabi_realloc(Int32, Int32, Int32, Int32) -> Int32 pub fn mbt_ffi_cabi_realloc(Int32, Int32, Int32, Int32) -> Int32
+46
View File
@@ -0,0 +1,46 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
pub fn mbt_ffi_cabi_realloc(
src_offset : Int,
src_size : Int,
_dst_alignment : Int,
dst_size : Int,
) -> Int {
// malloc
if src_offset == 0 && src_size == 0 {
return mbt_ffi_malloc(dst_size)
}
// free
if dst_size == 0 {
mbt_ffi_free(src_offset)
return 0
}
// realloc
let dst = mbt_ffi_malloc(dst_size)
mbt_ffi_copy(dst, src_offset, if src_size < dst_size { src_size } else { dst_size })
mbt_ffi_free(src_offset)
dst
}
///|
extern "wasm" fn mbt_ffi_copy(dest : Int, src : Int, len : Int) =
#|(func (param i32) (param i32) (param i32) local.get 0 local.get 1 local.get 2 memory.copy)
///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#|(func (param i32) (result i32) (local i32)
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
#| local.tee 1 i32.const 0 call $moonbit.init_array8
#| local.get 1)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///|
#doc(hidden)
pub fn wasmExportRun(p0 : Int, p1 : Int) -> Int {
@compositor.wasmExportRun(p0, p1)
}
+20
View File
@@ -0,0 +1,20 @@
import {
"chandra/desktop/components/compositor/gen/world/compositor" @compositor,
}
warnings = "-44"
pkgtype(kind: "foreign_library")
options(
link: {
"wasm": {
"export-memory-name": "memory",
"heap-start-address": 16,
"exports": [
"mbt_ffi_cabi_realloc:cabi_realloc",
"wasmExportRun:run"
],
},
},
)
@@ -0,0 +1,37 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
#doc(hidden)
pub fn wasmExportRun(p0 : Int, p1 : Int) -> Int {
let array : Array[String] = [];
for index = 0; index < (p1); index = index + 1 {
let iter_base = (p0) + (index * 8)
let result = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 0), mbt_ffi_load32((iter_base) + 4))
array.push(result)
}
mbt_ffi_free(p0)
let (result0) : (Int) = run(array);
let ret = result0
return ret
}
///|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
@@ -0,0 +1,5 @@
import {
"chandra/desktop/compositor/app" @app,
}
warnings = "-44"
@@ -0,0 +1,6 @@
///| The compositor component's entry point: everything lives in compositor/app.
///|
pub fn run(args : Array[String]) -> Int {
@app.run(args)
}
@@ -0,0 +1,5 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
/// Run the compositor until it exits. `args` are the command-line arguments (without argv[0]).
declare pub fn run(args : Array[String]) -> Int
+52
View File
@@ -0,0 +1,52 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
pub fn mbt_ffi_cabi_realloc(
src_offset : Int,
src_size : Int,
_dst_alignment : Int,
dst_size : Int,
) -> Int {
// malloc
if src_offset == 0 && src_size == 0 {
return mbt_ffi_malloc(dst_size)
}
// free
if dst_size == 0 {
mbt_ffi_free(src_offset)
return 0
}
// realloc
let dst = mbt_ffi_malloc(dst_size)
mbt_ffi_copy(dst, src_offset, if src_size < dst_size { src_size } else { dst_size })
mbt_ffi_free(src_offset)
dst
}
///|
extern "wasm" fn mbt_ffi_copy(dest : Int, src : Int, len : Int) =
#|(func (param i32) (param i32) (param i32) local.get 0 local.get 1 local.get 2 memory.copy)
///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#|(func (param i32) (result i32) (local i32)
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
#| local.tee 1 i32.const 0 call $moonbit.init_array8
#| local.get 1)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///|
#doc(hidden)
pub fn wasmExportRender(p0 : Int) -> Int {
@decoration.wasmExportRender(p0)
}
///|
#doc(hidden)
pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
@decoration.wasmExportRenderPostReturn(p0)
}
@@ -0,0 +1,226 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
#doc(hidden)
pub fn wasmExportRender(p0 : Int) -> Int {
let result = mbt_ffi_ptr2str(mbt_ffi_load32((p0) + 8), mbt_ffi_load32((p0) + 12))
let result0 = mbt_ffi_ptr2str(mbt_ffi_load32((p0) + 16), mbt_ffi_load32((p0) + 20))
let lifted : @types.Size? = match mbt_ffi_load8_u((p0) + 48) {
0 => Option::None
1 => {
Option::Some(@types.Size::{w : (mbt_ffi_load32((p0) + 52)).reinterpret_as_uint(), h : (mbt_ffi_load32((p0) + 56)).reinterpret_as_uint()})
}
_ => panic()
}
let (result1) : (DecorationFrame) = render(@policy.WindowState::{id : (mbt_ffi_load64((p0) + 0)).reinterpret_as_uint64(), app_id : result, title : result0, geometry : @types.Rect::{x : mbt_ffi_load32((p0) + 24), y : mbt_ffi_load32((p0) + 28), w : (mbt_ffi_load32((p0) + 32)).reinterpret_as_uint(), h : (mbt_ffi_load32((p0) + 36)).reinterpret_as_uint()}, min_size : @types.Size::{w : (mbt_ffi_load32((p0) + 40)).reinterpret_as_uint(), h : (mbt_ffi_load32((p0) + 44)).reinterpret_as_uint()}, max_size : lifted, focused : (mbt_ffi_load8_u((p0) + 60) != 0), maximized : (mbt_ffi_load8_u((p0) + 61) != 0), fullscreen : (mbt_ffi_load8_u((p0) + 62) != 0), workspace : (mbt_ffi_load32((p0) + 64)).reinterpret_as_uint(), caps : @policy.WindowCaps(mbt_ffi_load8_u((p0) + 68).to_byte())}, @types.Size::{w : (mbt_ffi_load32((p0) + 72)).reinterpret_as_uint(), h : (mbt_ffi_load32((p0) + 76)).reinterpret_as_uint()});
mbt_ffi_free(p0)
let return_area = mbt_ffi_malloc(32)
mbt_ffi_store32((return_area) + 0, (((result1).insets).0).reinterpret_as_int())
mbt_ffi_store32((return_area) + 4, (((result1).insets).1).reinterpret_as_int())
mbt_ffi_store32((return_area) + 8, (((result1).insets).2).reinterpret_as_int())
mbt_ffi_store32((return_area) + 12, (((result1).insets).3).reinterpret_as_int())
let address = mbt_ffi_malloc(((result1).ops).length() * 32);
for index = 0; index < ((result1).ops).length(); index = index + 1 {
let iter_elem : @types.DrawOp = ((result1).ops)[(index)]
let iter_base = address + (index * 32);
match iter_elem {
FillRect(payload) => {
mbt_ffi_store8((iter_base) + 0, (0))
mbt_ffi_store32((iter_base) + 4, ((payload).rect).x)
mbt_ffi_store32((iter_base) + 8, ((payload).rect).y)
mbt_ffi_store32((iter_base) + 12, (((payload).rect).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, (((payload).rect).h).reinterpret_as_int())
mbt_ffi_store8((iter_base) + 20, (((payload).color).r).to_int())
mbt_ffi_store8((iter_base) + 21, (((payload).color).g).to_int())
mbt_ffi_store8((iter_base) + 22, (((payload).color).b).to_int())
mbt_ffi_store8((iter_base) + 23, (((payload).color).a).to_int())
mbt_ffi_store32((iter_base) + 24, ((payload).radius).reinterpret_as_int())
()
}
StrokeRect(payload2) => {
mbt_ffi_store8((iter_base) + 0, (1))
mbt_ffi_store32((iter_base) + 4, ((payload2).rect).x)
mbt_ffi_store32((iter_base) + 8, ((payload2).rect).y)
mbt_ffi_store32((iter_base) + 12, (((payload2).rect).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, (((payload2).rect).h).reinterpret_as_int())
mbt_ffi_store8((iter_base) + 20, (((payload2).color).r).to_int())
mbt_ffi_store8((iter_base) + 21, (((payload2).color).g).to_int())
mbt_ffi_store8((iter_base) + 22, (((payload2).color).b).to_int())
mbt_ffi_store8((iter_base) + 23, (((payload2).color).a).to_int())
mbt_ffi_store32((iter_base) + 24, ((payload2).width).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 28, ((payload2).radius).reinterpret_as_int())
()
}
Line(payload3) => {
mbt_ffi_store8((iter_base) + 0, (2))
mbt_ffi_store32((iter_base) + 4, ((payload3).start).x)
mbt_ffi_store32((iter_base) + 8, ((payload3).start).y)
mbt_ffi_store32((iter_base) + 12, ((payload3).end).x)
mbt_ffi_store32((iter_base) + 16, ((payload3).end).y)
mbt_ffi_store8((iter_base) + 20, (((payload3).color).r).to_int())
mbt_ffi_store8((iter_base) + 21, (((payload3).color).g).to_int())
mbt_ffi_store8((iter_base) + 22, (((payload3).color).b).to_int())
mbt_ffi_store8((iter_base) + 23, (((payload3).color).a).to_int())
mbt_ffi_store32((iter_base) + 24, ((payload3).width).reinterpret_as_int())
()
}
Circle(payload4) => {
mbt_ffi_store8((iter_base) + 0, (3))
mbt_ffi_store32((iter_base) + 4, ((payload4).center).x)
mbt_ffi_store32((iter_base) + 8, ((payload4).center).y)
mbt_ffi_store32((iter_base) + 12, ((payload4).radius).reinterpret_as_int())
mbt_ffi_store8((iter_base) + 16, (((payload4).color).r).to_int())
mbt_ffi_store8((iter_base) + 17, (((payload4).color).g).to_int())
mbt_ffi_store8((iter_base) + 18, (((payload4).color).b).to_int())
mbt_ffi_store8((iter_base) + 19, (((payload4).color).a).to_int())
mbt_ffi_store8((iter_base) + 20, (if (payload4).filled { 1 } else { 0 }))
()
}
Text(payload5) => {
mbt_ffi_store8((iter_base) + 0, (4))
mbt_ffi_store32((iter_base) + 4, ((payload5).origin).x)
mbt_ffi_store32((iter_base) + 8, ((payload5).origin).y)
let ptr = mbt_ffi_str2ptr((payload5).text)
mbt_ffi_store32((iter_base) + 16, (payload5).text.length())
mbt_ffi_store32((iter_base) + 12, ptr)
mbt_ffi_store32((iter_base) + 20, (((payload5).style).size).reinterpret_as_int())
mbt_ffi_store8((iter_base) + 24, ((((payload5).style).color).r).to_int())
mbt_ffi_store8((iter_base) + 25, ((((payload5).style).color).g).to_int())
mbt_ffi_store8((iter_base) + 26, ((((payload5).style).color).b).to_int())
mbt_ffi_store8((iter_base) + 27, ((((payload5).style).color).a).to_int())
mbt_ffi_store8((iter_base) + 28, ((payload5).style).align.ordinal())
mbt_ffi_store8((iter_base) + 29, (if ((payload5).style).bold { 1 } else { 0 }))
()
}
PushClip(payload6) => {
mbt_ffi_store8((iter_base) + 0, (5))
mbt_ffi_store32((iter_base) + 4, (payload6).x)
mbt_ffi_store32((iter_base) + 8, (payload6).y)
mbt_ffi_store32((iter_base) + 12, ((payload6).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, ((payload6).h).reinterpret_as_int())
()
}
PopClip => {
mbt_ffi_store8((iter_base) + 0, (6))
()
}
Image(payload8) => {
mbt_ffi_store8((iter_base) + 0, (7))
mbt_ffi_store32((iter_base) + 4, ((payload8).rect).x)
mbt_ffi_store32((iter_base) + 8, ((payload8).rect).y)
mbt_ffi_store32((iter_base) + 12, (((payload8).rect).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, (((payload8).rect).h).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 20, ((payload8).image).reinterpret_as_int())
()
}
}
}
mbt_ffi_store32((return_area) + 20, ((result1).ops).length())
mbt_ffi_store32((return_area) + 16, address)
let address9 = mbt_ffi_malloc(((result1).hit_regions).length() * 20);
for index10 = 0; index10 < ((result1).hit_regions).length(); index10 = index10 + 1 {
let iter_elem : HitRegion = ((result1).hit_regions)[(index10)]
let iter_base = address9 + (index10 * 20);
mbt_ffi_store32((iter_base) + 0, ((iter_elem).rect).x)
mbt_ffi_store32((iter_base) + 4, ((iter_elem).rect).y)
mbt_ffi_store32((iter_base) + 8, (((iter_elem).rect).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 12, (((iter_elem).rect).h).reinterpret_as_int())
mbt_ffi_store8((iter_base) + 16, (iter_elem).role.ordinal())
}
mbt_ffi_store32((return_area) + 28, ((result1).hit_regions).length())
mbt_ffi_store32((return_area) + 24, address9)
let ret = return_area
return ret
}
///|
#doc(hidden)
pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
for index = 0; index < (mbt_ffi_load32((p0) + 20)); index = index + 1 {
let iter_base = (mbt_ffi_load32((p0) + 16)) + (index * 32)
match (mbt_ffi_load8_u((iter_base) + 0)) {
0 => ()
1 => ()
2 => ()
3 => ()
4 => {
mbt_ffi_free(mbt_ffi_load32((iter_base) + 12))
}
5 => ()
6 => ()
7 => ()
_ => panic()
}
}
mbt_ffi_free(mbt_ffi_load32((p0) + 16))
mbt_ffi_free(mbt_ffi_load32((p0) + 24))
}
///|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
///|
extern "wasm" fn mbt_ffi_load64(offset : Int) -> Int64 =
#|(func (param i32) (result i64) local.get 0 i64.load)
///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
///|
extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load8_u)
///|
extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#|(func (param i32) (result i32) (local i32)
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
#| local.tee 1 i32.const 0 call $moonbit.init_array8
#| local.get 1)
///|
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) local.get 0)
@@ -0,0 +1,8 @@
import {
"chandra/desktop/interface/chandra/desktop/types" @types,
"chandra/desktop/interface/chandra/desktop/theme" @theme,
"chandra/desktop/interface/chandra/wm/policy" @policy,
"chandra/desktop/lib/ui" @ui,
}
warnings = "-44"
@@ -0,0 +1,46 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/decoration-breeze/gen/interface/chandra/wm/decoration"
import {
"chandra/desktop/interface/chandra/desktop/types",
"chandra/desktop/interface/chandra/wm/policy",
}
// Values
pub fn render(@policy.WindowState, @types.Size) -> DecorationFrame
// Errors
// Types and methods
pub(all) struct DecorationFrame {
insets : (UInt32, UInt32, UInt32, UInt32)
ops : Array[@types.DrawOp]
hit_regions : Array[HitRegion]
}
pub(all) struct HitRegion {
rect : @types.Rect
role : HitRole
}
pub(all) enum HitRole {
NONE
TITLEBAR
CLOSE
MAXIMIZE
MINIMIZE
RESIZE_N
RESIZE_S
RESIZE_E
RESIZE_W
RESIZE_NW
RESIZE_NE
RESIZE_SW
RESIZE_SE
}
pub fn HitRole::from(Int32) -> Self
pub fn HitRole::ordinal(Self) -> Int32
// Type aliases
// Traits
@@ -0,0 +1,84 @@
///| `chandra:wm/decoration` Breeze-inspired server-side decoration component.
///|
pub fn render(
win : @policy.WindowState,
outer_size : @types.Size,
) -> DecorationFrame {
if win.fullscreen {
return { insets: (0U, 0U, 0U, 0U), ops: [], hit_regions: [] }
}
let t = @theme.get_tokens()
let p = t.palette
let w = outer_size.w.reinterpret_as_int()
let h = outer_size.h.reinterpret_as_int()
let title_h = 32
let border = 2
let radius = t.radius.reinterpret_as_int()
let title_bg = if win.focused { p.surface } else { @ui.with_alpha(p.surface, 210) }
let border_col = if win.focused { p.accent } else { p.border }
let title_fg = if win.focused { p.foreground } else { p.foreground_muted }
let ops : Array[@types.DrawOp] = [
// Titlebar + outer frame background
@ui.fill_rect(@ui.rect(0, 0, w, title_h), title_bg, radius=radius),
@ui.stroke_rect(@ui.rect(0, 0, w, h), border_col, width=border, radius=radius),
// Subtle separator under titlebar
@ui.line(border, title_h - 1, w - border, title_h - 1, p.border, width=1),
]
let label = if win.title.length() > 0 { win.title } else { win.app_id }
ops.push(
@ui.text(
14,
title_h / 2,
label,
t.font_size.reinterpret_as_int(),
title_fg,
align=LEFT,
bold=win.focused,
),
)
// Window control buttons on the right: [ _ ] [ [] ] [ X ]
let btn_size = 18
let btn_y = (title_h - btn_size) / 2
let close_x = w - 10 - btn_size
let max_x = close_x - 8 - btn_size
let min_x = max_x - 8 - btn_size
let close_bg = if win.focused { @ui.color(218, 68, 83, 255) } else { p.surface_hover }
let btn_bg = p.surface_hover
ops.push(@ui.fill_rect(@ui.rect(min_x, btn_y, btn_size, btn_size), btn_bg, radius=9))
ops.push(@ui.line(min_x + 5, btn_y + btn_size - 6, min_x + btn_size - 5, btn_y + btn_size - 6, title_fg, width=2))
ops.push(@ui.fill_rect(@ui.rect(max_x, btn_y, btn_size, btn_size), btn_bg, radius=9))
ops.push(@ui.stroke_rect(@ui.rect(max_x + 5, btn_y + 5, btn_size - 10, btn_size - 10), title_fg, width=1))
ops.push(@ui.fill_rect(@ui.rect(close_x, btn_y, btn_size, btn_size), close_bg, radius=9))
ops.push(@ui.line(close_x + 5, btn_y + 5, close_x + btn_size - 5, btn_y + btn_size - 5, p.accent_foreground, width=2))
ops.push(@ui.line(close_x + btn_size - 5, btn_y + 5, close_x + 5, btn_y + btn_size - 5, p.accent_foreground, width=2))
let hit_regions : Array[HitRegion] = [
{ rect: @ui.rect(close_x, btn_y, btn_size, btn_size), role: CLOSE },
{ rect: @ui.rect(max_x, btn_y, btn_size, btn_size), role: MAXIMIZE },
{ rect: @ui.rect(min_x, btn_y, btn_size, btn_size), role: MINIMIZE },
{ rect: @ui.rect(border, border, w - 2 * border, title_h - border), role: TITLEBAR },
{ rect: @ui.rect(0, 0, 8, 8), role: RESIZE_NW },
{ rect: @ui.rect(w - 8, 0, 8, 8), role: RESIZE_NE },
{ rect: @ui.rect(0, h - 8, 8, 8), role: RESIZE_SW },
{ rect: @ui.rect(w - 8, h - 8, 8, 8), role: RESIZE_SE },
{ rect: @ui.rect(8, 0, w - 16, 4), role: RESIZE_N },
{ rect: @ui.rect(8, h - 4, w - 16, 4), role: RESIZE_S },
{ rect: @ui.rect(0, 8, 4, h - 16), role: RESIZE_W },
{ rect: @ui.rect(w - 4, 8, 4, h - 16), role: RESIZE_E },
]
{
insets: (title_h.reinterpret_as_uint(), border.reinterpret_as_uint(), border.reinterpret_as_uint(), border.reinterpret_as_uint()),
ops,
hit_regions,
}
}
@@ -0,0 +1,55 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
pub(all) enum HitRole {
NONE; TITLEBAR; CLOSE; MAXIMIZE; MINIMIZE; RESIZE_N; RESIZE_S; RESIZE_E; RESIZE_W; RESIZE_NW; RESIZE_NE; RESIZE_SW; RESIZE_SE
} derive()
///|
pub fn HitRole::ordinal(self : HitRole) -> Int {
match self {
NONE => 0
TITLEBAR => 1
CLOSE => 2
MAXIMIZE => 3
MINIMIZE => 4
RESIZE_N => 5
RESIZE_S => 6
RESIZE_E => 7
RESIZE_W => 8
RESIZE_NW => 9
RESIZE_NE => 10
RESIZE_SW => 11
RESIZE_SE => 12
}
}
///|
pub fn HitRole::from(self : Int) -> HitRole {
match self {
0 => NONE
1 => TITLEBAR
2 => CLOSE
3 => MAXIMIZE
4 => MINIMIZE
5 => RESIZE_N
6 => RESIZE_S
7 => RESIZE_E
8 => RESIZE_W
9 => RESIZE_NW
10 => RESIZE_NE
11 => RESIZE_SW
12 => RESIZE_SE
_ => panic()
}
}
///|
pub(all) struct HitRegion {
rect : @types.Rect; role : HitRole
}
///|
pub(all) struct DecorationFrame {
insets : (UInt, UInt, UInt, UInt); ops : Array[@types.DrawOp]; hit_regions : Array[HitRegion]
}
///|
declare pub fn render(win : @policy.WindowState, outer_size : @types.Size) -> DecorationFrame
+21
View File
@@ -0,0 +1,21 @@
import {
"chandra/desktop/components/decoration-breeze/gen/interface/chandra/wm/decoration" @decoration,
}
warnings = "-44"
pkgtype(kind: "foreign_library")
options(
link: {
"wasm": {
"export-memory-name": "memory",
"heap-start-address": 16,
"exports": [
"mbt_ffi_cabi_realloc:cabi_realloc",
"wasmExportRender:chandra:wm/decoration@0.2.0#render",
"wasmExportRenderPostReturn:cabi_post_chandra:wm/decoration@0.2.0#render"
],
},
},
)
@@ -0,0 +1,13 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/decoration-breeze/gen"
// Values
pub fn mbt_ffi_cabi_realloc(Int32, Int32, Int32, Int32) -> Int32
// Errors
// Types and methods
// Type aliases
// Traits
+100
View File
@@ -0,0 +1,100 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
pub fn mbt_ffi_cabi_realloc(
src_offset : Int,
src_size : Int,
_dst_alignment : Int,
dst_size : Int,
) -> Int {
// malloc
if src_offset == 0 && src_size == 0 {
return mbt_ffi_malloc(dst_size)
}
// free
if dst_size == 0 {
mbt_ffi_free(src_offset)
return 0
}
// realloc
let dst = mbt_ffi_malloc(dst_size)
mbt_ffi_copy(dst, src_offset, if src_size < dst_size { src_size } else { dst_size })
mbt_ffi_free(src_offset)
dst
}
///|
extern "wasm" fn mbt_ffi_copy(dest : Int, src : Int, len : Int) =
#|(func (param i32) (param i32) (param i32) local.get 0 local.get 1 local.get 2 memory.copy)
///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#|(func (param i32) (result i32) (local i32)
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
#| local.tee 1 i32.const 0 call $moonbit.init_array8
#| local.get 1)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///|
#doc(hidden)
pub fn wasmExportConfigItems() -> Int {
@module-config.wasmExportConfigItems()
}
///|
#doc(hidden)
pub fn wasmExportConfigItemsPostReturn(p0 : Int) -> Unit {
@module-config.wasmExportConfigItemsPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportPopupPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportInfoPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportInfo() -> Int {
@plasmoid.wasmExportInfo()
}
///|
#doc(hidden)
pub fn wasmExportPopup() -> Int {
@plasmoid.wasmExportPopup()
}
///|
#doc(hidden)
pub fn wasmExportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
@module-config.wasmExportSetConfig(p0, p1, p2, p3)
}
///|
#doc(hidden)
pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
@plasmoid.wasmExportOnEvent(p0, p1, p2, p3)
}
///|
#doc(hidden)
pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int {
@plasmoid.wasmExportRender(p0, p1)
}
///|
#doc(hidden)
pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportRenderPostReturn(p0)
}
@@ -0,0 +1,5 @@
Optional: a module's own settings. A module that exports this gets a "Module settings" entry in
its right-click menu, listing the items below; the shell draws the menu (the same for every
module), remembers each choice per module in state.edn (`:module-config`), and hands the saved
values back through `set-config` right after the module is loaded. A module without it simply
has no settings: the export is looked up by name, so older modules keep loading.
@@ -0,0 +1,114 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
#doc(hidden)
pub fn wasmExportConfigItems() -> Int {
let (result) : (Array[ConfigItem]) = config_items();
let return_area = mbt_ffi_malloc(8)
let address3 = mbt_ffi_malloc((result).length() * 32);
for index4 = 0; index4 < (result).length(); index4 = index4 + 1 {
let iter_elem : ConfigItem = (result)[(index4)]
let iter_base = address3 + (index4 * 32);
let ptr = mbt_ffi_str2ptr((iter_elem).key)
mbt_ffi_store32((iter_base) + 4, (iter_elem).key.length())
mbt_ffi_store32((iter_base) + 0, ptr)
let ptr0 = mbt_ffi_str2ptr((iter_elem).label)
mbt_ffi_store32((iter_base) + 12, (iter_elem).label.length())
mbt_ffi_store32((iter_base) + 8, ptr0)
let address = mbt_ffi_malloc(((iter_elem).choices).length() * 8);
for index = 0; index < ((iter_elem).choices).length(); index = index + 1 {
let iter_elem : String = ((iter_elem).choices)[(index)]
let iter_base = address + (index * 8);
let ptr1 = mbt_ffi_str2ptr(iter_elem)
mbt_ffi_store32((iter_base) + 4, iter_elem.length())
mbt_ffi_store32((iter_base) + 0, ptr1)
}
mbt_ffi_store32((iter_base) + 20, ((iter_elem).choices).length())
mbt_ffi_store32((iter_base) + 16, address)
let ptr2 = mbt_ffi_str2ptr((iter_elem).value)
mbt_ffi_store32((iter_base) + 28, (iter_elem).value.length())
mbt_ffi_store32((iter_base) + 24, ptr2)
}
mbt_ffi_store32((return_area) + 4, (result).length())
mbt_ffi_store32((return_area) + 0, address3)
let ret = return_area
return ret
}
///|
#doc(hidden)
pub fn wasmExportConfigItemsPostReturn(p0 : Int) -> Unit {
for index0 = 0; index0 < (mbt_ffi_load32((p0) + 4)); index0 = index0 + 1 {
let iter_base = (mbt_ffi_load32((p0) + 0)) + (index0 * 32)
mbt_ffi_free(mbt_ffi_load32((iter_base) + 0))
mbt_ffi_free(mbt_ffi_load32((iter_base) + 8))
for index = 0; index < (mbt_ffi_load32((iter_base) + 20)); index = index + 1 {
let iter_base = (mbt_ffi_load32((iter_base) + 16)) + (index * 8)
mbt_ffi_free(mbt_ffi_load32((iter_base) + 0))
}
mbt_ffi_free(mbt_ffi_load32((iter_base) + 16))
mbt_ffi_free(mbt_ffi_load32((iter_base) + 24))
}
mbt_ffi_free(mbt_ffi_load32((p0) + 0))
}
///|
#doc(hidden)
pub fn wasmExportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
let result = mbt_ffi_ptr2str(p0, p1)
let result0 = mbt_ffi_ptr2str(p2, p3)
let (result1) : (Bool) = set_config(result, result0);
let ret = (if result1 { 1 } else { 0 })
return ret
}
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) local.get 0)
///|
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#|(func (param i32) (result i32) (local i32)
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
#| local.tee 1 i32.const 0 call $moonbit.init_array8
#| local.get 1)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
@@ -0,0 +1,5 @@
import {
"chandra/desktop/lib/dock" @logic,
}
warnings = "-44"
@@ -0,0 +1,21 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/dock/gen/interface/chandra/desktop/module-config"
// Values
pub fn config_items() -> Array[ConfigItem]
pub fn set_config(String, String) -> Bool
// Errors
// Types and methods
pub(all) struct ConfigItem {
key : String
label : String
choices : Array[String]
value : String
}
// Type aliases
// Traits
@@ -0,0 +1,12 @@
///| The dock's right-click settings (icon size, magnification, running apps) and its pinned apps
/// (a hidden setting the shell's per-app menu changes); the logic is in lib/dock.
///|
pub fn config_items() -> Array[ConfigItem] {
@logic.config.items().map(e => { key: e.key, label: e.label, choices: e.choices, value: e.value })
}
///|
pub fn set_config(key : String, value : String) -> Bool {
@logic.config.set(key, value)
}
@@ -0,0 +1,11 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
pub(all) struct ConfigItem {
key : String; label : String; choices : Array[String]; value : String
}
///|
declare pub fn config_items() -> Array[ConfigItem]
///|
/// Set `key` to `value` (unknown keys and values are ignored). True when the widget should redraw.
declare pub fn set_config(key : String, value : String) -> Bool
@@ -0,0 +1 @@
The widget (plasmoid) contract.
@@ -0,0 +1,431 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
#doc(hidden)
pub fn wasmExportInfo() -> Int {
let (result) : (PlasmoidInfo) = info();
let return_area = mbt_ffi_malloc(32)
let ptr = mbt_ffi_str2ptr((result).id)
mbt_ffi_store32((return_area) + 4, (result).id.length())
mbt_ffi_store32((return_area) + 0, ptr)
let ptr0 = mbt_ffi_str2ptr((result).name)
mbt_ffi_store32((return_area) + 12, (result).name.length())
mbt_ffi_store32((return_area) + 8, ptr0)
mbt_ffi_store32((return_area) + 16, (((result).preferred).w).reinterpret_as_int())
mbt_ffi_store32((return_area) + 20, (((result).preferred).h).reinterpret_as_int())
mbt_ffi_store32((return_area) + 24, ((result).min_width).reinterpret_as_int())
mbt_ffi_store8((return_area) + 28, (if (result).stretch { 1 } else { 0 }))
let ret = return_area
return ret
}
///|
#doc(hidden)
pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit {
mbt_ffi_free(mbt_ffi_load32((p0) + 0))
mbt_ffi_free(mbt_ffi_load32((p0) + 8))
}
///|
#doc(hidden)
pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int {
let (result) : (Array[@types.DrawOp]) = render(@types.Size::{w : (p0).reinterpret_as_uint(), h : (p1).reinterpret_as_uint()});
let return_area = mbt_ffi_malloc(8)
let address = mbt_ffi_malloc((result).length() * 32);
for index = 0; index < (result).length(); index = index + 1 {
let iter_elem : @types.DrawOp = (result)[(index)]
let iter_base = address + (index * 32);
match iter_elem {
FillRect(payload) => {
mbt_ffi_store8((iter_base) + 0, (0))
mbt_ffi_store32((iter_base) + 4, ((payload).rect).x)
mbt_ffi_store32((iter_base) + 8, ((payload).rect).y)
mbt_ffi_store32((iter_base) + 12, (((payload).rect).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, (((payload).rect).h).reinterpret_as_int())
mbt_ffi_store8((iter_base) + 20, (((payload).color).r).to_int())
mbt_ffi_store8((iter_base) + 21, (((payload).color).g).to_int())
mbt_ffi_store8((iter_base) + 22, (((payload).color).b).to_int())
mbt_ffi_store8((iter_base) + 23, (((payload).color).a).to_int())
mbt_ffi_store32((iter_base) + 24, ((payload).radius).reinterpret_as_int())
()
}
StrokeRect(payload0) => {
mbt_ffi_store8((iter_base) + 0, (1))
mbt_ffi_store32((iter_base) + 4, ((payload0).rect).x)
mbt_ffi_store32((iter_base) + 8, ((payload0).rect).y)
mbt_ffi_store32((iter_base) + 12, (((payload0).rect).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, (((payload0).rect).h).reinterpret_as_int())
mbt_ffi_store8((iter_base) + 20, (((payload0).color).r).to_int())
mbt_ffi_store8((iter_base) + 21, (((payload0).color).g).to_int())
mbt_ffi_store8((iter_base) + 22, (((payload0).color).b).to_int())
mbt_ffi_store8((iter_base) + 23, (((payload0).color).a).to_int())
mbt_ffi_store32((iter_base) + 24, ((payload0).width).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 28, ((payload0).radius).reinterpret_as_int())
()
}
Line(payload1) => {
mbt_ffi_store8((iter_base) + 0, (2))
mbt_ffi_store32((iter_base) + 4, ((payload1).start).x)
mbt_ffi_store32((iter_base) + 8, ((payload1).start).y)
mbt_ffi_store32((iter_base) + 12, ((payload1).end).x)
mbt_ffi_store32((iter_base) + 16, ((payload1).end).y)
mbt_ffi_store8((iter_base) + 20, (((payload1).color).r).to_int())
mbt_ffi_store8((iter_base) + 21, (((payload1).color).g).to_int())
mbt_ffi_store8((iter_base) + 22, (((payload1).color).b).to_int())
mbt_ffi_store8((iter_base) + 23, (((payload1).color).a).to_int())
mbt_ffi_store32((iter_base) + 24, ((payload1).width).reinterpret_as_int())
()
}
Circle(payload2) => {
mbt_ffi_store8((iter_base) + 0, (3))
mbt_ffi_store32((iter_base) + 4, ((payload2).center).x)
mbt_ffi_store32((iter_base) + 8, ((payload2).center).y)
mbt_ffi_store32((iter_base) + 12, ((payload2).radius).reinterpret_as_int())
mbt_ffi_store8((iter_base) + 16, (((payload2).color).r).to_int())
mbt_ffi_store8((iter_base) + 17, (((payload2).color).g).to_int())
mbt_ffi_store8((iter_base) + 18, (((payload2).color).b).to_int())
mbt_ffi_store8((iter_base) + 19, (((payload2).color).a).to_int())
mbt_ffi_store8((iter_base) + 20, (if (payload2).filled { 1 } else { 0 }))
()
}
Text(payload3) => {
mbt_ffi_store8((iter_base) + 0, (4))
mbt_ffi_store32((iter_base) + 4, ((payload3).origin).x)
mbt_ffi_store32((iter_base) + 8, ((payload3).origin).y)
let ptr = mbt_ffi_str2ptr((payload3).text)
mbt_ffi_store32((iter_base) + 16, (payload3).text.length())
mbt_ffi_store32((iter_base) + 12, ptr)
mbt_ffi_store32((iter_base) + 20, (((payload3).style).size).reinterpret_as_int())
mbt_ffi_store8((iter_base) + 24, ((((payload3).style).color).r).to_int())
mbt_ffi_store8((iter_base) + 25, ((((payload3).style).color).g).to_int())
mbt_ffi_store8((iter_base) + 26, ((((payload3).style).color).b).to_int())
mbt_ffi_store8((iter_base) + 27, ((((payload3).style).color).a).to_int())
mbt_ffi_store8((iter_base) + 28, ((payload3).style).align.ordinal())
mbt_ffi_store8((iter_base) + 29, (if ((payload3).style).bold { 1 } else { 0 }))
()
}
PushClip(payload4) => {
mbt_ffi_store8((iter_base) + 0, (5))
mbt_ffi_store32((iter_base) + 4, (payload4).x)
mbt_ffi_store32((iter_base) + 8, (payload4).y)
mbt_ffi_store32((iter_base) + 12, ((payload4).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, ((payload4).h).reinterpret_as_int())
()
}
PopClip => {
mbt_ffi_store8((iter_base) + 0, (6))
()
}
Image(payload6) => {
mbt_ffi_store8((iter_base) + 0, (7))
mbt_ffi_store32((iter_base) + 4, ((payload6).rect).x)
mbt_ffi_store32((iter_base) + 8, ((payload6).rect).y)
mbt_ffi_store32((iter_base) + 12, (((payload6).rect).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, (((payload6).rect).h).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 20, ((payload6).image).reinterpret_as_int())
()
}
}
}
mbt_ffi_store32((return_area) + 4, (result).length())
mbt_ffi_store32((return_area) + 0, address)
let ret = return_area
return ret
}
///|
#doc(hidden)
pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
for index = 0; index < (mbt_ffi_load32((p0) + 4)); index = index + 1 {
let iter_base = (mbt_ffi_load32((p0) + 0)) + (index * 32)
match (mbt_ffi_load8_u((iter_base) + 0)) {
0 => ()
1 => ()
2 => ()
3 => ()
4 => {
mbt_ffi_free(mbt_ffi_load32((iter_base) + 12))
}
5 => ()
6 => ()
7 => ()
_ => panic()
}
}
mbt_ffi_free(mbt_ffi_load32((p0) + 0))
}
///|
#doc(hidden)
pub fn wasmExportPopup() -> Int {
let (result) : (PopupSurface?) = popup();
let return_area = mbt_ffi_malloc(20)
match (result) {
None => {
mbt_ffi_store8((return_area) + 0, (0))
()
}
Some(payload0) => {
mbt_ffi_store8((return_area) + 0, (1))
mbt_ffi_store32((return_area) + 4, (((payload0).size).w).reinterpret_as_int())
mbt_ffi_store32((return_area) + 8, (((payload0).size).h).reinterpret_as_int())
let address = mbt_ffi_malloc(((payload0).ops).length() * 32);
for index = 0; index < ((payload0).ops).length(); index = index + 1 {
let iter_elem : @types.DrawOp = ((payload0).ops)[(index)]
let iter_base = address + (index * 32);
match iter_elem {
FillRect(payload1) => {
mbt_ffi_store8((iter_base) + 0, (0))
mbt_ffi_store32((iter_base) + 4, ((payload1).rect).x)
mbt_ffi_store32((iter_base) + 8, ((payload1).rect).y)
mbt_ffi_store32((iter_base) + 12, (((payload1).rect).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, (((payload1).rect).h).reinterpret_as_int())
mbt_ffi_store8((iter_base) + 20, (((payload1).color).r).to_int())
mbt_ffi_store8((iter_base) + 21, (((payload1).color).g).to_int())
mbt_ffi_store8((iter_base) + 22, (((payload1).color).b).to_int())
mbt_ffi_store8((iter_base) + 23, (((payload1).color).a).to_int())
mbt_ffi_store32((iter_base) + 24, ((payload1).radius).reinterpret_as_int())
()
}
StrokeRect(payload2) => {
mbt_ffi_store8((iter_base) + 0, (1))
mbt_ffi_store32((iter_base) + 4, ((payload2).rect).x)
mbt_ffi_store32((iter_base) + 8, ((payload2).rect).y)
mbt_ffi_store32((iter_base) + 12, (((payload2).rect).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, (((payload2).rect).h).reinterpret_as_int())
mbt_ffi_store8((iter_base) + 20, (((payload2).color).r).to_int())
mbt_ffi_store8((iter_base) + 21, (((payload2).color).g).to_int())
mbt_ffi_store8((iter_base) + 22, (((payload2).color).b).to_int())
mbt_ffi_store8((iter_base) + 23, (((payload2).color).a).to_int())
mbt_ffi_store32((iter_base) + 24, ((payload2).width).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 28, ((payload2).radius).reinterpret_as_int())
()
}
Line(payload3) => {
mbt_ffi_store8((iter_base) + 0, (2))
mbt_ffi_store32((iter_base) + 4, ((payload3).start).x)
mbt_ffi_store32((iter_base) + 8, ((payload3).start).y)
mbt_ffi_store32((iter_base) + 12, ((payload3).end).x)
mbt_ffi_store32((iter_base) + 16, ((payload3).end).y)
mbt_ffi_store8((iter_base) + 20, (((payload3).color).r).to_int())
mbt_ffi_store8((iter_base) + 21, (((payload3).color).g).to_int())
mbt_ffi_store8((iter_base) + 22, (((payload3).color).b).to_int())
mbt_ffi_store8((iter_base) + 23, (((payload3).color).a).to_int())
mbt_ffi_store32((iter_base) + 24, ((payload3).width).reinterpret_as_int())
()
}
Circle(payload4) => {
mbt_ffi_store8((iter_base) + 0, (3))
mbt_ffi_store32((iter_base) + 4, ((payload4).center).x)
mbt_ffi_store32((iter_base) + 8, ((payload4).center).y)
mbt_ffi_store32((iter_base) + 12, ((payload4).radius).reinterpret_as_int())
mbt_ffi_store8((iter_base) + 16, (((payload4).color).r).to_int())
mbt_ffi_store8((iter_base) + 17, (((payload4).color).g).to_int())
mbt_ffi_store8((iter_base) + 18, (((payload4).color).b).to_int())
mbt_ffi_store8((iter_base) + 19, (((payload4).color).a).to_int())
mbt_ffi_store8((iter_base) + 20, (if (payload4).filled { 1 } else { 0 }))
()
}
Text(payload5) => {
mbt_ffi_store8((iter_base) + 0, (4))
mbt_ffi_store32((iter_base) + 4, ((payload5).origin).x)
mbt_ffi_store32((iter_base) + 8, ((payload5).origin).y)
let ptr = mbt_ffi_str2ptr((payload5).text)
mbt_ffi_store32((iter_base) + 16, (payload5).text.length())
mbt_ffi_store32((iter_base) + 12, ptr)
mbt_ffi_store32((iter_base) + 20, (((payload5).style).size).reinterpret_as_int())
mbt_ffi_store8((iter_base) + 24, ((((payload5).style).color).r).to_int())
mbt_ffi_store8((iter_base) + 25, ((((payload5).style).color).g).to_int())
mbt_ffi_store8((iter_base) + 26, ((((payload5).style).color).b).to_int())
mbt_ffi_store8((iter_base) + 27, ((((payload5).style).color).a).to_int())
mbt_ffi_store8((iter_base) + 28, ((payload5).style).align.ordinal())
mbt_ffi_store8((iter_base) + 29, (if ((payload5).style).bold { 1 } else { 0 }))
()
}
PushClip(payload6) => {
mbt_ffi_store8((iter_base) + 0, (5))
mbt_ffi_store32((iter_base) + 4, (payload6).x)
mbt_ffi_store32((iter_base) + 8, (payload6).y)
mbt_ffi_store32((iter_base) + 12, ((payload6).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, ((payload6).h).reinterpret_as_int())
()
}
PopClip => {
mbt_ffi_store8((iter_base) + 0, (6))
()
}
Image(payload8) => {
mbt_ffi_store8((iter_base) + 0, (7))
mbt_ffi_store32((iter_base) + 4, ((payload8).rect).x)
mbt_ffi_store32((iter_base) + 8, ((payload8).rect).y)
mbt_ffi_store32((iter_base) + 12, (((payload8).rect).w).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 16, (((payload8).rect).h).reinterpret_as_int())
mbt_ffi_store32((iter_base) + 20, ((payload8).image).reinterpret_as_int())
()
}
}
}
mbt_ffi_store32((return_area) + 16, ((payload0).ops).length())
mbt_ffi_store32((return_area) + 12, address)
()
}
}
let ret = return_area
return ret
}
///|
#doc(hidden)
pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
match (mbt_ffi_load8_u((p0) + 0)) {
0 => ()
1 => {
for index = 0; index < (mbt_ffi_load32((p0) + 16)); index = index + 1 {
let iter_base = (mbt_ffi_load32((p0) + 12)) + (index * 32)
match (mbt_ffi_load8_u((iter_base) + 0)) {
0 => ()
1 => ()
2 => ()
3 => ()
4 => {
mbt_ffi_free(mbt_ffi_load32((iter_base) + 12))
}
5 => ()
6 => ()
7 => ()
_ => panic()
}
}
mbt_ffi_free(mbt_ffi_load32((p0) + 12))
}
_ => panic()
}
}
///|
#doc(hidden)
pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
let lifted = match (p1) {
0 => {
@types.InputEvent::PointerMove(@types.Point::{x : p2, y : p3})
}
1 => {
@types.InputEvent::PointerDown(@types.Point::{x : p2, y : p3})
}
2 => {
@types.InputEvent::PointerUp(@types.Point::{x : p2, y : p3})
}
3 => {
@types.InputEvent::PointerLeave
}
4 => {
@types.InputEvent::FocusLost
}
5 => {
let result = mbt_ffi_ptr2str(p2, p3)
@types.InputEvent::KeyDown(result)
}
_ => panic()
}
let (result0) : (Bool) = on_event(Surface::from(p0), lifted);
let ret = (if result0 { 1 } else { 0 })
return ret
}
///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#|(func (param i32) (result i32) (local i32)
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
#| local.tee 1 i32.const 0 call $moonbit.init_array8
#| local.get 1)
///|
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
///|
extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load8_u)
///|
extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8)
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) local.get 0)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
@@ -0,0 +1,11 @@
import {
"chandra/desktop/interface/chandra/desktop/types" @types,
"chandra/desktop/interface/chandra/desktop/theme" @theme,
"chandra/desktop/interface/chandra/desktop/app-catalog" @app_catalog,
"chandra/desktop/interface/chandra/desktop/app-launch" @app_launch,
"chandra/desktop/interface/chandra/desktop/windows" @windows,
"chandra/desktop/interface/chandra/desktop/icons" @icons,
"chandra/desktop/lib/dock" @logic,
}
warnings = "-44"
@@ -0,0 +1,42 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/dock/gen/interface/chandra/desktop/plasmoid"
import {
"chandra/desktop/interface/chandra/desktop/types",
}
// Values
pub fn info() -> PlasmoidInfo
pub fn on_event(Surface, @types.InputEvent) -> Bool
pub fn popup() -> PopupSurface?
pub fn render(@types.Size) -> Array[@types.DrawOp]
// Errors
// Types and methods
pub(all) struct PlasmoidInfo {
id : String
name : String
preferred : @types.Size
min_width : UInt32
stretch : Bool
}
pub(all) struct PopupSurface {
size : @types.Size
ops : Array[@types.DrawOp]
}
pub(all) enum Surface {
WIDGET
POPUP
}
pub fn Surface::from(Int32) -> Self
pub fn Surface::ordinal(Self) -> Int32
// Type aliases
// Traits
@@ -0,0 +1,92 @@
///| Implementation of `chandra:desktop/plasmoid` for the dock, the panel's task manager: pinned
/// apps, then running ones, with their theme icons, a dot per open window and (room allowing)
/// their window titles. A click starts the app or brings its windows
/// forward. Layout, hit-testing and drawing live in lib/dock (the shell uses the same code for the
/// hover label and the per-app right-click menu); this adapts host capabilities.
///| Item under the pointer, or -1.
let hover : Ref[Int] = Ref::new(-1)
///| Size of the widget at its last render (events carry no size).
let width : Ref[Int] = Ref::new(200)
///|
let height : Ref[Int] = Ref::new(34)
///| The windows as the dock sees them: `all` has the app ids, `list-windows` (by the low 32 bits
/// of the id) which are minimized.
fn dock_windows() -> Array[@logic.DockWindow] {
let mini : Map[UInt, Bool] = Map([])
for w in @windows.list_windows() {
if w.minimized != 0U {
mini.set(w.id, true)
}
}
@windows.all().map(d => {
id: d.id,
app_id: d.app_id,
focused: d.focused,
title: d.title,
minimized: mini.contains((d.id & 0xFFFFFFFFUL).to_uint()),
})
}
///| The window with keyboard focus, if any.
fn focused_window() -> UInt64? {
for d in @windows.all() {
if d.focused {
return Some(d.id)
}
}
None
}
///|
fn current_items() -> Array[@logic.DockItem] {
@logic.items(@logic.config, @app_catalog.list_apps(), dock_windows())
}
///|
pub fn info() -> PlasmoidInfo {
{
id: "org.chandra.dock",
name: "Dock",
// The shell works out the real width from the items as they change.
preferred: { w: @logic.preferred_width(current_items(), @logic.config, 34).reinterpret_as_uint(), h: 34U },
min_width: 60,
// The panel's task list: it takes the free room, and what follows packs right.
stretch: true,
}
}
///|
pub fn render(size : @types.Size) -> Array[@types.DrawOp] {
width.val = size.w.reinterpret_as_int()
height.val = size.h.reinterpret_as_int()
@logic.render(size, @theme.get_tokens(), @logic.config, current_items(), hover.val, @icons.app_icon)
}
///| The dock has no popup: the shell draws its hover label and right-click menu.
pub fn popup() -> PopupSurface? {
None
}
///|
pub fn on_event(_target : Surface, event : @types.InputEvent) -> Bool {
let (h, redraw, action) = @logic.handle(
current_items(),
@logic.config,
hover.val,
width.val,
height.val,
focused_window(),
event,
)
hover.val = h
match action {
Launch(id) => ignore(@app_launch.launch(id))
Focus(win) => @windows.focus(win)
Nothing => ()
}
redraw
}
@@ -0,0 +1,42 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
pub(all) struct PlasmoidInfo {
id : String; name : String; preferred : @types.Size; min_width : UInt; stretch : Bool
}
///|
pub(all) struct PopupSurface {
size : @types.Size; ops : Array[@types.DrawOp]
}
///|
pub(all) enum Surface {
WIDGET; POPUP
} derive()
///|
pub fn Surface::ordinal(self : Surface) -> Int {
match self {
WIDGET => 0
POPUP => 1
}
}
///|
pub fn Surface::from(self : Int) -> Surface {
match self {
0 => WIDGET
1 => POPUP
_ => panic()
}
}
///|
declare pub fn info() -> PlasmoidInfo
///|
/// Draw the widget into a `size` box (local coordinates).
declare pub fn render(size : @types.Size) -> Array[@types.DrawOp]
///|
/// Present when the widget wants a popup surface (e.g. a launcher menu).
declare pub fn popup() -> PopupSurface?
///|
/// Returns true when the widget's visuals changed and a redraw is needed.
declare pub fn on_event(target : Surface, event : @types.InputEvent) -> Bool
Loaded 100 of 875 files, more files were not shown because too many files have changed in this diff. Show more