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
This commit is contained in:
Claude committed 2026-11-26 00:30:32 +00:00
1 parent 30f5e88639
commit 0f71779819
79 files changed
+4579 -101

No files matched your search

+9 -2
View File
@@ -156,7 +156,7 @@ a recording shortcut again to stop.
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 (wallpapers), Panel (add, remove and replace modules), Power (screen off and
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
@@ -165,6 +165,13 @@ a recording shortcut again to stop.
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. Two ship: **Icon Desktop** (app
icons you click to launch and drag to arrange, positions remembered) and **Live Starfield** (an
animated starfield you steer with the pointer). 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.
@@ -178,7 +185,7 @@ keep pixels on the host rather than copying them through the component.
* `~/.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`), and the
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`.
+118
View File
@@ -0,0 +1,118 @@
// 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 wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
@plasmoid.wasmExportOnEvent(p0, p1, p2, p3)
}
///|
#doc(hidden)
pub fn wasmExportInfo() -> Int {
@plasmoid.wasmExportInfo()
}
///|
#doc(hidden)
pub fn wasmExportTick(p0 : Int) -> Int {
@desktop-module.wasmExportTick(p0)
}
///|
#doc(hidden)
pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportInfoPostReturn(p0)
}
///|
#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)
}
///|
#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 wasmExportPopup() -> Int {
@plasmoid.wasmExportPopup()
}
///|
#doc(hidden)
pub fn wasmExportBackdrop() -> Int {
@desktop-module.wasmExportBackdrop()
}
///|
#doc(hidden)
pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportPopupPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportOnScroll(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
@desktop-module.wasmExportOnScroll(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)
}
@@ -0,0 +1,19 @@
Optional export that turns a module into a desktop module: instead of a box in the panel it
owns the desktop itself, the whole output behind the windows (see docs/desktop-modules.md).
A desktop module is still a plasmoid (it exports `plasmoid` as well, and may export
`module-config` and import any capability a panel module can), so the same sandbox, draw ops
and capability grants apply. What changes is how the shell drives it:
- `plasmoid.render` is called with the output's full size (and again with the new size when
the output is resized), in desktop coordinates: (0, 0) is the output's top-left corner.
The panel and windows are drawn on top; the module draws the whole area.
- `plasmoid.on-event` gets the pointer (move, press, release, leave) only where no window,
panel, popup or menu covers the desktop, and keys only while the desktop has keyboard focus
(after a click on it, until a window is focused: it then gets `focus-lost`). A right-click
on the empty desktop always opens the shell's desktop menu (module settings, system
settings), never reaches the module.
- `plasmoid.popup` and `plasmoid.info`'s size fields are not used.
- Hidden settings (a `module-config` item with an empty label) are saved by the shell in
state.edn whenever their value changes after an event, and handed back at the next load:
that is how a desktop module keeps state such as icon positions.
@@ -0,0 +1,32 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
#doc(hidden)
pub fn wasmExportBackdrop() -> Int {
let (result) : (WallpaperMode) = backdrop();
let ret = result.ordinal()
return ret
}
///|
#doc(hidden)
pub fn wasmExportOnScroll(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
let (result) : (Bool) = on_scroll(@types.Point::{x : p0, y : p1}, p2, p3);
let ret = (if result { 1 } else { 0 })
return ret
}
///|
#doc(hidden)
pub fn wasmExportTick(p0 : Int) -> Int {
let (result) : (UInt) = tick((p0).reinterpret_as_uint());
let ret = (result).reinterpret_as_int()
return ret
}
@@ -0,0 +1,5 @@
import {
"chandra/desktop/interface/chandra/desktop/types" @types,
}
warnings = "-44"
@@ -0,0 +1,16 @@
///| The icon desktop draws over the wallpaper and only redraws on events: it never animates.
///|
pub fn backdrop() -> WallpaperMode {
OVER_WALLPAPER
}
///|
pub fn on_scroll(_at : @types.Point, _dx : Int, _dy : Int) -> Bool {
false
}
///|
pub fn tick(_now_ms : UInt) -> UInt {
0
}
@@ -0,0 +1,39 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
/// What happens to the wallpaper under the module.
pub(all) enum WallpaperMode {
OVER_WALLPAPER; REPLACE_WALLPAPER
} derive()
///|
pub fn WallpaperMode::ordinal(self : WallpaperMode) -> Int {
match self {
OVER_WALLPAPER => 0
REPLACE_WALLPAPER => 1
}
}
///|
pub fn WallpaperMode::from(self : Int) -> WallpaperMode {
match self {
0 => OVER_WALLPAPER
1 => REPLACE_WALLPAPER
_ => panic()
}
}
///|
/// Read once, right after loading.
declare pub fn backdrop() -> WallpaperMode
///|
/// Wheel or touchpad scroll over the empty desktop at `at`: `dx` / `dy` in pixels (positive:
/// right / down; one wheel notch is about 10). True when the module wants a redraw.
declare pub fn on_scroll(at : @types.Point, dx : Int, dy : Int) -> Bool
///|
/// The animation clock. `now-ms` counts milliseconds from when the module was loaded. It is
/// called once after loading, after every event the module handled, and again when the delay it
/// last returned has passed; the module is redrawn after each call. Return how many ms until the
/// next frame (16 for about 60 frames a second, 33 for 30), or 0 to sleep until the next event:
/// an idle desktop module costs nothing, so return 0 whenever nothing moves. Frames are paused
/// (no calls) while a window covers the whole desktop.
declare pub fn tick(now_ms : UInt) -> UInt
@@ -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_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
///|
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_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)
@@ -0,0 +1,5 @@
import {
"chandra/desktop/lib/icondesk" @logic,
}
warnings = "-44"
@@ -0,0 +1,12 @@
///| The icon desktop's right-click settings (apps shown, icon size) and the hidden `places`
/// setting the shell saves: where each icon was put.
///|
pub fn config_items() -> Array[ConfigItem] {
@logic.state.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.state.set_config(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_load8_u(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load8_u)
///|
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_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)
///|
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_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,10 @@
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/icons" @icons,
"chandra/desktop/lib/icondesk" @logic,
}
warnings = "-44"
@@ -0,0 +1,27 @@
///| The icon desktop's `plasmoid` export: a desktop module (it also exports desktop-module), so
/// `render` gets the whole output. All logic lives in lib/icondesk.
///|
pub fn info() -> PlasmoidInfo {
{ id: "org.chandra.icon-desktop", name: "Icon Desktop", preferred: { w: 0, h: 0 }, min_width: 0, stretch: false }
}
///|
pub fn render(size : @types.Size) -> Array[@types.DrawOp] {
@logic.state.render(@app_catalog.list_apps(), size, @theme.get_tokens(), id => @icons.app_icon(id))
}
///| Desktop modules have no popup.
pub fn popup() -> PopupSurface? {
None
}
///|
pub fn on_event(_target : Surface, event : @types.InputEvent) -> Bool {
let (redraw, action) = @logic.state.handle(@app_catalog.list_apps(), event)
match action {
Launch(id) => ignore(@app_launch.launch(id))
NoAction => ()
}
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
+34
View File
@@ -0,0 +1,34 @@
import {
"chandra/desktop/components/icon-desktop/gen/interface/chandra/desktop/desktop-module" @desktop-module,
"chandra/desktop/components/icon-desktop/gen/interface/chandra/desktop/module-config" @module-config,
"chandra/desktop/components/icon-desktop/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",
"wasmExportBackdrop:chandra:desktop/desktop-module@0.1.0#backdrop",
"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",
"wasmExportOnScroll:chandra:desktop/desktop-module@0.1.0#on-scroll",
"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",
"wasmExportTick:chandra:desktop/desktop-module@0.1.0#tick"
],
},
},
)
@@ -3,9 +3,9 @@
///
/// - Session: the session settings the shell offers (`session-settings.settings`: reopen windows
/// at login, remember window positions, dark mode), each with an on/off switch;
/// - Desktop: what is drawn on the desktop. Today that is the wallpaper (`wallpaper.wallpapers`,
/// the current one ticked); modules can't be placed on the desktop yet, so when they can they
/// get their own section here;
/// - Desktop: what fills the desktop (`wallpaper.desktops`: the wallpaper alone, the clock card,
/// or an installed desktop module, see docs/desktop-modules.md) and the wallpaper
/// (`wallpaper.wallpapers`), the current one of each ticked;
/// - Panel: the modules in the panel in panel order (left to right), each with move-up/down and
/// remove buttons; then the modules that can be added, grouped by kind with a short description
/// and an Add button (a module already in the panel is left out unless more than one makes
@@ -68,6 +68,8 @@ enum Row {
Heading(String)
Setting(Int, String)
Wallpaper(Int, String)
/// What fills the desktop: wallpaper only, the clock card, or a desktop module.
DesktopChoice(Int, String)
/// A group of modules in the Add list ("Clocks").
Category(String)
/// A loaded panel instance: slot, name, its place in the panel and how many there are.
@@ -190,6 +192,11 @@ fn rows() -> Array[Row] {
}
}
1 => {
rs.push(Heading("On the desktop"))
let desks = @wallpaper.desktops()
for i = 0; i < desks.length(); i = i + 1 {
rs.push(DesktopChoice(i, desks[i]))
}
rs.push(Heading("Wallpaper"))
let names = @wallpaper.wallpapers()
for i = 0; i < names.length(); i = i + 1 {
@@ -469,6 +476,7 @@ fn act(rs : Array[Row], i : Int, btn~ : Int = -1, x~ : Int = 0) -> Unit {
@settings.set_setting(idx, !@settings.is_on(idx))
}
Wallpaper(k, _) => @wallpaper.set_wallpaper(k.reinterpret_as_uint())
DesktopChoice(k, _) => @wallpaper.set_desktop(k.reinterpret_as_uint())
Loaded(slot, _, idx, n) =>
match btn {
0 => if idx > 0 { @modules.move_instance(slot, -1) }
@@ -581,6 +589,7 @@ pub fn popup() -> PopupSurface? {
}
ops.push(@ui.line(margin, rows_top - 3, w - margin, rows_top - 3, p.border, width=1))
let cur_wall = @wallpaper.current_wallpaper().reinterpret_as_int()
let cur_desk = if tab.val == 1 { @wallpaper.current_desktop().reinterpret_as_int() } else { -1 }
for i = 0; i < rs.length(); i = i + 1 {
let y = tops[i]
let rh = row_height(rs[i])
@@ -620,6 +629,13 @@ pub fn popup() -> PopupSurface? {
ops.push(@ui.circle(sx + switch_h / 2, mid, knob, p.foreground_muted))
}
}
DesktopChoice(k, name) => {
if k == cur_desk {
ops.push(@ui.line(margin + 8, mid, margin + 11, mid + 4, list_fg, width=2))
ops.push(@ui.line(margin + 11, mid + 4, margin + 18, mid - 4, list_fg, width=2))
}
ops.push(@ui.text(margin + 26, mid, name, fs - 1, list_fg, bold=k == cur_desk))
}
Wallpaper(k, name) => {
if k == cur_wall {
// A tick: two strokes.
+118
View File
@@ -0,0 +1,118 @@
// 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 wasmExportBackdrop() -> Int {
@desktop-module.wasmExportBackdrop()
}
///|
#doc(hidden)
pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportPopupPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportConfigItems() -> Int {
@module-config.wasmExportConfigItems()
}
///|
#doc(hidden)
pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportInfoPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
@plasmoid.wasmExportOnEvent(p0, p1, p2, p3)
}
///|
#doc(hidden)
pub fn wasmExportConfigItemsPostReturn(p0 : Int) -> Unit {
@module-config.wasmExportConfigItemsPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportPopup() -> Int {
@plasmoid.wasmExportPopup()
}
///|
#doc(hidden)
pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int {
@plasmoid.wasmExportRender(p0, p1)
}
///|
#doc(hidden)
pub fn wasmExportTick(p0 : Int) -> Int {
@desktop-module.wasmExportTick(p0)
}
///|
#doc(hidden)
pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportRenderPostReturn(p0)
}
///|
#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 wasmExportOnScroll(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
@desktop-module.wasmExportOnScroll(p0, p1, p2, p3)
}
@@ -0,0 +1,19 @@
Optional export that turns a module into a desktop module: instead of a box in the panel it
owns the desktop itself, the whole output behind the windows (see docs/desktop-modules.md).
A desktop module is still a plasmoid (it exports `plasmoid` as well, and may export
`module-config` and import any capability a panel module can), so the same sandbox, draw ops
and capability grants apply. What changes is how the shell drives it:
- `plasmoid.render` is called with the output's full size (and again with the new size when
the output is resized), in desktop coordinates: (0, 0) is the output's top-left corner.
The panel and windows are drawn on top; the module draws the whole area.
- `plasmoid.on-event` gets the pointer (move, press, release, leave) only where no window,
panel, popup or menu covers the desktop, and keys only while the desktop has keyboard focus
(after a click on it, until a window is focused: it then gets `focus-lost`). A right-click
on the empty desktop always opens the shell's desktop menu (module settings, system
settings), never reaches the module.
- `plasmoid.popup` and `plasmoid.info`'s size fields are not used.
- Hidden settings (a `module-config` item with an empty label) are saved by the shell in
state.edn whenever their value changes after an event, and handed back at the next load:
that is how a desktop module keeps state such as icon positions.
@@ -0,0 +1,32 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
#doc(hidden)
pub fn wasmExportBackdrop() -> Int {
let (result) : (WallpaperMode) = backdrop();
let ret = result.ordinal()
return ret
}
///|
#doc(hidden)
pub fn wasmExportOnScroll(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
let (result) : (Bool) = on_scroll(@types.Point::{x : p0, y : p1}, p2, p3);
let ret = (if result { 1 } else { 0 })
return ret
}
///|
#doc(hidden)
pub fn wasmExportTick(p0 : Int) -> Int {
let (result) : (UInt) = tick((p0).reinterpret_as_uint());
let ret = (result).reinterpret_as_int()
return ret
}
@@ -0,0 +1,6 @@
import {
"chandra/desktop/interface/chandra/desktop/types" @types,
"chandra/desktop/lib/starfield" @logic,
}
warnings = "-44"
@@ -0,0 +1,16 @@
///| The starfield replaces the wallpaper and animates at 30 frames a second while anything moves.
///|
pub fn backdrop() -> WallpaperMode {
REPLACE_WALLPAPER
}
///|
pub fn on_scroll(_at : @types.Point, _dx : Int, dy : Int) -> Bool {
@logic.state.scroll(dy)
}
///|
pub fn tick(now_ms : UInt) -> UInt {
@logic.state.tick(now_ms)
}
@@ -0,0 +1,39 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
/// What happens to the wallpaper under the module.
pub(all) enum WallpaperMode {
OVER_WALLPAPER; REPLACE_WALLPAPER
} derive()
///|
pub fn WallpaperMode::ordinal(self : WallpaperMode) -> Int {
match self {
OVER_WALLPAPER => 0
REPLACE_WALLPAPER => 1
}
}
///|
pub fn WallpaperMode::from(self : Int) -> WallpaperMode {
match self {
0 => OVER_WALLPAPER
1 => REPLACE_WALLPAPER
_ => panic()
}
}
///|
/// Read once, right after loading.
declare pub fn backdrop() -> WallpaperMode
///|
/// Wheel or touchpad scroll over the empty desktop at `at`: `dx` / `dy` in pixels (positive:
/// right / down; one wheel notch is about 10). True when the module wants a redraw.
declare pub fn on_scroll(at : @types.Point, dx : Int, dy : Int) -> Bool
///|
/// The animation clock. `now-ms` counts milliseconds from when the module was loaded. It is
/// called once after loading, after every event the module handled, and again when the delay it
/// last returned has passed; the module is redrawn after each call. Return how many ms until the
/// next frame (16 for about 60 frames a second, 33 for 30), or 0 to sleep until the next event:
/// an idle desktop module costs nothing, so return 0 whenever nothing moves. Frames are paused
/// (no calls) while a window covers the whole desktop.
declare pub fn tick(now_ms : UInt) -> UInt
@@ -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)
///|
#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_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_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/starfield" @logic,
}
warnings = "-44"
@@ -0,0 +1,11 @@
///| The starfield's right-click settings: speed, how many stars, moving or still.
///|
pub fn config_items() -> Array[ConfigItem] {
@logic.state.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.state.set_config(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_store8(offset : Int, value : Int) =
#|(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)
///|
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_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
@@ -0,0 +1,7 @@
import {
"chandra/desktop/interface/chandra/desktop/types" @types,
"chandra/desktop/interface/chandra/desktop/theme" @theme,
"chandra/desktop/lib/starfield" @logic,
}
warnings = "-44"
@@ -0,0 +1,22 @@
///| The starfield's `plasmoid` export: a desktop module (it also exports desktop-module), so
/// `render` gets the whole output. All logic lives in lib/starfield.
///|
pub fn info() -> PlasmoidInfo {
{ id: "org.chandra.starfield", name: "Live Starfield", preferred: { w: 0, h: 0 }, min_width: 0, stretch: false }
}
///|
pub fn render(size : @types.Size) -> Array[@types.DrawOp] {
@logic.state.render(size, @theme.get_tokens())
}
///| Desktop modules have no popup.
pub fn popup() -> PopupSurface? {
None
}
///|
pub fn on_event(_target : Surface, event : @types.InputEvent) -> Bool {
@logic.state.handle(event)
}
@@ -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
+34
View File
@@ -0,0 +1,34 @@
import {
"chandra/desktop/components/starfield/gen/interface/chandra/desktop/desktop-module" @desktop-module,
"chandra/desktop/components/starfield/gen/interface/chandra/desktop/module-config" @module-config,
"chandra/desktop/components/starfield/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",
"wasmExportBackdrop:chandra:desktop/desktop-module@0.1.0#backdrop",
"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",
"wasmExportOnScroll:chandra:desktop/desktop-module@0.1.0#on-scroll",
"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",
"wasmExportTick:chandra:desktop/desktop-module@0.1.0#tick"
],
},
},
)
+2 -2
View File
@@ -276,7 +276,7 @@ pub fn run(args : Array[String]) -> Int {
fds.push(pfd)
}
fds.append(comp.auth_fds()) // polkit asking for a password, and its helper
ignore(@sys.wait_readable(fds, idle.timeout()))
ignore(@sys.wait_readable(fds, comp.wake_timeout(idle.timeout())))
} else {
// Sleep out what is left of the frame budget (8 ms), not a fixed 8 ms on top of the work.
let spent = (@sys.monotonic_ms() - f0).to_int()
@@ -379,7 +379,7 @@ pub fn run(args : Array[String]) -> Int {
let spent = (@sys.monotonic_ms() - f0).to_int()
@sys.sleep_ms(if spent >= 16 { 1 } else { 16 - spent })
} else {
ignore(@sys.wait_readable(wait_fds, idle.timeout()))
ignore(@sys.wait_readable(wait_fds, comp.wake_timeout(idle.timeout())))
}
}
comp.save_session() // what is open now is reopened at the next start
+96 -3
View File
@@ -644,6 +644,37 @@ pub fn ChandraCompositor::has_timed_work(self : ChandraCompositor) -> Bool {
self.shell.animating()
}
///| How long an idle main loop may sleep: `idle_ms` (until the wall clock's next second), or
/// less when a desktop module's next animation frame is due sooner.
pub fn ChandraCompositor::wake_timeout(self : ChandraCompositor, idle_ms : Int) -> Int {
let d = self.shell.desktop_wake_ms(@sys.monotonic_ms())
if d >= 0 && d < idle_ms {
d
} else {
idle_ms
}
}
///| True when a window covers the whole work area (or the output), give or take the tiling gaps:
/// the desktop can't be seen.
fn ChandraCompositor::desktop_covered(self : ChandraCompositor) -> Bool {
let m = 16
let wa = self.work_area
let wa : @wm.Rect = { x: wa.x + m, y: wa.y + m, w: wa.w - 2 * m, h: wa.h - 2 * m }
for wid in self.wm.stacking_order() {
match self.windows.get(wid) {
Some(win) => {
let g = win.geometry
if g.x <= wa.x && g.y <= wa.y && g.x + g.w >= wa.x + wa.w && g.y + g.h >= wa.y + wa.h {
return true
}
}
None => ()
}
}
false
}
///|
pub fn ChandraCompositor::set_layout_mode(
self : ChandraCompositor,
@@ -769,6 +800,9 @@ fn ChandraCompositor::build_scene(
self.shell.win_list = entries
self.shell.screenshot_state = (if self.rec is Some(_) { 1 } else { 0 }) |
(if self.rec_pointer { 2 } else { 0 })
// A window over the whole desktop (maximized, fullscreen, monocle) pauses a desktop module's
// animation: nobody can see it.
self.shell.set_desktop_covered(self.desktop_covered())
let t0 = @sys.monotonic_ms()
let (bg_ops, shell_ops) = self.shell.render(self.output_w, self.output_h, self.theme)
// The overview goes under the panel and the launcher.
@@ -1030,6 +1064,7 @@ fn ChandraCompositor::set_kbd_focus(self : ChandraCompositor, wid : UInt64?) ->
self.kbd_win = wid
match wid {
Some(w) => {
self.shell.desktop_unfocus() // a window has the keyboard now, not the desktop
self.server.keyboard_enter(w)
self.server.keyboard_modifiers(w, self.mods, 0U, 0U, 0U)
}
@@ -1330,6 +1365,12 @@ fn key_name(code : UInt, shift : Bool) -> String {
28U => "Enter"
57U => " "
12U => "-"
13U => if shift { "+" } else { "=" }
15U => "Tab"
103U => "ArrowUp"
108U => "ArrowDown"
105U => "ArrowLeft"
106U => "ArrowRight"
52U => "."
53U => "/"
_ => ""
@@ -1411,8 +1452,16 @@ pub fn ChandraCompositor::handle_input(
}
return
}
if self.shell.desktop_grabbing() {
// A press on the desktop is held (an icon being dragged): the desktop module follows the
// pointer wherever it goes until the release.
self.leave_pointer()
ignore(self.shell.desktop_pointer_move(xi, yi))
return
}
if self.shell.pointer_move(xi, yi) || self.shell.hit(xi, yi) {
self.leave_pointer()
self.shell.desktop_leave()
return
}
match self.split_drag {
@@ -1424,10 +1473,12 @@ pub fn ChandraCompositor::handle_input(
}
if self.handle_at(xi, yi) is Some(_) || self.resize_at(xi, yi) is Some(_) {
self.leave_pointer()
self.shell.desktop_leave()
return
}
match self.window_at(xi, yi) {
Some((wid, true)) =>
Some((wid, true)) => {
self.shell.desktop_leave()
match self.windows.get(wid) {
Some(win) => {
let lx = x - win.geometry.x.to_double()
@@ -1441,7 +1492,16 @@ pub fn ChandraCompositor::handle_input(
}
None => ()
}
_ => self.leave_pointer()
}
Some((_, false)) => {
self.leave_pointer()
self.shell.desktop_leave()
}
None => {
// The empty desktop: a desktop module sees the pointer here.
self.leave_pointer()
ignore(self.shell.desktop_pointer_move(xi, yi))
}
}
}
Scroll(axis, v, discrete) => {
@@ -1488,7 +1548,15 @@ pub fn ChandraCompositor::handle_input(
}
None => ()
}
_ => ()
Some((_, false)) => ()
None =>
if !self.shell.hit(xi, yi) {
// The empty desktop: a desktop module gets the wheel (in pixels; a notch is ~10).
let d = if v != 0.0 { v.to_int() } else { discrete * 10 }
ignore(
self.shell.desktop_scroll(xi, yi, if axis == 1U { d } else { 0 }, if axis == 0U { d } else { 0 }),
)
}
}
}
PointerButton(button, pressed) => {
@@ -1527,6 +1595,10 @@ pub fn ChandraCompositor::handle_input(
self.run_shell_actions()
return
}
if !pressed && self.shell.desktop_release(xi, yi) {
self.run_shell_actions()
return
}
if !pressed && self.split_drag is Some(_) {
self.split_drag = None
return
@@ -1549,6 +1621,11 @@ pub fn ChandraCompositor::handle_input(
if button == 273U && pressed && self.shell.right_click(xi, yi) {
return
}
// Right button on the empty desktop: the desktop menu (module settings, system settings).
if button == 273U && pressed && self.window_at(xi, yi) is None && !self.shell.hit(xi, yi) &&
self.shell.desktop_menu(xi, yi) {
return
}
if pressed {
self.super_solo = false
if button != 273U && self.shell.pointer_down(xi, yi) {
@@ -1593,6 +1670,13 @@ pub fn ChandraCompositor::handle_input(
self.leave_pointer()
return
}
// A left press on the empty desktop: a desktop module gets it, and the keyboard.
if button == 272U && self.window_at(xi, yi) is None && self.shell.desktop_press(xi, yi) {
self.leave_pointer()
self.set_kbd_focus(None)
self.run_shell_actions()
return
}
match self.window_at(xi, yi) {
Some((wid, _)) => {
self.activate_window(wid)
@@ -1642,6 +1726,15 @@ pub fn ChandraCompositor::handle_input(
self.shell.key_down(name)
}
}
} else if self.kbd_win is None && self.shell.desktop_has_focus() {
// The desktop has the keyboard (it was clicked): keys go to the desktop module.
self.super_solo = false
if pressed {
let name = key_name(code, (self.mods & 1U) != 0U)
if name.length() > 0 && self.shell.desktop_key(name) {
self.run_shell_actions()
}
}
} else {
self.super_solo = false
match self.kbd_win {
+300
View File
@@ -0,0 +1,300 @@
///| Desktop modules (wit/desktop.wit, compositor/shell/desktop_module.mbt): a module that fills the
/// desktop behind the windows. Needs the sample modules built: scripts/build-modules.sh.
///| A compositor with a first frame drawn and six made-up apps (so icon positions don't depend on
/// the machine's .desktop files).
fn desk_comp(tag : String, fake_apps? : Bool = true) -> @host.ChandraCompositor {
let socket_path = "/tmp/wayland-moon-desk-" + tag + "-" + @sys.getpid().to_string() + ".sock"
let comp = @host.ChandraCompositor::new(socket_path, @scene.ThemeTokens::moon_night(), 1280, 720).unwrap()
if fake_apps {
comp.shell.apps.clear()
for i = 0; i < 6; i = i + 1 {
comp.shell.apps.push({
id: "app" + i.to_string(),
name: ["Files", "Browser", "Terminal", "Editor", "Mail", "Music"][i],
comment: "",
category: "",
glyph: "",
})
}
comp.shell.apps_dirty = true
}
ignore(comp.compose_frame())
comp
}
///|
fn desk_socket(tag : String) -> String {
"/tmp/wayland-moon-desk-" + tag + "-" + @sys.getpid().to_string() + ".sock"
}
///| Press at (x0, y0), move to (x1, y1) in steps, release there.
fn desk_drag(comp : @host.ChandraCompositor, x0 : Int, y0 : Int, x1 : Int, y1 : Int, t : UInt) -> Unit {
comp.handle_input(@nested.InputEvent::PointerMove(x0.to_double(), y0.to_double()), t)
comp.handle_input(@nested.InputEvent::PointerButton(272U, true), t + 1U)
for k = 1; k <= 4; k = k + 1 {
let x = x0 + (x1 - x0) * k / 4
let y = y0 + (y1 - y0) * k / 4
comp.handle_input(@nested.InputEvent::PointerMove(x.to_double(), y.to_double()), t + 2U + k.reinterpret_as_uint())
}
comp.handle_input(@nested.InputEvent::PointerButton(272U, false), t + 10U)
ignore(comp.compose_frame())
}
///| The value of the desktop module's setting `key` ("" when none).
fn desk_setting(comp : @host.ChandraCompositor, key : String) -> String {
for it in comp.shell.slot_config("desktop") {
if it.key == key {
return it.value
}
}
""
}
///| Whether the desktop module currently draws a focused selection (an outlined icon cell).
fn desk_selection_outlined(comp : @host.ChandraCompositor) -> Bool {
comp.shell.slot_ops("desktop").iter().any(op => op is StrokeRect(_))
}
///|
test "Settings > Desktop lists the desktop modules, and only the desktop takes them" {
let comp = desk_comp("choose")
let mods = comp.shell.desktop_modules()
assert_true(mods.contains(("icon-desktop", "Icon Desktop")))
assert_true(mods.contains(("starfield", "Live Starfield")))
// A desktop module is not a panel module, and the other way round.
assert_true(comp.shell.load_path("build/components/starfield.wasm") is None)
assert_false(comp.shell.set_desktop("launcher"))
assert_eq(comp.shell.desktop_choice(), "clock-card")
assert_true(comp.shell.desktop_module() is None)
// Choose one: it is loaded under the "desktop" slot (chandra-ctl list shows it last).
assert_true(comp.shell.set_desktop("icon-desktop"))
assert_eq(comp.shell.desktop_choice(), "icon-desktop")
let last = comp.shell.loaded_modules().last().unwrap()
assert_eq((last.0, last.1), ("desktop", "icon-desktop"))
// Another replaces it; the wallpaper alone unloads it.
assert_true(comp.shell.set_desktop("starfield"))
assert_eq(comp.shell.desktop_module().unwrap().module_id, "starfield")
assert_true(comp.shell.set_desktop("wallpaper"))
assert_true(comp.shell.desktop_module() is None)
// The built-in clock card can only be dragged while it is on the desktop.
assert_false(comp.shell.desk_hit(1280 - 100, 60))
assert_true(comp.shell.set_desktop("clock-card"))
assert_true(comp.shell.desk_hit(1280 - 100, 60))
}
///|
test "the empty desktop's pointer and keys reach the desktop module" {
let comp = desk_comp("input")
assert_true(comp.shell.set_desktop("icon-desktop"))
ignore(comp.compose_frame())
// Grid cells are 96 px from (20, 20): app0 at (0,0), app1 below it.
click_at(comp, 900, 300, 10U) // empty desktop, no icon there
assert_true(comp.shell.desktop_has_focus())
assert_false(desk_selection_outlined(comp))
// Arrow keys move the selection (drawn outlined while the desktop has the keyboard).
comp.handle_input(@nested.InputEvent::Key(108U, true), 20U) // Down
comp.handle_input(@nested.InputEvent::Key(108U, false), 21U)
ignore(comp.compose_frame())
assert_true(desk_selection_outlined(comp))
// Drag app0 to the cell at column 5, row 2: the arrangement is saved as the hidden setting.
desk_drag(comp, 68, 68, 20 + 5 * 96 + 40, 20 + 2 * 96 + 40, 30U)
assert_true(desk_setting(comp, "places").contains("app0=5,2"))
assert_eq(comp.shell.module_setting("icon-desktop", "places"), Some(desk_setting(comp, "places")))
// The wheel over the empty desktop goes to the module too (the icon desktop ignores it).
comp.handle_input(@nested.InputEvent::PointerMove(900.0, 300.0), 50U)
comp.handle_input(@nested.InputEvent::Scroll(0U, 10.0, 1), 51U)
assert_true(comp.shell.desktop_has_focus())
}
///|
test "windows and the panel win over the desktop module" {
let comp = desk_comp("hit")
assert_true(comp.shell.set_desktop("icon-desktop"))
ignore(comp.compose_frame())
// The panel: a click on a panel module doesn't reach the desktop.
let p = comp.shell.panel_rect
click_at(comp, p.x + p.w / 2, p.y + p.h / 2, 10U)
assert_false(comp.shell.desktop_has_focus())
assert_false(comp.shell.desktop_grabbing())
// A right-click on the panel opens the panel's menu, not the desktop's.
click_at(comp, p.x + p.w - 3, p.y + p.h / 2, 20U, btn=273U)
assert_true(comp.shell.menu_title != "Icon Desktop")
comp.shell.key_down("Escape")
// A window over the desktop (tiled: it fills the work area) takes clicks and keys.
let (_c, _shm, _surf, _xdg, _tl, _deco) = open_and_configure_client(comp, desk_socket("hit"), "Win", "test.win")
ignore(comp.compose_frame())
click_at(comp, 68, 68, 30U) // where app0's icon is, under the window
assert_false(comp.shell.desktop_has_focus())
assert_false(comp.shell.desktop_grabbing())
assert_eq(desk_setting(comp, "places"), "")
// No desktop menu over the window either.
click_at(comp, 68, 68, 40U, btn=273U)
assert_false(comp.shell.menu_open && comp.shell.menu_title == "Icon Desktop")
}
///|
test "a press on the desktop keeps the pointer until the release, even over a window" {
let comp = desk_comp("grab")
assert_true(comp.shell.set_desktop("icon-desktop"))
ignore(comp.compose_frame())
comp.handle_input(@nested.InputEvent::PointerMove(68.0, 68.0), 10U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, true), 11U)
assert_true(comp.shell.desktop_grabbing())
comp.handle_input(@nested.InputEvent::PointerMove(1200.0, 600.0), 12U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 13U)
assert_false(comp.shell.desktop_grabbing())
}
///|
test "right-click on the empty desktop opens the desktop menu" {
let comp = desk_comp("menu")
// No module: just System settings (on the Desktop tab).
click_at(comp, 600, 300, 10U, btn=273U)
assert_true(comp.shell.menu_open)
assert_eq(comp.shell.menu_title, "Desktop")
assert_eq(comp.shell.menu_rows.map(r => r.label), ["System settings..."])
comp.shell.key_down("Escape")
assert_true(comp.shell.set_desktop("starfield"))
click_at(comp, 600, 300, 20U, btn=273U)
assert_eq(comp.shell.menu_title, "Live Starfield")
assert_eq(comp.shell.menu_rows.map(r => r.label), ["Module settings...", "System settings..."])
// It opens at the pointer, not above the panel.
let m = comp.shell.menu_rect
assert_eq((m.x, m.y), (600, 300))
// Module settings: the module's own choices; picking one applies it.
click_at(comp, m.x + 20, m.y + 26 + 14, 30U)
assert_eq(comp.shell.menu_title, "Live Starfield settings")
assert_true(comp.shell.menu_rows.map(r => r.label).contains("Still"))
comp.shell.set_module_setting("desktop", "speed", "Fast")
assert_eq(desk_setting(comp, "speed"), "Fast")
ignore(@sys.write_file_bytes("_build/desktop_menu.png", @renderer.encode_png(comp.compose_frame())))
comp.shell.key_down("Escape")
// System settings opens the settings module on its Desktop tab, listing the choices.
click_at(comp, 600, 300, 40U, btn=273U)
let m = comp.shell.menu_rect
click_at(comp, m.x + 20, m.y + 26 + 28 + 14, 50U)
let slot = comp.shell.slot_of("session-settings")
let texts = comp.shell.slot_popup_texts(slot).map(t => t.0)
assert_true(texts.contains("On the desktop"))
assert_true(texts.contains("Live Starfield"))
assert_true(texts.contains("Icon Desktop"))
assert_true(texts.contains("Clock card"))
}
///|
test "the desktop module is drawn at the output's size, and again after a resize" {
let comp = desk_comp("resize")
assert_true(comp.shell.set_desktop("starfield"))
let f = comp.compose_frame()
assert_eq(comp.shell.desktop_module().unwrap().rect.w, 1280)
// It replaces the wallpaper: deep space in the corner, darker than any wallpaper's.
let dark = fn(px : @scene.Rgba?) {
match px {
Some(c) => c.r.to_int() + c.g.to_int() + c.b.to_int() < 120
None => false
}
}
assert_true(dark(f.pixel(3, 3)))
comp.resize(1600, 900)
let f = comp.compose_frame()
assert_eq(f.width, 1600)
let d = comp.shell.desktop_module().unwrap()
assert_eq((d.rect.w, d.rect.h), (1600, 900))
assert_true(dark(f.pixel(1595, 5)))
match comp.shell.slot_ops("desktop")[0] {
FillRect(r) => assert_eq(r.rect.w, 1600U)
_ => fail("the starfield starts with its background")
}
}
///|
test "a still desktop module lets the main loop sleep; an animated one sets its pace" {
let comp = desk_comp("idle")
assert_true(comp.shell.set_desktop("icon-desktop"))
ignore(comp.compose_frame())
ignore(comp.compose_frame())
// The icon desktop never animates: nothing keeps the loop awake, frames are unchanged.
assert_false(comp.shell.desktop_animating())
assert_false(comp.has_timed_work())
assert_eq(comp.wake_timeout(980), 980)
ignore(comp.compose_frame())
assert_false(comp.frame_changed)
// The starfield asks for a frame every 33 ms: the idle sleep is cut to that, and each due
// frame is a changed one.
assert_true(comp.shell.set_desktop("starfield"))
ignore(comp.compose_frame())
assert_true(comp.shell.desktop_animating())
let t = comp.wake_timeout(980)
assert_true(t >= 0 && t <= 33)
@sys.sleep_ms(40)
ignore(comp.compose_frame())
assert_true(comp.frame_changed)
// Still: it stops asking, and the loop sleeps until the next second again.
comp.shell.set_module_setting("desktop", "motion", "Still")
@sys.sleep_ms(40)
ignore(comp.compose_frame())
ignore(comp.compose_frame())
assert_false(comp.shell.desktop_animating())
assert_eq(comp.wake_timeout(980), 980)
ignore(comp.compose_frame())
assert_false(comp.frame_changed)
// Moving again, but a window covering the desktop pauses it.
comp.shell.set_module_setting("desktop", "motion", "Moving")
assert_true(comp.shell.desktop_animating())
let (_c, _shm, _surf, _xdg, _tl, _deco) = open_and_configure_client(comp, desk_socket("idle"), "Cover", "test.cover")
ignore(comp.compose_frame())
assert_eq(comp.wake_timeout(980), 980)
}
///|
test "reload brings the desktop module back from disk with its settings" {
let comp = desk_comp("reload")
assert_true(comp.shell.set_desktop("starfield"))
comp.shell.set_module_setting("desktop", "speed", "Fast")
let (lines, ok) = comp.shell.reload_modules("starfield")
assert_true(ok)
assert_eq(lines, ["reloaded desktop starfield"])
assert_eq(desk_setting(comp, "speed"), "Fast")
// `reload` with no name reloads it along with the panel; `reload desktop` names it.
let (all, ok) = comp.shell.reload_modules("")
assert_true(ok)
assert_true(all.contains("reloaded desktop starfield"))
assert_eq(comp.shell.reload_modules("desktop").0, ["reloaded desktop starfield"])
assert_eq(comp.shell.desktop_module().unwrap().module_id, "starfield")
}
///|
test "desktop screenshots: icons, starfield, the Desktop tab" {
let comp = desk_comp("shots", fake_apps=false)
assert_true(comp.shell.set_desktop("icon-desktop"))
comp.shell.set_module_setting("desktop", "count", "All")
ignore(comp.compose_frame())
// Hover one icon and select another with the keyboard.
click_at(comp, 900, 300, 10U)
comp.handle_input(@nested.InputEvent::Key(106U, true), 20U) // Right: selects the first
comp.handle_input(@nested.InputEvent::Key(108U, true), 21U) // Down
comp.handle_input(@nested.InputEvent::PointerMove(68.0, 68.0), 22U)
ignore(@sys.write_file_bytes("_build/desktop_icons.png", @renderer.encode_png(comp.compose_frame())))
assert_true(comp.shell.set_desktop("starfield"))
comp.shell.set_module_setting("desktop", "speed", "Normal")
comp.handle_input(@nested.InputEvent::PointerMove(900.0, 250.0), 30U)
for _ in 0..<6 {
@sys.sleep_ms(34)
ignore(comp.compose_frame())
}
ignore(@sys.write_file_bytes("_build/desktop_starfield.png", @renderer.encode_png(comp.compose_frame())))
// Warp pulse: a click streaks the stars.
click_at(comp, 900, 250, 40U)
for _ in 0..<3 {
@sys.sleep_ms(34)
ignore(comp.compose_frame())
}
ignore(@sys.write_file_bytes("_build/desktop_warp.png", @renderer.encode_png(comp.compose_frame())))
assert_true(comp.shell.open_settings(Desktop))
for _ in 0..<10 {
@sys.sleep_ms(40) // the popup slides in
ignore(comp.compose_frame())
}
ignore(@sys.write_file_bytes("_build/desktop_settings.png", @renderer.encode_png(comp.compose_frame())))
}
+12 -3
View File
@@ -1472,13 +1472,20 @@ test "the settings module lists the wallpapers and switches the desktop to the o
let pr = comp.shell.slot_popup_rect(slot)
assert_true(pr.h >= 40 + 6 * 28) // heading and one row per wallpaper below the tab bar
assert_eq(comp.shell.wallpaper_sel, 0)
// The wallpaper rows follow what fills the desktop (wallpaper only, clock card, modules).
let row_y = fn(name : String) {
match comp.shell.slot_popup_texts(slot).iter().find_first(t => t.0 == name) {
Some(t) => pr.y + t.2
None => -1
}
}
// Third wallpaper: Starfield. The list stays open and the backdrop is drawn anew.
let star = click_wallpaper_ops(comp, pr.x + 40, pr.y + 40 + 3 * 28 + 13, 5U)
let star = click_wallpaper_ops(comp, pr.x + 40, row_y("Starfield"), 5U)
assert_eq(comp.shell.wallpaper_sel, 2)
assert_true(star > 0)
assert_true(comp.shell.slot_popup_rect(slot).w > 0)
// Last row: Solid, a single fill. Escape then closes the list.
assert_eq(click_wallpaper_ops(comp, pr.x + 40, pr.y + 40 + 5 * 28 + 13, 10U), 1)
assert_eq(click_wallpaper_ops(comp, pr.x + 40, row_y("Solid"), 10U), 1)
assert_eq(comp.shell.wallpaper_sel, 4)
comp.shell.key_down("Escape")
ignore(comp.compose_frame())
@@ -1682,7 +1689,9 @@ test "open_settings opens the settings module on the tab asked for" {
assert_true(comp.shell.open_settings(Desktop))
ignore(comp.compose_frame())
let pr = comp.shell.slot_popup_rect(slot)
assert_eq(pr.h, 40 + 6 * 28 + 6) // the Wallpaper heading and the five wallpapers
// "On the desktop" and its choices (wallpaper only, clock card, the two desktop modules), then
// the Wallpaper heading and the five wallpapers.
assert_eq(pr.h, 40 + (1 + 4 + 6) * 28 + 6)
assert_true(comp.shell.open_settings(Session))
ignore(comp.compose_frame())
assert_eq(comp.shell.slot_popup_rect(slot).h, 40 + 4 * 28 + 6) // the four settings
+511
View File
@@ -0,0 +1,511 @@
///| Desktop modules (wit/desktop.wit, docs/desktop-modules.md): a wasm module that fills the
/// desktop, the whole output behind the windows, instead of a box in the panel.
///
/// What fills the desktop is one of: the wallpaper alone, the built-in clock card on it (the
/// default), or one installed desktop module, chosen in Settings > Desktop (the `wallpaper`
/// capability's `desktops` / `set-desktop`) and saved in state.edn as `:desktop`. The module is a
/// plasmoid like any panel module (same sandbox, draw ops, capabilities and right-click settings),
/// kept apart from the panel's `widgets` in `desk_mod` under the slot name "desktop".
///
/// The compositor routes input here only where nothing else is: no window, panel, popup or menu
/// (desktop_pointer_move / desktop_press / desktop_release / desktop_scroll), keys only while the
/// desktop has the keyboard (desktop_key), and a right-click on the empty desktop opens the
/// desktop menu (desktop_menu) instead of reaching the module. The module's drawing is cached and
/// redrawn only when it asks (an event returning true, an animation frame, a resize or theme
/// change); animation frames come from its `tick`, and the main loop sleeps until the next one is
/// due (desktop_wake_ms), so a still desktop module costs nothing while idle.
///| The slot name of the desktop module (menus, reload, settings).
pub let desktop_slot : String = "desktop"
///| The `:desktop` choices that aren't modules.
pub let wallpaper_desktop : String = "wallpaper"
///|
pub let clock_card_desktop : String = "clock-card"
///| What fills a fresh session's desktop: the clock card, as before desktop modules.
let default_desktop : String = "clock-card"
///| A module's frame request is capped at this (ms): a module can't put itself to sleep for
/// hours by mistake and miss its own animation.
let max_frame_delay : Int = 10000
///| Is any loaded module (panel or desktop) granted `cap`?
fn DesktopShell::any_cap(self : DesktopShell, cap : String) -> Bool {
self.widgets.iter().any(w => w.has_cap(cap)) ||
(match self.desk_mod {
Some(d) => d.has_cap(cap)
None => false
})
}
///| The desktop module, if one is loaded.
pub fn DesktopShell::desktop_module(self : DesktopShell) -> Widget? {
self.desk_mod
}
///| What fills the desktop now: "wallpaper", "clock-card" or the module's id.
pub fn DesktopShell::desktop_choice(self : DesktopShell) -> String {
self.read_desktop_choice()
self.desk_choice
}
// ---------------------------------------------------------------- choosing and loading
///| Read `:desktop` from state.edn once (with `persist`; else the default stays).
fn DesktopShell::read_desktop_choice(self : DesktopShell) -> Unit {
if self.desk_choice_read {
return
}
self.desk_choice_read = true
if !self.persist {
return
}
match lookup_key(read_state_file(), "desktop") {
Some(Text(s)) if s.length() > 0 => self.desk_choice = s
Some(Keyword(s)) if s.length() > 0 => self.desk_choice = s
_ => ()
}
}
///| Write `:desktop` (keeping every other key); nothing without `persist`. The default is left out.
fn DesktopShell::write_desktop_choice(self : DesktopShell) -> Unit {
if !self.persist {
return
}
let entries : Array[(@edn.Value, @edn.Value)] = []
for e in read_state_file() {
match e.0 {
Keyword("desktop") => ()
_ => entries.push(e)
}
}
if self.desk_choice != default_desktop {
entries.push((@edn.Value::Keyword("desktop"), @edn.Value::Text(self.desk_choice)))
}
write_state_file(entries)
}
///| At boot: load the saved desktop module, if that is the choice. A module that is gone or
/// fails leaves the clock card (the saved choice is kept for when it is back).
fn DesktopShell::boot_desktop(self : DesktopShell) -> Unit {
self.read_desktop_choice()
let c = self.desk_choice
if c == wallpaper_desktop || c == clock_card_desktop || self.desk_mod is Some(_) {
return
}
match self.load_desktop(c) {
Ok(_) => ()
Err(e) => self.say(e)
}
}
///| The desktop modules on the module path: (id, name), in catalog order.
pub fn DesktopShell::desktop_modules(self : DesktopShell) -> Array[(String, String)] {
self.name_catalog()
let out : Array[(String, String)] = []
for e in self.catalog {
if e.desktop {
out.push((e.id, e.name))
}
}
out
}
///| The Desktops table the settings module lists: wallpaper only, the clock card, each module;
/// and which of them is current.
fn DesktopShell::desktop_rows(self : DesktopShell) -> (Array[String], Int) {
let names = ["Wallpaper only", "Clock card"]
let mods = self.desktop_modules()
let choice = self.desktop_choice()
let mut cur = if choice == wallpaper_desktop { 0 } else { 1 }
for i, m in mods {
names.push(m.1)
match self.desk_mod {
Some(d) if d.module_id == m.0 => cur = i + 2
_ => ()
}
}
(names, cur)
}
///|
fn DesktopShell::publish_desktops(self : DesktopShell) -> Unit {
let (names, cur) = self.desktop_rows()
let t = @wasm.Table::new()
for n in names {
t.str(n)
t.end_row()
}
@wasm.publish(Desktops, t)
@wasm.publish_desktop(cur)
}
///| The settings module's `set-desktop`: index into the Desktops table.
fn DesktopShell::set_desktop_index(self : DesktopShell, i : Int) -> Unit {
let mods = self.desktop_modules()
let id = match i {
0 => wallpaper_desktop
1 => clock_card_desktop
_ if i - 2 < mods.length() && i >= 2 => mods[i - 2].0
_ => return
}
ignore(self.set_desktop(id))
}
///| Put `id` on the desktop ("wallpaper", "clock-card", or a desktop module's id or path) and
/// remember it. False, with a notice, when the module can't be loaded (what was there stays).
pub fn DesktopShell::set_desktop(self : DesktopShell, id : String) -> Bool {
self.ensure_booted()
self.read_desktop_choice()
if id == wallpaper_desktop || id == clock_card_desktop {
self.unload_desktop()
} else {
match self.load_desktop(id) {
Ok(w) => self.say("Desktop: " + w.pl.name)
Err(e) => {
self.say(e)
return false
}
}
}
self.desk_choice = id
self.write_desktop_choice()
self.bg_key = None
self.publish_desktops()
true
}
///| Load desktop module `id` (catalog id or path) in place of the current one.
fn DesktopShell::load_desktop(self : DesktopShell, id : String) -> Result[Widget, String] {
let path = match self.find_module(id) {
Some(c) => c.path
None => if id.contains("/") { id } else { return Err("Desktop module '" + id + "' not found") }
}
match @wasm.load(path, self.tokens) {
Err(e) => Err("Can't load desktop module: " + e)
Ok(pl) => {
let backdrop = pl.desktop_backdrop()
if backdrop < 0 {
pl.unload()
return Err(pl.name + " is a panel module, not a desktop module")
}
let known = match self.find_module(stem(path)) {
Some(c) => c.path == path
None => false
}
let w : Widget = {
slot: desktop_slot,
module_id: if known { stem(path) } else { path },
path,
pl,
caps: pl.imports(),
rect: { x: 0, y: 0, w: self.screen_w, h: self.screen_h },
popup_rect: { x: 0, y: 0, w: 0, h: 0 },
popup_ops: [],
popup_hot: false,
slide_t0: 0,
slide_in: false,
ghost_rect: { x: 0, y: 0, w: 0, h: 0 },
ghost_ops: [],
}
self.unload_desktop()
self.desk_mod = Some(w)
self.desk_backdrop = backdrop
self.apply_module_cfg(w)
self.desk_saved.clear()
for it in w.pl.config_items() {
if it.label.length() == 0 {
self.desk_saved.set(it.key, it.value)
}
}
self.desk_t0 = @sys.monotonic_ms()
self.desk_next = 0
self.desk_dirty = true
self.desk_drawn = None
self.bg_key = None
// Its clock starts: the first frame request.
self.desktop_tick(self.desk_t0)
Ok(w)
}
}
}
///| Unload the desktop module (the wallpaper / card shows again).
fn DesktopShell::unload_desktop(self : DesktopShell) -> Unit {
match self.desk_mod {
Some(d) => {
d.pl.unload()
self.desk_mod = None
self.desk_ops = []
self.desk_next = 0
self.desk_focus = false
self.desk_hover = false
self.desk_grab = false
self.desk_drawn = None
self.bg_key = None
if self.menu_slot == desktop_slot {
self.menu_open = false
}
}
None => ()
}
}
///| Reload the desktop module from its file (chandra-ctl reload): settings and hidden state are
/// handed back as at login. On failure the old instance stays.
fn DesktopShell::reload_desktop(self : DesktopShell) -> Result[Widget, String] {
match self.desk_mod {
None => Err("")
Some(old) => {
// Load the new one before dropping the old, so a broken build leaves the desktop as it was.
match @wasm.load(old.path, self.tokens) {
Err(e) => Err("Can't load module: " + e)
Ok(probe) => {
let ok = probe.desktop_backdrop() >= 0
probe.unload()
if !ok {
return Err("not a desktop module any more")
}
let id = if old.module_id.contains("/") { old.path } else { old.module_id }
let path = old.path
self.unload_desktop()
match self.load_desktop(if self.find_module(id) is Some(_) { id } else { path }) {
Ok(w) => Ok(w)
Err(e) => Err(e)
}
}
}
}
}
}
// ---------------------------------------------------------------- drawing and frames
///| Redraw the module's ops when needed: asked for, or the output size or theme changed (the
/// module is told the new size through `render`).
fn DesktopShell::desktop_render(
self : DesktopShell,
w : Int,
h : Int,
theme : @scene.ThemeTokens,
tokens : @theme.Tokens,
) -> Unit {
match self.desk_mod {
None => ()
Some(d) => {
self.desktop_pump(@sys.monotonic_ms())
let same = match self.desk_drawn {
Some((dw, dh, t)) => dw == w && dh == h && t == theme
None => false
}
if same && !self.desk_dirty {
return
}
let out : Array[@scene.DrawOp] = []
translate(d.pl.render(w, h, tokens), 0, 0, out)
self.process_requests()
d.rect = { x: 0, y: 0, w, h }
self.desk_ops = out
self.desk_gen = self.desk_gen + 1
self.desk_dirty = false
self.desk_drawn = Some((w, h, theme))
}
}
}
///| Run the module's clock: ask it when the next frame is due, and whether to redraw.
fn DesktopShell::desktop_tick(self : DesktopShell, now : UInt64) -> Unit {
match self.desk_mod {
None => ()
Some(d) => {
let ms = (now - self.desk_t0).to_int()
let r = d.pl.desktop_tick(ms)
let r = if r > max_frame_delay { max_frame_delay } else { r }
self.desk_next = if r > 0 { now + r.to_uint64() } else { 0 }
}
}
}
///| A due animation frame: tick, then redraw. Frames pause while a window covers the desktop.
fn DesktopShell::desktop_pump(self : DesktopShell, now : UInt64) -> Unit {
if self.desk_next != 0 && now >= self.desk_next && !self.desk_covered {
self.desktop_tick(now)
self.desk_dirty = true
}
}
///| Milliseconds until the desktop module's next animation frame, -1 when none is due (no
/// module, it asked for none, or a window covers the desktop). The main loop's idle sleep is
/// capped by this.
pub fn DesktopShell::desktop_wake_ms(self : DesktopShell, now : UInt64) -> Int {
if self.desk_mod is None || self.desk_next == 0 || self.desk_covered {
-1
} else if now >= self.desk_next {
0
} else {
(self.desk_next - now).to_int()
}
}
///| True while the desktop module is animating (it asked for a frame).
pub fn DesktopShell::desktop_animating(self : DesktopShell) -> Bool {
self.desk_mod is Some(_) && self.desk_next != 0
}
///| Tell the shell whether a window covers the whole desktop (the compositor, every frame).
pub fn DesktopShell::set_desktop_covered(self : DesktopShell, covered : Bool) -> Unit {
self.desk_covered = covered
}
///| After the module handled something: redraw if it asked, restart its clock, and save hidden
/// settings that changed (`save`: on releases and keys, not on every motion).
fn DesktopShell::desktop_changed(self : DesktopShell, redraw : Bool, save? : Bool = false) -> Unit {
if redraw {
self.desk_dirty = true
}
self.desktop_tick(@sys.monotonic_ms())
if save {
self.save_desktop_hidden()
}
}
///| Remember the module's hidden settings (empty label: e.g. where icons were put) that changed.
fn DesktopShell::save_desktop_hidden(self : DesktopShell) -> Unit {
match self.desk_mod {
None => ()
Some(d) =>
for it in d.pl.config_items() {
if it.label.length() == 0 && self.desk_saved.get(it.key) != Some(it.value) {
self.desk_saved.set(it.key, it.value)
self.remember_module_setting(d.module_id, it.key, it.value)
}
}
}
}
///| Deliver one event to the desktop module and carry out its requests.
fn DesktopShell::desktop_event(self : DesktopShell, ev : @wasm.PlasmoidEvent, save? : Bool = false) -> Bool {
match self.desk_mod {
None => false
Some(d) => {
self.publish_host_data()
let redraw = d.pl.on_event(false, ev)
self.process_requests()
self.desktop_changed(redraw, save~)
true
}
}
}
// ---------------------------------------------------------------- input
///| The pointer moved over the empty desktop (no window, panel, popup or menu there). True when
/// a desktop module took it.
pub fn DesktopShell::desktop_pointer_move(self : DesktopShell, x : Int, y : Int) -> Bool {
if self.desk_mod is None {
return false
}
self.desk_hover = true
self.desktop_event(PointerMove(x, y))
}
///| The pointer left the empty desktop (onto a window, the panel ...). While a press on the
/// desktop is held it keeps getting the motion instead (see `desktop_grabbing`).
pub fn DesktopShell::desktop_leave(self : DesktopShell) -> Unit {
if self.desk_hover && !self.desk_grab {
self.desk_hover = false
ignore(self.desktop_event(PointerLeave))
}
}
///| A left press on the empty desktop: the desktop takes the keyboard and the module the press.
/// True when a desktop module took it.
pub fn DesktopShell::desktop_press(self : DesktopShell, x : Int, y : Int) -> Bool {
self.ensure_booted()
if self.desk_mod is None {
return false
}
self.dismiss_popups("")
self.desk_focus = true
self.desk_grab = true
self.desk_hover = true
self.desktop_event(PointerDown(x, y))
}
///| True while a press on the desktop is held: motion and the release go to the module wherever
/// the pointer is.
pub fn DesktopShell::desktop_grabbing(self : DesktopShell) -> Bool {
self.desk_grab && self.desk_mod is Some(_)
}
///| The release of a press that went to the desktop. True when there was one.
pub fn DesktopShell::desktop_release(self : DesktopShell, x : Int, y : Int) -> Bool {
if !self.desk_grab {
return false
}
self.desk_grab = false
ignore(self.desktop_event(PointerUp(x, y), save=true))
true
}
///| Wheel over the empty desktop. True when a desktop module took it.
pub fn DesktopShell::desktop_scroll(self : DesktopShell, x : Int, y : Int, dx : Int, dy : Int) -> Bool {
match self.desk_mod {
None => false
Some(d) => {
self.publish_host_data()
let redraw = d.pl.desktop_scroll(x, y, dx, dy)
self.process_requests()
self.desktop_changed(redraw, save=true)
true
}
}
}
///| Does the desktop have the keyboard (clicked, and no window focused since)?
pub fn DesktopShell::desktop_has_focus(self : DesktopShell) -> Bool {
self.desk_focus && self.desk_mod is Some(_)
}
///| A key for the desktop module (only while it has the keyboard). True when it took it.
pub fn DesktopShell::desktop_key(self : DesktopShell, name : String) -> Bool {
if !self.desktop_has_focus() {
return false
}
self.desktop_event(KeyDown(name), save=true)
}
///| A window took the keyboard: the desktop module hears `focus-lost`.
pub fn DesktopShell::desktop_unfocus(self : DesktopShell) -> Unit {
if self.desk_focus {
self.desk_focus = false
ignore(self.desktop_event(FocusLost))
}
}
///| Right-click on the empty desktop: the desktop menu at the pointer, with the module's settings
/// (when it has any) and System settings on the Desktop tab. Always consumed.
pub fn DesktopShell::desktop_menu(self : DesktopShell, x : Int, y : Int) -> Bool {
self.ensure_booted()
if self.inspect_on {
return false
}
self.dismiss_popups("")
let rows : Array[MenuRow] = []
let title = match self.desk_mod {
Some(d) => {
if config_rows(d.pl.config_items()).length() > 0 {
rows.push(menu_row("Module settings...", 3))
} else {
rows.push(menu_row("No module settings", 5))
}
d.pl.name
}
None => "Desktop"
}
rows.push(menu_row("System settings...", 2, arg="desktop"))
self.open_menu(title, rows, desktop_slot, x, y~)
true
}
+3
View File
@@ -57,6 +57,9 @@ fn DesktopShell::desk_pos(self : DesktopShell) -> (Int, Int) {
///| True if (x, y) is over the desktop card.
pub fn DesktopShell::desk_hit(self : DesktopShell, x : Int, y : Int) -> Bool {
if self.desk_choice != clock_card_desktop || self.desk_mod is Some(_) {
return false // the clock card isn't on the desktop
}
let (cx, cy) = self.desk_pos()
x >= cx && x < cx + desktop_widget_w && y >= cy && y < cy + desktop_widget_h
}
+1 -1
View File
@@ -26,7 +26,7 @@ pub fn DesktopShell::set_network_backend(self : DesktopShell, b : &@network.NetB
///| Refresh and publish network state while a module imports `network`; drop the service (and
/// its bus connection) when none does any more.
fn DesktopShell::publish_network(self : DesktopShell) -> Unit {
if !self.widgets.iter().any(w => w.has_cap("network")) {
if !self.any_cap("network") {
match self.net {
Some(n) if n.probe() => {
n.close()
+85 -5
View File
@@ -197,6 +197,9 @@ pub(all) struct CatalogEntry {
path : String
/// Filled in (by loading the module once) the first time names are needed; "" until then.
mut name : String
/// A desktop module (it exports `desktop-module`): it fills the desktop, not a panel slot.
/// Known once names are (see `name_catalog`).
mut desktop : Bool
}
///| One row of the right-click menu. `kind`: 0 replace with module `arg` (a path), 1 remove,
@@ -359,6 +362,34 @@ pub(all) struct DesktopShell {
/// The launcher module's state as the shell follows it (dock.mbt `follow_launcher`): what its
/// popup lists, for the right-click "Pin to dock" menu.
launcher_state : @launcher.State
/// What fills the desktop (desktop_module.mbt): "wallpaper", "clock-card" or a desktop
/// module's id (or path); saved in state.edn as `:desktop`.
mut desk_choice : String
mut desk_choice_read : Bool
/// The loaded desktop module (slot "desktop"), its backdrop (0 over the wallpaper, 1 instead of
/// it) and when it was loaded (its clock's zero, monotonic ms).
mut desk_mod : Widget?
mut desk_backdrop : Int
mut desk_t0 : UInt64
/// When its next animation frame is due (monotonic ms, 0: none asked for).
mut desk_next : UInt64
/// Its last drawing (desktop coordinates), a counter bumped each time it is redrawn, whether it
/// must be redrawn, and the size and theme it was drawn for.
mut desk_ops : Array[@scene.DrawOp]
mut desk_gen : Int
mut desk_dirty : Bool
mut desk_drawn : (Int, Int, @scene.ThemeTokens)?
/// Input: the desktop has the keyboard (clicked, no window focused since), the pointer is over
/// it, a press on it is held (moves and the release go to it even over a window).
mut desk_focus : Bool
mut desk_hover : Bool
mut desk_grab : Bool
/// A window covers the whole desktop: animation frames pause (the compositor sets it).
mut desk_covered : Bool
/// The module's hidden settings (empty label) as last saved, to save only changes.
desk_saved : Map[String, String]
/// The menu's top edge when it opens at the pointer (the desktop menu); -1 above the panel.
mut menu_anchor_y : Int
}
///|
@@ -469,6 +500,22 @@ pub fn DesktopShell::new(display : String) -> DesktopShell {
wit_cache: {},
recents: [],
launcher_state: @launcher.State::new(),
desk_choice: default_desktop,
desk_choice_read: false,
desk_mod: None,
desk_backdrop: 0,
desk_t0: 0,
desk_next: 0,
desk_ops: [],
desk_gen: 0,
desk_dirty: false,
desk_drawn: None,
desk_focus: false,
desk_hover: false,
desk_grab: false,
desk_covered: false,
desk_saved: {},
menu_anchor_y: -1,
}
sh.order_apps()
sh
@@ -608,6 +655,9 @@ fn DesktopShell::widget_at(self : DesktopShell, x : Int, y : Int) -> Widget? {
///|
fn DesktopShell::widget_by_slot(self : DesktopShell, slot : String) -> Widget? {
if slot == desktop_slot {
return self.desk_mod
}
for w in self.widgets {
if w.slot == slot {
return Some(w)
@@ -920,6 +970,9 @@ struct BgKey {
date : (UInt, Byte, Byte, Byte)
hour : Byte
minute : Byte
/// The desktop module's drawing (`desk_gen`), -1 with the clock card, -2 with the wallpaper
/// alone.
desk : Int
}
///| The wallpaper and the desktop card. Building them costs most of an idle frame (the card's
@@ -932,9 +985,11 @@ fn DesktopShell::background(
theme : @scene.ThemeTokens,
tokens : @theme.Tokens,
) -> Array[@scene.DrawOp] {
let card = self.desk_choice == clock_card_desktop && self.desk_mod is None
let key : BgKey = if card {
let at = now()
let (dx, dy) = self.desk_pos()
let key : BgKey = {
{
w,
h,
theme,
@@ -944,14 +999,39 @@ fn DesktopShell::background(
date: (at.year, at.month, at.day, at.weekday),
hour: at.hour,
minute: at.minute,
desk: -1,
}
} else {
// The wallpaper alone, or under / instead of the desktop module: nothing follows the clock.
self.desktop_render(w, h, theme, tokens)
let replaced = self.desk_mod is Some(_) && self.desk_backdrop == 1
{
w,
h,
theme,
wallpaper: if replaced { -1 } else { self.wallpaper_sel },
x: 0,
y: 0,
date: (0, b'\x00', b'\x00', b'\x00'),
hour: b'\x00',
minute: b'\x00',
desk: if self.desk_mod is Some(_) { self.desk_gen } else { -2 },
}
}
if self.bg_key == Some(key) {
return self.bg_cache
}
let bg : Array[@scene.DrawOp] = []
if key.wallpaper >= 0 {
translate(@libshell.render_wallpaper(@ui.size(w, h), tokens, self.wallpaper_sel), 0, 0, bg)
}
self.wallpaper_len = bg.length()
render_desktop_widget(dx, dy, tokens, at, bg)
if card {
let (dx, dy) = self.desk_pos()
render_desktop_widget(dx, dy, tokens, now(), bg)
} else if self.desk_mod is Some(_) {
bg.append(self.desk_ops)
}
self.bg_cache = bg
self.bg_key = Some(key)
bg
@@ -973,14 +1053,14 @@ pub fn DesktopShell::render(
self.poll_picker()
self.publish_host_data()
// Machine state and the rich window list only matter to modules that import them.
if self.widgets.iter().any(w => w.has_cap("system")) {
if self.any_cap("system") {
self.sampler.refresh() // reads /proc once a second
}
if self.widgets.iter().any(w => w.has_cap("system") || w.has_cap("windows")) {
if self.any_cap("system") || self.any_cap("windows") {
@wasm.set_windows(self.win_list)
}
self.settle_dock_pins()
if self.widgets.iter().any(w => w.has_cap("icons")) {
if self.any_cap("icons") {
self.publish_icons()
}
let bg = self.background(w, h, theme, tokens)
+70 -16
View File
@@ -138,7 +138,7 @@ fn DesktopShell::scan_catalog(self : DesktopShell) -> Unit {
let id = stem(f)
if !seen.contains(id) && !retired_modules.contains(id) {
seen.set(id, true)
self.catalog.push({ id, path: dir + "/" + f, name: "" })
self.catalog.push({ id, path: dir + "/" + f, name: "", desktop: false })
}
}
}
@@ -156,6 +156,7 @@ fn DesktopShell::name_catalog(self : DesktopShell) -> Unit {
match @wasm.load(e.path, self.tokens) {
Ok(pl) => {
e.name = pl.name
e.desktop = pl.desktop_backdrop() >= 0
pl.unload()
keep.push(e)
}
@@ -316,6 +317,7 @@ fn DesktopShell::ensure_booted(self : DesktopShell) -> Unit {
Some(old) if old != entries => write_panel_file(entries)
_ => ()
}
self.boot_desktop()
for e in entries {
let path = if e.has_prefix("/") {
e
@@ -350,6 +352,11 @@ pub fn DesktopShell::load_path(self : DesktopShell, path : String) -> Widget? {
fn DesktopShell::try_load_path(self : DesktopShell, path : String) -> Result[Widget, String] {
match @wasm.load(path, self.tokens) {
Err(e) => Err("Can't load module: " + e)
Ok(pl) if pl.desktop_backdrop() >= 0 => {
// It fills the desktop, not a panel slot: Settings > Desktop puts it there.
pl.unload()
Err(pl.name + " is a desktop module: choose it in Settings > Desktop")
}
Ok(pl) => {
let id = stem(path)
let known = match self.find_module(id) {
@@ -510,6 +517,12 @@ pub fn DesktopShell::reload_modules(self : DesktopShell, name : String) -> (Arra
targets.push((w.slot, w.module_id, w.path))
}
}
// The desktop module too (slot "desktop").
match self.desk_mod {
Some(d) if name == "" || d.module_id == name || stem(d.path) == name || name == desktop_slot || d.path == name =>
targets.push((d.slot, d.module_id, d.path))
_ => ()
}
if targets.length() == 0 {
let msg = if name == "" {
"no modules are loaded"
@@ -523,7 +536,8 @@ pub fn DesktopShell::reload_modules(self : DesktopShell, name : String) -> (Arra
let mut last_err = ""
for t in targets {
let (slot, id, path) = t
match self.replace_slot_result(slot, path) {
let res = if slot == desktop_slot { self.reload_desktop() } else { self.replace_slot_result(slot, path) }
match res {
Ok(nw) => lines.push("reloaded " + nw.slot + " " + id)
Err(e) => {
failed = failed + 1
@@ -551,7 +565,12 @@ pub fn DesktopShell::reload_modules(self : DesktopShell, name : String) -> (Arra
///| The loaded modules in panel order: (slot, module id, path).
pub fn DesktopShell::loaded_modules(self : DesktopShell) -> Array[(String, String, String)] {
self.ensure_booted()
self.widgets.map(w => (w.slot, w.module_id, w.path))
let out = self.widgets.map(w => (w.slot, w.module_id, w.path))
match self.desk_mod {
Some(d) => out.push((d.slot, d.module_id, d.path)) // the desktop module, last
None => ()
}
out
}
///| Unload every module (the compositor is closing).
@@ -560,6 +579,7 @@ pub fn DesktopShell::shutdown(self : DesktopShell) -> Unit {
w.pl.unload()
}
self.widgets.clear()
self.unload_desktop()
}
///| Slot ids of the loaded modules, in panel order.
@@ -652,7 +672,7 @@ fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit {
}
@wasm.publish(Layouts, lt)
@wasm.publish_state(self.layout_sel, self.inspect_on)
if self.widgets.iter().any(w => w.has_cap("wallpaper")) {
if self.any_cap("wallpaper") {
let pt = @wasm.Table::new()
for n in @libshell.wallpaper_names {
pt.str(n)
@@ -660,8 +680,9 @@ fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit {
}
@wasm.publish(Wallpapers, pt)
@wasm.publish_wallpaper(self.wallpaper_sel)
self.publish_desktops()
}
if self.widgets.iter().any(w => w.has_cap("session-settings")) {
if self.any_cap("session-settings") {
let st = @wasm.Table::new()
for n in session_setting_names {
st.str(n)
@@ -670,19 +691,19 @@ fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit {
@wasm.publish(SessionSettings, st)
@wasm.publish_session_settings(self.session_settings_bits())
}
if self.widgets.iter().any(w => w.has_cap("power")) {
if self.any_cap("power") {
@wasm.publish_power(self.screen_off_min, self.suspend_min)
}
if self.widgets.iter().any(w => w.has_cap("shortcuts")) {
if self.any_cap("shortcuts") {
self.publish_shortcuts()
}
if self.widgets.iter().any(w => w.has_cap("default-apps")) {
if self.any_cap("default-apps") {
self.publish_default_apps()
}
if self.widgets.iter().any(w => w.has_cap("screenshot")) {
if self.any_cap("screenshot") {
@wasm.publish_screenshot(self.screenshot_state)
}
if self.widgets.iter().any(w => w.has_cap("battery")) {
if self.any_cap("battery") {
let b = self.battery.refresh()
@wasm.publish_battery(b.percent, b.state, b.secs_left)
}
@@ -705,6 +726,9 @@ fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit {
self.name_catalog()
let mt = @wasm.Table::new()
for e in self.catalog {
if e.desktop {
continue // chosen in Settings > Desktop, not added to the panel
}
let mut n = 0
for w in self.widgets {
if w.path == e.path {
@@ -810,6 +834,7 @@ fn DesktopShell::process_requests(self : DesktopShell) -> Unit {
self.actions.push(ModulesReloaded)
}
Some(SetWallpaper(i)) => self.set_wallpaper(i)
Some(SetDesktop(i)) => self.set_desktop_index(i)
Some(SetSessionSetting(i, on)) => self.set_session_setting(i, on)
Some(Screenshot(code)) => self.actions.push(Screenshot(code))
Some(SetScreenOff(m)) => self.set_power_timeouts(m, self.suspend_min)
@@ -900,7 +925,7 @@ fn DesktopShell::poll_picker(self : DesktopShell) -> Unit {
pub(all) enum SettingsTab {
/// The session switches.
Session
/// What is on the desktop: the wallpaper (modules can't be placed on the desktop yet).
/// What is on the desktop: the wallpaper, the clock card or a desktop module.
Desktop
/// The panel's modules: remove, add, browse.
Panel
@@ -1065,7 +1090,7 @@ fn DesktopShell::open_module_settings(self : DesktopShell, slot : String) -> Uni
if rows.length() == 0 {
rows.push(menu_row("No module settings", 5))
}
self.open_menu(w.pl.name + " settings", rows, slot, self.menu_anchor_x)
self.open_menu(w.pl.name + " settings", rows, slot, self.menu_anchor_x, y=self.menu_anchor_y)
}
}
}
@@ -1081,6 +1106,13 @@ pub fn DesktopShell::set_module_setting(self : DesktopShell, slot : String, key
ignore(o.pl.set_config(key, value))
}
}
match self.desk_mod {
Some(d) if d.module_id == w.module_id => {
ignore(d.pl.set_config(key, value))
self.desktop_changed(true)
}
_ => ()
}
}
}
}
@@ -1110,7 +1142,15 @@ fn DesktopShell::choose_module_setting(self : DesktopShell, slot : String, key :
}
///|
fn DesktopShell::open_menu(self : DesktopShell, title : String, rows : Array[MenuRow], slot : String, x : Int) -> Unit {
fn DesktopShell::open_menu(
self : DesktopShell,
title : String,
rows : Array[MenuRow],
slot : String,
x : Int,
y? : Int = -1,
) -> Unit {
self.menu_anchor_y = y
self.menu_open = true
self.menu_title = title
self.menu_rows = rows
@@ -1143,7 +1183,16 @@ fn DesktopShell::menu_pointer_down(self : DesktopShell, x : Int, y : Int) -> Boo
match row.kind {
0 => ignore(self.replace_slot(slot, row.arg))
1 => ignore(self.unload_slot(slot))
2 => ignore(self.open_settings(if row.arg == "panel" { Panel } else { Session }))
2 =>
ignore(
self.open_settings(
match row.arg {
"panel" => Panel
"desktop" => Desktop
_ => Session
},
),
)
3 => self.open_module_settings(slot)
4 => self.choose_module_setting(slot, row.arg, row.value)
6 => self.actions.push(Window(row.window_id, row.window_cmd))
@@ -1170,8 +1219,13 @@ fn DesktopShell::render_menu(
) -> Unit {
let n = self.menu_rows.length()
let mh = menu_title_h + n * menu_item_h + 6
let mx = clamp_menu(self.menu_anchor_x - menu_w / 2, 4, w - menu_w - 4)
let my = self.panel_rect.y - mh - 6
// Above the panel, centred on the click; or (the desktop menu) at the pointer.
let (mx, my) = if self.menu_anchor_y >= 0 {
let bottom = if self.panel_rect.h > 0 { self.panel_rect.y } else { self.screen_h }
(clamp_menu(self.menu_anchor_x, 4, w - menu_w - 4), clamp_menu(self.menu_anchor_y, 4, bottom - mh - 4))
} else {
(clamp_menu(self.menu_anchor_x - menu_w / 2, 4, w - menu_w - 4), self.panel_rect.y - mh - 6)
}
self.menu_rect = { x: mx, y: my, w: menu_w, h: mh }
let fs = tokens.font_size.reinterpret_as_int()
let r = tokens.radius.reinterpret_as_int()
+31
View File
@@ -246,6 +246,26 @@ pub fn Plasmoid::set_config(self : Plasmoid, key : String, value : String) -> Bo
@hostpl.set_config(self.handle.reinterpret_as_uint(), key, value)
}
///| A desktop module's backdrop: 0 over the wallpaper, 1 replacing it, -1 for a panel module.
pub fn Plasmoid::desktop_backdrop(self : Plasmoid) -> Int {
@hostpl.desktop_backdrop(self.handle.reinterpret_as_uint())
}
///| Scroll over a desktop module at (x, y) by (dx, dy) pixels. True when it wants a redraw.
pub fn Plasmoid::desktop_scroll(self : Plasmoid, x : Int, y : Int, dx : Int, dy : Int) -> Bool {
@hostpl.desktop_scroll(self.handle.reinterpret_as_uint(), x, y, dx, dy)
}
///| A desktop module's animation clock: ms until it wants the next frame, 0 for none.
pub fn Plasmoid::desktop_tick(self : Plasmoid, now_ms : Int) -> Int {
let r = @hostpl.desktop_tick(self.handle.reinterpret_as_uint(), now_ms.reinterpret_as_uint()).reinterpret_as_int()
if r < 0 {
0
} else {
r
}
}
///|
pub fn Plasmoid::imports(self : Plasmoid) -> Array[String] {
self.imports
@@ -309,6 +329,8 @@ pub(all) enum HostTable {
AppCategories
/// Default-app choices (issii: category id name icon current).
AppChoices
/// What can fill the desktop (s: name), served by `wallpaper.desktops`.
Desktops
}
///|
@@ -336,6 +358,7 @@ pub fn publish(which : HostTable, t : Table) -> Unit {
Shortcuts => 10U
AppCategories => 11U
AppChoices => 12U
Desktops => 20U
}
// Most tables are republished every frame unchanged: skip the copy into the host then.
let slot = id.reinterpret_as_int()
@@ -363,6 +386,11 @@ pub fn publish_wallpaper(current : Int) -> Unit {
@hostpl.publish_wallpaper(current)
}
///| What fills the desktop now (an index into the Desktops table).
pub fn publish_desktop(current : Int) -> Unit {
@hostpl.publish_desktop(current)
}
///| Which session settings are on: bit i for row i of the SessionSettings table.
pub fn publish_session_settings(on : Int) -> Unit {
@hostpl.publish_session_settings(on.reinterpret_as_uint())
@@ -416,6 +444,8 @@ pub(all) enum HostRequest {
DefaultApp(Int)
/// The session capability's `reload`: reload every loaded panel module from disk.
ReloadSession
/// The wallpaper capability's `set-desktop`: an index into the Desktops table.
SetDesktop(Int)
} derive(Eq, Debug)
///|
@@ -441,6 +471,7 @@ pub fn next_request() -> HostRequest? {
Some(Shortcut(code)) => Some(Shortcut(code))
Some(DefaultApp(code)) => Some(DefaultApp(code))
Some(ReloadSession) => Some(ReloadSession)
Some(SetDesktop(i)) => Some(SetDesktop(i))
}
}
+47
View File
@@ -152,6 +152,15 @@ let ex_post_cfg_items : Int = 9
///|
let ex_set_cfg : Int = 10
///| The optional `desktop-module` exports (wit/desktop.wit): absent in panel modules.
let ex_desk_backdrop : Int = 11
///|
let ex_desk_scroll : Int = 12
///|
let ex_desk_tick : Int = 13
///| The 64-byte `theme.tokens` record (name left empty) the guest reads through get-tokens.
pub fn pack_tokens(t : @theme.Tokens) -> Bytes {
let b = FixedArray::make(64, b'\x00')
@@ -625,6 +634,33 @@ pub fn Plasmoid::set_config(self : Plasmoid, key : String, value : String) -> Bo
}
}
///| A desktop module's backdrop (`desktop-module.backdrop`): 0 drawn over the wallpaper, 1
/// replacing it; -1 when the module doesn't export `desktop-module` (a panel module).
pub fn Plasmoid::desktop_backdrop(self : Plasmoid) -> Int {
let r = c_wasm_call(self.handle, ex_desk_backdrop, 0, 0, 0, 0)
if r == 0 || r == 1 {
r
} else {
-1
}
}
///| Scroll over a desktop module at (x, y) by (dx, dy) pixels. True when it wants a redraw.
pub fn Plasmoid::desktop_scroll(self : Plasmoid, x : Int, y : Int, dx : Int, dy : Int) -> Bool {
c_wasm_call(self.handle, ex_desk_scroll, x, y, dx, dy) == 1
}
///| A desktop module's animation clock (`now_ms` since it was loaded): the ms until it wants the
/// next frame, 0 for none (also when it trapped or has no `desktop-module`).
pub fn Plasmoid::desktop_tick(self : Plasmoid, now_ms : Int) -> Int {
let r = c_wasm_call(self.handle, ex_desk_tick, now_ms, 0, 0, 0)
if r < 0 {
0
} else {
r
}
}
///| Host interfaces (capabilities) the module's binary imports, e.g. ["theme", "clock"].
pub fn Plasmoid::imports(self : Plasmoid) -> Array[String] {
let buf = Bytes::make(512, b'\x00')
@@ -701,6 +737,8 @@ pub(all) enum HostTable {
AppCategories
/// Default-app choices (issii: category id name icon current).
AppChoices
/// What can fill the desktop (s: name), served by `wallpaper.desktops`.
Desktops
}
///| Publish `t` as the data behind `which` for every module's next call.
@@ -719,6 +757,7 @@ pub fn publish(which : HostTable, t : Table) -> Unit {
Shortcuts => 10
AppCategories => 11
AppChoices => 12
Desktops => 20
}
let out : Array[Byte] = []
for k = 0; k < 4; k = k + 1 {
@@ -741,6 +780,11 @@ pub fn publish_wallpaper(current : Int) -> Unit {
c_host_set_int(2, current)
}
///| Publish what fills the desktop now (an index into the Desktops table).
pub fn publish_desktop(current : Int) -> Unit {
c_host_set_int(20, current)
}
///| Publish which session settings are on: bit i for row i of the SessionSettings table.
pub fn publish_session_settings(on : Int) -> Unit {
c_host_set_int(3, on)
@@ -798,6 +842,8 @@ pub(all) enum HostRequest {
DefaultApp(Int)
/// The session capability's `reload`: reload every loaded panel module from disk.
ReloadSession
/// The wallpaper capability's `set-desktop`: an index into the Desktops table.
SetDesktop(Int)
} derive(Eq, Debug)
///|
@@ -839,6 +885,7 @@ pub fn next_request() -> HostRequest? {
}
18 => Some(Shortcut(c_host_req_int()))
19 => Some(DefaultApp(c_host_req_int()))
40 => Some(SetDesktop(c_host_req_int()))
_ => None
}
}
+20 -5
View File
@@ -17,7 +17,7 @@
#define MAX_INST 2048
enum { EX_INFO, EX_RENDER, EX_ONEVENT, EX_POPUP, EX_POST_INFO, EX_POST_RENDER, EX_POST_POPUP, EX_REALLOC,
EX_CFG_ITEMS, EX_POST_CFG_ITEMS, EX_SET_CFG, EX_N };
EX_CFG_ITEMS, EX_POST_CFG_ITEMS, EX_SET_CFG, EX_DESK_BACKDROP, EX_DESK_SCROLL, EX_DESK_TICK, EX_N };
static const char *ex_names[EX_N] = {
"chandra:desktop/plasmoid@0.1.0#info",
"chandra:desktop/plasmoid@0.1.0#render",
@@ -31,6 +31,10 @@ static const char *ex_names[EX_N] = {
"chandra:desktop/module-config@0.1.0#config-items",
"cabi_post_chandra:desktop/module-config@0.1.0#config-items",
"chandra:desktop/module-config@0.1.0#set-config",
/* optional: chandra:desktop/desktop-module (a module that fills the desktop, wit/desktop.wit) */
"chandra:desktop/desktop-module@0.1.0#backdrop",
"chandra:desktop/desktop-module@0.1.0#on-scroll",
"chandra:desktop/desktop-module@0.1.0#tick",
};
typedef struct Inst {
@@ -61,17 +65,20 @@ enum {
K_NET_STATUS, K_NET_LIST, K_NET_SCAN, K_NET_CONNECT, K_NET_DISCONNECT, K_NET_FORGET, K_NET_SET_WIFI,
K_NET_SET_AIRPLANE,
K_SC_LIST, K_SC_CAPTURE, K_SC_CANCEL, K_SC_RESET, K_SC_RESET_ALL,
K_DA_CATS, K_DA_APPS, K_DA_SET, K_DA_REFRESH
K_DA_CATS, K_DA_APPS, K_DA_SET, K_DA_REFRESH,
K_DESKTOPS, K_DESKTOP_CUR, K_SET_DESKTOP
};
typedef struct Env { Inst *inst; int kind; } Env;
/* ---- host data the shell publishes before calling a guest ----
* A table is [u32 rows] then rows of fields, each field a LE i32 ('i') or a u32 byte length + UTF-8 ('s'). */
enum { T_APPS, T_WINDOWS, T_LAYOUTS, T_MODULES, T_INSTANCES, T_WALLPAPERS, T_SESSION_SETTINGS, T_ICONS,
T_NET_STATUS, T_NET_NETWORKS, T_SHORTCUTS, T_APP_CATS, T_APP_CHOICES, T_N };
T_NET_STATUS, T_NET_NETWORKS, T_SHORTCUTS, T_APP_CATS, T_APP_CHOICES,
/* fixed numbers from here (wit/host/plasmoids.wit publish-table) */
T_DESKTOPS = 20, T_N = 32 };
typedef struct { uint8_t *data; size_t len; } Blob;
static Blob tables[T_N];
static int32_t host_ints[12] = {[7] = -1}; /* 0 layout mode, 1 inspector on, 2 current wallpaper, 3 session settings on (bit i: row i),
static int32_t host_ints[24] = {[7] = -1}; /* 0 layout mode, 1 inspector on, 2 current wallpaper, 3 session settings on (bit i: row i),
4 screenshot state (bit 0 recording, bit 1 pointer in recordings),
5 screen-off minutes, 6 suspend minutes (0: never),
7 battery percent (-1: none), 8 battery charge-state, 9 battery seconds left */
@@ -375,6 +382,11 @@ static wasm_trap_t *host_import(void *env, const wasm_val_vec_t *args, wasm_val_
case K_LOGOUT: push_req(8, 0, NULL); break;
case K_RELOAD: push_req(8, 1, NULL); break; /* 8: session; n 0 log out, 1 reload */
case K_SET_WALLPAPER: push_req(9, a0, NULL); break;
case K_DESKTOPS: build_list(in, T_DESKTOPS, "s", a0); break;
case K_DESKTOP_CUR:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[20]);
break;
case K_SET_DESKTOP: push_req(40, a0, NULL); break;
case K_SESSION_SET: push_req(a1 ? 11 : 10, a0, NULL); break; /* 10 off, 11 on */
/* Request 12 carries the screenshot code: 0-3 take, 10-12 record, 20 stop, 30/31 pointer. */
case K_SHOT_TAKE: if (a0 >= 0 && a0 <= 3) push_req(12, a0, NULL); break;
@@ -589,6 +601,9 @@ static int classify_import(const wasm_name_t *m, const wasm_name_t *f) {
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "wallpapers")) return K_WALLPAPERS;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "current-wallpaper")) return K_WALLPAPER_CUR;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "set-wallpaper")) return K_SET_WALLPAPER;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "desktops")) return K_DESKTOPS;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "current-desktop")) return K_DESKTOP_CUR;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "set-desktop")) return K_SET_DESKTOP;
if (!strcmp(iface, "session-settings") && !strcmp(fn, "settings")) return K_SESSION_SETTINGS;
if (!strcmp(iface, "session-settings") && !strcmp(fn, "is-on")) return K_SESSION_IS_ON;
if (!strcmp(iface, "session-settings") && !strcmp(fn, "set-setting")) return K_SESSION_SET;
@@ -882,7 +897,7 @@ void mp_host_set_table(int32_t which, moonbit_bytes_t data) {
MOONBIT_FFI_EXPORT
void mp_host_set_int(int32_t which, int32_t v) {
if (which >= 0 && which < 12) host_ints[which] = v;
if (which >= 0 && which < 24) host_ints[which] = v; /* 20: the desktop (wallpaper.current-desktop) */
}
/* Pop the next guest request: returns its kind (0 = none). Fetch its arguments with req_int / req_str. */
+113
View File
@@ -0,0 +1,113 @@
# Desktop modules
A desktop module is a wasm module that fills the desktop: the whole output behind the windows,
instead of a box in the panel. Use it for interactive desktops (an icon launcher, a live
wallpaper, a game, a dashboard). It runs in the same sandbox as a panel module, draws with the
same draw ops and asks for the same capabilities; only the way the shell drives it differs.
Two samples ship with Chandra:
* **Icon Desktop** (`components/icon-desktop`, logic in `lib/icondesk`): a grid of app icons on
the wallpaper. Click to launch, drag to move (dropping on another icon swaps them), arrow keys
and Enter after clicking the desktop, typing a letter jumps to the next app starting with it.
Positions are kept across logins. Module settings: how many apps (8, 12, 24, all) and icon size.
* **Live Starfield** (`components/starfield`, logic in `lib/starfield`): an animated starfield
that replaces the wallpaper. The pointer steers it, a click or Space sends a warp pulse, the
wheel changes speed. Module settings: speed, density, and Moving or Still (Still draws one
frame and then costs nothing).
![Icon Desktop](screenshots/desktop-icons.png)
![Live Starfield](screenshots/desktop-starfield.png)
## Choosing what fills the desktop
Settings > Desktop starts with **On the desktop**: *Wallpaper only*, *Clock card* (the default,
as before) and every installed desktop module. The choice takes effect at once, is saved in
`~/.config/chandra/state.edn` as `:desktop` (`"wallpaper"`, `"clock-card"` or the module's id)
and is loaded again at login. A module that is missing or fails to load leaves the clock card,
and the saved choice is kept for when it comes back.
Right-click the empty desktop for **Module settings...** (the module's own options) and
**System settings...** (Settings on the Desktop tab). A desktop module can't be added to the
panel: Settings > Panel doesn't list it, and adding one by path is refused with a notice.
## Writing one
A desktop module is a plasmoid (`wit/plasmoid.wit`) that also exports `desktop-module`
(`wit/desktop.wit`):
```wit
interface desktop-module {
enum wallpaper-mode { over-wallpaper, replace-wallpaper }
backdrop: func() -> wallpaper-mode;
on-scroll: func(at: point, dx: s32, dy: s32) -> bool;
tick: func(now-ms: u32) -> u32;
}
```
The smallest world is `desktop-widget` in `wit/worlds.wit` (`include widget; export
desktop-module;`). Add imports and `module-config` as a panel module would; the samples use
`icon-desktop-widget` (app catalog, app launch, icons, module config) and `starfield-widget`.
Add a line to `scripts/components.txt` and `scripts/build-modules.sh` builds it into
`build/components/NAME.wasm`; `just install` copies it to `/usr/local/share/chandra/modules/`,
the same place as panel modules. The shell tells desktop modules apart by the export.
How the shell drives it:
* **Drawing.** `plasmoid.render` gets the output's full size, in desktop coordinates ((0, 0) is
the output's top-left corner), and is called again with the new size when the output is
resized. The wallpaper is drawn first unless `backdrop` returns `replace-wallpaper`; windows
and the panel are drawn on top. The ops are cached: the shell calls `render` again only when
the module asked for a redraw, the size changed or the theme changed. `plasmoid.info`'s size
fields and `plasmoid.popup` are not used.
* **Pointer.** `plasmoid.on-event` gets move, press, release and leave only where nothing else
is: no window, panel, popup, menu or switcher covers that point. Moving onto a window or the
panel sends a leave. A press on the desktop keeps the pointer (a drag stays with the module
until release, even over a window). Right-click never reaches the module: it opens the desktop
menu. `on-scroll` gets the wheel over the empty desktop (one notch is about 10 pixels).
* **Keys.** Only while the desktop has the keyboard: after a click on the empty desktop, until a
window is focused (the module then gets `focus-lost`). Shortcuts are handled first, and a
focused window always gets its own keys.
* **Animation.** `tick(now-ms)` is the clock (`now-ms` counts from when the module was loaded).
It is called once after loading, after every event, and again when the delay it last returned
has passed. Return the ms until the next frame (16 for about 60 fps, 33 for 30) or 0 to sleep
until the next event. Each timed tick is followed by a redraw. The compositor's main loop
sleeps until the next frame is due, so a module that returns 0 costs no CPU while idle, and
frames are paused while a window covers the whole desktop. Requests are capped at 10 s.
* **Saved state.** `module-config` items with an empty label are hidden settings: the shell
doesn't show them, but saves them in state.edn (`:module-config`, under the module's id) when
their value changes after a release or a key, and hands them back with `set-config` at the
next load. Icon Desktop keeps its icon positions this way (`places`, `id=col,row;...`).
Logic is easiest to test outside the component: the samples keep it in `lib/` and test it with
`moon test --target wasm -p chandra/desktop/lib/starfield` (or `lib/icondesk`).
## Reloading
`chandra-ctl reload` (or `just reload`, Applications > Reload, SIGUSR1) reloads the desktop
module along with the panel modules; `chandra-ctl reload desktop` or `chandra-ctl reload
starfield` reloads only it. Settings and hidden state are handed back as at login. A broken file
is reported and the running instance stays (see [reloading.md](reloading.md)).
## Hosts
All three module hosts serve desktop modules: the native compositor and the MoonBit
`build/wasmhost` (both through `compositor/wasm/wasm_stub.c`) and the Rust `host-wasm`
(`src/plasmoid.rs`, bound with the `desktop-export` world). The compositor-as-wasm reaches them
through `desktop-backdrop`, `desktop-scroll`, `desktop-tick` and `publish-desktop` in
`wit/host/plasmoids.wit`. The settings module reads the list through the `wallpaper`
capability's `desktops`, `current-desktop` and `set-desktop` (`wit/capabilities.wit`).
## Tests
`compositor/host/desktop_test.mbt`: choosing and listing, input routing (windows and the panel
win, drags stay with the module), the right-click menu, resize, idle and animation pacing,
reload, and screenshots (`_build/desktop_*.png`). Run with:
```
XDG_CONFIG_HOME=$(mktemp -d) CHANDRA_TEST_CONFIG=1 \
moon test --target native --warn-list -a -p chandra/desktop/compositor/host --filter "*desktop*"
```
Also checked headless on `build/wasmhost` and `host-wasm` (`--gfx-out`) with `:desktop` set in
state.edn.
+1
View File
@@ -6,6 +6,7 @@ what it loaded at startup. What can be swapped without logging out:
| Part | Reload without logout? | How |
|---|---|---|
| Panel modules (`/usr/local/share/chandra/modules/*.wasm`) | yes | Applications → **Reload**, `just reload` / `chandra-ctl reload`, `kill -USR1`, or Settings → Panel (remove, add again) |
| The desktop module ([desktop-modules.md](desktop-modules.md)) | yes | the same; `chandra-ctl reload desktop` for only it |
| `compositor.wasm` (shell, WM, portal backend) | no | restart the session |
| `chandra-host` (`wasmhost`) | no | restart the session |
| `config/`, themes, assets | not checked | restart the session to be sure |
Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

+17
View File
@@ -193,6 +193,18 @@ impl chandra::host::plasmoids::Host for State {
self.pl().set_config(handle, &key, &value)
}
fn desktop_backdrop(&mut self, handle: u32) -> i32 {
self.pl().desktop_backdrop(handle)
}
fn desktop_scroll(&mut self, handle: u32, x: i32, y: i32, dx: i32, dy: i32) -> bool {
self.pl().desktop_scroll(handle, x, y, dx, dy)
}
fn desktop_tick(&mut self, handle: u32, now_ms: u32) -> u32 {
self.pl().desktop_tick(handle, now_ms)
}
fn publish_table(&mut self, which: u32, rows: Vec<u8>) {
if let Some(t) = self.pl().shared.borrow_mut().tables.get_mut(which as usize) {
*t = rows;
@@ -210,6 +222,10 @@ impl chandra::host::plasmoids::Host for State {
self.pl().shared.borrow_mut().wallpaper = current;
}
fn publish_desktop(&mut self, current: i32) {
self.pl().shared.borrow_mut().desktop = current;
}
fn publish_session_settings(&mut self, on: u32) {
self.pl().shared.borrow_mut().session_settings = on;
}
@@ -278,6 +294,7 @@ impl chandra::host::plasmoids::Host for State {
}
Req::Shortcut(code) => R::Shortcut(code),
Req::DefaultApp(code) => R::DefaultApp(code),
Req::SetDesktop(i) => R::SetDesktop(i),
})
}
+55 -2
View File
@@ -31,6 +31,14 @@ pub mod cfg {
});
}
pub use cfg::exports::chandra::desktop::module_config::ConfigItem;
/// The optional `desktop-module` export (wit/desktop.wit, world `desktop-export`): a module that
/// fills the desktop. Bound separately, like `module-config`.
pub mod desk {
wasmtime::component::bindgen!({
path: "../wit",
world: "desktop-export",
});
}
use ph::exports::chandra::desktop as ex;
use ph::chandra::desktop as d;
@@ -63,6 +71,8 @@ pub enum Req {
Shortcut(i32),
/// A default-apps request: category * 1000 + app sets a default, -1 scans again.
DefaultApp(i32),
/// `wallpaper.set-desktop`: an index into the desktops table.
SetDesktop(i32),
}
pub const T_APPS: usize = 0;
@@ -84,13 +94,17 @@ pub const T_SHORTCUTS: usize = 10;
pub const T_APP_CATS: usize = 11;
/// Default-app choices (issii): category id name icon current.
pub const T_APP_CHOICES: usize = 12;
/// What can fill the desktop (s): name, behind `wallpaper.desktops`.
pub const T_DESKTOPS: usize = 20;
/// Host data every module reads from, shared by all loaded modules.
#[derive(Default)]
pub struct Shared {
pub tables: [Vec<u8>; 13],
pub tables: [Vec<u8>; 21],
pub layout_mode: i32,
pub wallpaper: i32,
/// What fills the desktop (an index into the desktops table).
pub desktop: i32,
/// Which session settings are on: bit i for row i of the session settings table.
pub session_settings: u32,
/// Screenshot state: bit 0 a recording is running, bit 1 recordings show the pointer.
@@ -341,6 +355,15 @@ impl d::wallpaper::Host for PState {
fn set_wallpaper(&mut self, index: u32) {
self.shared.borrow_mut().requests.push_back(Req::SetWallpaper(index as i32));
}
fn desktops(&mut self) -> Vec<String> {
self.rows(T_DESKTOPS, "s").iter().map(|r| s(&r[0])).collect()
}
fn current_desktop(&mut self) -> u32 {
self.shared.borrow().desktop.max(0) as u32
}
fn set_desktop(&mut self, index: u32) {
self.shared.borrow_mut().requests.push_back(Req::SetDesktop(index as i32));
}
}
impl d::power::Host for PState {
@@ -585,6 +608,8 @@ struct Loaded {
inst: ph::PlasmoidHost,
/// Present when the module exports `module-config`.
cfg: Option<cfg::Configurable>,
/// Present when it exports `desktop-module` (a desktop module).
desk: Option<desk::DesktopExport>,
}
/// A file-chooser dialog in flight (zenity on the host session).
@@ -642,11 +667,12 @@ impl Runtime {
let inst = ph::PlasmoidHost::new(&mut store, &instance)
.map_err(|_| "no plasmoid (chandra:desktop/plasmoid) in this module".to_string())?;
let cfg = cfg::Configurable::new(&mut store, &instance).ok();
let desk = desk::DesktopExport::new(&mut store, &instance).ok();
let info = inst
.chandra_desktop_plasmoid()
.call_info(&mut store)
.map_err(|_| "widget trapped in info()".to_string())?;
let l = Loaded { store, inst, cfg };
let l = Loaded { store, inst, cfg, desk };
let handle = match self.slots.iter().position(|s| s.is_none()) {
Some(h) => {
self.slots[h] = Some(l);
@@ -695,6 +721,33 @@ impl Runtime {
c.chandra_desktop_module_config().call_set_config(&mut l.store, key, value).unwrap_or(false)
}
/// A desktop module's backdrop: 0 over the wallpaper, 1 replacing it; -1 for a panel module.
pub fn desktop_backdrop(&mut self, handle: u32) -> i32 {
use desk::exports::chandra::desktop::desktop_module::WallpaperMode;
let Some(l) = self.get(handle) else { return -1 };
let Some(dm) = &l.desk else { return -1 };
match dm.chandra_desktop_desktop_module().call_backdrop(&mut l.store) {
Ok(WallpaperMode::OverWallpaper) => 0,
Ok(WallpaperMode::ReplaceWallpaper) => 1,
Err(_) => -1,
}
}
/// Scroll over a desktop module; true when it wants a redraw.
pub fn desktop_scroll(&mut self, handle: u32, x: i32, y: i32, dx: i32, dy: i32) -> bool {
let Some(l) = self.get(handle) else { return false };
let Some(dm) = &l.desk else { return false };
let at = desk::chandra::desktop::types::Point { x, y };
dm.chandra_desktop_desktop_module().call_on_scroll(&mut l.store, at, dx, dy).unwrap_or(false)
}
/// A desktop module's animation clock: ms until its next frame, 0 for none (or a trap).
pub fn desktop_tick(&mut self, handle: u32, now_ms: u32) -> u32 {
let Some(l) = self.get(handle) else { return 0 };
let Some(dm) = &l.desk else { return 0 };
dm.chandra_desktop_desktop_module().call_tick(&mut l.store, now_ms).unwrap_or(0)
}
pub fn on_event(&mut self, handle: u32, on_popup: bool, ev: d::types::InputEvent) -> bool {
let Some(l) = self.get(handle) else { return false };
let target = if on_popup { ex::plasmoid::Surface::Popup } else { ex::plasmoid::Surface::Widget };
+16 -7
View File
@@ -10,15 +10,13 @@ fn wasmImportCurrentWallpaper() -> Int = "chandra:desktop/wallpaper@0.1.0" "curr
fn wasmImportSetWallpaper(p0 : Int) = "chandra:desktop/wallpaper@0.1.0" "set-wallpaper"
///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
fn wasmImportDesktops(p0 : Int) = "chandra:desktop/wallpaper@0.1.0" "desktops"
///|
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)
fn wasmImportCurrentDesktop() -> Int = "chandra:desktop/wallpaper@0.1.0" "current-desktop"
///|
fn wasmImportSetDesktop(p0 : Int) = "chandra:desktop/wallpaper@0.1.0" "set-desktop"
///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
@@ -31,3 +29,14 @@ extern "wasm" fn mbt_ffi_malloc(size : 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 =
#|(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)
@@ -35,4 +35,42 @@ pub fn set_wallpaper(index : UInt) -> Unit {
wasmImportSetWallpaper((index).reinterpret_as_int());
}
///|
/// What fills the desktop, as display names indexed by choice: 0 "Wallpaper only", 1 "Clock
/// card" (the built-in card), then every installed desktop module (docs/desktop-modules.md).
pub fn desktops() -> Array[String] {
let return_area = mbt_ffi_malloc(8)
wasmImportDesktops(return_area);
let array : Array[String] = [];
for index = 0; index < (mbt_ffi_load32((return_area) + 4)); index = index + 1 {
let iter_base = (mbt_ffi_load32((return_area) + 0)) + (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(mbt_ffi_load32((return_area) + 0))
let ret = array
mbt_ffi_free(return_area)
return ret
}
///|
pub fn current_desktop() -> UInt {
let result : Int = wasmImportCurrentDesktop();
let ret = (result).reinterpret_as_uint()
return ret
}
///|
/// Put desktop `index` on the desktop (out-of-range indices are ignored). The choice is
/// remembered (state.edn `:desktop`).
pub fn set_desktop(index : UInt) -> Unit {
wasmImportSetDesktop((index).reinterpret_as_int());
}
+31 -19
View File
@@ -24,6 +24,15 @@ fn wasmImportConfigItems(p0 : Int, p1 : Int) = "chandra:host/plasmoids@0.1.0" "
///|
fn wasmImportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) -> Int = "chandra:host/plasmoids@0.1.0" "set-config"
///|
fn wasmImportDesktopBackdrop(p0 : Int) -> Int = "chandra:host/plasmoids@0.1.0" "desktop-backdrop"
///|
fn wasmImportDesktopScroll(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) -> Int = "chandra:host/plasmoids@0.1.0" "desktop-scroll"
///|
fn wasmImportDesktopTick(p0 : Int, p1 : Int) -> Int = "chandra:host/plasmoids@0.1.0" "desktop-tick"
///|
fn wasmImportPublishTable(p0 : Int, p1 : Int, p2 : Int) = "chandra:host/plasmoids@0.1.0" "publish-table"
@@ -33,6 +42,9 @@ fn wasmImportPublishState(p0 : Int, p1 : Int) = "chandra:host/plasmoids@0.1.0"
///|
fn wasmImportPublishWallpaper(p0 : Int) = "chandra:host/plasmoids@0.1.0" "publish-wallpaper"
///|
fn wasmImportPublishDesktop(p0 : Int) = "chandra:host/plasmoids@0.1.0" "publish-desktop"
///|
fn wasmImportPublishSessionSettings(p0 : Int) = "chandra:host/plasmoids@0.1.0" "publish-session-settings"
@@ -67,22 +79,39 @@ fn wasmImportPickerStart() -> Int = "chandra:host/plasmoids@0.1.0" "picker-start
fn wasmImportPickerPoll(p0 : Int) = "chandra:host/plasmoids@0.1.0" "picker-poll"
///|
extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load8_u)
#owned(bytes)
extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> 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_load8_u(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load8_u)
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) 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_store8(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8)
///|
extern "wasm" fn mbt_ffi_store64(offset : Int, value : Int64) =
#|(func (param i32) (param i64) local.get 0 local.get 1 i64.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_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) (param i32) (result i32)
@@ -90,15 +119,6 @@ extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
///|
#owned(bytes)
extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int =
#|(func (param i32) (result i32) 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_malloc(size : Int) -> Int =
#|(func (param i32) (result i32) (local i32)
@@ -110,11 +130,3 @@ extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
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_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
@@ -40,6 +40,21 @@ fn wasmImportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) -> Int
abort("wasm-only host import")
}
///|
fn wasmImportDesktopBackdrop(p0 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportDesktopScroll(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportDesktopTick(p0 : Int, p1 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn wasmImportPublishTable(p0 : Int, p1 : Int, p2 : Int) -> Unit {
abort("wasm-only host import")
@@ -55,6 +70,11 @@ fn wasmImportPublishWallpaper(p0 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportPublishDesktop(p0 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportPublishSessionSettings(p0 : Int) -> Unit {
abort("wasm-only host import")
@@ -111,27 +131,7 @@ fn wasmImportPickerPoll(p0 : Int) -> Unit {
}
///|
fn mbt_ffi_malloc(size : Int) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_store64(offset : Int, value : Int64) -> Unit {
abort("wasm-only")
}
///|
fn mbt_ffi_load64(offset : Int) -> Int64 {
abort("wasm-only")
}
///|
fn mbt_ffi_free(position : Int) -> Unit {
abort("wasm-only")
}
///|
fn mbt_ffi_str2ptr(str : String) -> Int {
fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int {
abort("wasm-only")
}
@@ -140,27 +140,47 @@ fn mbt_ffi_store32(offset : Int, value : Int) -> Unit {
abort("wasm-only")
}
///|
fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String {
abort("wasm-only")
}
///|
fn mbt_ffi_load8_u(offset : Int) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_str2ptr(str : String) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_load64(offset : Int) -> Int64 {
abort("wasm-only")
}
///|
fn mbt_ffi_store8(offset : Int, value : Int) -> Unit {
abort("wasm-only")
}
///|
fn mbt_ffi_store64(offset : Int, value : Int64) -> Unit {
abort("wasm-only")
}
///|
fn mbt_ffi_load32(offset : Int) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String {
abort("wasm-only")
}
///|
fn mbt_ffi_malloc(size : Int) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_free(position : Int) -> Unit {
abort("wasm-only")
}
@@ -9,6 +9,12 @@ import {
// Values
pub fn config_items(UInt32) -> Array[ConfigItem]
pub fn desktop_backdrop(UInt32) -> Int32
pub fn desktop_scroll(UInt32, Int32, Int32, Int32, Int32) -> Bool
pub fn desktop_tick(UInt32, UInt32) -> UInt32
pub fn list_wasm_files(String) -> Array[String]
pub fn load(String) -> Result[Loaded, String]
@@ -25,6 +31,8 @@ pub fn popup(UInt32) -> PopupSurface?
pub fn publish_battery(Int32, UInt32, UInt32) -> Unit
pub fn publish_desktop(Int32) -> Unit
pub fn publish_power(UInt32, UInt32) -> Unit
pub fn publish_screenshot(UInt32) -> Unit
@@ -113,6 +121,7 @@ pub(all) enum Request {
Shortcut(Int32)
ReloadSession
DefaultApp(Int32)
SetDesktop(Int32)
}
pub(all) struct SettingChange {
+44 -1
View File
@@ -61,6 +61,7 @@ pub(all) enum Request {
Shortcut(Int)
ReloadSession
DefaultApp(Int)
SetDesktop(Int)
}
///|
/// A native file-chooser dialog (zenity on the host session) for "Add widget".
@@ -384,6 +385,36 @@ pub fn set_config(handle : UInt, key : String, value : String) -> Bool {
mbt_ffi_free(ptr0)
return ret
}
///|
/// Desktop modules (chandra:desktop/desktop-module, wit/desktop.wit): the module's backdrop (0
/// over the wallpaper, 1 replacing it), or -1 when it doesn't export desktop-module (a panel
/// module).
pub fn desktop_backdrop(handle : UInt) -> Int {
let result : Int = wasmImportDesktopBackdrop((handle).reinterpret_as_int());
let ret = result
return ret
}
///|
/// Scroll over the desktop at (x, y), `dx` / `dy` pixels. True when it wants a redraw.
pub fn desktop_scroll(handle : UInt, x : Int, y : Int, dx : Int, dy : Int) -> Bool {
let result : Int = wasmImportDesktopScroll((handle).reinterpret_as_int(), x, y, dx, dy);
let ret = (result != 0)
return ret
}
///|
/// The module's animation clock (`now-ms` since it was loaded): ms until it wants the next
/// frame, 0 for none.
pub fn desktop_tick(handle : UInt, now_ms : UInt) -> UInt {
let result : Int = wasmImportDesktopTick((handle).reinterpret_as_int(), (now_ms).reinterpret_as_int());
let ret = (result).reinterpret_as_uint()
return ret
}
///|
/// ---- host data modules read through their capabilities ----
@@ -395,7 +426,8 @@ pub fn set_config(handle : UInt, key : String, value : String) -> Bool {
/// 8 network status (one row, iissiiii: state signal name message wifi-enabled airplane
/// can-manage has-wifi), 9 Wi-Fi networks (siiii: ssid signal secured active saved), 10 keyboard
/// shortcuts (ssssi: name binding default-binding conflict capturing), 11 default-app
/// categories (sss: name current missing), 12 default-app choices (issii: category id name icon current).
/// categories (sss: name current missing), 12 default-app choices (issii: category id name icon current),
/// 20 desktops (s: name) served by `wallpaper.desktops`.
pub fn publish_table(which : UInt, rows : FixedArray[Byte]) -> Unit {
let ptr = mbt_ffi_bytes2ptr(rows)
@@ -417,6 +449,13 @@ pub fn publish_wallpaper(current : Int) -> Unit {
wasmImportPublishWallpaper(current);
}
///|
/// What is on the desktop now (an index into the desktops table).
pub fn publish_desktop(current : Int) -> Unit {
wasmImportPublishDesktop(current);
}
///|
/// Which session settings are on: bit i for row i of the session settings table.
@@ -581,6 +620,10 @@ pub fn next_request() -> Request? {
Request::DefaultApp(mbt_ffi_load32((return_area) + 8))
}
19 => {
Request::SetDesktop(mbt_ffi_load32((return_area) + 8))
}
_ => panic()
}
+515
View File
@@ -0,0 +1,515 @@
///| Icon desktop: the interactive sample desktop module (components/icon-desktop). App icons sit
/// in a grid on the wallpaper, top-left first, a column at a time. A click starts the app; a drag
/// moves its icon to another cell (swapping with the icon there), and the arrangement is kept as
/// the hidden `places` setting, which the shell saves in state.edn. The keyboard works while the
/// desktop has focus: arrows move the selection, Enter starts it, a letter jumps to the next app
/// whose name starts with it, Escape clears it.
///
/// Pure: the component hands in the app catalog, the theme, the size, an icon lookup and the
/// events; it carries out the `Launch` this returns.
///| One item of the module's right-click settings (the `module-config` record). An empty label
/// hides it from the menu (the shell still saves it): that is the arrangement.
#derive(Eq, Debug)
pub(all) struct ConfigEntry {
key : String
label : String
choices : Array[String]
value : String
}
///|
pub let count_choices : Array[String] = ["8", "12", "24", "All"]
///|
pub let size_choices : Array[String] = ["Small", "Medium", "Large"]
///| A non-negative decimal number, or `dflt` when `s` isn't one.
fn nat(s : String, dflt : Int) -> Int {
if s.length() == 0 || s.length() > 6 {
return dflt
}
let mut v = 0
for c in s {
if c < '0' || c > '9' {
return dflt
}
v = v * 10 + (c.to_int() - '0'.to_int())
}
v
}
///| Space kept free around the grid, in pixels.
let margin : Int = 20
///| A drag starts once the pointer has moved this far from the press.
let drag_threshold : Int = 5
///| What the module asks of the host after an event.
#derive(Eq, Debug)
pub(all) enum Action {
NoAction
Launch(String)
}
///| The desktop's state.
pub(all) struct Desk {
mut count : String
mut size : String
/// Where icons were put: app id -> (column, row).
places : Map[String, (Int, Int)]
mut w : Int
mut h : Int
/// Kept free at the bottom (the panel).
mut bottom : Int
/// Shown app under the pointer / selected (by id, "" for none), and whether the desktop has the
/// keyboard (the selection is drawn brighter then).
mut hover : String
mut selected : String
mut focused : Bool
/// A press on an icon: its id and where; whether it became a drag, and where the pointer is.
mut press_id : String
mut press_x : Int
mut press_y : Int
mut dragging : Bool
mut ptr_x : Int
mut ptr_y : Int
}
///|
pub fn Desk::new() -> Desk {
{
count: "12",
size: "Medium",
places: {},
w: 0,
h: 0,
bottom: 40,
hover: "",
selected: "",
focused: false,
press_id: "",
press_x: 0,
press_y: 0,
dragging: false,
ptr_x: 0,
ptr_y: 0,
}
}
///| (cell width, cell height, icon size) for the size setting.
pub fn Desk::cell(self : Desk) -> (Int, Int, Int) {
match self.size {
"Small" => (76, 76, 32)
"Large" => (120, 116, 64)
_ => (96, 96, 48)
}
}
///| Columns and rows that fit on the desktop (at least one of each).
pub fn Desk::grid(self : Desk) -> (Int, Int) {
let (cw, ch, _) = self.cell()
let cols = (self.w - 2 * margin) / cw
let rows = (self.h - self.bottom - 2 * margin) / ch
(if cols < 1 { 1 } else { cols }, if rows < 1 { 1 } else { rows })
}
///| The apps on the desktop: the first `count` of the catalog (its defaults and recent apps come
/// first).
pub fn Desk::shown(self : Desk, apps : Array[@types.AppEntry]) -> Array[@types.AppEntry] {
let n = match self.count {
"All" => apps.length()
c => nat(c, 12)
}
if n >= apps.length() {
apps
} else {
apps[:n].to_array()
}
}
///| Each shown app's cell, in `shown` order: its saved place when that is on the grid and free,
/// else the first free cell, a column at a time. (-1, -1) when the grid is full.
pub fn Desk::layout(self : Desk, apps : Array[@types.AppEntry]) -> Array[(Int, Int)] {
let shown = self.shown(apps)
let (cols, rows) = self.grid()
let taken : Map[(Int, Int), Bool] = {}
let out : Array[(Int, Int)] = Array::make(shown.length(), (-1, -1))
for i, a in shown {
match self.places.get(a.id) {
Some((c, r)) if c >= 0 && r >= 0 && c < cols && r < rows && !taken.contains((c, r)) => {
taken.set((c, r), true)
out[i] = (c, r)
}
_ => ()
}
}
let mut next = 0
for i = 0; i < shown.length(); i = i + 1 {
if out[i] != (-1, -1) {
continue
}
while next < cols * rows && taken.contains((next / rows, next % rows)) {
next = next + 1
}
if next < cols * rows {
let cr = (next / rows, next % rows)
taken.set(cr, true)
out[i] = cr
}
}
out
}
///| Top-left corner of cell (col, row).
pub fn Desk::cell_origin(self : Desk, col : Int, row : Int) -> (Int, Int) {
let (cw, ch, _) = self.cell()
(margin + col * cw, margin + row * ch)
}
///| The cell under (x, y), clamped to the grid.
pub fn Desk::cell_at(self : Desk, x : Int, y : Int) -> (Int, Int) {
let (cw, ch, _) = self.cell()
let (cols, rows) = self.grid()
let clamp = fn(v : Int, hi : Int) { if v < 0 { 0 } else if v > hi { hi } else { v } }
(clamp((x - margin) / cw, cols - 1), clamp((y - margin) / ch, rows - 1))
}
///| The id of the shown app whose icon cell holds (x, y), or "".
pub fn Desk::app_at(self : Desk, apps : Array[@types.AppEntry], x : Int, y : Int) -> String {
if x < margin || y < margin {
return ""
}
let (cw, ch, _) = self.cell()
let col = (x - margin) / cw
let row = (y - margin) / ch
let shown = self.shown(apps)
for i, cr in self.layout(apps) {
if cr == (col, row) {
return shown[i].id
}
}
""
}
///| Remember every shown icon where it is now, then put `id` at `to`, swapping with the icon
/// there (which takes `id`'s old cell).
fn Desk::move_to(self : Desk, apps : Array[@types.AppEntry], id : String, to : (Int, Int)) -> Unit {
let shown = self.shown(apps)
let cells = self.layout(apps)
let mut from = (-1, -1)
for i, a in shown {
if cells[i] != (-1, -1) {
self.places.set(a.id, cells[i])
}
if a.id == id {
from = cells[i]
}
}
for i, a in shown {
if a.id != id && cells[i] == to {
self.places.set(a.id, from)
}
}
self.places.set(id, to)
}
///| The `places` setting's value: "id=col,row" joined by ";".
pub fn Desk::encode_places(self : Desk) -> String {
let parts : Array[String] = []
for id, cr in self.places {
parts.push(id + "=" + cr.0.to_string() + "," + cr.1.to_string())
}
parts.join(";")
}
///| Read the `places` setting back (bad entries are skipped).
pub fn Desk::decode_places(self : Desk, s : String) -> Unit {
self.places.clear()
for part in s.split(";") {
let part = part.to_string()
match part.rev_find("=") {
None => ()
Some(eq) => {
let id = part[:eq].to_string()
let nums = part[eq + 1:].to_string().split(",").to_array()
if id.length() > 0 && nums.length() == 2 {
let c = nat(nums[0].to_string(), -1)
let r = nat(nums[1].to_string(), -1)
if c >= 0 && r >= 0 {
self.places.set(id, (c, r))
}
}
}
}
}
}
///| Move the selection one step in direction (dc, dr): the nearest icon that way.
fn Desk::step_selection(self : Desk, apps : Array[@types.AppEntry], dc : Int, dr : Int) -> Unit {
let shown = self.shown(apps)
let cells = self.layout(apps)
let mut cur = -1
for i, a in shown {
if a.id == self.selected {
cur = i
}
}
if cur < 0 {
if shown.length() > 0 {
self.selected = shown[0].id
}
return
}
let (c0, r0) = cells[cur]
let mut best = -1
let mut best_score = 0
for i = 0; i < shown.length(); i = i + 1 {
let (c, r) = cells[i]
if i == cur || c < 0 {
continue
}
let along = (c - c0) * dc + (r - r0) * dr
if along <= 0 {
continue
}
let across = if dc != 0 { (r - r0).abs() } else { (c - c0).abs() }
let score = along * 10 + across * 11
if best < 0 || score < best_score {
best = i
best_score = score
}
}
if best >= 0 {
self.selected = shown[best].id
}
}
///| Select the next app (after the selected one, wrapping) whose name starts with `k`.
fn Desk::jump_to(self : Desk, apps : Array[@types.AppEntry], k : String) -> Bool {
let shown = self.shown(apps)
let n = shown.length()
if n == 0 {
return false
}
let mut start = 0
for i, a in shown {
if a.id == self.selected {
start = i + 1
}
}
let key = k.to_lower()
for j = 0; j < n; j = j + 1 {
let a = shown[(start + j) % n]
if a.name.to_lower().has_prefix(key) {
self.selected = a.id
return true
}
}
false
}
///| An input event. Returns (redraw, what to do).
pub fn Desk::handle(self : Desk, apps : Array[@types.AppEntry], ev : @types.InputEvent) -> (Bool, Action) {
match ev {
PointerMove(p) => {
self.ptr_x = p.x
self.ptr_y = p.y
if self.press_id != "" && !self.dragging &&
((p.x - self.press_x).abs() > drag_threshold || (p.y - self.press_y).abs() > drag_threshold) {
self.dragging = true
}
if self.dragging {
return (true, NoAction)
}
let h = self.app_at(apps, p.x, p.y)
let changed = h != self.hover
self.hover = h
(changed, NoAction)
}
PointerLeave => {
let changed = self.hover != ""
self.hover = ""
(changed, NoAction)
}
PointerDown(p) => {
self.focused = true
self.ptr_x = p.x
self.ptr_y = p.y
let id = self.app_at(apps, p.x, p.y)
self.selected = id
self.press_id = id
self.press_x = p.x
self.press_y = p.y
self.dragging = false
(true, NoAction)
}
PointerUp(p) => {
let id = self.press_id
let was_drag = self.dragging
self.press_id = ""
self.dragging = false
if id == "" {
(false, NoAction)
} else if was_drag {
self.move_to(apps, id, self.cell_at(p.x, p.y))
self.hover = self.app_at(apps, p.x, p.y)
(true, NoAction)
} else if self.app_at(apps, p.x, p.y) == id {
(true, Launch(id))
} else {
(true, NoAction)
}
}
FocusLost => {
self.focused = false
self.press_id = ""
self.dragging = false
(true, NoAction)
}
KeyDown(k) => {
self.focused = true
match k {
"ArrowLeft" | "Left" => self.step_selection(apps, -1, 0)
"ArrowRight" | "Right" => self.step_selection(apps, 1, 0)
"ArrowUp" | "Up" => self.step_selection(apps, 0, -1)
"ArrowDown" | "Down" => self.step_selection(apps, 0, 1)
"Enter" | " " =>
return (false, if self.selected != "" { Launch(self.selected) } else { NoAction })
"Escape" => self.selected = ""
_ => if k.length() == 1 { ignore(self.jump_to(apps, k)) } else { return (false, NoAction) }
}
(true, NoAction)
}
}
}
///| A label that fits `max_w` pixels at text size `fs`: cut with "..." when too long.
fn fit_label(s : String, fs : Int, max_w : Int) -> String {
if @ui.text_width(s, fs) <= max_w {
return s
}
let mut n = s.length()
while n > 1 && @ui.text_width(s[:n].to_string() + "...", fs) > max_w {
n = n - 1
}
s[:n].to_string() + "..."
}
///| One icon with its label, its cell's top-left at (x, y).
fn Desk::draw_icon(
self : Desk,
ops : Array[@types.DrawOp],
a : @types.AppEntry,
x : Int,
y : Int,
tokens : @theme.Tokens,
icon : (String) -> UInt,
lifted~ : Bool = false,
) -> Unit {
let (cw, ch, isz) = self.cell()
let fs = tokens.font_size.reinterpret_as_int() - 2
let r = tokens.radius.reinterpret_as_int()
let sel = a.id == self.selected
if lifted || sel || a.id == self.hover {
let base = if sel || lifted { tokens.palette.accent } else { tokens.palette.surface_hover }
let alpha = if lifted { 120 } else if sel && self.focused { 110 } else if sel { 60 } else { 90 }
ops.push(@ui.fill_rect(@ui.rect(x + 4, y + 2, cw - 8, ch - 4), @ui.with_alpha(base, alpha), radius=r))
if sel && self.focused {
ops.push(@ui.stroke_rect(@ui.rect(x + 4, y + 2, cw - 8, ch - 4), tokens.palette.accent, radius=r))
}
}
let ix = x + (cw - isz) / 2
let iy = y + 8
let h = icon(a.id)
if h != 0U {
ops.push(@types.DrawOp::Image({ rect: @ui.rect(ix, iy, isz, isz), image: h }))
} else {
let glyph = if a.glyph.length() > 0 { a.glyph } else { @dock.app_glyph(a.id, a.name) }
for op in @dock.app_icon(ix + isz / 2, iy + isz / 2, isz, a.id, glyph) {
ops.push(op)
}
}
// The label, with a soft shadow so it reads on any wallpaper.
let label = fit_label(a.name, fs, cw - 8)
let ty = iy + isz + 6 + fs / 2 + 2
ops.push(@ui.text(x + cw / 2 + 1, ty + 1, label, fs, @ui.color(0, 0, 0, 170), align=CENTER))
ops.push(@ui.text(x + cw / 2, ty, label, fs, @ui.color(255, 255, 255, 255), align=CENTER))
}
///| Draw the icons over the wallpaper. `icon` gives an app id's theme icon handle (0: none, a
/// letter tile is drawn instead).
pub fn Desk::render(
self : Desk,
apps : Array[@types.AppEntry],
size : @types.Size,
tokens : @theme.Tokens,
icon : (String) -> UInt,
) -> Array[@types.DrawOp] {
self.w = size.w.reinterpret_as_int()
self.h = size.h.reinterpret_as_int()
self.bottom = tokens.panel_height.reinterpret_as_int()
let ops : Array[@types.DrawOp] = []
let shown = self.shown(apps)
let cells = self.layout(apps)
let mut dragged : @types.AppEntry? = None
for i, a in shown {
let (c, r) = cells[i]
if c < 0 {
continue
}
if self.dragging && a.id == self.press_id {
dragged = Some(a)
// Where it will land.
let (cw, ch, _) = self.cell()
let (tc, tr) = self.cell_at(self.ptr_x, self.ptr_y)
let (tx, ty) = self.cell_origin(tc, tr)
ops.push(
@ui.stroke_rect(@ui.rect(tx + 4, ty + 2, cw - 8, ch - 4), @ui.with_alpha(tokens.palette.foreground, 140), width=2, radius=tokens.radius.reinterpret_as_int()),
)
continue
}
let (x, y) = self.cell_origin(c, r)
self.draw_icon(ops, a, x, y, tokens, icon)
}
match dragged {
Some(a) => {
let (cw, ch, _) = self.cell()
self.draw_icon(ops, a, self.ptr_x - cw / 2, self.ptr_y - ch / 2, tokens, icon, lifted=true)
}
None => ()
}
ops
}
///| The right-click settings; `places` has no label (hidden, saved by the shell).
pub fn Desk::config_items(self : Desk) -> Array[ConfigEntry] {
[
{ key: "count", label: "Apps shown", choices: count_choices, value: self.count },
{ key: "size", label: "Icon size", choices: size_choices, value: self.size },
{ key: "places", label: "", choices: [], value: self.encode_places() },
]
}
///| Set one; true when it changed something on screen.
pub fn Desk::set_config(self : Desk, key : String, value : String) -> Bool {
match key {
"count" if count_choices.contains(value) => {
self.count = value
true
}
"size" if size_choices.contains(value) => {
self.size = value
true
}
"places" => {
self.decode_places(value)
true
}
_ => false
}
}
///| The one instance the component drives (its plasmoid, desktop-module and module-config
/// exports share it).
pub let state : Desk = Desk::new()
+87
View File
@@ -0,0 +1,87 @@
///|
fn apps(n : Int) -> Array[@types.AppEntry] {
Array::makei(n, i => {
id: "app" + i.to_string(),
name: ["Files", "Firefox", "Konsole", "Kate", "Gimp", "Foot"][i % 6] + i.to_string(),
comment: "",
category: "",
glyph: "A",
})
}
///|
fn desk() -> @icondesk.Desk {
let d = @icondesk.Desk::new()
// 1000 x 600 with a 40 px panel: medium cells (96) -> 10 columns, 5 rows.
d.w = 1000
d.h = 600
d.bottom = 40
d
}
///|
test "icons fill the grid a column at a time" {
let d = desk()
assert_eq(d.grid(), (10, 5))
let a = apps(20)
let cells = d.layout(a)
assert_eq(cells.length(), 12) // "12" apps shown by default
assert_eq(cells[0], (0, 0))
assert_eq(cells[4], (0, 4))
assert_eq(cells[5], (1, 0))
ignore(d.set_config("count", "All"))
assert_eq(d.layout(a).length(), 20)
}
///|
test "click launches, drag moves and swaps, positions round-trip through the setting" {
let d = desk()
let a = apps(12)
// Cell (0,0) holds app0 at x 20..116, y 20..116.
assert_eq(d.app_at(a, 60, 60), "app0")
assert_eq(d.app_at(a, 5, 5), "")
ignore(d.handle(a, PointerDown({ x: 60, y: 60 })))
assert_eq(d.handle(a, PointerUp({ x: 61, y: 61 })), (true, Launch("app0")))
// Drag app0 onto app5's cell (1,0): they swap.
ignore(d.handle(a, PointerDown({ x: 60, y: 60 })))
ignore(d.handle(a, PointerMove({ x: 120, y: 62 })))
assert_true(d.dragging)
assert_eq(d.handle(a, PointerUp({ x: 160, y: 62 })), (true, NoAction))
let cells = d.layout(a)
assert_eq(cells[0], (1, 0))
assert_eq(cells[5], (0, 0))
// Drag app1 to an empty cell far away.
ignore(d.handle(a, PointerDown({ x: 60, y: 150 })))
ignore(d.handle(a, PointerMove({ x: 900, y: 400 })))
ignore(d.handle(a, PointerUp({ x: 900, y: 400 })))
assert_eq(d.layout(a)[1], (9, 3))
// The hidden setting keeps it.
let saved = d.config_items().filter(c => c.key == "places")[0]
assert_eq(saved.label, "")
let d2 = desk()
ignore(d2.set_config("places", saved.value))
assert_eq(d2.layout(a), d.layout(a))
// A place off the grid (a smaller screen) falls back to a free cell.
d2.w = 400
assert_true(d2.layout(a)[1].0 < 3)
}
///|
test "keyboard moves the selection and launches" {
let d = desk()
let a = apps(12)
ignore(d.handle(a, KeyDown("ArrowDown")))
assert_eq(d.selected, "app0")
ignore(d.handle(a, KeyDown("ArrowDown")))
assert_eq(d.selected, "app1")
ignore(d.handle(a, KeyDown("ArrowRight")))
assert_eq(d.selected, "app6")
assert_eq(d.handle(a, KeyDown("Enter")), (false, Launch("app6")))
// A letter jumps to the next app with that initial.
ignore(d.handle(a, KeyDown("k")))
assert_eq(d.selected, "app8") // Konsole8 (Kate9 comes after it)
ignore(d.handle(a, KeyDown("Escape")))
assert_eq(d.selected, "")
ignore(d.handle(a, FocusLost))
assert_false(d.focused)
}
+6
View File
@@ -0,0 +1,6 @@
import {
"chandra/desktop/interface/chandra/desktop/types" @types,
"chandra/desktop/interface/chandra/desktop/theme" @theme,
"chandra/desktop/lib/ui" @ui,
"chandra/desktop/lib/dock" @dock,
}
+5
View File
@@ -0,0 +1,5 @@
import {
"chandra/desktop/interface/chandra/desktop/types" @types,
"chandra/desktop/interface/chandra/desktop/theme" @theme,
"chandra/desktop/lib/ui" @ui,
}
+395
View File
@@ -0,0 +1,395 @@
///| Starfield: the animated sample desktop module (components/starfield). Stars fly towards the
/// viewer out of a vanishing point that follows the pointer; the wheel changes speed, a click (or
/// Space) sends a warp pulse that streaks the stars for a moment. It replaces the wallpaper.
///
/// Pacing: `tick` asks for a frame every 33 ms (30 a second) while anything moves and returns 0
/// once nothing does, so with Motion set to Still the desktop costs nothing between events (a
/// pulse or a steer then animates until it settles, and stops again).
///
/// Pure: the component hands in the theme, the size and the events; everything is in `Field`.
///| Frame interval while animating, in ms.
pub let frame_ms : UInt = 33
///| Speed choices and their depth units per second.
pub let speed_choices : Array[String] = ["Slow", "Normal", "Fast"]
///|
pub let density_choices : Array[String] = ["Sparse", "Normal", "Dense"]
///|
pub let motion_choices : Array[String] = ["Moving", "Still"]
///| One item of the module's right-click settings (the `module-config` record).
#derive(Eq, Debug)
pub(all) struct ConfigEntry {
key : String
label : String
choices : Array[String]
value : String
}
///| A star in normalised space: x, y in [-1, 1], depth z in (0, 1] (1: far).
struct Star {
mut x : Double
mut y : Double
mut z : Double
/// Depth one frame ago, for the warp streaks.
mut pz : Double
}
///| The starfield's state.
pub(all) struct Field {
stars : Array[Star]
mut seed : UInt
mut speed : String
mut density : String
mut motion : String
/// Wheel multiplier on the speed, 0.25 .. 4.
mut boost : Double
/// Warp pulse, 1 right after a click, decaying to 0.
mut pulse : Double
/// Vanishing point offset from the centre (pixels), and where the pointer pulls it.
mut cx : Double
mut cy : Double
mut tx : Double
mut ty : Double
mut w : Int
mut h : Int
/// The clock at the last tick (ms since load), -1 before the first.
mut last : Int
/// Frames drawn, for tests.
mut frames : Int
}
///|
pub fn Field::new() -> Field {
let f : Field = {
stars: [],
seed: 0x2545F491U,
speed: "Normal",
density: "Normal",
motion: "Moving",
boost: 1.0,
pulse: 0.0,
cx: 0.0,
cy: 0.0,
tx: 0.0,
ty: 0.0,
w: 0,
h: 0,
last: -1,
frames: 0,
}
f.populate()
f
}
///| Uniform in [0, 1).
fn Field::rand(self : Field) -> Double {
// xorshift32
let mut s = self.seed
s = s ^ (s << 13)
s = s ^ (s >> 17)
s = s ^ (s << 5)
self.seed = s
(s >> 8).to_double() / 16777216.0
}
///|
fn Field::star_count(self : Field) -> Int {
match self.density {
"Sparse" => 180
"Dense" => 640
_ => 360
}
}
///| (Re)create the stars for the density, spread through the whole depth.
fn Field::populate(self : Field) -> Unit {
self.stars.clear()
for i = 0; i < self.star_count(); i = i + 1 {
// Spread over what is on screen at that depth (|x| < z), as if they had flown in from afar.
let z = 0.05 + 0.95 * self.rand()
self.stars.push({ x: (self.rand() * 2.0 - 1.0) * z, y: (self.rand() * 2.0 - 1.0) * z, z, pz: z })
}
}
///| Depth units per second.
fn Field::velocity(self : Field) -> Double {
let base = match self.speed {
"Slow" => 0.05
"Fast" => 0.32
_ => 0.13
}
let still = self.motion == "Still"
(if still { 0.0 } else { base * self.boost }) + self.pulse * 1.6
}
///| True while something on screen still moves (a frame is wanted).
pub fn Field::animating(self : Field) -> Bool {
self.velocity() > 0.0 ||
self.pulse > 0.0 ||
(self.tx - self.cx).abs() > 0.5 ||
(self.ty - self.cy).abs() > 0.5
}
///| The animation clock (`desktop-module.tick`): advance to `now` (ms since load) and return the
/// ms until the next frame, 0 when nothing moves.
pub fn Field::tick(self : Field, now : UInt) -> UInt {
let now = now.reinterpret_as_int()
let dt = if self.last < 0 {
0.0
} else {
let d = now - self.last
// A long gap (paused while covered, or idle) restarts smoothly instead of jumping.
(if d < 0 { 0 } else if d > 100 { 33 } else { d }).to_double() / 1000.0
}
self.last = now
self.step(dt)
if self.animating() {
frame_ms
} else {
0
}
}
///| Advance the simulation by `dt` seconds.
pub fn Field::step(self : Field, dt : Double) -> Unit {
let v = self.velocity()
for s in self.stars {
s.pz = s.z
s.z = s.z - v * dt
// Flown past the viewer, or out of the side of the view: start again far away.
if s.z <= 0.03 || s.x.abs() > s.z * 1.2 || s.y.abs() > s.z * 1.2 {
s.x = self.rand() * 2.0 - 1.0
s.y = self.rand() * 2.0 - 1.0
s.z = 1.0
s.pz = 1.0
}
}
// The pulse fades over about a second; the vanishing point eases towards the pointer.
self.pulse = if self.pulse < 0.02 { 0.0 } else { self.pulse * (1.0 - (dt * 2.5).min(1.0)) }
let k = (dt * 4.0).min(1.0)
self.cx = self.cx + (self.tx - self.cx) * k
self.cy = self.cy + (self.ty - self.cy) * k
if (self.tx - self.cx).abs() <= 0.5 {
self.cx = self.tx
}
if (self.ty - self.cy).abs() <= 0.5 {
self.cy = self.ty
}
}
///| An input event (`plasmoid.on-event`). True when a redraw is wanted now (the tick that follows
/// every event takes care of the animation).
pub fn Field::handle(self : Field, ev : @types.InputEvent) -> Bool {
match ev {
PointerMove(p) => {
// The pointer pulls the vanishing point a fifth of the way towards it.
self.tx = (p.x - self.w / 2).to_double() * 0.2
self.ty = (p.y - self.h / 2).to_double() * 0.2
false
}
PointerLeave => {
self.tx = 0.0
self.ty = 0.0
false
}
PointerDown(_) => {
self.pulse = 1.0
true
}
KeyDown(" ") => {
self.pulse = 1.0
true
}
KeyDown("+") | KeyDown("=") => {
ignore(self.scroll(-10))
true
}
KeyDown("-") => {
ignore(self.scroll(10))
true
}
_ => false
}
}
///| Wheel (`desktop-module.on-scroll`): up is faster, down slower. True: redraw.
pub fn Field::scroll(self : Field, dy : Int) -> Bool {
if dy == 0 {
return false
}
let f = if dy < 0 { 1.25 } else { 0.8 }
self.boost = (self.boost * f).max(0.25).min(4.0)
true
}
///|
fn shade(c : @types.Color, num : Int, den : Int) -> @types.Color {
@ui.color(
c.r.to_int() * num / den,
c.g.to_int() * num / den,
c.b.to_int() * num / den,
255,
)
}
///| Draw the whole desktop, `size` being the output.
pub fn Field::render(self : Field, size : @types.Size, tokens : @theme.Tokens) -> Array[@types.DrawOp] {
let w = size.w.reinterpret_as_int()
let h = size.h.reinterpret_as_int()
self.w = w
self.h = h
self.frames = self.frames + 1
let ops : Array[@types.DrawOp] = []
// Deep space: the theme's desktop colours, much darker, in bands from top to bottom.
let top = shade(tokens.palette.desktop_top, 1, 4)
let bottom = shade(tokens.palette.desktop_bottom, 1, 3)
let bands = 16
for i = 0; i < bands; i = i + 1 {
let y0 = h * i / bands
let y1 = h * (i + 1) / bands
ops.push(@ui.fill_rect(@ui.rect(0, y0, w, y1 - y0), @ui.lerp_color(top, bottom, i, bands - 1)))
}
// Two faint nebulae in the accent colour, drifting a little with the vanishing point.
let neb = tokens.palette.accent
let big = if w > h { w } else { h }
for k = 0; k < 6; k = k + 1 {
let r = big * (12 - k) / 40
ops.push(@ui.circle(w * 3 / 10 - self.cx.to_int() / 3, h * 2 / 5 - self.cy.to_int() / 3, r, @ui.with_alpha(neb, 3 + k)))
ops.push(@ui.circle(w * 3 / 4 - self.cx.to_int() / 4, h * 3 / 4 - self.cy.to_int() / 4, r * 2 / 3, @ui.with_alpha(@ui.color(180, 90, 200, 255), 2 + k)))
}
let ox = w / 2 + self.cx.to_int()
let oy = h / 2 + self.cy.to_int()
let scale = (if w > h { w } else { h }).to_double() * 0.5
let tint = tokens.palette.accent
let streak = self.pulse > 0.15
for s in self.stars {
let sx = ox + (s.x / s.z * scale).to_int()
let sy = oy + (s.y / s.z * scale).to_int()
if sx < -4 || sy < -4 || sx > w + 4 || sy > h + 4 {
continue
}
let near = 1.0 - s.z // 0 far .. 1 near
let lum = 120 + (near * 135.0).to_int()
// Near stars pick up a little of the accent colour.
let c = @ui.lerp_color(@ui.color(lum, lum, lum, 255), tint, (near * near * 40.0).to_int(), 100)
let r = 1 + (near * 3.4).to_int()
if streak && s.pz > s.z {
let px = ox + (s.x / s.pz * scale).to_int()
let py = oy + (s.y / s.pz * scale).to_int()
ops.push(@ui.line(px, py, sx, sy, c, width=r))
} else if r <= 1 {
ops.push(@ui.fill_rect(@ui.rect(sx, sy, 1, 1), c))
} else {
ops.push(@ui.fill_rect(@ui.rect(sx - r / 2, sy - r / 2, r, r), c, radius=r / 2))
}
}
ops
}
///| The right-click settings.
pub fn Field::config_items(self : Field) -> Array[ConfigEntry] {
[
{ key: "speed", label: "Speed", choices: speed_choices, value: self.speed },
{ key: "density", label: "Stars", choices: density_choices, value: self.density },
{ key: "motion", label: "Motion", choices: motion_choices, value: self.motion },
]
}
///| Set one; true when it changed something on screen.
pub fn Field::set_config(self : Field, key : String, value : String) -> Bool {
match key {
"speed" if speed_choices.contains(value) => {
self.speed = value
self.boost = 1.0
true
}
"density" if density_choices.contains(value) => {
if self.density != value {
self.density = value
self.populate()
}
true
}
"motion" if motion_choices.contains(value) => {
self.motion = value
true
}
_ => false
}
}
///|
test "moving stars keep asking for frames; still ones stop once settled" {
let f = Field::new()
assert_eq(f.tick(0), frame_ms)
assert_eq(f.tick(33), frame_ms)
ignore(f.set_config("motion", "Still"))
assert_eq(f.tick(66), 0)
// A click warps: frames until the pulse has faded, then sleep again.
ignore(f.handle(PointerDown({ x: 10, y: 10 })))
assert_eq(f.tick(99), frame_ms)
let mut t = 99
let mut n = 0
while f.tick(t.reinterpret_as_uint()) != 0 && n < 200 {
t = t + 33
n = n + 1
}
assert_true(n > 5 && n < 200)
// Steering eases towards the pointer, then stops.
f.w = 1000
f.h = 800
ignore(f.handle(PointerMove({ x: 900, y: 400 })))
assert_eq(f.tick((t + 33).reinterpret_as_uint()), frame_ms)
n = 0
while f.tick((t + 66 + n * 33).reinterpret_as_uint()) != 0 && n < 200 {
n = n + 1
}
assert_true(n < 200)
assert_eq(f.cx, 80.0)
}
///|
test "render fills the output and draws the stars" {
let f = Field::new()
let tokens : @theme.Tokens = {
name: "t",
palette: {
desktop_top: @ui.color(20, 30, 60, 255),
desktop_bottom: @ui.color(10, 10, 30, 255),
surface: @ui.color(0, 0, 0, 255),
surface_hover: @ui.color(0, 0, 0, 255),
surface_popup: @ui.color(0, 0, 0, 255),
foreground: @ui.color(255, 255, 255, 255),
foreground_muted: @ui.color(200, 200, 200, 255),
accent: @ui.color(100, 150, 255, 255),
accent_foreground: @ui.color(0, 0, 0, 255),
border: @ui.color(50, 50, 50, 255),
},
font_size: 14,
radius: 6,
spacing: 6,
panel_height: 40,
}
let ops = f.render(@ui.size(1280, 720), tokens)
match ops[0] {
FillRect(r) => assert_eq((r.rect.x, r.rect.y, r.rect.w), (0, 0, 1280))
_ => fail("background first")
}
assert_true(ops.length() > 100)
// Wheel speeds up and slows down within bounds.
for _ in 0..<20 {
ignore(f.scroll(-10))
}
assert_eq(f.boost, 4.0)
ignore(f.set_config("density", "Dense"))
assert_eq(f.stars.length(), 640)
assert_false(f.set_config("density", "Huge"))
}
///| The one instance the component drives (its plasmoid, desktop-module and module-config
/// exports share it).
pub let state : Field = Field::new()
+2
View File
@@ -10,3 +10,5 @@ session-settings session-settings-widget
screenshot screenshot-widget
battery battery-widget
network network-widget
icon-desktop icon-desktop-widget
starfield starfield-widget
+35
View File
@@ -262,6 +262,7 @@ fn request_val(r : @wasm.HostRequest) -> @wt.Val {
Shortcut(n) => Variant("shortcut", Some(S32(n)))
ReloadSession => Variant("reload-session", None)
DefaultApp(n) => Variant("default-app", Some(S32(n)))
SetDesktop(n) => Variant("set-desktop", Some(S32(n)))
}
}
@@ -404,6 +405,40 @@ fn plasmoid_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] {
none
},
),
(
"desktop-backdrop",
a => with_module(a, m => s32(m.desktop_backdrop()), s32(-1)),
),
(
"desktop-scroll",
a => with_module(
a,
m => boolean(
m.desktop_scroll(
a[1].to_int(),
a[2].to_int(),
a[3].to_int(),
a[4].to_int(),
),
),
boolean(false),
),
),
(
"desktop-tick",
a => with_module(
a,
m => [U32(m.desktop_tick(a[1].to_uint().reinterpret_as_int()).reinterpret_as_uint())],
[U32(0)],
),
),
(
"publish-desktop",
a => {
@wasm.publish_desktop(a[0].to_int())
none
},
),
(
"publish-wallpaper",
a => {
+7
View File
@@ -140,6 +140,13 @@ interface wallpaper {
current-wallpaper: func() -> u32;
/// Show wallpaper `index` (out-of-range indices are ignored). The choice is remembered.
set-wallpaper: func(index: u32);
/// What fills the desktop, as display names indexed by choice: 0 "Wallpaper only", 1 "Clock
/// card" (the built-in card), then every installed desktop module (docs/desktop-modules.md).
desktops: func() -> list<string>;
current-desktop: func() -> u32;
/// Put desktop `index` on the desktop (out-of-range indices are ignored). The choice is
/// remembered (state.edn `:desktop`).
set-desktop: func(index: u32);
}
/// Session settings: how the login session starts, what it remembers and how it looks (dark or
+48
View File
@@ -0,0 +1,48 @@
package chandra:desktop@0.1.0;
/// Optional export that turns a module into a desktop module: instead of a box in the panel it
/// owns the desktop itself, the whole output behind the windows (see docs/desktop-modules.md).
///
/// A desktop module is still a plasmoid (it exports `plasmoid` as well, and may export
/// `module-config` and import any capability a panel module can), so the same sandbox, draw ops
/// and capability grants apply. What changes is how the shell drives it:
///
/// - `plasmoid.render` is called with the output's full size (and again with the new size when
/// the output is resized), in desktop coordinates: (0, 0) is the output's top-left corner.
/// The panel and windows are drawn on top; the module draws the whole area.
/// - `plasmoid.on-event` gets the pointer (move, press, release, leave) only where no window,
/// panel, popup or menu covers the desktop, and keys only while the desktop has keyboard focus
/// (after a click on it, until a window is focused: it then gets `focus-lost`). A right-click
/// on the empty desktop always opens the shell's desktop menu (module settings, system
/// settings), never reaches the module.
/// - `plasmoid.popup` and `plasmoid.info`'s size fields are not used.
/// - Hidden settings (a `module-config` item with an empty label) are saved by the shell in
/// state.edn whenever their value changes after an event, and handed back at the next load:
/// that is how a desktop module keeps state such as icon positions.
interface desktop-module {
use types.{point};
/// What happens to the wallpaper under the module.
enum wallpaper-mode {
/// The wallpaper is drawn first and the module draws over it (leaving parts transparent).
over-wallpaper,
/// The module draws the whole background itself; the wallpaper is not drawn.
replace-wallpaper,
}
/// Read once, right after loading.
backdrop: func() -> wallpaper-mode;
/// Wheel or touchpad scroll over the empty desktop at `at`: `dx` / `dy` in pixels (positive:
/// right / down; one wheel notch is about 10). True when the module wants a redraw.
on-scroll: func(at: point, dx: s32, dy: s32) -> bool;
/// The animation clock. `now-ms` counts milliseconds from when the module was loaded. It is
/// called once after loading, after every event the module handled, and again when the delay it
/// last returned has passed. The module is redrawn after each timed call (an animation frame)
/// and after events that returned true; a call that follows an event only reschedules the
/// clock and does not redraw by itself. Return how many ms until the
/// next frame (16 for about 60 frames a second, 33 for 30), or 0 to sleep until the next event:
/// an idle desktop module costs nothing, so return 0 whenever nothing moves. Frames are paused
/// (no calls) while a window covers the whole desktop.
tick: func(now-ms: u32) -> u32;
}
+16 -1
View File
@@ -48,6 +48,16 @@ interface plasmoids {
/// Set one of them. True when the module wants a redraw (false without module-config).
set-config: func(handle: u32, key: string, value: string) -> bool;
/// Desktop modules (chandra:desktop/desktop-module, wit/desktop.wit): the module's backdrop (0
/// over the wallpaper, 1 replacing it), or -1 when it doesn't export desktop-module (a panel
/// module).
desktop-backdrop: func(handle: u32) -> s32;
/// Scroll over the desktop at (x, y), `dx` / `dy` pixels. True when it wants a redraw.
desktop-scroll: func(handle: u32, x: s32, y: s32, dx: s32, dy: s32) -> bool;
/// The module's animation clock (`now-ms` since it was loaded): ms until it wants the next
/// frame, 0 for none.
desktop-tick: func(handle: u32, now-ms: u32) -> u32;
// ---- host data modules read through their capabilities ----
/// Row tables, as built by compositor/wasm: a LE u32 row count, then per row each field as a LE
@@ -58,12 +68,15 @@ interface plasmoids {
/// 8 network status (one row, iissiiii: state signal name message wifi-enabled airplane
/// can-manage has-wifi), 9 Wi-Fi networks (siiii: ssid signal secured active saved), 10 keyboard
/// shortcuts (ssssi: name binding default-binding conflict capturing), 11 default-app
/// categories (sss: name current missing), 12 default-app choices (issii: category id name icon current).
/// categories (sss: name current missing), 12 default-app choices (issii: category id name icon current),
/// 20 desktops (s: name) served by `wallpaper.desktops`.
publish-table: func(which: u32, rows: list<u8>);
/// Layout mode (0 tiling, 1 monocle, 2 floating) and whether the Interface Explorer is on.
publish-state: func(layout-mode: s32, inspector-on: bool);
/// The wallpaper on the desktop now (an index into the wallpapers table).
publish-wallpaper: func(current: s32);
/// What is on the desktop now (an index into the desktops table).
publish-desktop: func(current: s32);
/// Which session settings are on: bit i for row i of the session settings table.
publish-session-settings: func(on: u32);
/// The power timeouts, in minutes (0: never).
@@ -146,6 +159,8 @@ interface plasmoids {
/// The default-apps capability: category * 1000 + app (set that category's default to its
/// app-th app), or -1 to scan the apps and defaults again.
default-app(s32),
/// The wallpaper capability's `set-desktop`: an index into the desktops table.
set-desktop(s32),
}
/// The next pending request, oldest first.
next-request: func() -> option<request>;
+32
View File
@@ -18,6 +18,12 @@ world configurable {
export module-config;
}
/// The optional `desktop-module` export on its own (wit/desktop.wit): what makes a module a
/// desktop module. Hosts look it up by name like `module-config` (host-wasm binds this world).
world desktop-export {
export desktop-module;
}
/// The application launcher. The launcher's popup
/// also ends in a session row: Reload, Log out, Suspend, Restart, Power off.
world launcher-widget {
@@ -133,3 +139,29 @@ world network-widget {
include widget;
import network;
}
/// A desktop module (wit/desktop.wit): a plasmoid drawn full screen behind the windows. The
/// minimum: theme tokens in, draw ops and input, the animation clock.
world desktop-widget {
include widget;
export desktop-module;
}
/// Sample desktop module: app icons on the desktop. Click one to start the app, drag it to
/// arrange the grid (positions are kept as a hidden setting); arrow keys, Enter and typing pick
/// one. Its settings choose how many apps and how big.
world icon-desktop-widget {
include desktop-widget;
import app-catalog;
import app-launch;
import icons;
export module-config;
}
/// Sample desktop module: an animated starfield replacing the wallpaper. The pointer steers it,
/// the wheel changes speed, a click sends a warp pulse; it animates at 30 frames a second and
/// sleeps when its settings say Still.
world starfield-widget {
include desktop-widget;
export module-config;
}
+3
View File
@@ -0,0 +1,3 @@
Sample desktop module: app icons on the desktop. Click one to start the app, drag it to
arrange the grid (positions are kept as a hidden setting); arrow keys, Enter and typing pick
one. Its settings choose how many apps and how big.
+2
View File
@@ -0,0 +1,2 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
+2
View File
@@ -0,0 +1,2 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
+1
View File
@@ -0,0 +1 @@
warnings = "-44"
+3
View File
@@ -0,0 +1,3 @@
Sample desktop module: an animated starfield replacing the wallpaper. The pointer steers it,
the wheel changes speed, a click sends a warp pulse; it animates at 30 frames a second and
sleeps when its settings say Still.
+2
View File
@@ -0,0 +1,2 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
+2
View File
@@ -0,0 +1,2 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
+1
View File
@@ -0,0 +1 @@
warnings = "-44"