Battery panel module: charge, charging state, time left, low-battery warning
CI / test (push) Failing after 18s
CI / test (push) Failing after 18s
- New `battery` panel module (components/battery, logic in lib/battery): a battery icon filled to
the charge with the percentage and time remaining ("73% 2:05"; time to full while charging).
The fill turns green when charging or full, amber at 20 % and below, and at 10 % the whole
button turns red and a "Battery low" popup opens by itself, once per discharge spell. A click
opens the details (charge, state, time left in words). Without a battery it shows a plug.
- Right-click "Module settings": Show percentage, Show time remaining, and Without a battery
(Show a plug / Show nothing). Saved per module in state.edn like the clocks' settings.
- New `battery` capability (wit/capabilities.wit: read -> status {percent, charge-state,
secs-left}). Served by the wasmer stub (host ints 7-9), host-wasm and wasmhost (publish-battery).
- Host side (compositor/shell/battery.mbt): reads /sys/class/power_supply, every battery
together (energy_* / power_now, or charge_* / current_now; capacity when that is all there
is; device-scope batteries like mice are skipped). The `system` snapshot the Power tab uses
now reads the battery through the same code. Time left follows a running average of the
rate, starting over when the state changes.
- A fresh panel gets the battery module before the clock only on a machine with a battery.
- wasm_stub: MAX_INST 512 -> 2048. The host test binary creates ~70 compositors without
unloading their modules; at 512 the last tests' panels came up half empty.
- Tests: sysfs reading against a fake power supply (energy and charge units, two packs,
charging, full, capacity only, no battery), the running average, the module in the panel
(text, settings, click, the critical warning, the plug), the rendering logic, and a
host-wasm test of the module.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hky51dmaUqiYW746Gz
This commit is contained in:
48 files changed
+2142
-16
No files matched your search
@@ -0,0 +1,100 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
|
||||
///|
|
||||
pub fn mbt_ffi_cabi_realloc(
|
||||
src_offset : Int,
|
||||
src_size : Int,
|
||||
_dst_alignment : Int,
|
||||
dst_size : Int,
|
||||
) -> Int {
|
||||
// malloc
|
||||
if src_offset == 0 && src_size == 0 {
|
||||
return mbt_ffi_malloc(dst_size)
|
||||
}
|
||||
// free
|
||||
if dst_size == 0 {
|
||||
mbt_ffi_free(src_offset)
|
||||
return 0
|
||||
}
|
||||
// realloc
|
||||
let dst = mbt_ffi_malloc(dst_size)
|
||||
mbt_ffi_copy(dst, src_offset, if src_size < dst_size { src_size } else { dst_size })
|
||||
mbt_ffi_free(src_offset)
|
||||
dst
|
||||
}
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_copy(dest : Int, src : Int, len : Int) =
|
||||
#|(func (param i32) (param i32) (param i32) local.get 0 local.get 1 local.get 2 memory.copy)
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
|
||||
#|(func (param i32) (result i32) (local i32)
|
||||
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
|
||||
#| local.tee 1 i32.const 0 call $moonbit.init_array8
|
||||
#| local.get 1)
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_free(position : Int) =
|
||||
#|(func (param i32) local.get 0 call $moonbit.decref)
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportPopup() -> Int {
|
||||
@plasmoid.wasmExportPopup()
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
|
||||
@plasmoid.wasmExportOnEvent(p0, p1, p2, p3)
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportConfigItems() -> Int {
|
||||
@module-config.wasmExportConfigItems()
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
|
||||
@module-config.wasmExportSetConfig(p0, p1, p2, p3)
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportInfo() -> Int {
|
||||
@plasmoid.wasmExportInfo()
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
|
||||
@plasmoid.wasmExportRenderPostReturn(p0)
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit {
|
||||
@plasmoid.wasmExportInfoPostReturn(p0)
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportConfigItemsPostReturn(p0 : Int) -> Unit {
|
||||
@module-config.wasmExportConfigItemsPostReturn(p0)
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int {
|
||||
@plasmoid.wasmExportRender(p0, p1)
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
|
||||
@plasmoid.wasmExportPopupPostReturn(p0)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
Optional: a module's own settings. A module that exports this gets a "Module settings" entry in
|
||||
its right-click menu, listing the items below; the shell draws the menu (the same for every
|
||||
module), remembers each choice per module in state.edn (`:module-config`), and hands the saved
|
||||
values back through `set-config` right after the module is loaded. A module without it simply
|
||||
has no settings: the export is looked up by name, so older modules keep loading.
|
||||
@@ -0,0 +1,114 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportConfigItems() -> Int {
|
||||
|
||||
let (result) : (Array[ConfigItem]) = config_items();
|
||||
let return_area = mbt_ffi_malloc(8)
|
||||
|
||||
let address3 = mbt_ffi_malloc((result).length() * 32);
|
||||
for index4 = 0; index4 < (result).length(); index4 = index4 + 1 {
|
||||
let iter_elem : ConfigItem = (result)[(index4)]
|
||||
let iter_base = address3 + (index4 * 32);
|
||||
|
||||
let ptr = mbt_ffi_str2ptr((iter_elem).key)
|
||||
mbt_ffi_store32((iter_base) + 4, (iter_elem).key.length())
|
||||
mbt_ffi_store32((iter_base) + 0, ptr)
|
||||
|
||||
let ptr0 = mbt_ffi_str2ptr((iter_elem).label)
|
||||
mbt_ffi_store32((iter_base) + 12, (iter_elem).label.length())
|
||||
mbt_ffi_store32((iter_base) + 8, ptr0)
|
||||
|
||||
let address = mbt_ffi_malloc(((iter_elem).choices).length() * 8);
|
||||
for index = 0; index < ((iter_elem).choices).length(); index = index + 1 {
|
||||
let iter_elem : String = ((iter_elem).choices)[(index)]
|
||||
let iter_base = address + (index * 8);
|
||||
|
||||
let ptr1 = mbt_ffi_str2ptr(iter_elem)
|
||||
mbt_ffi_store32((iter_base) + 4, iter_elem.length())
|
||||
mbt_ffi_store32((iter_base) + 0, ptr1)
|
||||
|
||||
}
|
||||
mbt_ffi_store32((iter_base) + 20, ((iter_elem).choices).length())
|
||||
mbt_ffi_store32((iter_base) + 16, address)
|
||||
|
||||
let ptr2 = mbt_ffi_str2ptr((iter_elem).value)
|
||||
mbt_ffi_store32((iter_base) + 28, (iter_elem).value.length())
|
||||
mbt_ffi_store32((iter_base) + 24, ptr2)
|
||||
|
||||
}
|
||||
mbt_ffi_store32((return_area) + 4, (result).length())
|
||||
mbt_ffi_store32((return_area) + 0, address3)
|
||||
let ret = return_area
|
||||
return ret
|
||||
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportConfigItemsPostReturn(p0 : Int) -> Unit {
|
||||
|
||||
for index0 = 0; index0 < (mbt_ffi_load32((p0) + 4)); index0 = index0 + 1 {
|
||||
let iter_base = (mbt_ffi_load32((p0) + 0)) + (index0 * 32)
|
||||
mbt_ffi_free(mbt_ffi_load32((iter_base) + 0))
|
||||
mbt_ffi_free(mbt_ffi_load32((iter_base) + 8))
|
||||
|
||||
for index = 0; index < (mbt_ffi_load32((iter_base) + 20)); index = index + 1 {
|
||||
let iter_base = (mbt_ffi_load32((iter_base) + 16)) + (index * 8)
|
||||
mbt_ffi_free(mbt_ffi_load32((iter_base) + 0))
|
||||
|
||||
}
|
||||
mbt_ffi_free(mbt_ffi_load32((iter_base) + 16))
|
||||
mbt_ffi_free(mbt_ffi_load32((iter_base) + 24))
|
||||
|
||||
}
|
||||
mbt_ffi_free(mbt_ffi_load32((p0) + 0))
|
||||
|
||||
}
|
||||
|
||||
///|
|
||||
#doc(hidden)
|
||||
pub fn wasmExportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
|
||||
|
||||
let result = mbt_ffi_ptr2str(p0, p1)
|
||||
|
||||
let result0 = mbt_ffi_ptr2str(p2, p3)
|
||||
|
||||
let (result1) : (Bool) = set_config(result, result0);
|
||||
let ret = (if result1 { 1 } else { 0 })
|
||||
return ret
|
||||
|
||||
}
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
|
||||
#|(func (param i32) (result i32) (local i32)
|
||||
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
|
||||
#| local.tee 1 i32.const 0 call $moonbit.init_array8
|
||||
#| local.get 1)
|
||||
|
||||
///|
|
||||
#owned(str)
|
||||
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
|
||||
#|(func (param i32) (result i32) local.get 0)
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
|
||||
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_free(position : Int) =
|
||||
#|(func (param i32) local.get 0 call $moonbit.decref)
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
|
||||
#|(func (param i32) (result i32) local.get 0 i32.load)
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
|
||||
#|(func (param i32) (param i32) (result i32)
|
||||
#| local.get 0
|
||||
#| local.get 1 call $moonbit.init_array16
|
||||
#| local.get 0)
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import {
|
||||
"chandra/desktop/lib/battery" @logic,
|
||||
}
|
||||
|
||||
warnings = "-44"
|
||||
@@ -0,0 +1,21 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "chandra/desktop/components/battery/gen/interface/chandra/desktop/module-config"
|
||||
|
||||
// Values
|
||||
pub fn config_items() -> Array[ConfigItem]
|
||||
|
||||
pub fn set_config(String, String) -> Bool
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
pub(all) struct ConfigItem {
|
||||
key : String
|
||||
label : String
|
||||
choices : Array[String]
|
||||
value : String
|
||||
}
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1,12 @@
|
||||
///| The battery module's right-click settings (percentage, time remaining, what shows without a
|
||||
/// battery); the logic is in lib/battery.
|
||||
|
||||
///|
|
||||
pub fn config_items() -> Array[ConfigItem] {
|
||||
@logic.config.items().map(e => { key: e.key, label: e.label, choices: e.choices, value: e.value })
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn set_config(key : String, value : String) -> Bool {
|
||||
@logic.config.set(key, value)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
///|
|
||||
pub(all) struct ConfigItem {
|
||||
key : String; label : String; choices : Array[String]; value : String
|
||||
}
|
||||
///|
|
||||
declare pub fn config_items() -> Array[ConfigItem]
|
||||
///|
|
||||
/// Set `key` to `value` (unknown keys and values are ignored). True when the widget should redraw.
|
||||
declare pub fn set_config(key : String, value : String) -> Bool
|
||||
|
||||
@@ -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_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_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)
|
||||
|
||||
///|
|
||||
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_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)
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import {
|
||||
"chandra/desktop/interface/chandra/desktop/types" @types,
|
||||
"chandra/desktop/interface/chandra/desktop/theme" @theme,
|
||||
"chandra/desktop/interface/chandra/desktop/battery" @battery,
|
||||
"chandra/desktop/lib/battery" @logic,
|
||||
}
|
||||
|
||||
warnings = "-44"
|
||||
@@ -0,0 +1,42 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "chandra/desktop/components/battery/gen/interface/chandra/desktop/plasmoid"
|
||||
|
||||
import {
|
||||
"chandra/desktop/interface/chandra/desktop/types",
|
||||
}
|
||||
|
||||
// Values
|
||||
pub fn info() -> PlasmoidInfo
|
||||
|
||||
pub fn on_event(Surface, @types.InputEvent) -> Bool
|
||||
|
||||
pub fn popup() -> PopupSurface?
|
||||
|
||||
pub fn render(@types.Size) -> Array[@types.DrawOp]
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
pub(all) struct PlasmoidInfo {
|
||||
id : String
|
||||
name : String
|
||||
preferred : @types.Size
|
||||
min_width : UInt32
|
||||
stretch : Bool
|
||||
}
|
||||
|
||||
pub(all) struct PopupSurface {
|
||||
size : @types.Size
|
||||
ops : Array[@types.DrawOp]
|
||||
}
|
||||
|
||||
pub(all) enum Surface {
|
||||
WIDGET
|
||||
POPUP
|
||||
}
|
||||
pub fn Surface::from(Int32) -> Self
|
||||
pub fn Surface::ordinal(Self) -> Int32
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1,82 @@
|
||||
///| Implementation of `chandra:desktop/plasmoid` for the battery module: charge as an icon and
|
||||
/// percentage, charging state and time remaining, turning amber when low and red when critical.
|
||||
/// A click opens the details; a critical battery opens them by itself once per discharge spell.
|
||||
/// All drawing is in lib/battery; this file only adapts the `battery` capability.
|
||||
|
||||
///|
|
||||
let open_ : Ref[Bool] = { val: false }
|
||||
|
||||
///| The open popup is the low-battery warning (not a click).
|
||||
let warning : Ref[Bool] = { val: false }
|
||||
|
||||
///|
|
||||
let low : @logic.LowWarning = @logic.LowWarning::new()
|
||||
|
||||
///| The host's reading, sampled about once a second.
|
||||
fn reading() -> @logic.Reading {
|
||||
let s = @battery.read()
|
||||
{ percent: s.percent, state: s.state.ordinal(), secs_left: s.secs_left.reinterpret_as_int() }
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn info() -> PlasmoidInfo {
|
||||
let (id, name, w, h, min_w) = @logic.info()
|
||||
{
|
||||
id,
|
||||
name,
|
||||
preferred: { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() },
|
||||
min_width: min_w.reinterpret_as_uint(),
|
||||
stretch: false,
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn render(size : @types.Size) -> Array[@types.DrawOp] {
|
||||
let r = reading()
|
||||
if low.update(r) {
|
||||
open_.val = true
|
||||
warning.val = true
|
||||
}
|
||||
@logic.render(size, @theme.get_tokens(), r, @logic.config, open=open_.val && !warning.val)
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn popup() -> PopupSurface? {
|
||||
if !open_.val {
|
||||
return None
|
||||
}
|
||||
let (w, h, ops) = @logic.render_popup(@theme.get_tokens(), reading(), warning=warning.val)
|
||||
Some({ size: { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() }, ops })
|
||||
}
|
||||
|
||||
///|
|
||||
fn close() -> Unit {
|
||||
open_.val = false
|
||||
warning.val = false
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn on_event(target : Surface, event : @types.InputEvent) -> Bool {
|
||||
match (target, event) {
|
||||
(WIDGET, PointerDown(_)) => {
|
||||
if open_.val {
|
||||
close()
|
||||
} else {
|
||||
open_.val = true
|
||||
}
|
||||
true
|
||||
}
|
||||
(POPUP, PointerDown(_)) => {
|
||||
close()
|
||||
true
|
||||
}
|
||||
(_, FocusLost) | (_, KeyDown("Escape")) =>
|
||||
if open_.val {
|
||||
close()
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
_ => false
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import {
|
||||
"chandra/desktop/components/battery/gen/interface/chandra/desktop/module-config" @module-config,
|
||||
"chandra/desktop/components/battery/gen/interface/chandra/desktop/plasmoid" @plasmoid,
|
||||
}
|
||||
|
||||
warnings = "-44"
|
||||
|
||||
pkgtype(kind: "foreign_library")
|
||||
|
||||
options(
|
||||
link: {
|
||||
"wasm": {
|
||||
"export-memory-name": "memory",
|
||||
"heap-start-address": 16,
|
||||
"exports": [
|
||||
"mbt_ffi_cabi_realloc:cabi_realloc",
|
||||
"wasmExportConfigItems:chandra:desktop/module-config@0.1.0#config-items",
|
||||
"wasmExportConfigItemsPostReturn:cabi_post_chandra:desktop/module-config@0.1.0#config-items",
|
||||
"wasmExportInfo:chandra:desktop/plasmoid@0.1.0#info",
|
||||
"wasmExportInfoPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#info",
|
||||
"wasmExportOnEvent:chandra:desktop/plasmoid@0.1.0#on-event",
|
||||
"wasmExportPopup:chandra:desktop/plasmoid@0.1.0#popup",
|
||||
"wasmExportPopupPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#popup",
|
||||
"wasmExportRender:chandra:desktop/plasmoid@0.1.0#render",
|
||||
"wasmExportRenderPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#render",
|
||||
"wasmExportSetConfig:chandra:desktop/module-config@0.1.0#set-config"
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "chandra/desktop/components/battery/gen"
|
||||
|
||||
// Values
|
||||
pub fn mbt_ffi_cabi_realloc(Int32, Int32, Int32, Int32) -> Int32
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1,184 @@
|
||||
///| The battery: reading a fake /sys/class/power_supply, and the battery panel module drawing it.
|
||||
|
||||
///| Write a fake power supply tree: (directory, [(file, contents)]) under a fresh directory.
|
||||
fn fake_supply(tag : String, entries : Array[(String, Array[(String, String)])]) -> String {
|
||||
let root = "/tmp/chandra-power-" + tag + "-" + @sys.getpid().to_string()
|
||||
for e in entries {
|
||||
let (name, files) = e
|
||||
ignore(@sys.mkdir_p(root + "/" + name))
|
||||
for f in files {
|
||||
let (file, text) = f
|
||||
ignore(@sys.write_file_bytes(root + "/" + name + "/" + file, @sys.str_to_utf8_bytes(text + "\n")))
|
||||
}
|
||||
}
|
||||
ignore(@sys.mkdir_p(root))
|
||||
root
|
||||
}
|
||||
|
||||
///|
|
||||
fn bat(status : String, capacity : Int, now : Int, full : Int, rate : Int) -> Array[(String, String)] {
|
||||
[
|
||||
("type", "Battery"),
|
||||
("status", status),
|
||||
("capacity", capacity.to_string()),
|
||||
("energy_now", now.to_string()),
|
||||
("energy_full", full.to_string()),
|
||||
("power_now", rate.to_string()),
|
||||
]
|
||||
}
|
||||
|
||||
///|
|
||||
test "no battery: percent -1, state none" {
|
||||
let root = fake_supply("none", [("AC", [("type", "Mains"), ("online", "1")])])
|
||||
assert_eq(@shell.read_battery(root~), { percent: -1, state: 0, secs_left: 0 })
|
||||
}
|
||||
|
||||
///|
|
||||
test "a discharging battery: percent from energy, time left at the current power" {
|
||||
let root = fake_supply("dis", [("BAT0", bat("Discharging", 59, 30000000, 50000000, 10000000))])
|
||||
// 30 Wh of 50 Wh at 10 W: 60 %, three hours.
|
||||
assert_eq(@shell.read_battery(root~), { percent: 60, state: 1, secs_left: 3 * 3600 })
|
||||
}
|
||||
|
||||
///|
|
||||
test "charging: time until full; full and not charging have no time" {
|
||||
let root = fake_supply("chg", [("BAT0", bat("Charging", 40, 20000000, 50000000, 15000000))])
|
||||
assert_eq(@shell.read_battery(root~), { percent: 40, state: 2, secs_left: 2 * 3600 })
|
||||
let root = fake_supply("full", [("BAT0", bat("Full", 100, 50000000, 50000000, 0))])
|
||||
assert_eq(@shell.read_battery(root~), { percent: 100, state: 3, secs_left: 0 })
|
||||
let root = fake_supply("hold", [("BAT0", bat("Not charging", 80, 40000000, 50000000, 0))])
|
||||
assert_eq(@shell.read_battery(root~), { percent: 80, state: 4, secs_left: 0 })
|
||||
}
|
||||
|
||||
///|
|
||||
test "two packs in charge units count together; a negative current is a discharge" {
|
||||
let root = fake_supply("two", [
|
||||
(
|
||||
"BAT0",
|
||||
[
|
||||
("type", "Battery"),
|
||||
("status", "Discharging"),
|
||||
("capacity", "50"),
|
||||
("charge_now", "2000000"),
|
||||
("charge_full", "4000000"),
|
||||
("current_now", "-1000000"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"BAT1",
|
||||
[
|
||||
("type", "Battery"),
|
||||
("status", "Not charging"),
|
||||
("capacity", "100"),
|
||||
("charge_now", "4000000"),
|
||||
("charge_full", "4000000"),
|
||||
("current_now", "0"),
|
||||
],
|
||||
),
|
||||
])
|
||||
// 6 of 8 Ah, draining at 1 A: six hours.
|
||||
assert_eq(@shell.read_battery(root~), { percent: 75, state: 1, secs_left: 6 * 3600 })
|
||||
}
|
||||
|
||||
///|
|
||||
test "a battery without energy or charge files uses its capacity; time is unknown" {
|
||||
let root = fake_supply("cap", [("BAT1", [("status", "Discharging"), ("capacity", "42")])])
|
||||
assert_eq(@shell.read_battery(root~), { percent: 42, state: 1, secs_left: 0 })
|
||||
}
|
||||
|
||||
///|
|
||||
test "time left is a running average while the state holds" {
|
||||
let m = @shell.BatteryMeter::new()
|
||||
m.feed({ percent: 50, state: 1, secs_left: 4000 })
|
||||
assert_eq(m.cur.secs_left, 4000)
|
||||
m.feed({ percent: 50, state: 1, secs_left: 8000 })
|
||||
assert_eq(m.cur.secs_left, 5000)
|
||||
// Plugging in starts over.
|
||||
m.feed({ percent: 50, state: 2, secs_left: 1200 })
|
||||
assert_eq(m.cur.secs_left, 1200)
|
||||
}
|
||||
|
||||
///|
|
||||
fn module_texts(comp : @host.ChandraCompositor) -> Array[String] {
|
||||
let out : Array[String] = []
|
||||
for op in comp.shell.slot_ops(comp.shell.slot_of("battery")) {
|
||||
if op is Text(t) {
|
||||
out.push(t.text)
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///| A compositor whose panel has the battery module. A fresh panel gets it from the (fake) battery;
|
||||
/// a panel.edn another test saved may not have it, so it is added (in place of their extra clock,
|
||||
/// which would not leave room).
|
||||
fn battery_comp(tag : String) -> @host.ChandraCompositor {
|
||||
let comp = new_comp(tag)
|
||||
if comp.shell.slot_of("battery") == "" {
|
||||
let extra = comp.shell.slot_of("clock-binary")
|
||||
if extra != "" {
|
||||
ignore(comp.shell.unload_slot(extra))
|
||||
}
|
||||
ignore(comp.shell.load_module("battery"))
|
||||
ignore(comp.compose_frame())
|
||||
}
|
||||
comp
|
||||
}
|
||||
|
||||
///| Wait for the wall clock's next second, so the shell samples the battery again.
|
||||
fn next_second(comp : @host.ChandraCompositor) -> Unit {
|
||||
let s = @sys.wall_time_field(5)
|
||||
let t0 = @sys.monotonic_ms()
|
||||
while @sys.wall_time_field(5) == s && @sys.monotonic_ms() - t0 < 2000UL {
|
||||
@sys.sleep_ms(20)
|
||||
}
|
||||
ignore(comp.compose_frame())
|
||||
}
|
||||
|
||||
///|
|
||||
test "the battery module shows charge and time left, its settings, and warns when critical" {
|
||||
let root = fake_supply("module", [("BAT0", bat("Discharging", 60, 30000000, 50000000, 10000000))])
|
||||
@shell.set_power_supply_root(root)
|
||||
let comp = battery_comp("battery")
|
||||
let slot = comp.shell.slot_of("battery")
|
||||
assert_true(comp.shell.slot_rect(slot).w > 0)
|
||||
assert_eq(module_texts(comp), ["60% 3:00"])
|
||||
assert_eq(comp.shell.slot_config(slot).map(i => i.key), ["percent", "time", "no-battery"])
|
||||
comp.shell.set_module_setting(slot, "time", "off")
|
||||
assert_eq(module_texts(comp), ["60%"])
|
||||
comp.shell.set_module_setting(slot, "time", "on")
|
||||
// A click opens the details.
|
||||
click_module(comp, "battery", 1U) catch {
|
||||
_ => fail("battery module not placed")
|
||||
}
|
||||
assert_true(comp.shell.slot_popup_rect(slot).w > 0)
|
||||
click_module(comp, "battery", 5U) catch {
|
||||
_ => fail("battery module not placed")
|
||||
}
|
||||
assert_eq(comp.shell.slot_popup_rect(slot).w, 0)
|
||||
// Down to 8 %: the warning opens by itself.
|
||||
ignore(
|
||||
@sys.write_file_bytes(root + "/BAT0/energy_now", @sys.str_to_utf8_bytes("4000000\n")),
|
||||
)
|
||||
next_second(comp)
|
||||
ignore(comp.compose_frame())
|
||||
// (The time left eases toward the new 24 minutes, a quarter per sample.)
|
||||
assert_true(module_texts(comp)[0].has_prefix("8% "))
|
||||
assert_true(comp.shell.slot_popup_rect(slot).w > 0)
|
||||
@shell.set_power_supply_root("/sys/class/power_supply")
|
||||
}
|
||||
|
||||
///|
|
||||
test "without a battery the module shows a plug, or nothing" {
|
||||
let root = fake_supply("module-none", [])
|
||||
@shell.set_power_supply_root(root)
|
||||
let comp = battery_comp("battery-none")
|
||||
let slot = comp.shell.slot_of("battery")
|
||||
let ops = comp.shell.slot_ops(slot)
|
||||
assert_true(ops.length() > 0)
|
||||
assert_eq(module_texts(comp), [])
|
||||
comp.shell.set_module_setting(slot, "no-battery", "Show nothing")
|
||||
assert_eq(comp.shell.slot_ops(slot).length(), 0)
|
||||
@shell.set_power_supply_root("/sys/class/power_supply")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
///| Linux provider for the `battery` capability (and the battery fields of `system`): reads
|
||||
/// /sys/class/power_supply. Every battery the machine has counts together (a laptop with two
|
||||
/// packs shows one charge). Modules never see these paths.
|
||||
|
||||
///| Where power supplies are read from; tests point it at a fake tree.
|
||||
let power_supply_root : Ref[String] = { val: "/sys/class/power_supply" }
|
||||
|
||||
///| Read batteries from `dir` instead of /sys/class/power_supply (tests: a fake power supply).
|
||||
pub fn set_power_supply_root(dir : String) -> Unit {
|
||||
power_supply_root.val = dir
|
||||
}
|
||||
|
||||
///| Names Linux gives batteries (ACPI, Apple, Chromebooks, many ARM boards). The tree is not listed:
|
||||
/// a lookup of each name keeps this to plain file reads, which every host serves.
|
||||
let battery_names : Array[String] = ["BAT0", "BAT1", "BAT2", "BATT", "BATC", "CMB0", "CMB1", "battery"]
|
||||
|
||||
///| The `battery.status` record: state is the `charge-state` index (0 none, 1 discharging,
|
||||
/// 2 charging, 3 full, 4 not charging).
|
||||
#derive(Eq, Debug)
|
||||
pub(all) struct BatteryInfo {
|
||||
percent : Int
|
||||
state : Int
|
||||
secs_left : Int
|
||||
}
|
||||
|
||||
///|
|
||||
let no_battery : BatteryInfo = { percent: -1, state: 0, secs_left: 0 }
|
||||
|
||||
///| One battery's numbers, in µWh/µW (energy_*, power_now) or µAh/µA (charge_*, current_now).
|
||||
priv struct Pack {
|
||||
capacity : Int
|
||||
status : String
|
||||
now : Int64
|
||||
full : Int64
|
||||
rate : Int64
|
||||
}
|
||||
|
||||
///|
|
||||
fn sysfs_text(path : String) -> String {
|
||||
@utf8.decode_lossy(@sys.read_proc_bytes(path)).trim(chars=" \n").to_string()
|
||||
}
|
||||
|
||||
///| A sysfs number ("-1234" allowed), or -1 when the file is missing or empty.
|
||||
fn sysfs_num(path : String) -> Int64 {
|
||||
let s = sysfs_text(path)
|
||||
if s.length() == 0 {
|
||||
return -1L
|
||||
}
|
||||
if s.has_prefix("-") {
|
||||
-parse_i64(s[1:].to_string())
|
||||
} else {
|
||||
parse_i64(s)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn read_pack(base : String) -> Pack? {
|
||||
let cap = sysfs_text(base + "/capacity")
|
||||
if cap.length() == 0 {
|
||||
return None
|
||||
}
|
||||
let ty = sysfs_text(base + "/type")
|
||||
// A mouse or headset battery (scope Device) is not the machine's.
|
||||
if (ty.length() > 0 && ty != "Battery") || sysfs_text(base + "/scope") == "Device" {
|
||||
return None
|
||||
}
|
||||
let energy = sysfs_num(base + "/energy_now") >= 0L
|
||||
let (n, f, r) = if energy {
|
||||
("energy_now", "energy_full", "power_now")
|
||||
} else {
|
||||
("charge_now", "charge_full", "current_now")
|
||||
}
|
||||
let rate = sysfs_num(base + "/" + r)
|
||||
Some({
|
||||
capacity: parse_i64(cap).to_int(),
|
||||
status: sysfs_text(base + "/status"),
|
||||
now: sysfs_num(base + "/" + n),
|
||||
full: sysfs_num(base + "/" + f),
|
||||
// Some firmware reports discharge as a negative rate.
|
||||
rate: if rate < 0L { -rate } else { rate },
|
||||
})
|
||||
}
|
||||
|
||||
///| The machine's batteries under `root`, summed: percent from the energy left over the energy
|
||||
/// when full (each pack's capacity if they don't say), state, and the seconds left at the current
|
||||
/// rate (0 when the firmware doesn't report one). Without a battery: percent -1, state 0.
|
||||
pub fn read_battery(root? : String = power_supply_root.val) -> BatteryInfo {
|
||||
let packs : Array[Pack] = []
|
||||
for name in battery_names {
|
||||
match read_pack(root + "/" + name) {
|
||||
Some(p) => packs.push(p)
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
if packs.length() == 0 {
|
||||
return no_battery
|
||||
}
|
||||
let mut now = 0L
|
||||
let mut full = 0L
|
||||
let mut rate = 0L
|
||||
let mut cap_sum = 0
|
||||
let mut sized = true
|
||||
let mut discharging = false
|
||||
let mut charging = false
|
||||
let mut all_full = true
|
||||
for p in packs {
|
||||
cap_sum = cap_sum + p.capacity
|
||||
if p.now < 0L || p.full <= 0L {
|
||||
sized = false
|
||||
} else {
|
||||
now = now + p.now
|
||||
full = full + p.full
|
||||
}
|
||||
if p.rate > 0L {
|
||||
rate = rate + p.rate
|
||||
}
|
||||
match p.status {
|
||||
"Discharging" => discharging = true
|
||||
"Charging" => charging = true
|
||||
_ => ()
|
||||
}
|
||||
if p.status != "Full" && p.capacity < 100 {
|
||||
all_full = false
|
||||
}
|
||||
}
|
||||
let percent = if sized {
|
||||
((now * 100L + full / 2L) / full).to_int()
|
||||
} else {
|
||||
cap_sum / packs.length()
|
||||
}
|
||||
let percent = if percent < 0 { 0 } else if percent > 100 { 100 } else { percent }
|
||||
let state = if discharging { 1 } else if charging { 2 } else if all_full { 3 } else { 4 }
|
||||
let secs = if !sized || rate <= 0L {
|
||||
0
|
||||
} else if state == 1 {
|
||||
(now * 3600L / rate).to_int()
|
||||
} else if state == 2 {
|
||||
let left = full - now
|
||||
if left > 0L { (left * 3600L / rate).to_int() } else { 0 }
|
||||
} else {
|
||||
0
|
||||
}
|
||||
{ percent, state, secs_left: secs }
|
||||
}
|
||||
|
||||
///| Samples the battery about once a second for the `battery` capability. The discharge rate
|
||||
/// jumps with load, so time left follows a running average of it rather than each sample.
|
||||
pub(all) struct BatteryMeter {
|
||||
mut last_secs : Int
|
||||
mut last_state : Int
|
||||
/// Average seconds left, scaled by the latest reading's energy (0: none yet).
|
||||
mut avg_secs : Int
|
||||
mut cur : BatteryInfo
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn BatteryMeter::new() -> BatteryMeter {
|
||||
{ last_secs: -1, last_state: -1, avg_secs: 0, cur: no_battery }
|
||||
}
|
||||
|
||||
///| Feed one reading: the time left is averaged (a quarter of each new sample) while the state
|
||||
/// holds, and starts over when it changes (plugged in, unplugged).
|
||||
pub fn BatteryMeter::feed(self : BatteryMeter, b : BatteryInfo) -> Unit {
|
||||
if b.state != self.last_state || b.secs_left <= 0 || self.avg_secs <= 0 {
|
||||
self.avg_secs = b.secs_left
|
||||
} else {
|
||||
self.avg_secs = (self.avg_secs * 3 + b.secs_left) / 4
|
||||
}
|
||||
self.last_state = b.state
|
||||
self.cur = { ..b, secs_left: self.avg_secs }
|
||||
}
|
||||
|
||||
///| Re-read if a wall-clock second passed since the last call; cheap otherwise.
|
||||
pub fn BatteryMeter::refresh(self : BatteryMeter) -> BatteryInfo {
|
||||
let now = wall_secs()
|
||||
if now != self.last_secs {
|
||||
self.last_secs = now
|
||||
self.feed(read_battery())
|
||||
}
|
||||
self.cur
|
||||
}
|
||||
@@ -261,6 +261,8 @@ pub(all) struct DesktopShell {
|
||||
mut picker : @wasm.Picker?
|
||||
/// Machine-state provider behind the `system` interface, and the window list behind `windows`.
|
||||
sampler : SysSampler
|
||||
/// The battery for modules with the `battery` capability (battery.mbt).
|
||||
battery : BatteryMeter
|
||||
mut win_list : Array[@wasm.WindowEntry]
|
||||
mut notice : String
|
||||
mut notice_frames : Int
|
||||
@@ -358,6 +360,7 @@ pub fn DesktopShell::new(display : String) -> DesktopShell {
|
||||
actions: [],
|
||||
apps_dirty: true,
|
||||
sampler: SysSampler::new(),
|
||||
battery: BatteryMeter::new(),
|
||||
win_list: [],
|
||||
picker: None,
|
||||
notice: "",
|
||||
|
||||
@@ -146,17 +146,10 @@ fn mem_kib() -> (Int64, Int64) {
|
||||
(total, avail)
|
||||
}
|
||||
|
||||
///| (percent, plugged-in) for the first battery, or (-1, true) without one.
|
||||
///| (percent, plugged-in) for the machine's batteries (battery.mbt), or (-1, true) without one.
|
||||
fn battery() -> (Int, Bool) {
|
||||
for name in ["BAT0", "BAT1", "BATT"] {
|
||||
let base = "/sys/class/power_supply/" + name
|
||||
let cap = proc_text(base + "/capacity")
|
||||
if cap.length() > 0 {
|
||||
let status = proc_text(base + "/status").trim(chars=" \n").to_string()
|
||||
return (parse_i64(cap).to_int(), status != "Discharging")
|
||||
}
|
||||
}
|
||||
(-1, true)
|
||||
let b = read_battery()
|
||||
(b.percent, b.state != 1)
|
||||
}
|
||||
|
||||
///| Re-sample if a wall-clock second passed since the last call; cheap otherwise.
|
||||
|
||||
@@ -17,6 +17,29 @@ let default_panel : Array[String] = [
|
||||
"logout",
|
||||
]
|
||||
|
||||
///| A fresh panel's modules: the defaults, plus the battery before the clock on a machine that
|
||||
/// has one (a desktop gets no battery module; it can be added from the settings module).
|
||||
fn fresh_panel(has_battery : Bool) -> Array[String] {
|
||||
if !has_battery {
|
||||
return default_panel
|
||||
}
|
||||
let out : Array[String] = []
|
||||
for m in default_panel {
|
||||
if m == "clock-digital12" {
|
||||
out.push("battery")
|
||||
}
|
||||
out.push(m)
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
test "a fresh panel gets the battery module only on a machine with a battery" {
|
||||
assert_false(fresh_panel(false).contains("battery"))
|
||||
let p = fresh_panel(true)
|
||||
assert_eq(p.search("battery").unwrap() + 1, p.search("clock-digital12").unwrap())
|
||||
}
|
||||
|
||||
///| The module whose popup holds the wasm picker (its Modules tab).
|
||||
let manager_module : String = "session-settings"
|
||||
|
||||
@@ -209,7 +232,7 @@ fn DesktopShell::ensure_booted(self : DesktopShell) -> Unit {
|
||||
self.scan_catalog()
|
||||
let entries = match self.load_panel_config() {
|
||||
Some(e) => migrate_panel(e)
|
||||
None => default_panel
|
||||
None => fresh_panel(read_battery().state != 0)
|
||||
}
|
||||
for e in entries {
|
||||
let path = if e.has_prefix("/") {
|
||||
@@ -436,6 +459,10 @@ fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit {
|
||||
if self.widgets.iter().any(w => w.has_cap("screenshot")) {
|
||||
@wasm.publish_screenshot(self.screenshot_state)
|
||||
}
|
||||
if self.widgets.iter().any(w => w.has_cap("battery")) {
|
||||
let b = self.battery.refresh()
|
||||
@wasm.publish_battery(b.percent, b.state, b.secs_left)
|
||||
}
|
||||
let it = @wasm.Table::new()
|
||||
for w in self.widgets {
|
||||
it.str(w.slot)
|
||||
|
||||
@@ -323,6 +323,11 @@ pub fn publish_power(screen_off : Int, suspend : Int) -> Unit {
|
||||
@hostpl.publish_power(screen_off.reinterpret_as_uint(), suspend.reinterpret_as_uint())
|
||||
}
|
||||
|
||||
///| The battery (the `battery` capability): percent (-1: none), charge-state index, seconds left.
|
||||
pub fn publish_battery(percent : Int, state : Int, secs_left : Int) -> Unit {
|
||||
@hostpl.publish_battery(percent, state.reinterpret_as_uint(), secs_left.reinterpret_as_uint())
|
||||
}
|
||||
|
||||
///| Something a module asked the host to do during a call.
|
||||
pub(all) enum HostRequest {
|
||||
Launch(String)
|
||||
|
||||
@@ -741,6 +741,14 @@ pub fn publish_power(screen_off : Int, suspend : Int) -> Unit {
|
||||
c_host_set_int(6, suspend)
|
||||
}
|
||||
|
||||
///| Publish the battery (the `battery` capability): percent (-1: none), charge-state index,
|
||||
/// seconds left (0: unknown).
|
||||
pub fn publish_battery(percent : Int, state : Int, secs_left : Int) -> Unit {
|
||||
c_host_set_int(7, percent)
|
||||
c_host_set_int(8, state)
|
||||
c_host_set_int(9, secs_left)
|
||||
}
|
||||
|
||||
///| Something a module asked the host to do during a call.
|
||||
pub(all) enum HostRequest {
|
||||
Launch(String)
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
#include <wasm.h>
|
||||
#include "moonbit.h"
|
||||
|
||||
#define MAX_INST 512
|
||||
#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 };
|
||||
static const char *ex_names[EX_N] = {
|
||||
@@ -56,7 +56,8 @@ enum {
|
||||
K_SESSION_SETTINGS, K_SESSION_IS_ON, K_SESSION_SET,
|
||||
K_APP_ICON,
|
||||
K_SHOT_TAKE, K_SHOT_RECORD, K_SHOT_STOP, K_SHOT_IS_REC, K_SHOT_PTR, K_SHOT_SET_PTR,
|
||||
K_PW_SCREEN, K_PW_SET_SCREEN, K_PW_SUSP, K_PW_SET_SUSP, K_PW_SUSPEND, K_PW_OFF, K_PW_REBOOT
|
||||
K_PW_SCREEN, K_PW_SET_SCREEN, K_PW_SUSP, K_PW_SET_SUSP, K_PW_SUSPEND, K_PW_OFF, K_PW_REBOOT,
|
||||
K_BAT_READ
|
||||
};
|
||||
typedef struct Env { Inst *inst; int kind; } Env;
|
||||
|
||||
@@ -65,9 +66,10 @@ typedef struct Env { Inst *inst; int kind; } Env;
|
||||
enum { T_APPS, T_WINDOWS, T_LAYOUTS, T_MODULES, T_INSTANCES, T_WALLPAPERS, T_SESSION_SETTINGS, T_ICONS, T_N };
|
||||
typedef struct { uint8_t *data; size_t len; } Blob;
|
||||
static Blob tables[T_N];
|
||||
static int32_t host_ints[8]; /* 0 layout mode, 1 inspector on, 2 current wallpaper, 3 session settings on (bit i: row i),
|
||||
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),
|
||||
4 screenshot state (bit 0 recording, bit 1 pointer in recordings),
|
||||
5 screen-off minutes, 6 suspend minutes (0: never) */
|
||||
5 screen-off minutes, 6 suspend minutes (0: never),
|
||||
7 battery percent (-1: none), 8 battery charge-state, 9 battery seconds left */
|
||||
|
||||
/* ---- requests a guest made of the host (launch, focus, ...) ; drained by the shell after each call ---- */
|
||||
typedef struct { int kind; int32_t n; char *s; } Req;
|
||||
@@ -364,6 +366,16 @@ static wasm_trap_t *host_import(void *env, const wasm_val_vec_t *args, wasm_val_
|
||||
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(h);
|
||||
break;
|
||||
}
|
||||
case K_BAT_READ: {
|
||||
/* battery.status: percent s32 @0, charge-state u8 @4, secs-left u32 @8 */
|
||||
uint8_t st[12] = {0};
|
||||
int32_t state = host_ints[8] >= 0 && host_ints[8] <= 4 ? host_ints[8] : 0;
|
||||
memcpy(st, &host_ints[7], 4);
|
||||
st[4] = (uint8_t)state;
|
||||
memcpy(st + 8, &host_ints[9], 4);
|
||||
if (args->size >= 1) mem_write(in, a0, st, 12);
|
||||
break;
|
||||
}
|
||||
case K_SYSTEM_READ:
|
||||
if (args->size >= 1) mem_write(in, a0, g_system, 64);
|
||||
break;
|
||||
@@ -473,6 +485,7 @@ static int classify_import(const wasm_name_t *m, const wasm_name_t *f) {
|
||||
if (!strcmp(iface, "windows") && !strcmp(fn, "all")) return K_WIN_ALL;
|
||||
if (!strcmp(iface, "windows") && !strcmp(fn, "focus")) return K_WIN_FOCUS_ID;
|
||||
if (!strcmp(iface, "system") && !strcmp(fn, "read")) return K_SYSTEM_READ;
|
||||
if (!strcmp(iface, "battery") && !strcmp(fn, "read")) return K_BAT_READ;
|
||||
if (!strcmp(iface, "icons") && !strcmp(fn, "app-icon")) return K_APP_ICON;
|
||||
if (!strcmp(iface, "session") && !strcmp(fn, "logout")) return K_LOGOUT;
|
||||
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "wallpapers")) return K_WALLPAPERS;
|
||||
@@ -753,7 +766,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 < 8) host_ints[which] = v;
|
||||
if (which >= 0 && which < 12) host_ints[which] = v;
|
||||
}
|
||||
|
||||
/* Pop the next guest request: returns its kind (0 = none). Fetch its arguments with req_int / req_str. */
|
||||
|
||||
@@ -211,6 +211,10 @@ impl chandra::host::plasmoids::Host for State {
|
||||
sh.suspend_min = suspend;
|
||||
}
|
||||
|
||||
fn publish_battery(&mut self, percent: i32, state: u32, secs_left: u32) {
|
||||
self.pl().shared.borrow_mut().battery = (percent, state, secs_left);
|
||||
}
|
||||
|
||||
fn publish_system(&mut self, s: chandra::host::plasmoids::SystemSnapshot) {
|
||||
use plasmoid::ph::chandra::desktop::system::Snapshot;
|
||||
self.pl().shared.borrow_mut().system = Some(Snapshot {
|
||||
|
||||
@@ -79,6 +79,8 @@ pub struct Shared {
|
||||
pub suspend_min: u32,
|
||||
pub inspector_on: bool,
|
||||
pub system: Option<d::system::Snapshot>,
|
||||
/// The battery (`battery.read`): percent (-1: none), charge-state index, seconds left.
|
||||
pub battery: (i32, u32, u32),
|
||||
/// (id, title, app id, focused)
|
||||
pub windows: Vec<(u64, String, String, bool)>,
|
||||
pub requests: VecDeque<Req>,
|
||||
@@ -387,6 +389,21 @@ impl d::icons::Host for PState {
|
||||
}
|
||||
}
|
||||
|
||||
impl d::battery::Host for PState {
|
||||
fn read(&mut self) -> d::battery::Status {
|
||||
use d::battery::ChargeState as C;
|
||||
let (percent, state, secs_left) = self.shared.borrow().battery;
|
||||
let state = match state {
|
||||
1 => C::Discharging,
|
||||
2 => C::Charging,
|
||||
3 => C::Full,
|
||||
4 => C::NotCharging,
|
||||
_ => C::None,
|
||||
};
|
||||
d::battery::Status { percent: if state == C::None { -1 } else { percent }, state, secs_left }
|
||||
}
|
||||
}
|
||||
|
||||
impl d::system::Host for PState {
|
||||
fn read(&mut self) -> d::system::Snapshot {
|
||||
self.shared.borrow().system.clone().unwrap_or(d::system::Snapshot {
|
||||
@@ -860,4 +877,28 @@ mod tests {
|
||||
assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::PowerAction(1))));
|
||||
rt.unload(h);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn battery_module_shows_charge_time_left_and_warns() {
|
||||
let mut rt = runtime();
|
||||
let l = rt.load(&module("battery")).expect("battery loads");
|
||||
assert!(l.imports.contains(&"battery".to_string()));
|
||||
let h = l.handle;
|
||||
let size = Size { w: 104, h: 34 };
|
||||
// No battery: a plug and no text.
|
||||
assert!(!rt.render(h, size).is_empty());
|
||||
assert!(texts(&rt.render(h, size)).is_empty());
|
||||
rt.shared.borrow_mut().battery = (64, 1, 2 * 3600 + 5 * 60);
|
||||
assert_eq!(texts(&rt.render(h, size)), vec!["64% 2:05".to_string()]);
|
||||
assert!(rt.set_config(h, "time", "off"));
|
||||
assert_eq!(texts(&rt.render(h, size)), vec!["64%".to_string()]);
|
||||
// Critical: the warning opens by itself; a click on it closes it.
|
||||
rt.shared.borrow_mut().battery = (7, 1, 600);
|
||||
rt.render(h, size);
|
||||
let ts = texts(&rt.popup(h).expect("warning open").ops);
|
||||
assert!(ts.contains(&"Battery low: 7%".to_string()));
|
||||
assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 5, y: 5 })));
|
||||
assert!(rt.popup(h).is_none());
|
||||
rt.unload(h);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
The battery, as the battery panel module shows it. The host samples it about once a second
|
||||
(on Linux from /sys/class/power_supply, every battery together); the module never reads it
|
||||
itself.
|
||||
@@ -0,0 +1,24 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
|
||||
///|
|
||||
fn wasmImportRead(p0 : Int) = "chandra:desktop/battery@0.1.0" "read"
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int =
|
||||
#|(func (param i32) (result i32) local.get 0 i32.load8_u)
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_free(position : Int) =
|
||||
#|(func (param i32) local.get 0 call $moonbit.decref)
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_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)
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
warnings = "-44"
|
||||
@@ -0,0 +1,28 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "chandra/desktop/interface/chandra/desktop/battery"
|
||||
|
||||
// Values
|
||||
pub fn read() -> Status
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
pub(all) enum ChargeState {
|
||||
NONE
|
||||
DISCHARGING
|
||||
CHARGING
|
||||
FULL
|
||||
NOT_CHARGING
|
||||
}
|
||||
pub fn ChargeState::from(Int32) -> Self
|
||||
pub fn ChargeState::ordinal(Self) -> Int32
|
||||
|
||||
pub(all) struct Status {
|
||||
percent : Int32
|
||||
state : ChargeState
|
||||
secs_left : UInt32
|
||||
}
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1,43 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
///|
|
||||
pub(all) enum ChargeState {
|
||||
NONE; DISCHARGING; CHARGING; FULL; NOT_CHARGING
|
||||
} derive()
|
||||
|
||||
///|
|
||||
pub fn ChargeState::ordinal(self : ChargeState) -> Int {
|
||||
match self {
|
||||
NONE => 0
|
||||
DISCHARGING => 1
|
||||
CHARGING => 2
|
||||
FULL => 3
|
||||
NOT_CHARGING => 4
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn ChargeState::from(self : Int) -> ChargeState {
|
||||
match self {
|
||||
0 => NONE
|
||||
1 => DISCHARGING
|
||||
2 => CHARGING
|
||||
3 => FULL
|
||||
4 => NOT_CHARGING
|
||||
_ => panic()
|
||||
}
|
||||
}
|
||||
///|
|
||||
pub(all) struct Status {
|
||||
percent : Int; state : ChargeState; secs_left : UInt
|
||||
}
|
||||
///|
|
||||
pub fn read() -> Status {
|
||||
|
||||
let return_area = mbt_ffi_malloc(12)
|
||||
wasmImportRead(return_area);
|
||||
let ret = Status::{percent : mbt_ffi_load32((return_area) + 0), state : ChargeState::from(mbt_ffi_load8_u((return_area) + 4)), secs_left : (mbt_ffi_load32((return_area) + 8)).reinterpret_as_uint()}
|
||||
mbt_ffi_free(return_area)
|
||||
return ret
|
||||
|
||||
}
|
||||
|
||||
@@ -39,6 +39,9 @@ fn wasmImportPublishSessionSettings(p0 : Int) = "chandra:host/plasmoids@0.1.0"
|
||||
///|
|
||||
fn wasmImportPublishPower(p0 : Int, p1 : Int) = "chandra:host/plasmoids@0.1.0" "publish-power"
|
||||
|
||||
///|
|
||||
fn wasmImportPublishBattery(p0 : Int, p1 : Int, p2 : Int) = "chandra:host/plasmoids@0.1.0" "publish-battery"
|
||||
|
||||
///|
|
||||
fn wasmImportPublishScreenshot(p0 : Int) = "chandra:host/plasmoids@0.1.0" "publish-screenshot"
|
||||
|
||||
|
||||
@@ -65,6 +65,11 @@ fn wasmImportPublishPower(p0 : Int, p1 : Int) -> Unit {
|
||||
abort("wasm-only host import")
|
||||
}
|
||||
|
||||
///|
|
||||
fn wasmImportPublishBattery(p0 : Int, p1 : Int, p2 : Int) -> Unit {
|
||||
abort("wasm-only host import")
|
||||
}
|
||||
|
||||
///|
|
||||
fn wasmImportPublishScreenshot(p0 : Int) -> Unit {
|
||||
abort("wasm-only host import")
|
||||
|
||||
@@ -23,6 +23,8 @@ pub fn picker_start() -> Bool
|
||||
|
||||
pub fn popup(UInt32) -> PopupSurface?
|
||||
|
||||
pub fn publish_battery(Int32, UInt32, UInt32) -> Unit
|
||||
|
||||
pub fn publish_power(UInt32, UInt32) -> Unit
|
||||
|
||||
pub fn publish_screenshot(UInt32) -> Unit
|
||||
|
||||
@@ -411,6 +411,14 @@ pub fn publish_power(screen_off : UInt, suspend : UInt) -> Unit {
|
||||
|
||||
wasmImportPublishPower((screen_off).reinterpret_as_int(), (suspend).reinterpret_as_int());
|
||||
|
||||
}
|
||||
///|
|
||||
/// The battery: percent (-1: none), state (the battery capability's charge-state, as its index)
|
||||
/// and estimated seconds left (0: unknown).
|
||||
pub fn publish_battery(percent : Int, state : UInt, secs_left : UInt) -> Unit {
|
||||
|
||||
wasmImportPublishBattery(percent, (state).reinterpret_as_int(), (secs_left).reinterpret_as_int());
|
||||
|
||||
}
|
||||
///|
|
||||
/// Screenshot state: bit 0 a recording is running, bit 1 recordings show the pointer.
|
||||
|
||||
@@ -0,0 +1,364 @@
|
||||
///| Render logic for the battery panel module (pure: tokens + a reading in, ops out).
|
||||
///
|
||||
/// The module (components/battery) only adapts the `battery` capability to `Reading` and keeps
|
||||
/// one `BatteryConfig` and one `LowWarning`; everything it draws is decided here.
|
||||
|
||||
///| What the host reported: the `battery` capability's `status`, with the charge state as its
|
||||
/// index (STATE_*).
|
||||
#derive(Eq, Debug)
|
||||
pub(all) struct Reading {
|
||||
/// 0..100, or -1 without a battery.
|
||||
percent : Int
|
||||
state : Int
|
||||
/// Estimated seconds until empty (discharging) or full (charging); 0 unknown.
|
||||
secs_left : Int
|
||||
}
|
||||
|
||||
///| Charge states, in the order of the `charge-state` enum.
|
||||
pub let state_none : Int = 0
|
||||
|
||||
///|
|
||||
pub let state_discharging : Int = 1
|
||||
|
||||
///|
|
||||
pub let state_charging : Int = 2
|
||||
|
||||
///|
|
||||
pub let state_full : Int = 3
|
||||
|
||||
///|
|
||||
pub let state_not_charging : Int = 4
|
||||
|
||||
///| Below this (discharging) the icon turns amber.
|
||||
pub let low_percent : Int = 20
|
||||
|
||||
///| At or below this (discharging) the module turns red and opens its low-battery warning.
|
||||
pub let critical_percent : Int = 10
|
||||
|
||||
///|
|
||||
pub fn info() -> (String, String, Int, Int, Int) {
|
||||
// id, name, preferred w, preferred h, min w
|
||||
("org.chandra.battery", "Battery", 104, 34, 34)
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Reading::has_battery(self : Reading) -> Bool {
|
||||
self.percent >= 0 && self.state != state_none
|
||||
}
|
||||
|
||||
///| 0 normal, 1 low, 2 critical. Only a discharging battery is ever low.
|
||||
pub fn Reading::level(self : Reading) -> Int {
|
||||
if !self.has_battery() || self.state != state_discharging {
|
||||
0
|
||||
} else if self.percent <= critical_percent {
|
||||
2
|
||||
} else if self.percent <= low_percent {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
///| "2:05" (hours:minutes), rounded down to the minute; "" when unknown.
|
||||
pub fn short_time(secs : Int) -> String {
|
||||
if secs <= 0 {
|
||||
return ""
|
||||
}
|
||||
let m = secs / 60
|
||||
let mm = m % 60
|
||||
(m / 60).to_string() + ":" + (if mm < 10 { "0" } else { "" }) + mm.to_string()
|
||||
}
|
||||
|
||||
///| "2 h 05 min" / "35 min"; "" when unknown.
|
||||
pub fn long_time(secs : Int) -> String {
|
||||
if secs <= 0 {
|
||||
return ""
|
||||
}
|
||||
let m = secs / 60
|
||||
if m < 60 {
|
||||
return m.to_string() + " min"
|
||||
}
|
||||
let mm = m % 60
|
||||
(m / 60).to_string() + " h " + (if mm < 10 { "0" } else { "" }) + mm.to_string() + " min"
|
||||
}
|
||||
|
||||
///| One line describing the state: "Discharging, 2 h 05 min left".
|
||||
pub fn Reading::describe(self : Reading) -> String {
|
||||
if !self.has_battery() {
|
||||
return "No battery: on mains power"
|
||||
}
|
||||
let t = long_time(self.secs_left)
|
||||
match self.state {
|
||||
1 => if t == "" { "Discharging" } else { "Discharging, " + t + " left" }
|
||||
2 => if t == "" { "Charging" } else { "Charging, full in " + t }
|
||||
3 => "Fully charged, plugged in"
|
||||
4 => "Plugged in, not charging"
|
||||
_ => ""
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- settings
|
||||
|
||||
///| One item of the right-click "Module settings" menu (the `module-config` record).
|
||||
#derive(Eq, Debug)
|
||||
pub(all) struct ConfigEntry {
|
||||
key : String
|
||||
label : String
|
||||
choices : Array[String]
|
||||
value : String
|
||||
}
|
||||
|
||||
///| What the user picked for the module.
|
||||
pub(all) struct BatteryConfig {
|
||||
mut show_percent : Bool
|
||||
mut show_time : Bool
|
||||
/// Without a battery: draw a plug (true) or nothing.
|
||||
mut plug_without_battery : Bool
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn BatteryConfig::new() -> BatteryConfig {
|
||||
{ show_percent: true, show_time: true, plug_without_battery: true }
|
||||
}
|
||||
|
||||
///|
|
||||
fn on_off(b : Bool) -> String {
|
||||
if b { "on" } else { "off" }
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn BatteryConfig::items(self : BatteryConfig) -> Array[ConfigEntry] {
|
||||
[
|
||||
{ key: "percent", label: "Show percentage", choices: [], value: on_off(self.show_percent) },
|
||||
{ key: "time", label: "Show time remaining", choices: [], value: on_off(self.show_time) },
|
||||
{
|
||||
key: "no-battery",
|
||||
label: "Without a battery",
|
||||
choices: ["Show a plug", "Show nothing"],
|
||||
value: if self.plug_without_battery { "Show a plug" } else { "Show nothing" },
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
///| Apply one setting; true when it changed something. Unknown keys and values are ignored.
|
||||
pub fn BatteryConfig::set(self : BatteryConfig, 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 {
|
||||
"percent" => flag(self.show_percent, fn(b) { self.show_percent = b })
|
||||
"time" => flag(self.show_time, fn(b) { self.show_time = b })
|
||||
"no-battery" =>
|
||||
match value {
|
||||
"Show a plug" if !self.plug_without_battery => { self.plug_without_battery = true; true }
|
||||
"Show nothing" if self.plug_without_battery => { self.plug_without_battery = false; true }
|
||||
_ => false
|
||||
}
|
||||
_ => false
|
||||
}
|
||||
}
|
||||
|
||||
///| The module's settings (one module instance per wasm instance).
|
||||
pub let config : BatteryConfig = BatteryConfig::new()
|
||||
|
||||
// ---------------------------------------------------------------- low-battery warning
|
||||
|
||||
///| Opens the warning once per discharge spell when the charge reaches `critical_percent`; it
|
||||
/// arms again after the machine is plugged in (or charges above it).
|
||||
pub(all) struct LowWarning {
|
||||
mut fired : Bool
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn LowWarning::new() -> LowWarning {
|
||||
{ fired: false }
|
||||
}
|
||||
|
||||
///| Feed a reading; true when the warning should open now.
|
||||
pub fn LowWarning::update(self : LowWarning, r : Reading) -> Bool {
|
||||
if r.level() == 2 {
|
||||
if self.fired {
|
||||
false
|
||||
} else {
|
||||
self.fired = true
|
||||
true
|
||||
}
|
||||
} else {
|
||||
self.fired = false
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- drawing
|
||||
|
||||
///|
|
||||
let red : @types.Color = @ui.color(235, 64, 52, 255)
|
||||
|
||||
///|
|
||||
let amber : @types.Color = @ui.color(240, 165, 30, 255)
|
||||
|
||||
///|
|
||||
let green : @types.Color = @ui.color(70, 185, 90, 255)
|
||||
|
||||
///| Icon width (body plus the terminal nub).
|
||||
let icon_w : Int = 24
|
||||
|
||||
///| A horizontal battery at (x, cy): outline, nub, fill for the charge, and a bolt when charging.
|
||||
fn battery_icon(x : Int, cy : Int, r : Reading, fg : @types.Color, fill : @types.Color) -> Array[@types.DrawOp] {
|
||||
let bw = 21
|
||||
let bh = 12
|
||||
let y = cy - bh / 2
|
||||
let ops = [
|
||||
@ui.stroke_rect(@ui.rect(x, y, bw, bh), fg, width=1, radius=2),
|
||||
@ui.fill_rect(@ui.rect(x + bw, cy - 3, 3, 6), fg, radius=1),
|
||||
]
|
||||
let inner = bw - 4
|
||||
let pct = if r.percent < 0 { 0 } else if r.percent > 100 { 100 } else { r.percent }
|
||||
let fw = if pct == 0 { 0 } else if inner * pct / 100 < 1 { 1 } else { inner * pct / 100 }
|
||||
if fw > 0 {
|
||||
ops.push(@ui.fill_rect(@ui.rect(x + 2, y + 2, fw, bh - 4), fill, radius=1))
|
||||
}
|
||||
if r.state == state_charging {
|
||||
// A bolt over the middle, outlined in the panel colour so it shows on the fill.
|
||||
let mx = x + bw / 2
|
||||
ops.push(@ui.line(mx + 2, y - 1, mx - 3, cy + 1, fg, width=2))
|
||||
ops.push(@ui.line(mx - 3, cy + 1, mx + 3, cy - 1, fg, width=2))
|
||||
ops.push(@ui.line(mx + 3, cy - 1, mx - 2, y + bh + 1, fg, width=2))
|
||||
}
|
||||
ops
|
||||
}
|
||||
|
||||
///| A mains plug at (x, cy): two prongs, the head, and the cable.
|
||||
fn plug_icon(x : Int, cy : Int, fg : @types.Color) -> Array[@types.DrawOp] {
|
||||
[
|
||||
@ui.line(x + 6, cy - 8, x + 6, cy - 4, fg, width=2),
|
||||
@ui.line(x + 12, cy - 8, x + 12, cy - 4, fg, width=2),
|
||||
@ui.fill_rect(@ui.rect(x + 3, cy - 4, 13, 7), fg, radius=2),
|
||||
@ui.line(x + 9, cy + 3, x + 9, cy + 8, fg, width=2),
|
||||
]
|
||||
}
|
||||
|
||||
///| The text after the icon: "73%", "73% 2:05", "2:05" or "".
|
||||
pub fn panel_text(r : Reading, c : BatteryConfig) -> String {
|
||||
if !r.has_battery() {
|
||||
return ""
|
||||
}
|
||||
let parts : Array[String] = []
|
||||
if c.show_percent {
|
||||
parts.push(r.percent.to_string() + "%")
|
||||
}
|
||||
if c.show_time && (r.state == state_discharging || r.state == state_charging) {
|
||||
let t = short_time(r.secs_left)
|
||||
if t != "" {
|
||||
parts.push(t)
|
||||
}
|
||||
}
|
||||
parts.join(" ")
|
||||
}
|
||||
|
||||
///| The panel button. Critical: a red chip with white content; open popup: the accent chip.
|
||||
pub fn render(
|
||||
size : @types.Size,
|
||||
t : @theme.Tokens,
|
||||
r : Reading,
|
||||
c : BatteryConfig,
|
||||
open? : Bool = false,
|
||||
) -> Array[@types.DrawOp] {
|
||||
let w = size.w.reinterpret_as_int()
|
||||
let h = size.h.reinterpret_as_int()
|
||||
let fs = t.font_size.reinterpret_as_int() - 2
|
||||
let radius = t.radius.reinterpret_as_int()
|
||||
let p = t.palette
|
||||
let ops : Array[@types.DrawOp] = []
|
||||
if !r.has_battery() && !c.plug_without_battery {
|
||||
return ops
|
||||
}
|
||||
let level = r.level()
|
||||
let fg = if level == 2 {
|
||||
@ui.color(255, 255, 255, 255)
|
||||
} else if open {
|
||||
p.accent_foreground
|
||||
} else {
|
||||
p.foreground
|
||||
}
|
||||
if level == 2 {
|
||||
ops.push(@ui.fill_rect(@ui.rect(0, 0, w, h), red, radius~))
|
||||
} else if open {
|
||||
ops.push(@ui.fill_rect(@ui.rect(0, 0, w, h), p.accent, radius~))
|
||||
}
|
||||
let cy = h / 2
|
||||
if !r.has_battery() {
|
||||
ops.append(plug_icon(w / 2 - 9, cy, fg))
|
||||
return ops
|
||||
}
|
||||
let fill = if level == 2 {
|
||||
fg
|
||||
} else if level == 1 {
|
||||
amber
|
||||
} else if r.state == state_charging || r.state == state_full {
|
||||
green
|
||||
} else {
|
||||
fg
|
||||
}
|
||||
// Text only when it fits; the icon and text are centred together.
|
||||
let txt = panel_text(r, c)
|
||||
let tw = if txt == "" { 0 } else { @ui.text_width(txt, fs) }
|
||||
let show_txt = tw > 0 && icon_w + 6 + tw + 8 <= w
|
||||
let total = if show_txt { icon_w + 6 + tw } else { icon_w }
|
||||
let x0 = (w - total) / 2
|
||||
ops.append(battery_icon(x0, cy, r, fg, fill))
|
||||
if show_txt {
|
||||
ops.push(@ui.text(x0 + icon_w + 6, cy, txt, fs, fg))
|
||||
}
|
||||
ops
|
||||
}
|
||||
|
||||
///| Popup width; rows are `popup_row_h` tall.
|
||||
pub let popup_w : Int = 260
|
||||
|
||||
///|
|
||||
let popup_row_h : Int = 24
|
||||
|
||||
///| The details popup (a click on the module, or the low-battery warning): the charge in large
|
||||
/// type, the state with time left, and on a critical battery a line asking to plug in.
|
||||
pub fn render_popup(t : @theme.Tokens, r : Reading, warning? : Bool = false) -> (Int, Int, Array[@types.DrawOp]) {
|
||||
let fs = t.font_size.reinterpret_as_int()
|
||||
let radius = t.radius.reinterpret_as_int()
|
||||
let p = t.palette
|
||||
let lines : Array[(String, Int, @types.Color, Bool)] = [] // text, size, colour, bold
|
||||
if !r.has_battery() {
|
||||
lines.push(("Power", fs, p.foreground, true))
|
||||
lines.push((r.describe(), fs - 2, p.foreground_muted, false))
|
||||
} else {
|
||||
let critical = r.level() == 2
|
||||
let head = if warning && critical { "Battery low: " } else { "Battery " }
|
||||
lines.push(
|
||||
(
|
||||
head + r.percent.to_string() + "%",
|
||||
fs + 2,
|
||||
if critical { red } else { p.foreground },
|
||||
true,
|
||||
),
|
||||
)
|
||||
lines.push((r.describe(), fs - 2, p.foreground_muted, false))
|
||||
if critical {
|
||||
lines.push(("Plug in the computer to keep working.", fs - 2, p.foreground, false))
|
||||
}
|
||||
}
|
||||
let m = 10
|
||||
let h = m * 2 + lines.length() * popup_row_h
|
||||
let w = popup_w
|
||||
let ops = [
|
||||
@ui.fill_rect(@ui.rect(0, 0, w, h), p.surface_popup, radius~),
|
||||
@ui.stroke_rect(@ui.rect(0, 0, w, h), if warning { red } else { p.border }, width=1, radius~),
|
||||
]
|
||||
for i, l in lines {
|
||||
let (s, size, col, bold) = l
|
||||
ops.push(@ui.text(m + 4, m + i * popup_row_h + popup_row_h / 2, s, size, col, bold~))
|
||||
}
|
||||
(w, h, ops)
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
///|
|
||||
fn test_tokens() -> @theme.Tokens {
|
||||
let c = @ui.color(10, 20, 30, 255)
|
||||
{
|
||||
name: "t",
|
||||
palette: {
|
||||
desktop_top: c,
|
||||
desktop_bottom: c,
|
||||
surface: c,
|
||||
surface_hover: c,
|
||||
surface_popup: c,
|
||||
foreground: c,
|
||||
foreground_muted: c,
|
||||
accent: c,
|
||||
accent_foreground: c,
|
||||
border: c,
|
||||
},
|
||||
font_size: 14,
|
||||
radius: 6,
|
||||
spacing: 6,
|
||||
panel_height: 44,
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn texts(ops : Array[@types.DrawOp]) -> Array[String] {
|
||||
let out : Array[String] = []
|
||||
for op in ops {
|
||||
if op is Text(t) {
|
||||
out.push(t.text)
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
fn has_red(ops : Array[@types.DrawOp]) -> Bool {
|
||||
ops.iter().any(op => op is FillRect(f) && f.color.r == b'\xEB' && f.color.g == b'\x40')
|
||||
}
|
||||
|
||||
///|
|
||||
let size : @types.Size = { w: 104, h: 34 }
|
||||
|
||||
///|
|
||||
test "time formats" {
|
||||
assert_eq(short_time(0), "")
|
||||
assert_eq(short_time(59), "0:00")
|
||||
assert_eq(short_time(7500), "2:05")
|
||||
assert_eq(long_time(35 * 60 + 20), "35 min")
|
||||
assert_eq(long_time(7500), "2 h 05 min")
|
||||
assert_eq(long_time(-1), "")
|
||||
}
|
||||
|
||||
///|
|
||||
test "panel shows percent and time, each switchable" {
|
||||
let c = BatteryConfig::new()
|
||||
let r = { percent: 73, state: state_discharging, secs_left: 7500 }
|
||||
assert_eq(texts(render(size, test_tokens(), r, c)), ["73% 2:05"])
|
||||
assert_true(c.set("time", "off"))
|
||||
assert_false(c.set("time", "off"))
|
||||
assert_eq(texts(render(size, test_tokens(), r, c)), ["73%"])
|
||||
assert_true(c.set("percent", "off"))
|
||||
assert_eq(texts(render(size, test_tokens(), r, c)), [])
|
||||
assert_true(c.set("time", "on"))
|
||||
assert_eq(texts(render(size, test_tokens(), r, c)), ["2:05"])
|
||||
assert_eq(c.items().map(i => i.value), ["off", "on", "Show a plug"])
|
||||
assert_false(c.set("bogus", "on"))
|
||||
// Too narrow for text: icon only.
|
||||
c.show_percent = true
|
||||
assert_eq(texts(render({ w: 34, h: 34 }, test_tokens(), r, c)), [])
|
||||
}
|
||||
|
||||
///|
|
||||
test "charging shows time to full; full and unknown times show percent only" {
|
||||
let c = BatteryConfig::new()
|
||||
let charging = { percent: 40, state: state_charging, secs_left: 3600 }
|
||||
assert_eq(texts(render(size, test_tokens(), charging, c)), ["40% 1:00"])
|
||||
assert_eq(charging.describe(), "Charging, full in 1 h 00 min")
|
||||
let full = { percent: 100, state: state_full, secs_left: 0 }
|
||||
assert_eq(texts(render(size, test_tokens(), full, c)), ["100%"])
|
||||
assert_eq(full.describe(), "Fully charged, plugged in")
|
||||
let unknown = { percent: 55, state: state_discharging, secs_left: 0 }
|
||||
assert_eq(texts(render(size, test_tokens(), unknown, c)), ["55%"])
|
||||
assert_eq(unknown.describe(), "Discharging")
|
||||
assert_eq({ percent: 80, state: state_not_charging, secs_left: 0 }.describe(), "Plugged in, not charging")
|
||||
}
|
||||
|
||||
///|
|
||||
test "low and critical levels; charging is never low" {
|
||||
assert_eq({ percent: 21, state: state_discharging, secs_left: 0 }.level(), 0)
|
||||
assert_eq({ percent: 20, state: state_discharging, secs_left: 0 }.level(), 1)
|
||||
assert_eq({ percent: 10, state: state_discharging, secs_left: 0 }.level(), 2)
|
||||
assert_eq({ percent: 5, state: state_charging, secs_left: 0 }.level(), 0)
|
||||
let c = BatteryConfig::new()
|
||||
let crit = { percent: 8, state: state_discharging, secs_left: 600 }
|
||||
assert_true(has_red(render(size, test_tokens(), crit, c)))
|
||||
assert_false(has_red(render(size, test_tokens(), { ..crit, percent: 50 }, c)))
|
||||
let (_, _, ops) = render_popup(test_tokens(), crit, warning=true)
|
||||
assert_eq(texts(ops), ["Battery low: 8%", "Discharging, 10 min left", "Plug in the computer to keep working."])
|
||||
}
|
||||
|
||||
///|
|
||||
test "the low-battery warning opens once per discharge spell" {
|
||||
let lw = LowWarning::new()
|
||||
let r = { percent: 11, state: state_discharging, secs_left: 0 }
|
||||
assert_false(lw.update(r))
|
||||
assert_true(lw.update({ ..r, percent: 10 }))
|
||||
assert_false(lw.update({ ..r, percent: 9 }))
|
||||
assert_false(lw.update({ ..r, percent: 9, state: state_charging }))
|
||||
assert_true(lw.update({ ..r, percent: 9 }))
|
||||
}
|
||||
|
||||
///|
|
||||
test "without a battery: a plug, or nothing" {
|
||||
let c = BatteryConfig::new()
|
||||
let none = { percent: -1, state: state_none, secs_left: 0 }
|
||||
let ops = render(size, test_tokens(), none, c)
|
||||
assert_true(ops.length() > 0)
|
||||
assert_eq(texts(ops), [])
|
||||
assert_true(c.set("no-battery", "Show nothing"))
|
||||
assert_eq(render(size, test_tokens(), none, c).length(), 0)
|
||||
assert_eq(none.describe(), "No battery: on mains power")
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import {
|
||||
"chandra/desktop/interface/chandra/desktop/types" @types,
|
||||
"chandra/desktop/interface/chandra/desktop/theme" @theme,
|
||||
"chandra/desktop/lib/ui" @ui,
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "chandra/desktop/lib/battery"
|
||||
|
||||
import {
|
||||
"chandra/desktop/interface/chandra/desktop/theme",
|
||||
"chandra/desktop/interface/chandra/desktop/types",
|
||||
"moonbitlang/core/debug",
|
||||
}
|
||||
|
||||
// Values
|
||||
pub let config : BatteryConfig
|
||||
|
||||
pub let critical_percent : Int32
|
||||
|
||||
pub fn info() -> (String, String, Int32, Int32, Int32)
|
||||
|
||||
pub fn long_time(Int32) -> String
|
||||
|
||||
pub let low_percent : Int32
|
||||
|
||||
pub fn panel_text(Reading, BatteryConfig) -> String
|
||||
|
||||
pub let popup_w : Int32
|
||||
|
||||
pub fn render(@types.Size, @theme.Tokens, Reading, BatteryConfig, open? : Bool) -> Array[@types.DrawOp]
|
||||
|
||||
pub fn render_popup(@theme.Tokens, Reading, warning? : Bool) -> (Int32, Int32, Array[@types.DrawOp])
|
||||
|
||||
pub fn short_time(Int32) -> String
|
||||
|
||||
pub let state_charging : Int32
|
||||
|
||||
pub let state_discharging : Int32
|
||||
|
||||
pub let state_full : Int32
|
||||
|
||||
pub let state_none : Int32
|
||||
|
||||
pub let state_not_charging : Int32
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
pub(all) struct BatteryConfig {
|
||||
mut show_percent : Bool
|
||||
mut show_time : Bool
|
||||
mut plug_without_battery : Bool
|
||||
}
|
||||
pub fn BatteryConfig::items(Self) -> Array[ConfigEntry]
|
||||
pub fn BatteryConfig::new() -> Self
|
||||
pub fn BatteryConfig::set(Self, String, String) -> Bool
|
||||
|
||||
#derive(Eq, @debug.Debug)
|
||||
pub(all) struct ConfigEntry {
|
||||
key : String
|
||||
label : String
|
||||
choices : Array[String]
|
||||
value : String
|
||||
}
|
||||
|
||||
pub(all) struct LowWarning {
|
||||
mut fired : Bool
|
||||
}
|
||||
pub fn LowWarning::new() -> Self
|
||||
pub fn LowWarning::update(Self, Reading) -> Bool
|
||||
|
||||
#derive(Eq, @debug.Debug)
|
||||
pub(all) struct Reading {
|
||||
percent : Int32
|
||||
state : Int32
|
||||
secs_left : Int32
|
||||
}
|
||||
pub fn Reading::describe(Self) -> String
|
||||
pub fn Reading::has_battery(Self) -> Bool
|
||||
pub fn Reading::level(Self) -> Int32
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -11,3 +11,4 @@ inspector inspector-widget
|
||||
logout logout-widget
|
||||
session-settings session-settings-widget
|
||||
screenshot screenshot-widget
|
||||
battery battery-widget
|
||||
@@ -415,6 +415,13 @@ fn plasmoid_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] {
|
||||
none
|
||||
},
|
||||
),
|
||||
(
|
||||
"publish-battery",
|
||||
a => {
|
||||
@wasm.publish_battery(a[0].to_int(), a[1].to_int(), a[2].to_int())
|
||||
none
|
||||
},
|
||||
),
|
||||
(
|
||||
"publish-screenshot",
|
||||
a => {
|
||||
|
||||
@@ -183,3 +183,26 @@ interface power {
|
||||
power-off: func();
|
||||
reboot: func();
|
||||
}
|
||||
|
||||
/// The battery, as the battery panel module shows it. The host samples it about once a second
|
||||
/// (on Linux from /sys/class/power_supply, every battery together); the module never reads it
|
||||
/// itself.
|
||||
interface battery {
|
||||
enum charge-state {
|
||||
/// No battery: a desktop on mains power.
|
||||
none,
|
||||
discharging,
|
||||
charging,
|
||||
full,
|
||||
/// On mains power but not charging (a charge limit, or the battery is too warm).
|
||||
not-charging,
|
||||
}
|
||||
record status {
|
||||
/// 0..100, or -1 without a battery.
|
||||
percent: s32,
|
||||
state: charge-state,
|
||||
/// Estimated seconds until empty while discharging, until full while charging; 0 unknown.
|
||||
secs-left: u32,
|
||||
}
|
||||
read: func() -> status;
|
||||
}
|
||||
@@ -64,6 +64,9 @@ interface plasmoids {
|
||||
publish-session-settings: func(on: u32);
|
||||
/// The power timeouts, in minutes (0: never).
|
||||
publish-power: func(screen-off: u32, suspend: u32);
|
||||
/// The battery: percent (-1: none), state (the battery capability's charge-state, as its index)
|
||||
/// and estimated seconds left (0: unknown).
|
||||
publish-battery: func(percent: s32, state: u32, secs-left: u32);
|
||||
/// Screenshot state: bit 0 a recording is running, bit 1 recordings show the pointer.
|
||||
publish-screenshot: func(state: u32);
|
||||
|
||||
|
||||
@@ -81,6 +81,7 @@ world plasmoid-host {
|
||||
import icons;
|
||||
import screenshot;
|
||||
import power;
|
||||
import battery;
|
||||
export plasmoid;
|
||||
}
|
||||
|
||||
@@ -107,3 +108,11 @@ world screenshot-widget {
|
||||
include widget;
|
||||
import screenshot;
|
||||
}
|
||||
|
||||
/// Battery charge, charging state and time left in the panel; its right-click settings choose what
|
||||
/// shows.
|
||||
world battery-widget {
|
||||
include widget;
|
||||
import battery;
|
||||
export module-config;
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
Battery charge, charging state and time left in the panel; its right-click settings choose what
|
||||
shows.
|
||||
@@ -0,0 +1,2 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
warnings = "-44"
|
||||
@@ -0,0 +1,12 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "chandra/desktop/world/battery-widget"
|
||||
|
||||
// Values
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
Reference in new issue
Block a user