diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..54e07e1 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,50 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 30 + # Node (jco host + tests) and a recent glibc (the moon toolchain is dynamically linked). + container: node:20-bookworm + steps: + - name: Checkout + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + # The job container has git but no actions runtime assumptions; fetch the commit directly. + git init -q . + git -c http.extraHeader="Authorization: Basic $(printf 'x-access-token:%s' "$GITHUB_TOKEN" | base64 -w0)" \ + fetch -q --depth 1 "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git" "${GITHUB_SHA}" + git checkout -q --detach FETCH_HEAD + + - name: Install MoonBit + run: | + curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash + echo "$HOME/.moon/bin" >> "$GITHUB_PATH" + + - name: Install wasm-tools, wit-bindgen, wasmtime + run: scripts/setup-toolchain.sh + + - name: Install host dependencies (jco) + run: cd host && npm ci + + - name: Versions + run: | + export PATH="$HOME/.moon/bin:$PWD/.tools/bin:$PATH" + moon version; wasm-tools --version; wit-bindgen --version; wasmtime --version + node --version; host/node_modules/.bin/jco --version + + - name: Verify (bindings fresh, moon check/test, build, conformance, host tests) + run: | + export PATH="$HOME/.moon/bin:$PWD/.tools/bin:$PATH" + scripts/test.sh + + - name: Headless render of the composed desktop + run: | + node host/src/cli.mjs --time 2026-11-24T14:07:00 --click-launcher | tail -n 45 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/README.md b/README.md index 47f03f6..43d2a78 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,90 @@ # moon-plasma -A modular KDE Plasma-like desktop shell in MoonBit where every part is a WebAssembly component \ No newline at end of file +A modular, KDE-Plasma-inspired desktop environment where **every part is a +WebAssembly component** (Component Model, WIT interfaces) written in +[MoonBit](https://www.moonbitlang.com), on top of a deliberately tiny trusted host. + +![launcher open](docs/screenshots/m0-2-launcher-open.png) + +*Headless-Chromium capture of the M0 browser host: the shell, the launcher and the clock +are three separate MoonBit components.* + +## Vision + +Plasma's strength is its decomposition (shell, widgets, window manager, runner, +settings modules, notifications, tray). moon-plasma keeps that decomposition and +makes each seam a **typed WIT interface** with **deny-by-default capabilities**: + +* the **host** only owns engine/lifecycle, devices, the capability broker and the + render-list rasteriser; +* **everything else is a component**: swap the clock for another implementation, + swap the whole shell, change the theme, without rebuilding the rest; +* components draw by returning a **render-list** (`list`), never pixels; +* components can't touch anything their imports + the desktop config don't grant. + +Read [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) (Plasma→component mapping, host +decision, rendering, input, permissions, versioning, roadmap M0–M8) and +[docs/TOOLCHAIN.md](docs/TOOLCHAIN.md) (what works today, exact versions). + +## Status: M0 (proof of concept) + +Works today: + +* WIT package `moonplasma:desktop@0.1.0` (`wit/`): worlds `widget`, `clock-widget`, + `launcher-widget`, `panel`, `shell`. +* Four MoonBit components, each an independently built `.wasm` component of 24–33 KB: + `clock-digital`, `clock-binary` (drop-in replacement), `launcher` (kickoff-like with + keyboard search), `shell` (desktop background + bottom panel layout + theme tokens). +* 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, +notifications, settings, tray, session, shortcuts, clipboard, files; `launch` only logs; +host does input hit-testing; fixed-advance text metrics, no real fonts/icons; native +wasmtime host is M3; no CPU/fuel limits under jco. + +## Quickstart + +Requirements: Linux x86_64, Node ≥ 20, [MoonBit](https://www.moonbitlang.com/download). + +```bash +export PATH="$HOME/.moon/bin:$PATH" +scripts/setup-toolchain.sh # wasm-tools, wit-bindgen, wasmtime -> ./.tools (no root) +(cd host && npm ci) # jco +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 +node host/serve.mjs 8080 # browser host: http://127.0.0.1:8080/ +node host/serve.mjs & # then try ?config=desktop.binary-clock.json or ?theme=moon-day +``` + +Swap the clock **without rebuilding anything else**: + +```bash +node host/src/cli.mjs --config config/desktop.binary-clock.json +scripts/build.sh clock-binary # builds just that component +# in the browser console: await moonPlasma.swap('clock', 'clock-binary') +``` + +Screenshots: see the end of [docs/TOOLCHAIN.md](docs/TOOLCHAIN.md). + +## Layout + +``` +wit/ the WIT package (host-agnostic API) +interface/ world/ generated shared MoonBit bindings (wit-bindgen; committed) +components//gen/ generated export bindings + hand-written thin stub.mbt +lib/ pure, unit-tested logic (ui helpers, panel layout, launcher state machine, ...) +host/ JS host: src/desktop.mjs (core), loaders, renderers, tests, web/ (browser) +config/ desktop configs (grants!), themes, static app list +scripts/ setup-toolchain, gen-bindings, build, test, screenshot +docs/ ARCHITECTURE, TOOLCHAIN, screenshots +``` + +## License + +Apache-2.0 (see LICENSE). diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..9967510 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,277 @@ +# moon-plasma architecture + +> Status legend used throughout: **[M0]** implemented in this repository today, +> **[designed]** interface sketched here but not in `wit/` yet, **[open]** needs a decision. + +moon-plasma is a KDE-Plasma-like desktop in which **every part is a WebAssembly +component** (Component Model, WIT-defined interfaces, written in MoonBit) running +on top of a deliberately tiny trusted **host**. The point is not to clone Plasma +pixel for pixel; it is to take Plasma's *decomposition* (shell / window manager / +runner / settings / notifications / tray / session …) and make each seam a typed, +versioned, permission-checked, hot-swappable interface. + +## 1. Plasma → component-model map + +| Plasma piece | What it does | moon-plasma counterpart | Component or host? | +|---|---|---|---| +| `plasmashell` (containments, panels) | Hosts the desktop & panels, loads plasmoids | `shell` component exporting `desktop-surface` + `panel-layout` **[M0]** | component | +| Plasmoids / widgets (QML + C++/JS) | Clock, task manager, kickoff… | `widget` world exporting `plasmoid` **[M0]**: `digital-clock`, `binary-clock`, `launcher` | component, one instance per widget | +| Plasma Look-and-Feel, colour schemes, Breeze, Kirigami theme | Design tokens, icons, cursors, fonts | `theme` interface (`tokens`) **[M0]**; icon/cursor/font interfaces **[designed]**; a "look-and-feel" bundle = theme tokens + default layout + wallpaper | tokens served by a `theme-provider` component (M0: static JSON in host) | +| KWin (WM policy: stacking, focus, tiling, rules, virtual desktops) | Decides where windows go | `window-manager` world: exports `wm-policy` (place/resize/focus decisions), imports `window-registry` **[designed]** | component | +| KWin (compositing: scene graph, damage, scanout) | Draws windows to screen | Rasteriser/scanout of the **render-list** | **host** (only because it touches GPU/DRM) | +| KWin decorations (Aurorae etc.) | Titlebar/borders | `decoration` interface: returns draw-ops + hit regions for a window state **[designed]** | component | +| KWin effects / scripts | Overview, blur, wobbly… | `effect` interface: declarative per-frame transform of the scene (no raw shaders in M-early) **[designed]** | component (+ host primitives like blur) | +| KRunner / Kickoff search | Query many backends, ranked results | `search-provider` interface (`query(text) → list`, `run(match)`); `runner` component fans out to providers **[designed]**. Launcher widget does substring search locally in M0 | components | +| System Settings + KCM modules | Config UIs per area | `settings-page` interface: a KCM is a component with grants only for its own config groups **[designed]** | components | +| KConfig / kconfig XT | Hierarchical typed config, cascading, immutable keys | `config-store` interface: `group/key → value` variant, change events, layered (system < user < activity) **[designed]** | store in **host** (needs durable FS), policy in components | +| KNotifications / `plasma-workspace` notification server | `org.freedesktop.Notifications`, history, DND | `notifications` interface (apps `notify`), `notification-center` component renders toasts + history **[designed]** | components | +| StatusNotifierItem / system tray | Tray icons + menus from apps | `tray-registry` (items register `tray-item` exports), `system-tray` widget **[designed]** | components | +| `ksmserver` / `startplasma` / systemd integration | Session start, restore, logout | `session` interface (logout, suspend, lock; power events) **[designed]**; **init sequence** = host reads `session.json`, starts a `session-manager` component which starts the rest | host (bootstrap only) + component | +| KGlobalAccel / KWin shortcuts | Global shortcuts | `shortcuts` interface: components register accelerators → action ids; host matches raw key events against the table **[designed]** | table in host (input path), policy in component | +| Activities (`kactivitymanagerd`) | Per-activity layouts/history | `activities` component holding current activity; `config-store` layering keys on it **[designed]** | component | +| KIO / Dolphin | URL-based VFS, file manager | `vfs` interface with URL schemes; `vfs-provider` components (`file`, `trash`, `sftp`…); Dolphin = a component app using `vfs` + `plasmoid`-style render lists **[designed]** | providers: components atop host `fs`/`net` capabilities | +| Klipper | Clipboard manager | `clipboard` interface (read/write typed MIME list; separate read/write grants) **[designed]** | host owns the system clipboard; history = component | +| Powerdevil, solid | Power & hardware | `power`/`devices` interfaces **[designed]** | host (hardware), policy = component | +| KScreen | Output config | `outputs` interface **[designed]** | host (display), UI = KCM component | +| KWallet | Secrets | `secrets` interface; separate trust level **[designed]** | component with a very narrow grant | +| Baloo | File index | `search-provider` over `vfs` **[designed]** | component | +| SDDM | Login | `login` world: a full shell variant that gets `auth` capability **[open]** | component | + +## 2. What is in the host, and nothing else + +The host is the trusted computing base. Rule of thumb: **if it can be expressed as +"a pure function of its inputs + capabilities we hand it", it is a component.** +The host only does what a component *cannot* do by construction: + +1. **Engine & lifecycle** – compile/instantiate components, supervise them + (trap → visible fault + restart policy), enforce resource limits + (fuel/epoch deadlines on wasmtime; **not available under jco** — a looping + component can hang the M0 host, a known limitation), hot-swap instances. +2. **Capability broker** – owns the *only* path from components to the outside + world; wires each instance with exactly the interface implementations it is + granted (§6). +3. **Device ownership** – display/DRM/GPU, input devices (libinput), audio, + network sockets, real filesystem, clipboard, D-Bus/portal bridges. Components + see these only through narrow WIT interfaces. +4. **Render-list rasteriser / scanout** – turns the composed render-list into + pixels (Canvas2D in M0). It interprets a *closed vocabulary* of draw-ops; it + has no policy. +5. **Input demux & delivery** – reads raw events, applies the shortcut table, + delivers the rest to the focus/grab target the `window-manager`/shell + component names (§5). +6. **Bootstrap** – reads `session.json` (which components, which grants) and + starts the session-manager component. + +Everything else – panel layout, window placement, focus policy, decorations, +theming, search, notifications, settings UIs, tray, the launcher – is a component +and can be replaced by a different `.wasm` that implements the same world. + +```mermaid +flowchart TB + subgraph host["host (trusted, small)"] + eng["engine + supervisor + hot-swap"] + cap["capability broker"] + ras["render-list rasteriser / scanout"] + inp["input demux"] + dev["devices: display, input, fs, net, clipboard"] + end + subgraph comps["components (sandboxed, swappable)"] + shell["shell (desktop-surface, panel-layout)"] + wm["window-manager policy"] + w1["widget: clock"] + w2["widget: launcher"] + run["runner + search providers"] + notif["notification-center"] + kcm["settings pages"] + end + comps -- "typed WIT calls\n(host-mediated)" --> host + host -- "render-list" --> ras --> dev + dev -- "raw input" --> inp --> comps + cap --- comps +``` + +## 3. Component-to-component communication: host-mediated calls (decision) + +Options considered: + +| | static composition (`wasm-tools compose`/WAC) | dynamic linking / shared-everything | **host-mediated typed calls (chosen)** | +|---|---|---|---| +| Hot-swap one part | re-link and restart the composite | not available in toolchains yet | swap one instance; others keep state | +| Per-link capability attenuation | none (composed = same trust) | none | yes: each instance gets its own import wiring | +| Fault isolation | one trap kills the composite | n/a | per-instance | +| Third-party/untrusted widgets | no | no | yes | +| Cost | none (direct calls) | none | host call per hop (JS: ~µs; fine for UI-rate calls) | +| Maturity today | good (`wac`, `wasm-tools compose`) | immature | works now (what M0 does) | + +**Decision:** components never call each other directly. The host holds the +instances and routes: today it is hub-and-spoke (host → shell for layout, host → +widget for render/events, as in `host/src/desktop.mjs`), later through a +**service registry**: a component *exports* a typed interface (e.g. +`search-provider`), the host lets *importers* with the matching grant call it, +via a host-owned `registry` interface (`lookup(interface-name) → handle`). +Messages stay typed WIT values (records/variants); no stringly-typed JSON bus. +Event broadcast (theme changed, activity changed) is a `subscribe/poll` pair +until component-model async (WASI p3) is usable in our hosts. + +Static composition remains available as a **build-time optimisation inside one +trust domain** (e.g. fusing `shell` with a built-in tray into one `.wasm`), never +across grants. + +## 4. Rendering: shared render-list, not per-component textures (decision) + +Components return **render-lists** (`list`, see `wit/types.wit`) in +their own local coordinates; the host/compositor translates, clips, orders and +rasterises them. Components never receive pixels or GPU handles. + +Why: it is sandbox-friendly (no shared memory, nothing to leak or overrun), +serialisable (record/replay, remote desktop, golden-file tests — the ASCII and +scene-JSON dumps in M0 are exactly this), host-agnostic (Canvas2D now, +Skia/wgpu/software later, all from the same WIT), and cheap for UI-sized scenes. + +Costs and mitigations: (a) copying lists across the boundary each frame → +add a revision counter and let `render` return "unchanged" so the host reuses the +cached list; add damage rects; (b) text needs metrics → M0 uses a fixed 0.6 em +advance contract; a host `text` interface (`measure`, shaping, fonts) is the next +step; (c) content that is *not* vector (video, foreign Wayland/X clients, WebGL +canvases) → add a second surface kind: a WIT **resource** `buffer-surface` +(dmabuf/shm handle owned by the host, written by a granted producer) which the +render-list references via a `draw-surface` op **[designed, M5]**. + +The UI toolkit question: components can link any MoonBit library into +themselves. `moon-gpui` (GPUI port) is a natural fit because its scene/geometry/ +colour packages map almost 1:1 onto our draw-op vocabulary; in that arrangement +GPUI runs *inside each component* and its scene is flattened into +`list`. This is **[open]**: `/workspace/moon-gpui` currently only has a +README, so nothing was verified. + +## 5. Input routing + +* The host reads raw device events and (a) matches them against the global + shortcut table, (b) otherwise hands them to the **routing component**: + `window-manager`/`shell` returns the target (surface id, local coordinates, + grab/focus changes). This keeps focus-follows-mouse, click-to-raise, tiling + gestures, etc. as replaceable policy. +* **[M0 shortcut, stated honestly]** the host itself does hit-testing against the + placements the shell returned, and routes: popup > widget under pointer; + pointer-down outside an open popup sends `focus-lost` to the popup owner, then + falls through. Keyboard goes to the popup owner. This is ~60 lines of host code + and is the first thing to move into the shell component (M2). +* Events are values (`input-event` variant), delivered with surface-local + coordinates, so a component never learns screen geometry it was not given. + +## 6. Permission / capability model + +WASI-style, deny-by-default: + +1. A component's **imports are its declared needs.** `scripts/build.sh` records + them in `build/components/.meta.json` (derived from the binary). +2. The **desktop config** (`config/desktop.json`) *grants* capabilities per + component instance. **[M0]** The host refuses to start a component whose + imports are not all granted (`PermissionError`), rejects unknown capability + names, and wires only granted interfaces into the import object. + Tests: `host/test/desktop.test.mjs`. +3. **Attenuation, not just on/off [designed]:** a grant supplies the host's + implementation of the interface *for that instance*: a `vfs` granted to + System Settings is rooted at `~/.config`, the same interface granted to a + file manager is rooted at `$HOME`; `config-store` is scoped to named groups; + `net` carries a host allowlist. +4. **Unforgeable handles:** capabilities that are objects (an open file, a + `buffer-surface`, a notification handle) are WIT `resource`s — a component can + only use handles the host gave it. +5. **User consent [designed]:** requests outside the manifest go to a + `permission-prompt` component (itself heavily restricted); decisions persist in + `config-store`. +6. **Supervision [M0 partial]:** a trapping component becomes a *visible* error + tile + a recorded fault (never swallowed); the CLI exits non-zero when faults + exist. Automatic restart/backoff is **[designed]**. + +## 7. Versioning WIT packages + +* Packages are semver'd (`moonplasma:desktop@0.1.0`). While `0.x`, any minor may + break; components pin the exact package version in their world. +* From `1.0`: **additive-only minors** – new interfaces, new functions, new + worlds, new variant cases at the *end* only when consumers are required to + handle unknown cases. WIT records cannot grow compatibly, so anything likely to + grow (e.g. `plasmoid-info`, `tokens`) should become `record` + `option`/`list` + extension points before 1.0, or be replaced by a new interface version + (`plasmoid@1.1`) that the host serves alongside the old one. +* Split by domain so versions move independently: `moonplasma:desktop` (types, + theme, plasmoid, panel), later `moonplasma:wm`, `moonplasma:search`, + `moonplasma:notify`, `moonplasma:config`, `moonplasma:session`, `moonplasma:vfs`. +* The host advertises the set of interface versions it implements and may + serve N and N-1 side by side via adapters; a component declares what it + targets and fails to load otherwise (no silent downgrade). +* CI gate **[M0]**: every component must pass `wasm-tools component targets + --world wit `; generated bindings must match `wit/` + (`scripts/gen-bindings.sh --check`). Registry publication (OCI/warg) **[open]**. + +## 8. Host strategy (decision and feasibility) + +| Option | What it is | Time-to-pixels | Fits the "everything is a component" goal | Main risks | +|---|---|---|---|---| +| **(a) Browser/Node host with jco** | components transpiled to JS+core wasm; host in JS; Canvas2D now, WebGPU later | **hours — done in M0** | components yes; host = JS runtime (large TCB: browser) | no real windows/devices; JS can't pre-empt a looping component; browser is not a desktop session | +| **(b) Native host embedding wasmtime** | Rust host using `wasmtime::component` + `bindgen!`; software/GPU rendering into a window (winit/SDL) or DRM | days–weeks | best: small native TCB, fuel/epoch limits, real FS/net/devices | host is Rust, not MoonBit; wasmtime's C API cannot instantiate components with host imports as conveniently, so a MoonBit-native host via FFI is **unverified** and probably not worth it | +| **(c) Nested compositor in an existing session** | (b) running as a window/Wayland client first, later a real compositor (smithay) hosting foreign Wayland apps | weeks–months | needed to run real apps | scope; Wayland/EGL/input details | + +**Recommendation:** (a) for M0–M2 (done: it is the fastest way to prove the WIT +design with real MoonBit components), then (b) as the *reference host* in M3–M4 +using the **same WIT and the same build outputs** (the components are standard; +only `host/` changes), then (c) from M5 as the path to real windows. The WIT stays +host-agnostic: nothing in `wit/` mentions JS, a browser or a window system. What +does **not** transfer is `host/src/desktop.mjs`; it is intentionally small +(~200 lines) and is the executable spec for the Rust host. + +## 9. Interface catalogue + +Implemented in `wit/` (package `moonplasma:desktop@0.1.0`): + +| Interface | Purpose | +|---|---| +| `types` | geometry, colour, `draw-op` render-list vocabulary, `input-event`, `datetime`, `app-entry` | +| `theme` | `get-tokens()` – palette + metrics (read per render so theme swaps are live) | +| `plasmoid` (export) | `info`, `render(size)`, `popup`, `on-event(surface, event)` | +| `panel-layout` (export) | `compute-layout`, `render-panel`, `popup-position` | +| `desktop-surface` (export) | `render-background` | +| `clock`, `app-catalog`, `app-launch` (imports) | host capabilities used by the PoC widgets | + +Worlds: `widget` (theme + plasmoid), `clock-widget`, `launcher-widget`, `panel`, `shell`. + +Designed next (no WIT yet): `window-registry`/`wm-policy`/`decoration`, `search-provider`, +`config-store`, `notifications`, `tray-registry`, `shortcuts`, `clipboard`, `session`/`power`, +`vfs`, `activities`, `settings-page`, `registry`, `buffer-surface`, `text`. + +## 10. What is a PoC stub today + +* Host does hit-testing/routing (see §5), time and app list are host-provided statics. +* `app-launch.launch` records the id and logs; it does not start anything. +* Text uses a fixed-advance contract; no font/shaping/icon interfaces (glyph letters stand in for icons). +* No window manager, compositor, notifications, settings, tray, session, shortcuts, clipboard, files. +* Theme is a JSON file read by the host, not a `theme-provider` component. +* No resource limits under jco; no hot reload on file change (swap is an API call). + +## 11. Roadmap + +| M | Goal | Status | +|---|---|---| +| **M0** | Toolchain proof, WIT v0.1 (`widget`/`panel`/`shell`), host (Node+browser), 4 components, tests, CI, swap/theme/permission demos | **done (this PR)** | +| M1 | `config-store` + `theme-provider` component; persisted settings; hot reload of `.wasm` on change; `text` interface (measure/fonts) and icon theme | next | +| M2 | Move input routing + focus policy into the shell/WM component; more widgets (task manager stub, system tray, notifications toasts); `search-provider` + KRunner component | | +| M3 | Native reference host: Rust + wasmtime (`bindgen!`), software rasteriser into a winit window, fuel/epoch limits, restart supervision; CI runs the *same* integration tests against both hosts | | +| M4 | Window-manager world with synthetic windows (no real apps yet): stacking/tiling policies as swappable components, decorations, virtual desktops, activities | | +| M5 | Nested compositor (smithay) hosting real Wayland clients; `buffer-surface` resource; GPU rasteriser | | +| M6 | Settings (KCM-style) framework, notifications daemon bridge (D-Bus portal), tray (SNI bridge), clipboard, power/session | | +| M7 | `vfs` + file manager component; search/indexer; look-and-feel packages | | +| M8 | Standalone session (DRM/KMS + libinput), login manager world, packaging/registry for components | | + +## 12. Open design questions (with recommendations) + +1. **Host language/long-term host** — Rust+wasmtime native host vs trying to keep even the host in MoonBit. *Recommend Rust+wasmtime for M3; revisit MoonBit-native host only if wasmtime's C API gains full component embedding.* +2. **Render-list vs textures** — *Recommend render-list as the default, `buffer-surface` resource only for non-vector content (§4).* +3. **UI toolkit inside components** — adopt `moon-gpui` or a tiny immediate-mode helper (`lib/ui`)? *Recommend `lib/ui` until moon-gpui has a stable scene package and a flatten-to-draw-op adapter, then migrate widget internals; keep the WIT draw-op vocabulary as the stable boundary.* +4. **Text and fonts** — host-provided shaping (`text` interface) vs components bundling a shaper. *Recommend host-provided: layout needs metrics from the same engine that rasterises.* +5. **Async** — wait for WASI p3 async in jco/wasmtime/wit-bindgen-moonbit or keep sync + poll. *Recommend sync + poll through M3; the backend support exists but hosts are not uniformly ready.* +6. **Who owns hit-testing** — move to the shell/WM component at M2 (§5). *Recommend yes, host only for grabs it must enforce (shortcuts, secure attention).* +7. **Config format & ownership** — KConfig-like INI layering vs structured store. *Recommend a typed `config-store` with layered scopes (system/user/activity) and change events; INI import/export as a component.* +8. **Packaging & trust** — signed component bundles with manifests (grants requested, WIT versions targeted) vs bare `.wasm` + config. *Recommend a manifest custom section in the `.wasm` + signature, host shows requested grants; M3+.* +9. **Foreign-app strategy** — nested Wayland (M5) vs only native components. *Recommend nested Wayland; otherwise the desktop is not usable day to day.* +10. **Plasma compatibility** — try to load real plasmoid QML/KPackages? *Recommend no; mimic concepts (containments, plasmoids, KCM, KRunner plugins) but not binary/QML compatibility.* diff --git a/docs/TOOLCHAIN.md b/docs/TOOLCHAIN.md new file mode 100644 index 0000000..45cd441 --- /dev/null +++ b/docs/TOOLCHAIN.md @@ -0,0 +1,124 @@ +# Toolchain: what works today (verified 2026-11-24) + +Everything here was run on x86_64 Linux (glibc 2.43 locally; CI uses +`node:20-bookworm`, glibc 2.36), without root. + +## Verdict + +**MoonBit can produce real WebAssembly Components today**, via the official +`wit-bindgen moonbit` backend plus `wasm-tools component new`. No MoonBit +compiler flag is needed: MoonBit emits a *core* wasm module (linear-memory +`wasm` target) that exports the canonical-ABI symbols `wit-bindgen` generated, +and `wasm-tools` wraps it into a component. + +| Piece | Status | Notes | +|---|---|---| +| `moon build --target wasm` | works | Used for all components (linear memory, own GC/alloc). | +| `moon build --target wasm-gc` | not usable for components | The canonical ABI needs linear memory + `cabi_realloc`; wit-bindgen's MoonBit backend targets `wasm` only (`preferred_target = "wasm"` in the generated `moon.mod`). | +| `wit-bindgen moonbit` (0.63.0) | works | Generates guest bindings: types, imports, `declare pub fn` stubs for exports, `link.exports` config. Handles records, variants, enums, options, results, lists, strings. Resources/async/streams exist in the backend but are **not** used here. | +| `wasm-tools component embed/new` (1.263.0) | works | `--encoding utf16` (MoonBit strings are UTF-16). | +| `wasm-tools component targets` | works | Used as a **WIT conformance test**: asserts each component implements its declared world. | +| `jco transpile` (1.42.0) | works | Component → JS + core wasm. Used for the M0 host. `--instantiation async` lets the host pass a *per-instance* import object, which is how capability grants work. | +| `wasmtime` (51.0.0) | validates/compiles | `wasmtime compile` accepts every component. We do **not** run them under wasmtime yet: a component with host imports needs an embedder (Rust/C-API) to supply them — `wasmtime run` cannot. That is M4. | +| mooncakes packages | see below | Nothing needed at M0. | + +### Pipeline + +``` +wit/*.wit ──wit-bindgen moonbit──▶ interface/ world/ components//gen/ (committed) + │ + stub.mbt (hand-written, thin) → lib/* (pure logic, unit-tested) +moon build --target wasm --release ──▶ _build/.../gen.wasm (core module) +wasm-tools component embed wit --world W --encoding utf16 ─▶ wasm-tools component new ─▶ build/components/.wasm +wasm-tools component targets --world W wit .wasm (conformance) +jco transpile --instantiation async ─▶ build/jco// (host glue) +``` + +Component sizes are 24–33 KB each (release build, no wasm-opt). + +### Workflow details / gotchas found + +* `wit-bindgen moonbit` does **not** write a stub for exported functions in this + version; export packages contain `declare pub fn …` and you implement them in + a `stub.mbt` *in the same package*. We keep `stub.mbt` to adapters only; logic + lives in `lib/*` packages so `moon test` can cover it. +* Using one `--out-dir .` with a distinct `--gen-dir components//gen` per + component makes all components share **one** copy of the imported types + (`interface/…/types`), so `lib/*` helpers work across components. +* Generated helper functions are emitted in nondeterministic order, so + `scripts/gen-bindings.sh --check` compares sorted lines, not bytes. +* `moon.mod.json` is no longer accepted by this moon (0.1.20261119): use `moon.mod`. +* jco strips the `@version` from import keys (`moonplasma:desktop/clock`), and + maps WIT `variant` → `{tag, val}`, `enum` → string, `option` → value/`undefined`, + `result` import returns → `{tag:'ok'|'err', val}` (or throw). +* `moon test` runs on the wasm target through `moonrun`; packages that import the + generated `types` package are testable (the extern "wasm" helpers are only called + at the boundary). +* wit-bindgen 0.63 moonbit emits deprecation warnings under newer moon + (`#deprecated pub extend`); harmless. + +### Packages surveyed on mooncakes.io (for later milestones) + +| Package | Relevance | Backends / caveat | +|---|---|---| +| `mizchi/wit` 0.4.x | WIT parser/resolver in MoonBit | could power an in-MoonBit `moon-plasma` CLI that inspects worlds; not needed at M0 | +| `moonrockz/wit` | WIT scanner/CST/formatter | same | +| `mizchi/wite` 0.11 | component-aware analyzer/optimizer (`wite` can verify a component against WIT, compose WAC) | candidate replacement for `wasm-tools` size/verify steps | +| `moonbitlang/async` | async runtime (native/…); not a component-model async | the component-model async ABI (WASIp3) is in wit-bindgen's backend but out of scope until hosts support it | +| `moonbitlang/core/json` | JSON | core, all backends — for the settings store (M3) | + +The `wasm2elf-mb`, `moonview`, `webby`, `curl-wasm`, `moon-mud` and `moon-gpui` +checkouts on this machine were consulted for conventions only; nothing is +imported from them. (`moon-gpui` currently contains only a README here — the +`docs/PORTING.md` referenced in the task is not present in `/workspace/moon-gpui`.) + +## Exact setup + +```bash +# 1. MoonBit (not installed by our scripts) +curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash # moon 0.1.20261119 +export PATH="$HOME/.moon/bin:$PATH" + +# 2. wasm-tools, wit-bindgen, wasmtime → ./.tools/bin (versions in scripts/versions.env) +scripts/setup-toolchain.sh + +# 3. jco + playwright-core → host/node_modules (Node ≥ 20) +(cd host && npm ci) + +# 4. build every component, then test everything +scripts/build.sh # or: scripts/build.sh clock-binary (one component only) +scripts/test.sh +``` + +Pinned versions: moon 0.1.20261119 (moonc `738607b`), wasm-tools 1.263.0, +wit-bindgen 0.63.0, wasmtime 51.0.0, jco 1.42.0, Node 20/24. + +### Hello-world proof (what `scripts/build.sh` does for `clock-digital`) + +```bash +wit-bindgen moonbit wit --world clock-widget --out-dir . \ + --gen-dir components/clock-digital/gen --project-name moonplasma/desktop --ignore-module-file +moon build --target wasm --release +wasm-tools component embed wit _build/wasm/release/build/components/clock-digital/gen/gen.wasm \ + --world clock-widget --encoding utf16 -o e.wasm +wasm-tools component new e.wasm -o build/components/clock-digital.wasm +wasm-tools component wit build/components/clock-digital.wasm +# world root { import moonplasma:desktop/types@0.1.0; +# import moonplasma:desktop/clock@0.1.0; +# import moonplasma:desktop/theme@0.1.0; +# export moonplasma:desktop/plasmoid@0.1.0; } +jco transpile build/components/clock-digital.wasm -o build/jco/clock-digital --instantiation async +node host/src/cli.mjs --time 2026-11-24T14:07:00 # instantiates all components, prints the desktop +``` + +### Browser screenshots + +`scripts/screenshot.mjs` drives the browser host in headless Chromium through +`playwright-core`. It needs a Chromium **headless shell** binary; locally: + +```bash +export CHROME_PATH=$(ls ~/.cache/ms-playwright/chromium_headless_shell-*/*/chrome-headless-shell) +node scripts/screenshot.mjs docs/screenshots --tag m0 +``` + +(The full `chrome` binary under `chromium-*/` hung on launch in this sandbox; the headless shell works.) +CI does not take screenshots (no browser in the job image); the Node host tests cover the same code path minus Canvas2D. diff --git a/docs/screenshots/m0-1-desktop.png b/docs/screenshots/m0-1-desktop.png new file mode 100644 index 0000000..95b83b5 Binary files /dev/null and b/docs/screenshots/m0-1-desktop.png differ diff --git a/docs/screenshots/m0-2-launcher-open.png b/docs/screenshots/m0-2-launcher-open.png new file mode 100644 index 0000000..6b12d3b Binary files /dev/null and b/docs/screenshots/m0-2-launcher-open.png differ diff --git a/docs/screenshots/m0-3-binary-clock-swapped.png b/docs/screenshots/m0-3-binary-clock-swapped.png new file mode 100644 index 0000000..baa6559 Binary files /dev/null and b/docs/screenshots/m0-3-binary-clock-swapped.png differ diff --git a/docs/screenshots/m0-4-day-theme.png b/docs/screenshots/m0-4-day-theme.png new file mode 100644 index 0000000..a535914 Binary files /dev/null and b/docs/screenshots/m0-4-day-theme.png differ diff --git a/host/serve.mjs b/host/serve.mjs new file mode 100644 index 0000000..7465401 --- /dev/null +++ b/host/serve.mjs @@ -0,0 +1,30 @@ +#!/usr/bin/env node +// Minimal static server for the browser host (serves host/, config/, build/ only). +// node host/serve.mjs [port] (default: $PORT or 8080) +import http from 'node:http'; +import { readFile } from 'node:fs/promises'; +import { join, extname, normalize } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const ROOT = join(fileURLToPath(import.meta.url), '..', '..'); +const MIME = { '.html': 'text/html', '.mjs': 'text/javascript', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm' }; +const ALLOWED = ['host/', 'config/', 'build/']; + +export function serve(port = 0) { + const srv = http.createServer(async (req, res) => { + try { + let p = decodeURIComponent(new URL(req.url, 'http://x').pathname); + if (p === '/') p = '/host/web/index.html'; + const rel = normalize(p).replace(/^\/+/, ''); + if (rel.includes('..') || !ALLOWED.some((a) => rel.startsWith(a)) || rel.startsWith('host/node_modules')) { res.writeHead(404).end('not found'); return; } + const body = await readFile(join(ROOT, rel)); + res.writeHead(200, { 'content-type': MIME[extname(rel)] ?? 'application/octet-stream', 'cache-control': 'no-store' }).end(body); + } catch { res.writeHead(404).end('not found'); } + }); + return new Promise((resolve) => srv.listen(port, '127.0.0.1', () => resolve(srv))); +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const srv = await serve(Number(process.argv[2] ?? process.env.PORT ?? 8080)); + console.log(`moon-plasma host: http://127.0.0.1:${srv.address().port}/`); +} diff --git a/host/src/loader-web.mjs b/host/src/loader-web.mjs new file mode 100644 index 0000000..ff9a2c1 --- /dev/null +++ b/host/src/loader-web.mjs @@ -0,0 +1,16 @@ +/** Loader for browsers: fetches the jco output under /build/. */ +export function webLoader(base) { + return async (name) => { + const r = await fetch(`${base}/build/components/${name}.meta.json`); + if (!r.ok) throw new Error(`cannot load ${name}.meta.json: HTTP ${r.status}`); + const meta = await r.json(); + const dir = `${base}/build/jco/${name}`; + const mod = await import(`${dir}/${name}.js`); + const getCoreModule = async (p) => { + const res = await fetch(`${dir}/${p}`); + if (!res.ok) throw new Error(`cannot fetch ${p}: HTTP ${res.status}`); + return WebAssembly.compile(await res.arrayBuffer()); + }; + return { meta, instantiate: (imports) => mod.instantiate(getCoreModule, imports) }; + }; +} diff --git a/host/web/canvas.mjs b/host/web/canvas.mjs new file mode 100644 index 0000000..9effac7 --- /dev/null +++ b/host/web/canvas.mjs @@ -0,0 +1,50 @@ +// Canvas2D backend: rasterises a render list (draw-ops in screen coordinates). +import { colorCss } from '../src/scene.mjs'; + +function roundRectPath(ctx, r, radius) { + ctx.beginPath(); + const rad = Math.min(radius, r.w / 2, r.h / 2); + if (rad > 0) ctx.roundRect(r.x, r.y, r.w, r.h, rad); else ctx.rect(r.x, r.y, r.w, r.h); +} + +export function paint(ctx, ops, screen) { + ctx.clearRect(0, 0, screen.w, screen.h); + let depth = 0; + for (const op of ops) { + const v = op.val; + switch (op.tag) { + case 'push-clip': + ctx.save(); depth++; + ctx.beginPath(); ctx.rect(v.x, v.y, v.w, v.h); ctx.clip(); + break; + case 'pop-clip': + if (depth === 0) throw new Error('pop-clip without push-clip'); + ctx.restore(); depth--; + break; + case 'fill-rect': + ctx.fillStyle = colorCss(v.color); roundRectPath(ctx, v.rect, v.radius); ctx.fill(); + break; + case 'stroke-rect': + ctx.strokeStyle = colorCss(v.color); ctx.lineWidth = v.width; + roundRectPath(ctx, { x: v.rect.x + 0.5, y: v.rect.y + 0.5, w: v.rect.w - 1, h: v.rect.h - 1 }, v.radius); ctx.stroke(); + break; + case 'line': + ctx.strokeStyle = colorCss(v.color); ctx.lineWidth = v.width; + ctx.beginPath(); ctx.moveTo(v.start.x + 0.5, v.start.y + 0.5); ctx.lineTo(v.end.x + 0.5, v.end.y + 0.5); ctx.stroke(); + break; + case 'circle': + ctx.beginPath(); ctx.arc(v.center.x, v.center.y, v.radius, 0, Math.PI * 2); + if (v.filled) { ctx.fillStyle = colorCss(v.color); ctx.fill(); } + else { ctx.strokeStyle = colorCss(v.color); ctx.lineWidth = 1.5; ctx.stroke(); } + break; + case 'text': + ctx.font = `${v.style.bold ? '600 ' : ''}${v.style.size}px system-ui, "DejaVu Sans", sans-serif`; + ctx.fillStyle = colorCss(v.style.color); + ctx.textAlign = v.style.align; ctx.textBaseline = 'middle'; + ctx.fillText(v.text, v.origin.x, v.origin.y); + break; + default: throw new Error(`unknown draw-op ${op.tag}`); + } + } + if (depth !== 0) throw new Error(`unbalanced clip stack (${depth})`); +} diff --git a/host/web/index.html b/host/web/index.html new file mode 100644 index 0000000..ddf885b --- /dev/null +++ b/host/web/index.html @@ -0,0 +1,17 @@ + + + + + moon-plasma + + + + +
loading components…
+ + + diff --git a/host/web/main.mjs b/host/web/main.mjs new file mode 100644 index 0000000..44077ce --- /dev/null +++ b/host/web/main.mjs @@ -0,0 +1,46 @@ +import { Desktop } from '../src/desktop.mjs'; +import { createPlatform } from '../src/platform.mjs'; +import { tokensFromJson } from '../src/theme.mjs'; +import { webLoader } from '../src/loader-web.mjs'; +import { paint } from './canvas.mjs'; + +const base = new URL('../../', import.meta.url).href.replace(/\/$/, ''); +const q = new URLSearchParams(location.search); +const getJson = async (p) => { + const r = await fetch(`${base}/${p}`); + if (!r.ok) throw new Error(`GET ${p}: HTTP ${r.status}`); + return r.json(); +}; + +const status = document.getElementById('status'); +try { + const config = await getJson(`config/${q.get('config') ?? 'desktop.json'}`); + const apps = await getJson('config/apps.json'); + const tokens = tokensFromJson(await getJson(`config/themes/${q.get('theme') ?? config.theme}.json`)); + const fixed = q.get('time') ? new Date(q.get('time')) : null; + const platform = createPlatform({ apps, tokens, now: fixed ? () => fixed : undefined }); + const desktop = await new Desktop({ config, loader: webLoader(base), platform }).start(); + + const canvas = document.getElementById('screen'); + canvas.width = desktop.screen.w; canvas.height = desktop.screen.h; + const ctx = canvas.getContext('2d'); + const redraw = () => paint(ctx, desktop.frame().ops, desktop.screen); + const pos = (e) => { const r = canvas.getBoundingClientRect(); return [Math.round((e.clientX - r.left) * canvas.width / r.width), Math.round((e.clientY - r.top) * canvas.height / r.height)]; }; + for (const [ev, kind] of [['pointermove', 'move'], ['pointerdown', 'down'], ['pointerup', 'up']]) { + canvas.addEventListener(ev, (e) => { const [x, y] = pos(e); if (desktop.pointer(kind, x, y)) redraw(); }); + } + window.addEventListener('keydown', (e) => { + const k = e.key.length === 1 || ['Backspace', 'Enter', 'Escape'].includes(e.key) ? e.key : null; + if (k && desktop.key(k)) { e.preventDefault(); redraw(); } + }); + redraw(); + if (!fixed) setInterval(redraw, 1000); + status.textContent = `${desktop.widgets.map((w) => `${w.id}=${w.componentName}`).join(' ')} | theme: ${platform.tokens.name}`; + // Handle for automation / the browser console. + window.moonPlasma = { desktop, platform, redraw, swap: async (id, c) => { await desktop.swap(id, c); redraw(); }, ready: true }; +} catch (e) { + status.textContent = `ERROR: ${e.message}`; + status.style.color = '#f66'; + window.moonPlasmaError = String(e.stack ?? e); + throw e; +} diff --git a/scripts/gen-bindings.sh b/scripts/gen-bindings.sh index 88ac10d..0f7460a 100755 --- a/scripts/gen-bindings.sh +++ b/scripts/gen-bindings.sh @@ -5,20 +5,43 @@ # components); each component's export bindings land in components//gen. # The first run also writes moon.pkg for each package; later runs pass # --ignore-stub so hand-edited moon.pkg / stub.mbt files are preserved. -# `scripts/gen-bindings.sh --check` fails if regeneration changes tracked files. +# +# scripts/gen-bindings.sh regenerate in place +# scripts/gen-bindings.sh --check regenerate into a temp dir and fail if the +# committed bindings differ (order-insensitive: +# wit-bindgen 0.63 emits helper fns in varying order) set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT" export PATH="$ROOT/.tools/bin:$PATH" -while read -r name world; do - case "$name" in ''|'#'*) continue;; esac - extra=() - [ -d "components/$name/gen" ] && extra+=(--ignore-stub) - wit-bindgen moonbit wit --world "$world" --out-dir . \ - --gen-dir "components/$name/gen" --project-name moonplasma/desktop \ - --ignore-module-file "${extra[@]}" >/dev/null 2>"$ROOT/.tools/bindgen.log" || { cat "$ROOT/.tools/bindgen.log" >&2; exit 1; } - echo "bindings: $name ($world)" -done < scripts/components.txt +mkdir -p .tools +log="$ROOT/.tools/bindgen.log" + +generate() { # + local out="$1" ignore="$2" name world extra + while read -r name world; do + case "$name" in ''|'#'*) continue;; esac + extra=(); [ "$ignore" = 1 ] && extra+=(--ignore-stub) + wit-bindgen moonbit wit --world "$world" --out-dir "$out" \ + --gen-dir "components/$name/gen" --project-name moonplasma/desktop \ + --ignore-module-file "${extra[@]}" >/dev/null 2>"$log" || { cat "$log" >&2; exit 1; } + done < scripts/components.txt +} + if [ "${1:-}" = "--check" ]; then - git diff --exit-code -- interface world components '*/gen/*' \ - || { echo "error: generated bindings are stale; run scripts/gen-bindings.sh and commit" >&2; exit 1; } + tmp="$(mktemp -d)"; trap 'rm -rf "$tmp"' EXIT + generate "$tmp" 0 + bad=0 + while IFS= read -r f; do + rel="${f#"$tmp"/}" + case "$rel" in */moon.pkg|*/README.md) continue;; esac # hand-edited / docs + if [ ! -f "$rel" ] || ! diff -q <(sort "$f") <(sort "$rel") >/dev/null; then + echo "stale binding: $rel" >&2; bad=1 + fi + done < <(find "$tmp" -type f) + [ "$bad" = 0 ] || { echo "error: bindings differ from wit/; run scripts/gen-bindings.sh and commit" >&2; exit 1; } + echo "bindings up to date" +else + first=0; [ -d components/shell/gen ] || first=1 + generate . $((1 - first)) + echo "bindings regenerated" fi diff --git a/scripts/screenshot.mjs b/scripts/screenshot.mjs new file mode 100644 index 0000000..9fb14cd --- /dev/null +++ b/scripts/screenshot.mjs @@ -0,0 +1,54 @@ +#!/usr/bin/env node +// Drive the browser host with headless Chromium and save PNG screenshots. +// CHROME_PATH=/path/to/chrome node scripts/screenshot.mjs [--tag name] +// Uses playwright-core (devDependency of host/) with an already-installed +// Chromium; nothing is downloaded here. +import { mkdir } from 'node:fs/promises'; +import { join } from 'node:path'; +import { createRequire } from 'node:module'; +import { fileURLToPath } from 'node:url'; +import { serve } from '../host/serve.mjs'; + +const require = createRequire(join(fileURLToPath(import.meta.url), '..', '..', 'host', 'package.json')); +const { chromium } = require('playwright-core'); +const outdir = process.argv[2]; +if (!outdir) { console.error('usage: screenshot.mjs [--tag name]'); process.exit(2); } +const tagI = process.argv.indexOf('--tag'); +const tag = tagI > 0 ? process.argv[tagI + 1] : 'desktop'; +const exe = process.env.CHROME_PATH; +if (!exe) { console.error('error: set CHROME_PATH to a Chromium/Chrome executable'); process.exit(2); } +await mkdir(outdir, { recursive: true }); + +const srv = await serve(0); +const url = `http://127.0.0.1:${srv.address().port}/host/web/index.html`; +const browser = await chromium.launch({ executablePath: exe, args: ['--no-sandbox'] }); +const page = await browser.newPage({ viewport: { width: 1280, height: 748 } }); +const errors = []; +page.on('pageerror', (e) => errors.push(String(e))); +page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); }); +const T = 'time=2026-11-24T14:07:37'; +const shot = async (name, query, steps) => { + await page.goto(`${url}?${T}&${query}`); + await page.waitForFunction(() => window.moonPlasma?.ready || window.moonPlasmaError, null, { timeout: 30000 }); + const err = await page.evaluate(() => window.moonPlasmaError); + if (err) throw new Error(`host failed in browser: ${err}`); + if (steps) await steps(); + const f = join(outdir, `${tag}-${name}.png`); + await page.locator('#screen').screenshot({ path: f }); + console.log(f); +}; +const canvasPoint = async (x, y) => { const b = await page.locator('#screen').boundingBox(); return [b.x + x, b.y + y]; }; +const click = async (x, y) => { const [px, py] = await canvasPoint(x, y); await page.mouse.move(px, py); await page.mouse.down(); await page.mouse.up(); }; + +await shot('1-desktop', 'config=desktop.json'); +await shot('2-launcher-open', 'config=desktop.json', async () => { + await click(60, 700); + await page.keyboard.type('s'); + const [px, py] = await canvasPoint(100, 450); await page.mouse.move(px, py); +}); +await shot('3-binary-clock-swapped', 'config=desktop.json', async () => { + await page.evaluate(() => window.moonPlasma.swap('clock', 'clock-binary')); +}); +await shot('4-day-theme', 'config=desktop.json&theme=moon-day', async () => { await click(60, 700); }); +await browser.close(); srv.close(); +if (errors.length) { console.error('browser errors:\n' + errors.join('\n')); process.exit(1); } diff --git a/scripts/test.sh b/scripts/test.sh new file mode 100755 index 0000000..8f15a27 --- /dev/null +++ b/scripts/test.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Full verification, identical to CI: +# WIT parses -> bindings are fresh -> moon check/test (pure logic) -> +# build all components -> conformance -> host integration tests. +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT" +export PATH="$ROOT/.tools/bin:$HOME/.moon/bin:$PATH" +step() { printf '\n== %s\n' "$*"; } + +step "bindings are in sync with wit/" +scripts/gen-bindings.sh --check + +step "moon check" +moon check + +step "moon test (pure logic, wasm target)" +moon test + +step "build components" +scripts/build.sh + +if command -v wasmtime >/dev/null; then + step "wasmtime accepts every component (compile only; hosts supply the imports)" + for f in build/components/*.wasm; do + wasmtime compile "$f" -o "$(mktemp -u).cwasm" >/dev/null && echo " ok $(basename "$f")" + done +fi + +step "host integration tests (jco + Node)" +(cd host && npm test)