Module settings in each module's right-click menu, and System settings
CI / test (push) Failing after 15s

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjuApkJR4sVRYDpDLy
This commit is contained in:
Claude committed 2026-11-25 18:58:43 +00:00
1 parent a7909014b8
commit 4fc4a963b4
37 files changed
+1266 -109

No files matched your search

+32 -14
View File
@@ -50,24 +50,30 @@ pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int {
@plasmoid.wasmExportRender(p0, p1) @plasmoid.wasmExportRender(p0, p1)
} }
///|
#doc(hidden)
pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportInfoPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportRenderPostReturn(p0)
}
///| ///|
#doc(hidden) #doc(hidden)
pub fn wasmExportPopup() -> Int { pub fn wasmExportPopup() -> Int {
@plasmoid.wasmExportPopup() @plasmoid.wasmExportPopup()
} }
///|
#doc(hidden)
pub fn wasmExportConfigItems() -> Int {
@module-config.wasmExportConfigItems()
}
///|
#doc(hidden)
pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
@plasmoid.wasmExportOnEvent(p0, p1, p2, p3)
}
///|
#doc(hidden)
pub fn wasmExportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
@module-config.wasmExportSetConfig(p0, p1, p2, p3)
}
///| ///|
#doc(hidden) #doc(hidden)
pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit { pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
@@ -76,7 +82,19 @@ pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
///| ///|
#doc(hidden) #doc(hidden)
pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportOnEvent(p0, p1, p2, p3) @plasmoid.wasmExportInfoPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportConfigItemsPostReturn(p0 : Int) -> Unit {
@module-config.wasmExportConfigItemsPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportRenderPostReturn(p0)
} }
@@ -0,0 +1,5 @@
Optional: a module's own settings. A module that exports this gets a "Module settings" entry in
its right-click menu, listing the items below; the shell draws the menu (the same for every
module), remembers each choice per module in state.edn (`:module-config`), and hands the saved
values back through `set-config` right after the module is loaded. A module without it simply
has no settings: the export is looked up by name, so older modules keep loading.
@@ -0,0 +1,114 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
#doc(hidden)
pub fn wasmExportConfigItems() -> Int {
let (result) : (Array[ConfigItem]) = config_items();
let return_area = mbt_ffi_malloc(8)
let address3 = mbt_ffi_malloc((result).length() * 32);
for index4 = 0; index4 < (result).length(); index4 = index4 + 1 {
let iter_elem : ConfigItem = (result)[(index4)]
let iter_base = address3 + (index4 * 32);
let ptr = mbt_ffi_str2ptr((iter_elem).key)
mbt_ffi_store32((iter_base) + 4, (iter_elem).key.length())
mbt_ffi_store32((iter_base) + 0, ptr)
let ptr0 = mbt_ffi_str2ptr((iter_elem).label)
mbt_ffi_store32((iter_base) + 12, (iter_elem).label.length())
mbt_ffi_store32((iter_base) + 8, ptr0)
let address = mbt_ffi_malloc(((iter_elem).choices).length() * 8);
for index = 0; index < ((iter_elem).choices).length(); index = index + 1 {
let iter_elem : String = ((iter_elem).choices)[(index)]
let iter_base = address + (index * 8);
let ptr1 = mbt_ffi_str2ptr(iter_elem)
mbt_ffi_store32((iter_base) + 4, iter_elem.length())
mbt_ffi_store32((iter_base) + 0, ptr1)
}
mbt_ffi_store32((iter_base) + 20, ((iter_elem).choices).length())
mbt_ffi_store32((iter_base) + 16, address)
let ptr2 = mbt_ffi_str2ptr((iter_elem).value)
mbt_ffi_store32((iter_base) + 28, (iter_elem).value.length())
mbt_ffi_store32((iter_base) + 24, ptr2)
}
mbt_ffi_store32((return_area) + 4, (result).length())
mbt_ffi_store32((return_area) + 0, address3)
let ret = return_area
return ret
}
///|
#doc(hidden)
pub fn wasmExportConfigItemsPostReturn(p0 : Int) -> Unit {
for index0 = 0; index0 < (mbt_ffi_load32((p0) + 4)); index0 = index0 + 1 {
let iter_base = (mbt_ffi_load32((p0) + 0)) + (index0 * 32)
mbt_ffi_free(mbt_ffi_load32((iter_base) + 0))
mbt_ffi_free(mbt_ffi_load32((iter_base) + 8))
for index = 0; index < (mbt_ffi_load32((iter_base) + 20)); index = index + 1 {
let iter_base = (mbt_ffi_load32((iter_base) + 16)) + (index * 8)
mbt_ffi_free(mbt_ffi_load32((iter_base) + 0))
}
mbt_ffi_free(mbt_ffi_load32((iter_base) + 16))
mbt_ffi_free(mbt_ffi_load32((iter_base) + 24))
}
mbt_ffi_free(mbt_ffi_load32((p0) + 0))
}
///|
#doc(hidden)
pub fn wasmExportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
let result = mbt_ffi_ptr2str(p0, p1)
let result0 = mbt_ffi_ptr2str(p2, p3)
let (result1) : (Bool) = set_config(result, result0);
let ret = (if result1 { 1 } else { 0 })
return ret
}
///|
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) local.get 0)
///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#|(func (param i32) (result i32) (local i32)
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
#| local.tee 1 i32.const 0 call $moonbit.init_array8
#| local.get 1)
///|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
@@ -0,0 +1,5 @@
import {
"chandra/desktop/lib/clock" @logic,
}
warnings = "-44"
@@ -0,0 +1,21 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/clock-binary/gen/interface/chandra/desktop/module-config"
// Values
pub fn config_items() -> Array[ConfigItem]
pub fn set_config(String, String) -> Bool
// Errors
// Types and methods
pub(all) struct ConfigItem {
key : String
label : String
choices : Array[String]
value : String
}
// Type aliases
// Traits
@@ -0,0 +1,16 @@
///| The binary clock's right-click settings (seconds columns); the logic is in lib/clock.
///|
pub fn config_items() -> Array[ConfigItem] {
@logic.binary_config.binary_items().map(e => {
key: e.key,
label: e.label,
choices: e.choices,
value: e.value,
})
}
///|
pub fn set_config(key : String, value : String) -> Bool {
@logic.binary_config.set(key, value)
}
@@ -0,0 +1,11 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
pub(all) struct ConfigItem {
key : String; label : String; choices : Array[String]; value : String
}
///|
declare pub fn config_items() -> Array[ConfigItem]
///|
/// Set `key` to `value` (unknown keys and values are ignored). True when the widget should redraw.
declare pub fn set_config(key : String, value : String) -> Bool
@@ -15,7 +15,7 @@ pub fn info() -> PlasmoidInfo {
///| ///|
pub fn render(size : @types.Size) -> Array[@types.DrawOp] { pub fn render(size : @types.Size) -> Array[@types.DrawOp] {
@logic.render_binary(size, @theme.get_tokens(), @clock.now()) @logic.render_binary(size, @theme.get_tokens(), @clock.now(), seconds=@logic.binary_config.seconds)
} }
///| ///|
+5 -1
View File
@@ -1,4 +1,5 @@
import { import {
"chandra/desktop/components/clock-binary/gen/interface/chandra/desktop/module-config" @module-config,
"chandra/desktop/components/clock-binary/gen/interface/chandra/desktop/plasmoid" @plasmoid, "chandra/desktop/components/clock-binary/gen/interface/chandra/desktop/plasmoid" @plasmoid,
} }
@@ -13,13 +14,16 @@ options(
"heap-start-address": 16, "heap-start-address": 16,
"exports": [ "exports": [
"mbt_ffi_cabi_realloc:cabi_realloc", "mbt_ffi_cabi_realloc:cabi_realloc",
"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", "wasmExportInfo:chandra:desktop/plasmoid@0.1.0#info",
"wasmExportInfoPostReturn:cabi_post_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", "wasmExportOnEvent:chandra:desktop/plasmoid@0.1.0#on-event",
"wasmExportPopup:chandra:desktop/plasmoid@0.1.0#popup", "wasmExportPopup:chandra:desktop/plasmoid@0.1.0#popup",
"wasmExportPopupPostReturn:cabi_post_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", "wasmExportRender:chandra:desktop/plasmoid@0.1.0#render",
"wasmExportRenderPostReturn:cabi_post_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"
], ],
}, },
}, },
+28 -10
View File
@@ -44,6 +44,18 @@ pub fn wasmExportInfo() -> Int {
@plasmoid.wasmExportInfo() @plasmoid.wasmExportInfo()
} }
///|
#doc(hidden)
pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
@plasmoid.wasmExportOnEvent(p0, p1, p2, p3)
}
///|
#doc(hidden)
pub fn wasmExportConfigItems() -> Int {
@module-config.wasmExportConfigItems()
}
///| ///|
#doc(hidden) #doc(hidden)
pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit { pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
@@ -52,14 +64,8 @@ pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
///| ///|
#doc(hidden) #doc(hidden)
pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit { pub fn wasmExportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
@plasmoid.wasmExportInfoPostReturn(p0) @module-config.wasmExportSetConfig(p0, p1, p2, p3)
}
///|
#doc(hidden)
pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportPopupPostReturn(p0)
} }
///| ///|
@@ -68,6 +74,12 @@ pub fn wasmExportPopup() -> Int {
@plasmoid.wasmExportPopup() @plasmoid.wasmExportPopup()
} }
///|
#doc(hidden)
pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportInfoPostReturn(p0)
}
///| ///|
#doc(hidden) #doc(hidden)
pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int { pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int {
@@ -76,7 +88,13 @@ pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int {
///| ///|
#doc(hidden) #doc(hidden)
pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
@plasmoid.wasmExportOnEvent(p0, p1, p2, p3) @plasmoid.wasmExportPopupPostReturn(p0)
}
///|
#doc(hidden)
pub fn wasmExportConfigItemsPostReturn(p0 : Int) -> Unit {
@module-config.wasmExportConfigItemsPostReturn(p0)
} }
@@ -0,0 +1,5 @@
Optional: a module's own settings. A module that exports this gets a "Module settings" entry in
its right-click menu, listing the items below; the shell draws the menu (the same for every
module), remembers each choice per module in state.edn (`:module-config`), and hands the saved
values back through `set-config` right after the module is loaded. A module without it simply
has no settings: the export is looked up by name, so older modules keep loading.
@@ -0,0 +1,114 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
#doc(hidden)
pub fn wasmExportConfigItems() -> Int {
let (result) : (Array[ConfigItem]) = config_items();
let return_area = mbt_ffi_malloc(8)
let address3 = mbt_ffi_malloc((result).length() * 32);
for index4 = 0; index4 < (result).length(); index4 = index4 + 1 {
let iter_elem : ConfigItem = (result)[(index4)]
let iter_base = address3 + (index4 * 32);
let ptr = mbt_ffi_str2ptr((iter_elem).key)
mbt_ffi_store32((iter_base) + 4, (iter_elem).key.length())
mbt_ffi_store32((iter_base) + 0, ptr)
let ptr0 = mbt_ffi_str2ptr((iter_elem).label)
mbt_ffi_store32((iter_base) + 12, (iter_elem).label.length())
mbt_ffi_store32((iter_base) + 8, ptr0)
let address = mbt_ffi_malloc(((iter_elem).choices).length() * 8);
for index = 0; index < ((iter_elem).choices).length(); index = index + 1 {
let iter_elem : String = ((iter_elem).choices)[(index)]
let iter_base = address + (index * 8);
let ptr1 = mbt_ffi_str2ptr(iter_elem)
mbt_ffi_store32((iter_base) + 4, iter_elem.length())
mbt_ffi_store32((iter_base) + 0, ptr1)
}
mbt_ffi_store32((iter_base) + 20, ((iter_elem).choices).length())
mbt_ffi_store32((iter_base) + 16, address)
let ptr2 = mbt_ffi_str2ptr((iter_elem).value)
mbt_ffi_store32((iter_base) + 28, (iter_elem).value.length())
mbt_ffi_store32((iter_base) + 24, ptr2)
}
mbt_ffi_store32((return_area) + 4, (result).length())
mbt_ffi_store32((return_area) + 0, address3)
let ret = return_area
return ret
}
///|
#doc(hidden)
pub fn wasmExportConfigItemsPostReturn(p0 : Int) -> Unit {
for index0 = 0; index0 < (mbt_ffi_load32((p0) + 4)); index0 = index0 + 1 {
let iter_base = (mbt_ffi_load32((p0) + 0)) + (index0 * 32)
mbt_ffi_free(mbt_ffi_load32((iter_base) + 0))
mbt_ffi_free(mbt_ffi_load32((iter_base) + 8))
for index = 0; index < (mbt_ffi_load32((iter_base) + 20)); index = index + 1 {
let iter_base = (mbt_ffi_load32((iter_base) + 16)) + (index * 8)
mbt_ffi_free(mbt_ffi_load32((iter_base) + 0))
}
mbt_ffi_free(mbt_ffi_load32((iter_base) + 16))
mbt_ffi_free(mbt_ffi_load32((iter_base) + 24))
}
mbt_ffi_free(mbt_ffi_load32((p0) + 0))
}
///|
#doc(hidden)
pub fn wasmExportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
let result = mbt_ffi_ptr2str(p0, p1)
let result0 = mbt_ffi_ptr2str(p2, p3)
let (result1) : (Bool) = set_config(result, result0);
let ret = (if result1 { 1 } else { 0 })
return ret
}
///|
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
///|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
#|(func (param i32) (result i32) (local i32)
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
#| local.tee 1 i32.const 0 call $moonbit.init_array8
#| local.get 1)
///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) local.get 0)
///|
extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref)
///|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
#|(func (param i32) (param i32) (result i32)
#| local.get 0
#| local.get 1 call $moonbit.init_array16
#| local.get 0)
@@ -0,0 +1,5 @@
import {
"chandra/desktop/lib/clock" @logic,
}
warnings = "-44"
@@ -0,0 +1,21 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/clock-digital/gen/interface/chandra/desktop/module-config"
// Values
pub fn config_items() -> Array[ConfigItem]
pub fn set_config(String, String) -> Bool
// Errors
// Types and methods
pub(all) struct ConfigItem {
key : String
label : String
choices : Array[String]
value : String
}
// Type aliases
// Traits
@@ -0,0 +1,16 @@
///| The digital clock's right-click settings (time format, date line); the logic is in lib/clock.
///|
pub fn config_items() -> Array[ConfigItem] {
@logic.digital_config.digital_items().map(e => {
key: e.key,
label: e.label,
choices: e.choices,
value: e.value,
})
}
///|
pub fn set_config(key : String, value : String) -> Bool {
@logic.digital_config.set(key, value)
}
@@ -0,0 +1,11 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
///|
pub(all) struct ConfigItem {
key : String; label : String; choices : Array[String]; value : String
}
///|
declare pub fn config_items() -> Array[ConfigItem]
///|
/// Set `key` to `value` (unknown keys and values are ignored). True when the widget should redraw.
declare pub fn set_config(key : String, value : String) -> Bool
@@ -15,7 +15,8 @@ pub fn info() -> PlasmoidInfo {
///| ///|
pub fn render(size : @types.Size) -> Array[@types.DrawOp] { pub fn render(size : @types.Size) -> Array[@types.DrawOp] {
@logic.render_digital(size, @theme.get_tokens(), @clock.now()) let c = @logic.digital_config
@logic.render_digital(size, @theme.get_tokens(), @clock.now(), hour12=c.hour12, show_date=c.show_date)
} }
///| ///|
+5 -1
View File
@@ -1,4 +1,5 @@
import { import {
"chandra/desktop/components/clock-digital/gen/interface/chandra/desktop/module-config" @module-config,
"chandra/desktop/components/clock-digital/gen/interface/chandra/desktop/plasmoid" @plasmoid, "chandra/desktop/components/clock-digital/gen/interface/chandra/desktop/plasmoid" @plasmoid,
} }
@@ -13,13 +14,16 @@ options(
"heap-start-address": 16, "heap-start-address": 16,
"exports": [ "exports": [
"mbt_ffi_cabi_realloc:cabi_realloc", "mbt_ffi_cabi_realloc:cabi_realloc",
"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", "wasmExportInfo:chandra:desktop/plasmoid@0.1.0#info",
"wasmExportInfoPostReturn:cabi_post_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", "wasmExportOnEvent:chandra:desktop/plasmoid@0.1.0#on-event",
"wasmExportPopup:chandra:desktop/plasmoid@0.1.0#popup", "wasmExportPopup:chandra:desktop/plasmoid@0.1.0#popup",
"wasmExportPopupPostReturn:cabi_post_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", "wasmExportRender:chandra:desktop/plasmoid@0.1.0#render",
"wasmExportRenderPostReturn:cabi_post_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"
], ],
}, },
}, },
+78 -2
View File
@@ -327,7 +327,7 @@ test "right-click a panel module to replace it in place, or remove it" {
let bin = find_row("Replace with Binary Clock") let bin = find_row("Replace with Binary Clock")
assert_true(bin >= 0) assert_true(bin >= 0)
assert_true(find_row("Remove widget") >= 0) assert_true(find_row("Remove widget") >= 0)
assert_true(find_row("Module manager...") >= 0) assert_true(find_row("System settings...") >= 0)
// Hover the row (hand cursor), click it: the binary clock takes the digital clock's place. // Hover the row (hand cursor), click it: the binary clock takes the digital clock's place.
let ix = m.x + m.w / 2 let ix = m.x + m.w / 2
let iy = m.y + 26 + 28 * bin + 14 let iy = m.y + 26 + 28 * bin + 14
@@ -353,6 +353,82 @@ test "right-click a panel module to replace it in place, or remove it" {
assert_eq(comp.shell.slots().length(), before.length() - 1) assert_eq(comp.shell.slots().length(), before.length() - 1)
} }
///|
test "right-click a module for its own settings: they apply at once and are remembered" {
let comp = new_comp("modcfg")
assert_true(comp.shell.load_module("clock-digital"))
ignore(comp.compose_frame())
let clock = rect_of(comp, "clock-digital")
assert_true(clock.w > 0)
let row_y = fn(k : Int) { comp.shell.menu_rect.y + 26 + 28 * k + 14 }
let find_row = fn(label : String) {
let mut i = -1
for k = 0; k < comp.shell.menu_rows.length(); k = k + 1 {
if comp.shell.menu_rows[k].label == label {
i = k
}
}
i
}
let time_text = fn() {
let mut t = ""
for op in comp.shell.slot_ops(comp.shell.slot_of("clock-digital")) {
match op {
Text(x) => if t == "" { t = x.text }
_ => ()
}
}
t
}
assert_false(time_text().has_suffix("M")) // 24-hour by default
click_at(comp, clock.x + clock.w / 2, clock.y + clock.h / 2, 1U, btn=273U)
assert_true(comp.shell.menu_open)
assert_eq(comp.shell.menu_rows[0].label, "Module settings...")
assert_eq(comp.shell.menu_rows[1].label, "System settings...")
click_at(comp, comp.shell.menu_rect.x + 60, row_y(0), 10U)
// The module's own menu: a "Time format" heading, its two choices, and the "Show date" switch.
assert_true(comp.shell.menu_open)
assert_eq(comp.shell.menu_title, "Digital Clock settings")
let h12 = find_row("12-hour")
assert_true(h12 > 0 && find_row("Time format") == h12 - 2)
assert_true(comp.shell.menu_rows[h12 - 1].ticked) // 24-hour
click_at(comp, comp.shell.menu_rect.x + 60, row_y(h12), 20U)
assert_true(comp.shell.menu_open) // stays open, now ticking 12-hour
assert_true(comp.shell.menu_rows[find_row("12-hour")].ticked)
assert_true(time_text().has_suffix("AM") || time_text().has_suffix("PM"))
assert_eq(comp.shell.module_setting("clock-digital", "format"), Some("12-hour"))
// A heading does nothing; Escape closes.
click_at(comp, comp.shell.menu_rect.x + 60, row_y(find_row("Time format")), 30U)
assert_true(comp.shell.menu_open)
comp.handle_input(@nested.InputEvent::Key(1U, true), 40U)
assert_false(comp.shell.menu_open)
// A second instance of the module starts with the chosen setting.
assert_true(comp.shell.unload_slot(comp.shell.slot_of("clock-digital")))
assert_true(comp.shell.load_module("clock-digital"))
ignore(comp.compose_frame())
assert_true(time_text().has_suffix("AM") || time_text().has_suffix("PM"))
}
///|
test "module settings are saved in state.edn and handed back at the next start" {
if @sys.getenv("CHANDRA_TEST_CONFIG") == "1" {
let theme = @scene.ThemeTokens::moon_night()
let a = @shell.DesktopShell::new("x")
a.persist = true
a.set_output(theme, 1280, 720)
assert_true(a.load_module("clock-binary"))
a.set_module_setting(a.slot_of("clock-binary"), "seconds", "off")
a.save_state() // the rest of state.edn is rewritten: :module-config stays
let b = @shell.DesktopShell::new("x")
b.persist = true
b.set_output(theme, 1280, 720)
assert_eq(b.module_setting("clock-binary", "seconds"), Some("off"))
let slot = b.slot_of("clock-binary")
assert_true(slot != "")
assert_eq(b.slot_config(slot)[0].value, "off")
}
}
///| ///|
test "tapping Super toggles the launcher; Super+key does not" { test "tapping Super toggles the launcher; Super+key does not" {
let comp = new_comp("super") let comp = new_comp("super")
@@ -404,7 +480,7 @@ test "the wasm picker opens the settings module's Panel tab, which loads and unl
let panel = comp.shell.panel_rect let panel = comp.shell.panel_rect
click_at(comp, 1, panel.y + 5, 1U, btn=273U) click_at(comp, 1, panel.y + 5, 1U, btn=273U)
assert_true(comp.shell.menu_open) assert_true(comp.shell.menu_open)
assert_eq(comp.shell.menu_rows[0].label, "Modules...") assert_eq(comp.shell.menu_rows[0].label, "System settings...")
let m = comp.shell.menu_rect let m = comp.shell.menu_rect
click_at(comp, m.x + m.w / 2, m.y + 26 + 14, 10U) click_at(comp, m.x + m.w / 2, m.y + 26 + 14, 10U)
assert_eq(comp.shell.slots().length(), n0) // nothing new was loaded for it assert_eq(comp.shell.slots().length(), n0) // nothing new was loaded for it
+134
View File
@@ -0,0 +1,134 @@
///| Each module's own settings (the optional `module-config` export, shown under "Module settings"
/// in its right-click menu), remembered by module id in state.edn:
///
/// :module-config {"clock-digital" {"format" "12-hour" "date" "off"}}
///
/// Saved values go back to a module through `set-config` right after it is loaded, so every
/// instance of a module starts with what was last chosen. Like `:session`, the key is not in
/// state.mbt's `owned_keys`, so `save_state` keeps it as it is.
///| Read `:module-config` from state.edn once (nothing without `persist`).
fn DesktopShell::read_module_cfg(self : DesktopShell) -> Unit {
if self.module_cfg_read {
return
}
self.module_cfg_read = true
if !self.persist {
return
}
match lookup_key(read_state_file(), "module-config") {
Some(v) =>
for id, m in parse_module_cfg(v) {
self.module_cfg.set(id, m)
}
None => ()
}
}
///| `{"module" {"key" "value"}}` -> map; entries that aren't strings are skipped.
fn parse_module_cfg(v : @edn.Value) -> Map[String, Map[String, String]] {
let out : Map[String, Map[String, String]] = {}
match v {
Mapping(mods) =>
for e in mods {
match e {
(Text(id), Mapping(kvs)) => {
let m : Map[String, String] = {}
for kv in kvs {
match kv {
(Text(k), Text(val)) => m.set(k, val)
(Text(k), Bool(b)) => m.set(k, if b { "on" } else { "off" })
_ => ()
}
}
out.set(id, m)
}
_ => ()
}
}
_ => ()
}
out
}
///|
fn module_cfg_value(cfg : Map[String, Map[String, String]]) -> @edn.Value {
let mods : Array[(@edn.Value, @edn.Value)] = []
for id, m in cfg {
let kvs : Array[(@edn.Value, @edn.Value)] = []
for k, v in m {
kvs.push((@edn.Value::Text(k), @edn.Value::Text(v)))
}
mods.push((@edn.Value::Text(id), @edn.Value::Mapping(kvs)))
}
@edn.Value::Mapping(mods)
}
///| Hand a freshly loaded module its saved settings.
fn DesktopShell::apply_module_cfg(self : DesktopShell, w : Widget) -> Unit {
self.read_module_cfg()
match self.module_cfg.get(w.module_id) {
Some(m) =>
for k, v in m {
ignore(w.pl.set_config(k, v))
}
None => ()
}
}
///| Remember a module's setting and write `:module-config` (keeping every other key).
fn DesktopShell::remember_module_setting(self : DesktopShell, id : String, key : String, value : String) -> Unit {
self.read_module_cfg()
match self.module_cfg.get(id) {
Some(m) => m.set(key, value)
None => {
let m : Map[String, String] = {}
m.set(key, value)
self.module_cfg.set(id, m)
}
}
if !self.persist {
return
}
let entries : Array[(@edn.Value, @edn.Value)] = []
let mut placed = false
for e in read_state_file() {
match e.0 {
Keyword("module-config") => {
entries.push((e.0, module_cfg_value(self.module_cfg)))
placed = true
}
_ => entries.push(e)
}
}
if !placed {
entries.push((@edn.Value::Keyword("module-config"), module_cfg_value(self.module_cfg)))
}
write_state_file(entries)
}
///| The setting `key` of module `id` as last chosen, if any.
pub fn DesktopShell::module_setting(self : DesktopShell, id : String, key : String) -> String? {
self.read_module_cfg()
match self.module_cfg.get(id) {
Some(m) => m.get(key)
None => None
}
}
///|
test "module settings round-trip through EDN" {
let cfg : Map[String, Map[String, String]] = {
"clock-digital": { "format": "12-hour", "date": "off" },
"clock-binary": { "seconds": "on" },
}
let text = @edn.pretty(module_cfg_value(cfg), layout={ width: 100, indent: 1 })
let back = parse_module_cfg(@edn.read(text))
assert_eq(back.get("clock-digital").unwrap().get("format"), Some("12-hour"))
assert_eq(back.get("clock-digital").unwrap().get("date"), Some("off"))
assert_eq(back.get("clock-binary").unwrap().get("seconds"), Some("on"))
// Hand-written booleans read as on/off.
let hand = parse_module_cfg(@edn.read("{\"x\" {\"a\" true \"b\" false} 3 4}"))
assert_eq(hand.get("x").unwrap().get("a"), Some("on"))
assert_eq(hand.get("x").unwrap().get("b"), Some("off"))
}
+19 -2
View File
@@ -169,11 +169,22 @@ pub(all) struct CatalogEntry {
mut name : String mut name : String
} }
///| One row of the right-click menu: kind 0 replace with module `arg` (a path), 1 remove, 2 open the module manager. ///| One row of the right-click menu. `kind`: 0 replace with module `arg` (a path), 1 remove,
/// 2 open System settings, 3 open the module's own settings, 4 set the module's setting `arg` to
/// `value`, 5 a heading or note (not clickable).
pub(all) struct MenuRow { pub(all) struct MenuRow {
label : String label : String
kind : Int kind : Int
arg : String arg : String
/// The setting value a kind-4 row sets.
value : String
/// Draw a tick: the value a kind-4 row sets is the current one.
ticked : Bool
}
///| A plain menu row (no setting value, no tick).
fn menu_row(label : String, kind : Int, arg? : String = "") -> MenuRow {
{ label, kind, arg, value: "", ticked: false }
} }
///| The desktop shell: wallpaper + a bottom panel made entirely of wasm modules ///| The desktop shell: wallpaper + a bottom panel made entirely of wasm modules
@@ -246,6 +257,10 @@ pub(all) struct DesktopShell {
mut menu_hover : Int mut menu_hover : Int
mut menu_anchor_x : Int mut menu_anchor_x : Int
mut menu_slot : String mut menu_slot : String
/// Each module's own settings (`module-config`), by module id, as saved in state.edn
/// `:module-config`; read on first use.
module_cfg : Map[String, Map[String, String]]
mut module_cfg_read : Bool
/// Panel widget being dragged (slot id, "" if none), press point, and whether it moved past the click threshold. /// Panel widget being dragged (slot id, "" if none), press point, and whether it moved past the click threshold.
mut drag_slot : String mut drag_slot : String
/// Panel widget the pointer is over (it gets pointer-move / pointer-leave), "" for none. /// Panel widget the pointer is over (it gets pointer-move / pointer-leave), "" for none.
@@ -334,6 +349,8 @@ pub fn DesktopShell::new(display : String) -> DesktopShell {
menu_hover: -1, menu_hover: -1,
menu_anchor_x: 0, menu_anchor_x: 0,
menu_slot: "", menu_slot: "",
module_cfg: {},
module_cfg_read: false,
drag_slot: "", drag_slot: "",
hover_slot: "", hover_slot: "",
drag_x0: 0, drag_x0: 0,
@@ -575,7 +592,7 @@ pub fn DesktopShell::cursor_at(self : DesktopShell, x : Int, y : Int) -> UInt {
} else if self.drag_active { } else if self.drag_active {
17U // grabbing 17U // grabbing
} else if self.menu_open && inside(self.menu_rect, x, y) { } else if self.menu_open && inside(self.menu_rect, x, y) {
if self.menu_hover >= 0 { 4U } else { 1U } if self.menu_hover >= 0 && self.menu_rows[self.menu_hover].kind != 5 { 4U } else { 1U }
} else if self.popup_at(x, y) is Some(_) { } else if self.popup_at(x, y) is Some(_) {
1U 1U
} else if self.widget_at(x, y) is Some(_) { } else if self.widget_at(x, y) is Some(_) {
+113 -12
View File
@@ -7,8 +7,9 @@
/// `app-launch` for the application menu, `windows` for the task list, `layout-control` /// `app-launch` for the application menu, `windows` for the task list, `layout-control`
/// for the layout switcher, `inspector` for the Interface Explorer button, and /// for the layout switcher, `inspector` for the Interface Explorer button, and
/// `session-settings`, `wallpaper` and `modules` for the settings module. Managing modules is a /// `session-settings`, `wallpaper` and `modules` for the settings module. Managing modules is a
/// tab of that module: the wasm picker ("Modules..." in the panel menu) loads it on demand and /// tab of that module: "System settings..." in the empty-panel right-click menu loads it on demand
/// opens that tab. /// and opens that tab. A module may also export `module-config`: its own settings, listed under
/// "Module settings..." in its right-click menu and remembered in state.edn (module_config.mbt).
///| Modules loaded into a fresh panel, in order. `tasks` stretches, so what follows it packs right. ///| Modules loaded into a fresh panel, in order. `tasks` stretches, so what follows it packs right.
let default_panel : Array[String] = [ let default_panel : Array[String] = [
@@ -253,6 +254,7 @@ pub fn DesktopShell::load_path(self : DesktopShell, path : String) -> Widget? {
popup_hot: false, popup_hot: false,
} }
self.next_slot = self.next_slot + 1 self.next_slot = self.next_slot + 1
self.apply_module_cfg(w)
self.widgets.push(w) self.widgets.push(w)
if self.screen_w > 0 && !self.panel_fits() { if self.screen_w > 0 && !self.panel_fits() {
self.widgets.retain(x => x.slot != w.slot) self.widgets.retain(x => x.slot != w.slot)
@@ -657,8 +659,8 @@ let menu_w : Int = 250
///| Most "Replace with" rows listed. ///| Most "Replace with" rows listed.
let max_replace_rows : Int = 8 let max_replace_rows : Int = 8
///| Right-click: on a module its replace/remove menu, on empty panel space the picker entry. ///| Right-click: on a module its menu (Module settings, System settings, replace, remove); on
/// True when consumed. /// empty panel space System settings (whose Panel tab adds modules). True when consumed.
pub fn DesktopShell::right_click(self : DesktopShell, x : Int, y : Int) -> Bool { pub fn DesktopShell::right_click(self : DesktopShell, x : Int, y : Int) -> Bool {
self.ensure_booted() self.ensure_booted()
if self.inspect_on { if self.inspect_on {
@@ -671,25 +673,33 @@ pub fn DesktopShell::right_click(self : DesktopShell, x : Int, y : Int) -> Bool
Some(w) => { Some(w) => {
self.name_catalog() self.name_catalog()
let rows : Array[MenuRow] = [] let rows : Array[MenuRow] = []
if w.pl.config_items().length() > 0 {
rows.push(menu_row("Module settings...", 3))
} else {
rows.push(menu_row("No module settings", 5))
}
rows.push(menu_row("System settings...", 2))
// Only modules of the same kind (same WIT world) can stand in for this one. // Only modules of the same kind (same WIT world) can stand in for this one.
let world = module_world(w.path) let world = module_world(w.path)
let mut replace = 0
for e in self.catalog { for e in self.catalog {
if world.length() > 0 && if world.length() > 0 &&
e.id != w.module_id && e.id != w.module_id &&
e.path != w.path && e.path != w.path &&
rows.length() < max_replace_rows && replace < max_replace_rows &&
module_world(e.path) == world { module_world(e.path) == world {
rows.push({ label: "Replace with " + e.name, kind: 0, arg: e.path }) rows.push(menu_row("Replace with " + e.name, 0, arg=e.path))
replace = replace + 1
} }
} }
rows.push({ label: "Remove widget", kind: 1, arg: "" }) rows.push(menu_row("Remove widget", 1))
rows.push({ label: "Modules...", kind: 2, arg: "" })
self.open_menu(w.pl.name, rows, w.slot, x) self.open_menu(w.pl.name, rows, w.slot, x)
true true
} }
None => None =>
if inside(self.panel_rect, x, y) { if inside(self.panel_rect, x, y) {
self.open_menu("Add widget", [{ label: "Modules...", kind: 2, arg: "" }], "", x) // Empty panel space: System settings on its Panel tab, where modules are added.
self.open_menu("Panel", [menu_row("System settings...", 2, arg="panel")], "", x)
true true
} else { } else {
was_open was_open
@@ -697,6 +707,77 @@ pub fn DesktopShell::right_click(self : DesktopShell, x : Int, y : Int) -> Bool
} }
} }
///| The module's own settings as menu rows: an on/off setting is one row, ticked when on; a
/// setting with choices is a heading and one row per choice, the current one ticked.
fn config_rows(items : Array[@wasm.ConfigItem]) -> Array[MenuRow] {
let rows : Array[MenuRow] = []
for it in items {
if it.choices.length() == 0 {
let on = it.value == "on"
rows.push({ label: it.label, kind: 4, arg: it.key, value: if on { "off" } else { "on" }, ticked: on })
} else {
rows.push(menu_row(it.label, 5))
for c in it.choices {
rows.push({ label: c, kind: 4, arg: it.key, value: c, ticked: c == it.value })
}
}
}
rows
}
///| Show the "Module settings" menu of the module in `slot` (in place of its right-click menu).
fn DesktopShell::open_module_settings(self : DesktopShell, slot : String) -> Unit {
match self.widget_by_slot(slot) {
None => ()
Some(w) => {
let rows = config_rows(w.pl.config_items())
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)
}
}
}
///| Set a setting of the module in `slot` (and of its other instances) and remember it in state.edn.
pub fn DesktopShell::set_module_setting(self : DesktopShell, slot : String, key : String, value : String) -> Unit {
match self.widget_by_slot(slot) {
None => ()
Some(w) => {
self.remember_module_setting(w.module_id, key, value)
for o in self.widgets {
if o.module_id == w.module_id {
ignore(o.pl.set_config(key, value))
}
}
}
}
}
///| The settings the module in `slot` offers, with their current values.
pub fn DesktopShell::slot_config(self : DesktopShell, slot : String) -> Array[@wasm.ConfigItem] {
match self.widget_by_slot(slot) {
Some(w) => w.pl.config_items()
None => []
}
}
///| What the module in `slot` draws in its panel box now.
pub fn DesktopShell::slot_ops(self : DesktopShell, slot : String) -> Array[@types.DrawOp] {
match self.widget_by_slot(slot) {
Some(w) => w.pl.render(w.rect.w, w.rect.h, self.tokens)
None => []
}
}
///| A setting chosen in the module's menu: apply it, remember it, and refresh the menu.
fn DesktopShell::choose_module_setting(self : DesktopShell, slot : String, key : String, value : String) -> Unit {
self.set_module_setting(slot, key, value)
let hover = self.menu_hover
self.open_module_settings(slot)
self.menu_hover = hover
}
///| ///|
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) -> Unit {
self.menu_open = true self.menu_open = true
@@ -731,7 +812,11 @@ fn DesktopShell::menu_pointer_down(self : DesktopShell, x : Int, y : Int) -> Boo
match row.kind { match row.kind {
0 => ignore(self.replace_slot(slot, row.arg)) 0 => ignore(self.replace_slot(slot, row.arg))
1 => ignore(self.unload_slot(slot)) 1 => ignore(self.unload_slot(slot))
_ => ignore(self.open_module_manager()) 2 => ignore(self.open_settings(if row.arg == "panel" { Panel } else { Session }))
3 => self.open_module_settings(slot)
4 => self.choose_module_setting(slot, row.arg, row.value)
// A heading: the menu stays open.
_ => self.menu_open = true
} }
} }
over over
@@ -764,11 +849,27 @@ fn DesktopShell::render_menu(
] ]
for i = 0; i < n; i = i + 1 { for i = 0; i < n; i = i + 1 {
let top = menu_title_h + i * menu_item_h let top = menu_title_h + i * menu_item_h
let hot = i == self.menu_hover let row = self.menu_rows[i]
let hot = i == self.menu_hover && row.kind != 5
if hot { if hot {
ops.push(@ui.fill_rect(@ui.rect(4, top, menu_w - 8, menu_item_h - 2), tokens.palette.surface_hover, radius=r)) ops.push(@ui.fill_rect(@ui.rect(4, top, menu_w - 8, menu_item_h - 2), tokens.palette.surface_hover, radius=r))
} }
ops.push(@ui.text(14, top + menu_item_h / 2, self.menu_rows[i].label, fs - 2, tokens.palette.foreground)) if row.kind == 5 {
ops.push(@ui.text(14, top + menu_item_h / 2, row.label, fs - 3, tokens.palette.foreground_muted))
} else if row.kind == 4 {
// A setting: a check box, filled with the accent colour when ticked.
let cy = top + menu_item_h / 2
if row.ticked {
ops.push(@ui.fill_rect(@ui.rect(16, cy - 6, 12, 12), tokens.palette.accent, radius=3))
ops.push(@ui.line(19, cy, 21, cy + 3, tokens.palette.accent_foreground, width=2))
ops.push(@ui.line(21, cy + 3, 26, cy - 3, tokens.palette.accent_foreground, width=2))
} else {
ops.push(@ui.stroke_rect(@ui.rect(16, cy - 6, 12, 12), tokens.palette.foreground_muted, radius=3))
}
ops.push(@ui.text(36, cy, row.label, fs - 2, tokens.palette.foreground))
} else {
ops.push(@ui.text(14, top + menu_item_h / 2, row.label, fs - 2, tokens.palette.foreground))
}
} }
translate(ops, mx, my, out) translate(ops, mx, my, out)
} }
+24
View File
@@ -182,6 +182,30 @@ pub fn Plasmoid::on_event(self : Plasmoid, popup : Bool, ev : PlasmoidEvent) ->
@hostpl.on_event(self.handle.reinterpret_as_uint(), popup, e) @hostpl.on_event(self.handle.reinterpret_as_uint(), popup, e)
} }
///| One of a module's own settings (the WIT `module-config.config-item`): `choices` empty means
/// an on/off switch whose value is "on" or "off".
pub(all) struct ConfigItem {
key : String
label : String
choices : Array[String]
value : String
} derive(Eq, Debug)
///| The module's settings for its right-click menu; empty when it doesn't export `module-config`.
pub fn Plasmoid::config_items(self : Plasmoid) -> Array[ConfigItem] {
@hostpl.config_items(self.handle.reinterpret_as_uint()).map(c => {
key: c.key,
label: c.label,
choices: c.choices,
value: c.value,
})
}
///| Set one of the module's settings. True when the widget asks for a redraw.
pub fn Plasmoid::set_config(self : Plasmoid, key : String, value : String) -> Bool {
@hostpl.set_config(self.handle.reinterpret_as_uint(), key, value)
}
///| ///|
pub fn Plasmoid::imports(self : Plasmoid) -> Array[String] { pub fn Plasmoid::imports(self : Plasmoid) -> Array[String] {
self.imports self.imports
+86 -8
View File
@@ -143,6 +143,15 @@ let ex_post_popup : Int = 6
///| ///|
let ex_realloc : Int = 7 let ex_realloc : Int = 7
///| The optional `module-config` exports (absent in most modules: calls then return -1).
let ex_cfg_items : Int = 8
///|
let ex_post_cfg_items : Int = 9
///|
let ex_set_cfg : Int = 10
///| The 64-byte `theme.tokens` record (name left empty) the guest reads through get-tokens. ///| The 64-byte `theme.tokens` record (name left empty) the guest reads through get-tokens.
pub fn pack_tokens(t : @theme.Tokens) -> Bytes { pub fn pack_tokens(t : @theme.Tokens) -> Bytes {
let b = FixedArray::make(64, b'\x00') let b = FixedArray::make(64, b'\x00')
@@ -513,11 +522,20 @@ pub fn Plasmoid::on_event(self : Plasmoid, popup : Bool, ev : PlasmoidEvent) ->
PointerUp(x, y) => c_wasm_call(self.handle, ex_onevent, target, 2, x, y) PointerUp(x, y) => c_wasm_call(self.handle, ex_onevent, target, 2, x, y)
PointerLeave => c_wasm_call(self.handle, ex_onevent, target, 3, 0, 0) PointerLeave => c_wasm_call(self.handle, ex_onevent, target, 3, 0, 0)
FocusLost => c_wasm_call(self.handle, ex_onevent, target, 4, 0, 0) FocusLost => c_wasm_call(self.handle, ex_onevent, target, 4, 0, 0)
KeyDown(k) => { KeyDown(k) =>
// The guest owns a UTF-16 copy of the key name. match self.guest_str(k) {
None => -1
Some((ptr, units)) => c_wasm_call(self.handle, ex_onevent, target, 5, ptr, units)
}
}
r == 1
}
///| Copy `s` into guest memory as UTF-16 (the guest owns the copy): (pointer, code units).
fn Plasmoid::guest_str(self : Plasmoid, s : String) -> (Int, Int)? {
let b : Array[Byte] = [] let b : Array[Byte] = []
let mut units = 0 let mut units = 0
for ch in k { for ch in s {
let c = ch.to_int() let c = ch.to_int()
if c >= 0x10000 { if c >= 0x10000 {
let v = c - 0x10000 let v = c - 0x10000
@@ -535,15 +553,75 @@ pub fn Plasmoid::on_event(self : Plasmoid, popup : Bool, ev : PlasmoidEvent) ->
} }
} }
let ptr = c_wasm_call(self.handle, ex_realloc, 0, 0, 2, if units * 2 < 4 { 4 } else { units * 2 }) let ptr = c_wasm_call(self.handle, ex_realloc, 0, 0, 2, if units * 2 < 4 { 4 } else { units * 2 })
if ptr < 0 { if ptr <= 0 {
-1 return None
} else { }
if units > 0 {
ignore(c_wasm_write(self.handle, ptr, Bytes::from_array(b), b.length())) ignore(c_wasm_write(self.handle, ptr, Bytes::from_array(b), b.length()))
c_wasm_call(self.handle, ex_onevent, target, 5, ptr, units) }
Some((ptr, units))
}
///| One of a module's own settings (the WIT `module-config.config-item`): `choices` empty means
/// an on/off switch whose value is "on" or "off".
pub(all) struct ConfigItem {
key : String
label : String
choices : Array[String]
value : String
} derive(Eq, Debug)
///| The module's settings for its right-click menu; empty when it doesn't export `module-config`.
pub fn Plasmoid::config_items(self : Plasmoid) -> Array[ConfigItem] {
let out : Array[ConfigItem] = []
let ra = c_wasm_call(self.handle, ex_cfg_items, 0, 0, 0, 0)
if ra <= 0 {
return out
}
match self.mem(ra, 8) {
None => ()
Some(hdr) => {
let base = rd32(hdr, 0)
let n = rd32(hdr, 4)
if n > 0 && n <= 64 {
match self.mem(base, n * 32) {
None => ()
Some(b) =>
for i = 0; i < n; i = i + 1 {
let o = i * 32
let choices : Array[String] = []
let cn = rd32(b, o + 20)
if cn > 0 && cn <= 64 {
match self.mem(rd32(b, o + 16), cn * 8) {
None => ()
Some(cb) =>
for k = 0; k < cn; k = k + 1 {
choices.push(self.str(rd32(cb, k * 8), rd32(cb, k * 8 + 4)))
} }
} }
} }
r == 1 out.push({
key: self.str(rd32(b, o), rd32(b, o + 4)),
label: self.str(rd32(b, o + 8), rd32(b, o + 12)),
choices,
value: self.str(rd32(b, o + 24), rd32(b, o + 28)),
})
}
}
}
}
}
ignore(c_wasm_call(self.handle, ex_post_cfg_items, ra, 0, 0, 0))
out
}
///| Set one of the module's settings. True when the widget asks for a redraw; false when it has no
/// `module-config` export, ignored the value, or trapped.
pub fn Plasmoid::set_config(self : Plasmoid, key : String, value : String) -> Bool {
match (self.guest_str(key), self.guest_str(value)) {
(Some((kp, kn)), Some((vp, vn))) => c_wasm_call(self.handle, ex_set_cfg, kp, kn, vp, vn) == 1
_ => false
}
} }
///| Host interfaces (capabilities) the module's binary imports, e.g. ["theme", "clock"]. ///| Host interfaces (capabilities) the module's binary imports, e.g. ["theme", "clock"].
+6 -1
View File
@@ -16,7 +16,8 @@
#include "moonbit.h" #include "moonbit.h"
#define MAX_INST 512 #define MAX_INST 512
enum { EX_INFO, EX_RENDER, EX_ONEVENT, EX_POPUP, EX_POST_INFO, EX_POST_RENDER, EX_POST_POPUP, EX_REALLOC, EX_N }; 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 };
static const char *ex_names[EX_N] = { static const char *ex_names[EX_N] = {
"chandra:desktop/plasmoid@0.1.0#info", "chandra:desktop/plasmoid@0.1.0#info",
"chandra:desktop/plasmoid@0.1.0#render", "chandra:desktop/plasmoid@0.1.0#render",
@@ -26,6 +27,10 @@ static const char *ex_names[EX_N] = {
"cabi_post_chandra:desktop/plasmoid@0.1.0#render", "cabi_post_chandra:desktop/plasmoid@0.1.0#render",
"cabi_post_chandra:desktop/plasmoid@0.1.0#popup", "cabi_post_chandra:desktop/plasmoid@0.1.0#popup",
"cabi_realloc", "cabi_realloc",
/* optional: chandra:desktop/module-config (the module's own right-click settings) */
"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",
}; };
typedef struct Inst { typedef struct Inst {
+27
View File
@@ -93,6 +93,33 @@ fn drain() -> Array[HostRequest] {
out out
} }
///|
test "a module's own settings (module-config) are listed and set through wasmer" {
let p = load_module("clock-digital")
let items = p.config_items()
assert_eq(items.length(), 2)
assert_eq(items[0], { key: "format", label: "Time format", choices: ["24-hour", "12-hour"], value: "24-hour" })
assert_eq(items[1].choices.length(), 0) // an on/off switch
assert_true(p.set_config("format", "12-hour"))
assert_false(p.set_config("format", "12-hour")) // unchanged
assert_false(p.set_config("bogus", "x"))
assert_eq(p.config_items()[0].value, "12-hour")
let mut ampm = false
for op in p.render(p.pref_w, p.pref_h, test_tokens()) {
match op {
Text(t) => if t.text.has_suffix("AM") || t.text.has_suffix("PM") { ampm = true }
_ => ()
}
}
assert_true(ampm)
p.unload()
// Modules without the export have no settings, and setting one is a no-op.
let l = load_module("layout")
assert_eq(l.config_items().length(), 0)
assert_false(l.set_config("format", "12-hour"))
l.unload()
}
///| ///|
test "task list module draws the host's windows and asks to focus one" { test "task list module draws the host's windows and asks to focus one" {
let p = load_module("tasks") let p = load_module("tasks")
+12
View File
@@ -166,6 +166,18 @@ impl chandra::host::plasmoids::Host for State {
self.pl().on_event(handle, on_popup, event) self.pl().on_event(handle, on_popup, event)
} }
fn config_items(&mut self, handle: u32) -> Vec<chandra::host::plasmoids::ConfigItem> {
self.pl()
.config_items(handle)
.into_iter()
.map(|c| chandra::host::plasmoids::ConfigItem { key: c.key, label: c.label, choices: c.choices, value: c.value })
.collect()
}
fn set_config(&mut self, handle: u32, key: String, value: String) -> bool {
self.pl().set_config(handle, &key, &value)
}
fn publish_table(&mut self, which: u32, rows: Vec<u8>) { 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) { if let Some(t) = self.pl().shared.borrow_mut().tables.get_mut(which as usize) {
*t = rows; *t = rows;
+51 -3
View File
@@ -22,6 +22,15 @@ pub mod ph {
additional_derives: [PartialEq], additional_derives: [PartialEq],
}); });
} }
/// The optional `module-config` export (wit/worlds.wit `configurable`): a module's own settings
/// for its right-click menu. Bound separately so modules without it still instantiate.
pub mod cfg {
wasmtime::component::bindgen!({
path: "../wit",
world: "configurable",
});
}
pub use cfg::exports::chandra::desktop::module_config::ConfigItem;
use ph::exports::chandra::desktop as ex; use ph::exports::chandra::desktop as ex;
use ph::chandra::desktop as d; use ph::chandra::desktop as d;
@@ -337,6 +346,8 @@ impl d::system::Host for PState {
struct Loaded { struct Loaded {
store: Store<PState>, store: Store<PState>,
inst: ph::PlasmoidHost, inst: ph::PlasmoidHost,
/// Present when the module exports `module-config`.
cfg: Option<cfg::Configurable>,
} }
/// A file-chooser dialog in flight (zenity on the host session). /// A file-chooser dialog in flight (zenity on the host session).
@@ -389,13 +400,16 @@ impl Runtime {
} }
} }
let mut store = Store::new(&self.engine, PState { shared: self.shared.clone() }); let mut store = Store::new(&self.engine, PState { shared: self.shared.clone() });
let inst = ph::PlasmoidHost::instantiate(&mut store, &component, &self.linker) let instance =
.map_err(|_| "wasm runtime error".to_string())?; self.linker.instantiate(&mut store, &component).map_err(|_| "wasm runtime error".to_string())?;
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 info = inst let info = inst
.chandra_desktop_plasmoid() .chandra_desktop_plasmoid()
.call_info(&mut store) .call_info(&mut store)
.map_err(|_| "widget trapped in info()".to_string())?; .map_err(|_| "widget trapped in info()".to_string())?;
let l = Loaded { store, inst }; let l = Loaded { store, inst, cfg };
let handle = match self.slots.iter().position(|s| s.is_none()) { let handle = match self.slots.iter().position(|s| s.is_none()) {
Some(h) => { Some(h) => {
self.slots[h] = Some(l); self.slots[h] = Some(l);
@@ -430,6 +444,20 @@ impl Runtime {
l.inst.chandra_desktop_plasmoid().call_popup(&mut l.store).ok().flatten() l.inst.chandra_desktop_plasmoid().call_popup(&mut l.store).ok().flatten()
} }
/// The module's settings; empty without `module-config` (or when it traps).
pub fn config_items(&mut self, handle: u32) -> Vec<ConfigItem> {
let Some(l) = self.get(handle) else { return Vec::new() };
let Some(c) = &l.cfg else { return Vec::new() };
c.chandra_desktop_module_config().call_config_items(&mut l.store).unwrap_or_default()
}
/// Set one of the module's settings; true when it wants a redraw.
pub fn set_config(&mut self, handle: u32, key: &str, value: &str) -> bool {
let Some(l) = self.get(handle) else { return false };
let Some(c) = &l.cfg else { return false };
c.chandra_desktop_module_config().call_set_config(&mut l.store, key, value).unwrap_or(false)
}
pub fn on_event(&mut self, handle: u32, on_popup: bool, ev: d::types::InputEvent) -> bool { 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 Some(l) = self.get(handle) else { return false };
let target = if on_popup { ex::plasmoid::Surface::Popup } else { ex::plasmoid::Surface::Widget }; let target = if on_popup { ex::plasmoid::Surface::Popup } else { ex::plasmoid::Surface::Widget };
@@ -557,6 +585,26 @@ mod tests {
assert!(rt.load(junk.to_str().unwrap()).is_err()); assert!(rt.load(junk.to_str().unwrap()).is_err());
} }
#[test]
fn module_settings_are_listed_and_set_when_the_module_exports_them() {
let mut rt = runtime();
let c = rt.load(&module("clock-digital")).expect("clock loads");
let items = rt.config_items(c.handle);
assert_eq!(items.len(), 2);
assert_eq!(items[0].key, "format");
assert_eq!(items[0].choices, vec!["24-hour".to_string(), "12-hour".to_string()]);
assert_eq!(items[0].value, "24-hour");
assert!(rt.set_config(c.handle, "format", "12-hour"));
assert!(!rt.set_config(c.handle, "bogus", "x"));
assert_eq!(rt.config_items(c.handle)[0].value, "12-hour");
let ops = rt.render(c.handle, d::types::Size { w: 120, h: 36 });
assert!(texts(&ops).iter().any(|t| t.ends_with("AM") || t.ends_with("PM")));
// A module without the export: no settings, and setting one does nothing.
let l = rt.load(&module("layout")).expect("layout loads");
assert!(rt.config_items(l.handle).is_empty());
assert!(!rt.set_config(l.handle, "format", "12-hour"));
}
#[test] #[test]
fn layout_module_follows_the_published_mode_and_sets_it() { fn layout_module_follows_the_published_mode_and_sets_it() {
let mut rt = runtime(); let mut rt = runtime();
+40 -34
View File
@@ -18,6 +18,12 @@ fn wasmImportPopup(p0 : Int, p1 : Int) = "chandra:host/plasmoids@0.1.0" "popup"
///| ///|
fn wasmImportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) -> Int = "chandra:host/plasmoids@0.1.0" "on-event" fn wasmImportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) -> Int = "chandra:host/plasmoids@0.1.0" "on-event"
///|
fn wasmImportConfigItems(p0 : Int, p1 : Int) = "chandra:host/plasmoids@0.1.0" "config-items"
///|
fn wasmImportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) -> Int = "chandra:host/plasmoids@0.1.0" "set-config"
///| ///|
fn wasmImportPublishTable(p0 : Int, p1 : Int, p2 : Int) = "chandra:host/plasmoids@0.1.0" "publish-table" fn wasmImportPublishTable(p0 : Int, p1 : Int, p2 : Int) = "chandra:host/plasmoids@0.1.0" "publish-table"
@@ -51,10 +57,42 @@ fn wasmImportPickerStart() -> Int = "chandra:host/plasmoids@0.1.0" "picker-start
///| ///|
fn wasmImportPickerPoll(p0 : Int) = "chandra:host/plasmoids@0.1.0" "picker-poll" fn wasmImportPickerPoll(p0 : Int) = "chandra:host/plasmoids@0.1.0" "picker-poll"
///|
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_store8(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8)
///|
#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_store64(offset : Int, value : Int64) =
#|(func (param i32) (param i64) local.get 0 local.get 1 i64.store)
///| ///|
extern "wasm" fn mbt_ffi_load64(offset : Int) -> Int64 = extern "wasm" fn mbt_ffi_load64(offset : Int) -> Int64 =
#|(func (param i32) (result i64) local.get 0 i64.load) #|(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)
#| 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_load8_u(offset : Int) -> Int = extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load8_u) #|(func (param i32) (result i32) local.get 0 i32.load8_u)
@@ -63,43 +101,11 @@ extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int =
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) = extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store) #|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
///|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load)
///|
#owned(str)
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
#|(func (param i32) (result i32) 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)
///|
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_store8(offset : Int, value : Int) =
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8)
///| ///|
extern "wasm" fn mbt_ffi_free(position : Int) = extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref) #|(func (param i32) local.get 0 call $moonbit.decref)
///| ///|
#owned(bytes) extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int = #|(func (param i32) (result i32) local.get 0 i32.load)
#|(func (param i32) (result i32) local.get 0)
///|
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)
@@ -30,6 +30,16 @@ fn wasmImportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) -> Int {
abort("wasm-only host import") abort("wasm-only host import")
} }
///|
fn wasmImportConfigItems(p0 : Int, p1 : Int) -> Unit {
abort("wasm-only host import")
}
///|
fn wasmImportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) -> Int {
abort("wasm-only host import")
}
///| ///|
fn wasmImportPublishTable(p0 : Int, p1 : Int, p2 : Int) -> Unit { fn wasmImportPublishTable(p0 : Int, p1 : Int, p2 : Int) -> Unit {
abort("wasm-only host import") abort("wasm-only host import")
@@ -86,12 +96,7 @@ fn wasmImportPickerPoll(p0 : Int) -> Unit {
} }
///| ///|
fn mbt_ffi_malloc(size : Int) -> Int { fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String {
abort("wasm-only")
}
///|
fn mbt_ffi_free(position : Int) -> Unit {
abort("wasm-only") abort("wasm-only")
} }
@@ -110,18 +115,18 @@ fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int {
abort("wasm-only") abort("wasm-only")
} }
///|
fn mbt_ffi_store64(offset : Int, value : Int64) -> Unit {
abort("wasm-only")
}
///| ///|
fn mbt_ffi_load64(offset : Int) -> Int64 { fn mbt_ffi_load64(offset : Int) -> Int64 {
abort("wasm-only") abort("wasm-only")
} }
///| ///|
fn mbt_ffi_store32(offset : Int, value : Int) -> Unit { fn mbt_ffi_malloc(size : Int) -> Int {
abort("wasm-only")
}
///|
fn mbt_ffi_load32(offset : Int) -> Int {
abort("wasm-only") abort("wasm-only")
} }
@@ -131,11 +136,16 @@ fn mbt_ffi_load8_u(offset : Int) -> Int {
} }
///| ///|
fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String { fn mbt_ffi_store32(offset : Int, value : Int) -> Unit {
abort("wasm-only") abort("wasm-only")
} }
///| ///|
fn mbt_ffi_store64(offset : Int, value : Int64) -> Unit { fn mbt_ffi_free(position : Int) -> Unit {
abort("wasm-only")
}
///|
fn mbt_ffi_load32(offset : Int) -> Int {
abort("wasm-only") abort("wasm-only")
} }
@@ -7,6 +7,8 @@ import {
} }
// Values // Values
pub fn config_items(UInt32) -> Array[ConfigItem]
pub fn list_wasm_files(String) -> Array[String] pub fn list_wasm_files(String) -> Array[String]
pub fn load(String) -> Result[Loaded, String] pub fn load(String) -> Result[Loaded, String]
@@ -35,6 +37,8 @@ pub fn publish_windows(Array[WindowEntry]) -> Unit
pub fn render(UInt32, @types.Size) -> Array[@types.DrawOp] pub fn render(UInt32, @types.Size) -> Array[@types.DrawOp]
pub fn set_config(UInt32, String, String) -> Bool
pub fn set_tokens(@theme.Tokens) -> Unit pub fn set_tokens(@theme.Tokens) -> Unit
pub fn take_focus_request() -> UInt64? pub fn take_focus_request() -> UInt64?
@@ -44,6 +48,13 @@ pub fn unload(UInt32) -> Unit
// Errors // Errors
// Types and methods // Types and methods
pub(all) struct ConfigItem {
key : String
label : String
choices : Array[String]
value : String
}
pub(all) struct Loaded { pub(all) struct Loaded {
handle : UInt32 handle : UInt32
id : String id : String
+55
View File
@@ -10,6 +10,12 @@ pub(all) struct PopupSurface {
box : @types.Size; ops : Array[@types.DrawOp] box : @types.Size; ops : Array[@types.DrawOp]
} }
///| ///|
/// One of a module's own settings (chandra:desktop/module-config `config-item`): `choices`
/// empty means an on/off switch whose value is "on" or "off".
pub(all) struct ConfigItem {
key : String; label : String; choices : Array[String]; value : String
}
///|
pub(all) struct SystemSnapshot { pub(all) struct SystemSnapshot {
cpu_permille : UInt; mem_used_kib : UInt64; mem_total_kib : UInt64; battery_percent : Int; charging : Bool; uptime_secs : UInt64; net_rx_bytes_per_sec : UInt64; net_tx_bytes_per_sec : UInt64; load_centi : UInt cpu_permille : UInt; mem_used_kib : UInt64; mem_total_kib : UInt64; battery_percent : Int; charging : Bool; uptime_secs : UInt64; net_rx_bytes_per_sec : UInt64; net_tx_bytes_per_sec : UInt64; load_centi : UInt
} }
@@ -309,6 +315,55 @@ pub fn on_event(handle : UInt, on_popup : Bool, event : @types.InputEvent) -> Bo
cleanup_list.each(mbt_ffi_free) cleanup_list.each(mbt_ffi_free)
return ret return ret
}
///|
/// The module's settings for its right-click menu; empty when it doesn't export module-config.
pub fn config_items(handle : UInt) -> Array[ConfigItem] {
let return_area = mbt_ffi_malloc(8)
wasmImportConfigItems((handle).reinterpret_as_int(), return_area);
let array3 : Array[ConfigItem] = [];
for index4 = 0; index4 < (mbt_ffi_load32((return_area) + 4)); index4 = index4 + 1 {
let iter_base = (mbt_ffi_load32((return_area) + 0)) + (index4 * 32)
let result = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 0), mbt_ffi_load32((iter_base) + 4))
let result0 = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 8), mbt_ffi_load32((iter_base) + 12))
let array : Array[String] = [];
for index = 0; index < (mbt_ffi_load32((iter_base) + 20)); index = index + 1 {
let iter_base = (mbt_ffi_load32((iter_base) + 16)) + (index * 8)
let result1 = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 0), mbt_ffi_load32((iter_base) + 4))
array.push(result1)
}
mbt_ffi_free(mbt_ffi_load32((iter_base) + 16))
let result2 = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 24), mbt_ffi_load32((iter_base) + 28))
array3.push(ConfigItem::{key : result, label : result0, choices : array, value : result2})
}
mbt_ffi_free(mbt_ffi_load32((return_area) + 0))
let ret = array3
mbt_ffi_free(return_area)
return ret
}
///|
/// Set one of them. True when the module wants a redraw (false without module-config).
pub fn set_config(handle : UInt, key : String, value : String) -> Bool {
let ptr = mbt_ffi_str2ptr(key)
let ptr0 = mbt_ffi_str2ptr(value)
let result : Int = wasmImportSetConfig((handle).reinterpret_as_int(), ptr, key.length(), ptr0, value.length());
let ret = (result != 0)
mbt_ffi_free(ptr)
mbt_ffi_free(ptr0)
return ret
} }
///| ///|
/// ---- host data modules read through their capabilities ---- /// ---- host data modules read through their capabilities ----
+103 -3
View File
@@ -12,6 +12,7 @@ pub fn render_digital(
t : @theme.Tokens, t : @theme.Tokens,
now : @types.Datetime, now : @types.Datetime,
hour12? : Bool = false, hour12? : Bool = false,
show_date? : Bool = true,
) -> Array[@types.DrawOp] { ) -> Array[@types.DrawOp] {
let w = size.w.reinterpret_as_int() let w = size.w.reinterpret_as_int()
let h = size.h.reinterpret_as_int() let h = size.h.reinterpret_as_int()
@@ -21,6 +22,9 @@ pub fn render_digital(
} else { } else {
@timefmt.hhmm(now.hour.to_int(), now.minute.to_int()) @timefmt.hhmm(now.hour.to_int(), now.minute.to_int())
} }
if !show_date {
return [@ui.text(w / 2, h / 2, time, fs + 4, t.palette.foreground, align=CENTER, bold=true)]
}
let date = @timefmt.date_line( let date = @timefmt.date_line(
now.weekday.to_int(), now.weekday.to_int(),
now.day.to_int(), now.day.to_int(),
@@ -43,6 +47,7 @@ pub fn render_binary(
size : @types.Size, size : @types.Size,
t : @theme.Tokens, t : @theme.Tokens,
now : @types.Datetime, now : @types.Datetime,
seconds? : Bool = true,
) -> Array[@types.DrawOp] { ) -> Array[@types.DrawOp] {
let w = size.w.reinterpret_as_int() let w = size.w.reinterpret_as_int()
let h = size.h.reinterpret_as_int() let h = size.h.reinterpret_as_int()
@@ -51,14 +56,16 @@ pub fn render_binary(
(now.hour.to_int() % 10, 4), (now.hour.to_int() % 10, 4),
(now.minute.to_int() / 10, 3), (now.minute.to_int() / 10, 3),
(now.minute.to_int() % 10, 4), (now.minute.to_int() % 10, 4),
(now.second.to_int() / 10, 3),
(now.second.to_int() % 10, 4),
] ]
if seconds {
digits.push((now.second.to_int() / 10, 3))
digits.push((now.second.to_int() % 10, 4))
}
let ops = [] let ops = []
let cols = digits.length() let cols = digits.length()
// Columns are grouped HH MM SS with a wider gap between groups. // Columns are grouped HH MM SS with a wider gap between groups.
let group_gap = 8 let group_gap = 8
let step_x = (w - 2 * group_gap) / cols let step_x = (w - (cols / 2 - 1) * group_gap) / cols
let step_y = h / 4 let step_y = h / 4
let r = (if step_x < step_y { step_x } else { step_y }) / 2 - 1 let r = (if step_x < step_y { step_x } else { step_y }) / 2 - 1
let lit = t.palette.accent let lit = t.palette.accent
@@ -160,3 +167,96 @@ test "binary clock draws one dot per displayed bit" {
// 14:07:37 -> 1,4,0,7,3,7 -> popcount 1+1+0+3+2+3 // 14:07:37 -> 1,4,0,7,3,7 -> popcount 1+1+0+3+2+3
assert_eq(lit, 10) assert_eq(lit, 10)
} }
// ---------------------------------------------------------------- module settings
///| One item of a clock's right-click "Module settings" menu (the `module-config` record, minus
/// the generated type): key, label, choices (empty: an on/off switch) and the current value.
#derive(Eq, Debug)
pub(all) struct ConfigEntry {
key : String
label : String
choices : Array[String]
value : String
}
///| What the user picked for a clock; each clock module keeps one.
pub(all) struct ClockConfig {
mut hour12 : Bool
mut show_date : Bool
mut seconds : Bool
}
///|
pub fn ClockConfig::new() -> ClockConfig {
{ hour12: false, show_date: true, seconds: true }
}
///|
fn on_off(b : Bool) -> String {
if b { "on" } else { "off" }
}
///| The digital clock's settings: time format and whether the date line shows.
pub fn ClockConfig::digital_items(self : ClockConfig) -> Array[ConfigEntry] {
[
{
key: "format",
label: "Time format",
choices: ["24-hour", "12-hour"],
value: if self.hour12 { "12-hour" } else { "24-hour" },
},
{ key: "date", label: "Show date", choices: [], value: on_off(self.show_date) },
]
}
///| The binary clock's settings: whether the seconds columns show.
pub fn ClockConfig::binary_items(self : ClockConfig) -> Array[ConfigEntry] {
[{ key: "seconds", label: "Show seconds", choices: [], value: on_off(self.seconds) }]
}
///| Apply one setting; true when it changed something. Unknown keys and values are ignored.
pub fn ClockConfig::set(self : ClockConfig, key : String, value : String) -> Bool {
let flag = fn(cur : Bool, set : (Bool) -> Unit) -> Bool {
match value {
"on" if !cur => { set(true); true }
"off" if cur => { set(false); true }
_ => false
}
}
match key {
"format" =>
match value {
"12-hour" if !self.hour12 => { self.hour12 = true; true }
"24-hour" if self.hour12 => { self.hour12 = false; true }
_ => false
}
"date" => flag(self.show_date, fn(b) { self.show_date = b })
"seconds" => flag(self.seconds, fn(b) { self.seconds = b })
_ => false
}
}
///|
test "clock settings" {
let c = ClockConfig::new()
assert_eq(c.digital_items()[0].value, "24-hour")
assert_true(c.set("format", "12-hour"))
assert_false(c.set("format", "12-hour")) // no change
assert_false(c.set("format", "bogus"))
assert_eq(c.digital_items()[0].value, "12-hour")
assert_true(c.set("date", "off"))
assert_eq(c.digital_items()[1].value, "off")
assert_false(c.set("nope", "on"))
let ops = render_digital(@ui.size(120, 36), test_tokens(), test_time(), show_date=false)
assert_eq(ops.length(), 1)
assert_true(c.set("seconds", "off"))
let bin = render_binary(@ui.size(96, 36), test_tokens(), test_time(), seconds=false)
assert_eq(bin.length() < 30, true) // two columns fewer
}
///| The digital clock module's settings (one module instance per wasm instance).
pub let digital_config : ClockConfig = ClockConfig::new()
///| The binary clock module's settings.
pub let binary_config : ClockConfig = ClockConfig::new()
+24 -2
View File
@@ -4,20 +4,42 @@ package "chandra/desktop/lib/clock"
import { import {
"chandra/desktop/interface/chandra/desktop/theme", "chandra/desktop/interface/chandra/desktop/theme",
"chandra/desktop/interface/chandra/desktop/types", "chandra/desktop/interface/chandra/desktop/types",
"moonbitlang/core/debug",
} }
// Values // Values
pub let binary_config : ClockConfig
pub fn binary_info() -> (String, String, Int32, Int32, Int32) pub fn binary_info() -> (String, String, Int32, Int32, Int32)
pub let digital_config : ClockConfig
pub fn digital_info() -> (String, String, Int32, Int32, Int32) pub fn digital_info() -> (String, String, Int32, Int32, Int32)
pub fn render_binary(@types.Size, @theme.Tokens, @types.Datetime) -> Array[@types.DrawOp] pub fn render_binary(@types.Size, @theme.Tokens, @types.Datetime, seconds? : Bool) -> Array[@types.DrawOp]
pub fn render_digital(@types.Size, @theme.Tokens, @types.Datetime, hour12? : Bool) -> Array[@types.DrawOp] pub fn render_digital(@types.Size, @theme.Tokens, @types.Datetime, hour12? : Bool, show_date? : Bool) -> Array[@types.DrawOp]
// Errors // Errors
// Types and methods // Types and methods
pub(all) struct ClockConfig {
mut hour12 : Bool
mut show_date : Bool
mut seconds : Bool
}
pub fn ClockConfig::binary_items(Self) -> Array[ConfigEntry]
pub fn ClockConfig::digital_items(Self) -> Array[ConfigEntry]
pub fn ClockConfig::new() -> Self
pub fn ClockConfig::set(Self, String, String) -> Bool
#derive(Eq, @debug.Debug)
pub(all) struct ConfigEntry {
key : String
label : String
choices : Array[String]
value : String
}
// Type aliases // Type aliases
+13
View File
@@ -35,6 +35,19 @@ interface plasmoids {
/// Deliver an event to the module (`on-popup`: to its popup surface). True when it wants a redraw. /// Deliver an event to the module (`on-popup`: to its popup surface). True when it wants a redraw.
on-event: func(handle: u32, on-popup: bool, event: input-event) -> bool; on-event: func(handle: u32, on-popup: bool, event: input-event) -> bool;
/// One of a module's own settings (chandra:desktop/module-config `config-item`): `choices`
/// empty means an on/off switch whose value is "on" or "off".
record config-item {
key: string,
label: string,
choices: list<string>,
value: string,
}
/// The module's settings for its right-click menu; empty when it doesn't export module-config.
config-items: func(handle: u32) -> list<config-item>;
/// 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;
// ---- host data modules read through their capabilities ---- // ---- 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 /// Row tables, as built by compositor/wasm: a LE u32 row count, then per row each field as a LE
+22
View File
@@ -29,3 +29,25 @@ interface plasmoid {
/// Returns true when the widget's visuals changed and a redraw is needed. /// Returns true when the widget's visuals changed and a redraw is needed.
on-event: func(target: surface, event: input-event) -> bool; on-event: func(target: surface, event: input-event) -> bool;
} }
/// 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.
interface module-config {
record config-item {
/// Stable key, saved in state.edn, e.g. "format".
key: string,
/// What the menu shows, e.g. "Time format".
label: string,
/// The values to choose from, shown as one row each (the current one ticked). Empty: an on/off
/// switch, whose value is "on" or "off".
choices: list<string>,
/// The current value.
value: string,
}
config-items: func() -> list<config-item>;
/// Set `key` to `value` (unknown keys and values are ignored). True when the widget should redraw.
set-config: func(key: string, value: string) -> bool;
}
+7
View File
@@ -9,6 +9,13 @@ world widget {
world clock-widget { world clock-widget {
include widget; include widget;
import clock; import clock;
export module-config;
}
/// The optional `module-config` export on its own. A module of any world may add it to get its own
/// settings in its right-click menu; hosts look it up separately (host-wasm binds it with this world).
world configurable {
export module-config;
} }
world launcher-widget { world launcher-widget {