diff --git a/README.md b/README.md index 3daa415..f2a95c0 100644 --- a/README.md +++ b/README.md @@ -180,9 +180,10 @@ a recording shortcut again to stop. **Desktop modules**: a module can fill the desktop itself, behind the windows, instead of sitting in the panel. Choose one in Settings > Desktop (*Wallpaper only*, *Clock card*, or any installed -desktop module); right-click the empty desktop for its settings. Two ship: **Icon Desktop** (app -icons you click to launch and drag to arrange, positions remembered) and **Live Starfield** (an -animated starfield you steer with the pointer). See +desktop module); right-click the empty desktop for its settings. Three ship: **Icon Desktop** (app +icons you click to launch and drag to arrange, positions remembered), **Live Starfield** (an +animated starfield you steer with the pointer) and **Gamerig Library** (gamerig's game library +for a streaming rig, [docs/gamerig-library.md](docs/gamerig-library.md)). See [docs/desktop-modules.md](docs/desktop-modules.md) to write one. Right-click any module for **Module settings** (its own options, such as the clock's format, diff --git a/components/gamerig-library/gen/ffi.mbt b/components/gamerig-library/gen/ffi.mbt new file mode 100644 index 0000000..99be3ee --- /dev/null +++ b/components/gamerig-library/gen/ffi.mbt @@ -0,0 +1,118 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + +///| +pub fn mbt_ffi_cabi_realloc( +src_offset : Int, +src_size : Int, +_dst_alignment : Int, +dst_size : Int, +) -> Int { + // malloc + if src_offset == 0 && src_size == 0 { + return mbt_ffi_malloc(dst_size) + } + // free + if dst_size == 0 { + mbt_ffi_free(src_offset) + return 0 + } + // realloc + let dst = mbt_ffi_malloc(dst_size) + mbt_ffi_copy(dst, src_offset, if src_size < dst_size { src_size } else { dst_size }) + mbt_ffi_free(src_offset) + dst +} + +///| +extern "wasm" fn mbt_ffi_copy(dest : Int, src : Int, len : Int) = +#|(func (param i32) (param i32) (param i32) local.get 0 local.get 1 local.get 2 memory.copy) + +///| +extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = +#|(func (param i32) (result i32) (local i32) +#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc +#| local.tee 1 i32.const 0 call $moonbit.init_array8 +#| local.get 1) + +///| +extern "wasm" fn mbt_ffi_free(position : Int) = +#|(func (param i32) local.get 0 call $moonbit.decref) + +///| +#doc(hidden) +pub fn wasmExportInfo() -> Int { + @plasmoid.wasmExportInfo() +} + +///| +#doc(hidden) +pub fn wasmExportTick(p0 : Int) -> Int { + @desktop-module.wasmExportTick(p0) +} + +///| +#doc(hidden) +pub fn wasmExportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { + @module-config.wasmExportSetConfig(p0, p1, p2, p3) +} + +///| +#doc(hidden) +pub fn wasmExportBackdrop() -> Int { + @desktop-module.wasmExportBackdrop() +} + +///| +#doc(hidden) +pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit { + @plasmoid.wasmExportRenderPostReturn(p0) +} + +///| +#doc(hidden) +pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit { + @plasmoid.wasmExportPopupPostReturn(p0) +} + +///| +#doc(hidden) +pub fn wasmExportConfigItemsPostReturn(p0 : Int) -> Unit { + @module-config.wasmExportConfigItemsPostReturn(p0) +} + +///| +#doc(hidden) +pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { + @plasmoid.wasmExportOnEvent(p0, p1, p2, p3) +} + +///| +#doc(hidden) +pub fn wasmExportPopup() -> Int { + @plasmoid.wasmExportPopup() +} + +///| +#doc(hidden) +pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit { + @plasmoid.wasmExportInfoPostReturn(p0) +} + +///| +#doc(hidden) +pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int { + @plasmoid.wasmExportRender(p0, p1) +} + +///| +#doc(hidden) +pub fn wasmExportOnScroll(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { + @desktop-module.wasmExportOnScroll(p0, p1, p2, p3) +} + +///| +#doc(hidden) +pub fn wasmExportConfigItems() -> Int { + @module-config.wasmExportConfigItems() +} + diff --git a/components/gamerig-library/gen/interface/chandra/desktop/desktop-module/README.md b/components/gamerig-library/gen/interface/chandra/desktop/desktop-module/README.md new file mode 100644 index 0000000..f8e5e0e --- /dev/null +++ b/components/gamerig-library/gen/interface/chandra/desktop/desktop-module/README.md @@ -0,0 +1,19 @@ +Optional export that turns a module into a desktop module: instead of a box in the panel it +owns the desktop itself, the whole output behind the windows (see docs/desktop-modules.md). + +A desktop module is still a plasmoid (it exports `plasmoid` as well, and may export +`module-config` and import any capability a panel module can), so the same sandbox, draw ops +and capability grants apply. What changes is how the shell drives it: + +- `plasmoid.render` is called with the output's full size (and again with the new size when + the output is resized), in desktop coordinates: (0, 0) is the output's top-left corner. + The panel and windows are drawn on top; the module draws the whole area. +- `plasmoid.on-event` gets the pointer (move, press, release, leave) only where no window, + panel, popup or menu covers the desktop, and keys only while the desktop has keyboard focus + (after a click on it, until a window is focused: it then gets `focus-lost`). A right-click + on the empty desktop always opens the shell's desktop menu (module settings, system + settings), never reaches the module. +- `plasmoid.popup` and `plasmoid.info`'s size fields are not used. +- Hidden settings (a `module-config` item with an empty label) are saved by the shell in + state.edn whenever their value changes after an event, and handed back at the next load: + that is how a desktop module keeps state such as icon positions. \ No newline at end of file diff --git a/components/gamerig-library/gen/interface/chandra/desktop/desktop-module/ffi.mbt b/components/gamerig-library/gen/interface/chandra/desktop/desktop-module/ffi.mbt new file mode 100644 index 0000000..c4e93b1 --- /dev/null +++ b/components/gamerig-library/gen/interface/chandra/desktop/desktop-module/ffi.mbt @@ -0,0 +1,32 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + +///| +#doc(hidden) +pub fn wasmExportBackdrop() -> Int { + + let (result) : (WallpaperMode) = backdrop(); + let ret = result.ordinal() + return ret + +} + +///| +#doc(hidden) +pub fn wasmExportOnScroll(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { + + let (result) : (Bool) = on_scroll(@types.Point::{x : p0, y : p1}, p2, p3); + let ret = (if result { 1 } else { 0 }) + return ret + +} + +///| +#doc(hidden) +pub fn wasmExportTick(p0 : Int) -> Int { + + let (result) : (UInt) = tick((p0).reinterpret_as_uint()); + let ret = (result).reinterpret_as_int() + return ret + +} + diff --git a/components/gamerig-library/gen/interface/chandra/desktop/desktop-module/moon.pkg b/components/gamerig-library/gen/interface/chandra/desktop/desktop-module/moon.pkg new file mode 100644 index 0000000..535debf --- /dev/null +++ b/components/gamerig-library/gen/interface/chandra/desktop/desktop-module/moon.pkg @@ -0,0 +1,6 @@ +import { + "chandra/desktop/interface/chandra/desktop/types" @types, + "chandra/desktop/lib/gamelib" @logic, +} + +warnings = "-44" diff --git a/components/gamerig-library/gen/interface/chandra/desktop/desktop-module/stub.mbt b/components/gamerig-library/gen/interface/chandra/desktop/desktop-module/stub.mbt new file mode 100644 index 0000000..67858d7 --- /dev/null +++ b/components/gamerig-library/gen/interface/chandra/desktop/desktop-module/stub.mbt @@ -0,0 +1,17 @@ +///| The library replaces the wallpaper (gamerig's own background) and only redraws on events and +/// when the shell has new data from the daemon: it never animates. + +///| +pub fn backdrop() -> WallpaperMode { + REPLACE_WALLPAPER +} + +///| +pub fn on_scroll(_at : @types.Point, _dx : Int, dy : Int) -> Bool { + @logic.state.scroll_by(dy) +} + +///| +pub fn tick(_now_ms : UInt) -> UInt { + 0 +} diff --git a/components/gamerig-library/gen/interface/chandra/desktop/desktop-module/top.mbt b/components/gamerig-library/gen/interface/chandra/desktop/desktop-module/top.mbt new file mode 100644 index 0000000..4da9629 --- /dev/null +++ b/components/gamerig-library/gen/interface/chandra/desktop/desktop-module/top.mbt @@ -0,0 +1,41 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! +///| +/// What happens to the wallpaper under the module. +pub(all) enum WallpaperMode { + OVER_WALLPAPER; REPLACE_WALLPAPER +} derive() + +///| +pub fn WallpaperMode::ordinal(self : WallpaperMode) -> Int { + match self { + OVER_WALLPAPER => 0 + REPLACE_WALLPAPER => 1 + } +} + +///| +pub fn WallpaperMode::from(self : Int) -> WallpaperMode { + match self { + 0 => OVER_WALLPAPER + 1 => REPLACE_WALLPAPER + _ => panic() + } +} +///| +/// Read once, right after loading. +declare pub fn backdrop() -> WallpaperMode +///| +/// Wheel or touchpad scroll over the empty desktop at `at`: `dx` / `dy` in pixels (positive: +/// right / down; one wheel notch is about 10). True when the module wants a redraw. +declare pub fn on_scroll(at : @types.Point, dx : Int, dy : Int) -> Bool +///| +/// The animation clock. `now-ms` counts milliseconds from when the module was loaded. It is +/// called once after loading, after every event the module handled, and again when the delay it +/// last returned has passed. The module is redrawn after each timed call (an animation frame) +/// and after events that returned true; a call that follows an event only reschedules the +/// clock and does not redraw by itself. Return how many ms until the +/// next frame (16 for about 60 frames a second, 33 for 30), or 0 to sleep until the next event: +/// an idle desktop module costs nothing, so return 0 whenever nothing moves. Frames are paused +/// (no calls) while a window covers the whole desktop. +declare pub fn tick(now_ms : UInt) -> UInt + diff --git a/components/gamerig-library/gen/interface/chandra/desktop/module-config/README.md b/components/gamerig-library/gen/interface/chandra/desktop/module-config/README.md new file mode 100644 index 0000000..0123c3f --- /dev/null +++ b/components/gamerig-library/gen/interface/chandra/desktop/module-config/README.md @@ -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. \ No newline at end of file diff --git a/components/gamerig-library/gen/interface/chandra/desktop/module-config/ffi.mbt b/components/gamerig-library/gen/interface/chandra/desktop/module-config/ffi.mbt new file mode 100644 index 0000000..ddc49fe --- /dev/null +++ b/components/gamerig-library/gen/interface/chandra/desktop/module-config/ffi.mbt @@ -0,0 +1,114 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + +///| +#doc(hidden) +pub fn wasmExportConfigItems() -> Int { + + let (result) : (Array[ConfigItem]) = config_items(); + let return_area = mbt_ffi_malloc(8) + + let address3 = mbt_ffi_malloc((result).length() * 32); + for index4 = 0; index4 < (result).length(); index4 = index4 + 1 { + let iter_elem : ConfigItem = (result)[(index4)] + let iter_base = address3 + (index4 * 32); + + let ptr = mbt_ffi_str2ptr((iter_elem).key) + mbt_ffi_store32((iter_base) + 4, (iter_elem).key.length()) + mbt_ffi_store32((iter_base) + 0, ptr) + + let ptr0 = mbt_ffi_str2ptr((iter_elem).label) + mbt_ffi_store32((iter_base) + 12, (iter_elem).label.length()) + mbt_ffi_store32((iter_base) + 8, ptr0) + + let address = mbt_ffi_malloc(((iter_elem).choices).length() * 8); + for index = 0; index < ((iter_elem).choices).length(); index = index + 1 { + let iter_elem : String = ((iter_elem).choices)[(index)] + let iter_base = address + (index * 8); + + let ptr1 = mbt_ffi_str2ptr(iter_elem) + mbt_ffi_store32((iter_base) + 4, iter_elem.length()) + mbt_ffi_store32((iter_base) + 0, ptr1) + + } + mbt_ffi_store32((iter_base) + 20, ((iter_elem).choices).length()) + mbt_ffi_store32((iter_base) + 16, address) + + let ptr2 = mbt_ffi_str2ptr((iter_elem).value) + mbt_ffi_store32((iter_base) + 28, (iter_elem).value.length()) + mbt_ffi_store32((iter_base) + 24, ptr2) + + } + mbt_ffi_store32((return_area) + 4, (result).length()) + mbt_ffi_store32((return_area) + 0, address3) + let ret = return_area + return ret + +} + +///| +#doc(hidden) +pub fn wasmExportConfigItemsPostReturn(p0 : Int) -> Unit { + + for index0 = 0; index0 < (mbt_ffi_load32((p0) + 4)); index0 = index0 + 1 { + let iter_base = (mbt_ffi_load32((p0) + 0)) + (index0 * 32) + mbt_ffi_free(mbt_ffi_load32((iter_base) + 0)) + mbt_ffi_free(mbt_ffi_load32((iter_base) + 8)) + + for index = 0; index < (mbt_ffi_load32((iter_base) + 20)); index = index + 1 { + let iter_base = (mbt_ffi_load32((iter_base) + 16)) + (index * 8) + mbt_ffi_free(mbt_ffi_load32((iter_base) + 0)) + + } + mbt_ffi_free(mbt_ffi_load32((iter_base) + 16)) + mbt_ffi_free(mbt_ffi_load32((iter_base) + 24)) + + } + mbt_ffi_free(mbt_ffi_load32((p0) + 0)) + +} + +///| +#doc(hidden) +pub fn wasmExportSetConfig(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { + + let result = mbt_ffi_ptr2str(p0, p1) + + let result0 = mbt_ffi_ptr2str(p2, p3) + + let (result1) : (Bool) = set_config(result, result0); + let ret = (if result1 { 1 } else { 0 }) + return ret + +} + +///| +#owned(str) +extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = +#|(func (param i32) (result i32) local.get 0) + +///| +extern "wasm" fn mbt_ffi_free(position : Int) = +#|(func (param i32) local.get 0 call $moonbit.decref) + +///| +extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = +#|(func (param i32) (param i32) (result i32) +#| local.get 0 +#| local.get 1 call $moonbit.init_array16 +#| local.get 0) + +///| +extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = +#|(func (param i32) (result i32) (local i32) +#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc +#| local.tee 1 i32.const 0 call $moonbit.init_array8 +#| local.get 1) + +///| +extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) = +#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store) + +///| +extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = +#|(func (param i32) (result i32) local.get 0 i32.load) + diff --git a/components/gamerig-library/gen/interface/chandra/desktop/module-config/moon.pkg b/components/gamerig-library/gen/interface/chandra/desktop/module-config/moon.pkg new file mode 100644 index 0000000..fab9e5d --- /dev/null +++ b/components/gamerig-library/gen/interface/chandra/desktop/module-config/moon.pkg @@ -0,0 +1,5 @@ +import { + "chandra/desktop/lib/icondesk" @logic, +} + +warnings = "-44" diff --git a/components/gamerig-library/gen/interface/chandra/desktop/module-config/stub.mbt b/components/gamerig-library/gen/interface/chandra/desktop/module-config/stub.mbt new file mode 100644 index 0000000..48d3d55 --- /dev/null +++ b/components/gamerig-library/gen/interface/chandra/desktop/module-config/stub.mbt @@ -0,0 +1,11 @@ +///| The library's right-click settings (colours: gamerig dark or light, or follow the desktop). + +///| +pub fn config_items() -> Array[ConfigItem] { + @logic.state.config_items().map(e => { key: e.key, label: e.label, choices: e.choices, value: e.value }) +} + +///| +pub fn set_config(key : String, value : String) -> Bool { + @logic.state.set_config(key, value) +} diff --git a/components/gamerig-library/gen/interface/chandra/desktop/module-config/top.mbt b/components/gamerig-library/gen/interface/chandra/desktop/module-config/top.mbt new file mode 100644 index 0000000..4cea3df --- /dev/null +++ b/components/gamerig-library/gen/interface/chandra/desktop/module-config/top.mbt @@ -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 + diff --git a/components/gamerig-library/gen/interface/chandra/desktop/plasmoid/README.md b/components/gamerig-library/gen/interface/chandra/desktop/plasmoid/README.md new file mode 100644 index 0000000..53ecf69 --- /dev/null +++ b/components/gamerig-library/gen/interface/chandra/desktop/plasmoid/README.md @@ -0,0 +1 @@ +The widget (plasmoid) contract. \ No newline at end of file diff --git a/components/gamerig-library/gen/interface/chandra/desktop/plasmoid/ffi.mbt b/components/gamerig-library/gen/interface/chandra/desktop/plasmoid/ffi.mbt new file mode 100644 index 0000000..1ad6422 --- /dev/null +++ b/components/gamerig-library/gen/interface/chandra/desktop/plasmoid/ffi.mbt @@ -0,0 +1,431 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + +///| +#doc(hidden) +pub fn wasmExportInfo() -> Int { + + let (result) : (PlasmoidInfo) = info(); + let return_area = mbt_ffi_malloc(32) + + let ptr = mbt_ffi_str2ptr((result).id) + mbt_ffi_store32((return_area) + 4, (result).id.length()) + mbt_ffi_store32((return_area) + 0, ptr) + + let ptr0 = mbt_ffi_str2ptr((result).name) + mbt_ffi_store32((return_area) + 12, (result).name.length()) + mbt_ffi_store32((return_area) + 8, ptr0) + mbt_ffi_store32((return_area) + 16, (((result).preferred).w).reinterpret_as_int()) + mbt_ffi_store32((return_area) + 20, (((result).preferred).h).reinterpret_as_int()) + mbt_ffi_store32((return_area) + 24, ((result).min_width).reinterpret_as_int()) + mbt_ffi_store8((return_area) + 28, (if (result).stretch { 1 } else { 0 })) + let ret = return_area + return ret + +} + +///| +#doc(hidden) +pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit { + mbt_ffi_free(mbt_ffi_load32((p0) + 0)) + mbt_ffi_free(mbt_ffi_load32((p0) + 8)) + +} + +///| +#doc(hidden) +pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int { + + let (result) : (Array[@types.DrawOp]) = render(@types.Size::{w : (p0).reinterpret_as_uint(), h : (p1).reinterpret_as_uint()}); + let return_area = mbt_ffi_malloc(8) + + let address = mbt_ffi_malloc((result).length() * 32); + for index = 0; index < (result).length(); index = index + 1 { + let iter_elem : @types.DrawOp = (result)[(index)] + let iter_base = address + (index * 32); + + match iter_elem { + FillRect(payload) => { + mbt_ffi_store8((iter_base) + 0, (0)) + mbt_ffi_store32((iter_base) + 4, ((payload).rect).x) + mbt_ffi_store32((iter_base) + 8, ((payload).rect).y) + mbt_ffi_store32((iter_base) + 12, (((payload).rect).w).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 16, (((payload).rect).h).reinterpret_as_int()) + mbt_ffi_store8((iter_base) + 20, (((payload).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, ((payload).radius).reinterpret_as_int()) + + () + } + StrokeRect(payload0) => { + mbt_ffi_store8((iter_base) + 0, (1)) + mbt_ffi_store32((iter_base) + 4, ((payload0).rect).x) + mbt_ffi_store32((iter_base) + 8, ((payload0).rect).y) + mbt_ffi_store32((iter_base) + 12, (((payload0).rect).w).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 16, (((payload0).rect).h).reinterpret_as_int()) + mbt_ffi_store8((iter_base) + 20, (((payload0).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload0).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload0).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload0).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, ((payload0).width).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 28, ((payload0).radius).reinterpret_as_int()) + + () + } + Line(payload1) => { + mbt_ffi_store8((iter_base) + 0, (2)) + mbt_ffi_store32((iter_base) + 4, ((payload1).start).x) + mbt_ffi_store32((iter_base) + 8, ((payload1).start).y) + mbt_ffi_store32((iter_base) + 12, ((payload1).end).x) + mbt_ffi_store32((iter_base) + 16, ((payload1).end).y) + mbt_ffi_store8((iter_base) + 20, (((payload1).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload1).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload1).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload1).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, ((payload1).width).reinterpret_as_int()) + + () + } + Circle(payload2) => { + mbt_ffi_store8((iter_base) + 0, (3)) + mbt_ffi_store32((iter_base) + 4, ((payload2).center).x) + mbt_ffi_store32((iter_base) + 8, ((payload2).center).y) + mbt_ffi_store32((iter_base) + 12, ((payload2).radius).reinterpret_as_int()) + mbt_ffi_store8((iter_base) + 16, (((payload2).color).r).to_int()) + mbt_ffi_store8((iter_base) + 17, (((payload2).color).g).to_int()) + mbt_ffi_store8((iter_base) + 18, (((payload2).color).b).to_int()) + mbt_ffi_store8((iter_base) + 19, (((payload2).color).a).to_int()) + mbt_ffi_store8((iter_base) + 20, (if (payload2).filled { 1 } else { 0 })) + + () + } + Text(payload3) => { + mbt_ffi_store8((iter_base) + 0, (4)) + mbt_ffi_store32((iter_base) + 4, ((payload3).origin).x) + mbt_ffi_store32((iter_base) + 8, ((payload3).origin).y) + + let ptr = mbt_ffi_str2ptr((payload3).text) + mbt_ffi_store32((iter_base) + 16, (payload3).text.length()) + mbt_ffi_store32((iter_base) + 12, ptr) + mbt_ffi_store32((iter_base) + 20, (((payload3).style).size).reinterpret_as_int()) + mbt_ffi_store8((iter_base) + 24, ((((payload3).style).color).r).to_int()) + mbt_ffi_store8((iter_base) + 25, ((((payload3).style).color).g).to_int()) + mbt_ffi_store8((iter_base) + 26, ((((payload3).style).color).b).to_int()) + mbt_ffi_store8((iter_base) + 27, ((((payload3).style).color).a).to_int()) + mbt_ffi_store8((iter_base) + 28, ((payload3).style).align.ordinal()) + mbt_ffi_store8((iter_base) + 29, (if ((payload3).style).bold { 1 } else { 0 })) + + () + } + PushClip(payload4) => { + mbt_ffi_store8((iter_base) + 0, (5)) + mbt_ffi_store32((iter_base) + 4, (payload4).x) + mbt_ffi_store32((iter_base) + 8, (payload4).y) + mbt_ffi_store32((iter_base) + 12, ((payload4).w).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 16, ((payload4).h).reinterpret_as_int()) + + () + } + PopClip => { + mbt_ffi_store8((iter_base) + 0, (6)) + + () + } + Image(payload6) => { + mbt_ffi_store8((iter_base) + 0, (7)) + mbt_ffi_store32((iter_base) + 4, ((payload6).rect).x) + mbt_ffi_store32((iter_base) + 8, ((payload6).rect).y) + mbt_ffi_store32((iter_base) + 12, (((payload6).rect).w).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 16, (((payload6).rect).h).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 20, ((payload6).image).reinterpret_as_int()) + + () + } + } + + } + mbt_ffi_store32((return_area) + 4, (result).length()) + mbt_ffi_store32((return_area) + 0, address) + let ret = return_area + return ret + +} + +///| +#doc(hidden) +pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit { + + for index = 0; index < (mbt_ffi_load32((p0) + 4)); index = index + 1 { + let iter_base = (mbt_ffi_load32((p0) + 0)) + (index * 32) + + match (mbt_ffi_load8_u((iter_base) + 0)) { + 0 => () + 1 => () + 2 => () + 3 => () + 4 => { + mbt_ffi_free(mbt_ffi_load32((iter_base) + 12)) + + } + 5 => () + 6 => () + 7 => () + _ => panic() + } + + } + mbt_ffi_free(mbt_ffi_load32((p0) + 0)) + +} + +///| +#doc(hidden) +pub fn wasmExportPopup() -> Int { + + let (result) : (PopupSurface?) = popup(); + let return_area = mbt_ffi_malloc(20) + + match (result) { + None => { + mbt_ffi_store8((return_area) + 0, (0)) + + () + } + Some(payload0) => { + mbt_ffi_store8((return_area) + 0, (1)) + mbt_ffi_store32((return_area) + 4, (((payload0).size).w).reinterpret_as_int()) + mbt_ffi_store32((return_area) + 8, (((payload0).size).h).reinterpret_as_int()) + + let address = mbt_ffi_malloc(((payload0).ops).length() * 32); + for index = 0; index < ((payload0).ops).length(); index = index + 1 { + let iter_elem : @types.DrawOp = ((payload0).ops)[(index)] + let iter_base = address + (index * 32); + + match iter_elem { + FillRect(payload1) => { + mbt_ffi_store8((iter_base) + 0, (0)) + mbt_ffi_store32((iter_base) + 4, ((payload1).rect).x) + mbt_ffi_store32((iter_base) + 8, ((payload1).rect).y) + mbt_ffi_store32((iter_base) + 12, (((payload1).rect).w).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 16, (((payload1).rect).h).reinterpret_as_int()) + mbt_ffi_store8((iter_base) + 20, (((payload1).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload1).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload1).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload1).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, ((payload1).radius).reinterpret_as_int()) + + () + } + StrokeRect(payload2) => { + mbt_ffi_store8((iter_base) + 0, (1)) + mbt_ffi_store32((iter_base) + 4, ((payload2).rect).x) + mbt_ffi_store32((iter_base) + 8, ((payload2).rect).y) + mbt_ffi_store32((iter_base) + 12, (((payload2).rect).w).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 16, (((payload2).rect).h).reinterpret_as_int()) + mbt_ffi_store8((iter_base) + 20, (((payload2).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload2).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload2).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload2).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, ((payload2).width).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 28, ((payload2).radius).reinterpret_as_int()) + + () + } + Line(payload3) => { + mbt_ffi_store8((iter_base) + 0, (2)) + mbt_ffi_store32((iter_base) + 4, ((payload3).start).x) + mbt_ffi_store32((iter_base) + 8, ((payload3).start).y) + mbt_ffi_store32((iter_base) + 12, ((payload3).end).x) + mbt_ffi_store32((iter_base) + 16, ((payload3).end).y) + mbt_ffi_store8((iter_base) + 20, (((payload3).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload3).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload3).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload3).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, ((payload3).width).reinterpret_as_int()) + + () + } + Circle(payload4) => { + mbt_ffi_store8((iter_base) + 0, (3)) + mbt_ffi_store32((iter_base) + 4, ((payload4).center).x) + mbt_ffi_store32((iter_base) + 8, ((payload4).center).y) + mbt_ffi_store32((iter_base) + 12, ((payload4).radius).reinterpret_as_int()) + mbt_ffi_store8((iter_base) + 16, (((payload4).color).r).to_int()) + mbt_ffi_store8((iter_base) + 17, (((payload4).color).g).to_int()) + mbt_ffi_store8((iter_base) + 18, (((payload4).color).b).to_int()) + mbt_ffi_store8((iter_base) + 19, (((payload4).color).a).to_int()) + mbt_ffi_store8((iter_base) + 20, (if (payload4).filled { 1 } else { 0 })) + + () + } + Text(payload5) => { + mbt_ffi_store8((iter_base) + 0, (4)) + mbt_ffi_store32((iter_base) + 4, ((payload5).origin).x) + mbt_ffi_store32((iter_base) + 8, ((payload5).origin).y) + + let ptr = mbt_ffi_str2ptr((payload5).text) + mbt_ffi_store32((iter_base) + 16, (payload5).text.length()) + mbt_ffi_store32((iter_base) + 12, ptr) + mbt_ffi_store32((iter_base) + 20, (((payload5).style).size).reinterpret_as_int()) + mbt_ffi_store8((iter_base) + 24, ((((payload5).style).color).r).to_int()) + mbt_ffi_store8((iter_base) + 25, ((((payload5).style).color).g).to_int()) + mbt_ffi_store8((iter_base) + 26, ((((payload5).style).color).b).to_int()) + mbt_ffi_store8((iter_base) + 27, ((((payload5).style).color).a).to_int()) + mbt_ffi_store8((iter_base) + 28, ((payload5).style).align.ordinal()) + mbt_ffi_store8((iter_base) + 29, (if ((payload5).style).bold { 1 } else { 0 })) + + () + } + PushClip(payload6) => { + mbt_ffi_store8((iter_base) + 0, (5)) + mbt_ffi_store32((iter_base) + 4, (payload6).x) + mbt_ffi_store32((iter_base) + 8, (payload6).y) + mbt_ffi_store32((iter_base) + 12, ((payload6).w).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 16, ((payload6).h).reinterpret_as_int()) + + () + } + PopClip => { + mbt_ffi_store8((iter_base) + 0, (6)) + + () + } + Image(payload8) => { + mbt_ffi_store8((iter_base) + 0, (7)) + mbt_ffi_store32((iter_base) + 4, ((payload8).rect).x) + mbt_ffi_store32((iter_base) + 8, ((payload8).rect).y) + mbt_ffi_store32((iter_base) + 12, (((payload8).rect).w).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 16, (((payload8).rect).h).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 20, ((payload8).image).reinterpret_as_int()) + + () + } + } + + } + mbt_ffi_store32((return_area) + 16, ((payload0).ops).length()) + mbt_ffi_store32((return_area) + 12, address) + + () + } + } + let ret = return_area + return ret + +} + +///| +#doc(hidden) +pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit { + + match (mbt_ffi_load8_u((p0) + 0)) { + 0 => () + 1 => { + + for index = 0; index < (mbt_ffi_load32((p0) + 16)); index = index + 1 { + let iter_base = (mbt_ffi_load32((p0) + 12)) + (index * 32) + + match (mbt_ffi_load8_u((iter_base) + 0)) { + 0 => () + 1 => () + 2 => () + 3 => () + 4 => { + mbt_ffi_free(mbt_ffi_load32((iter_base) + 12)) + + } + 5 => () + 6 => () + 7 => () + _ => panic() + } + + } + mbt_ffi_free(mbt_ffi_load32((p0) + 12)) + + } + _ => panic() + } + +} + +///| +#doc(hidden) +pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { + + let lifted = match (p1) { + 0 => { + + @types.InputEvent::PointerMove(@types.Point::{x : p2, y : p3}) + } + 1 => { + + @types.InputEvent::PointerDown(@types.Point::{x : p2, y : p3}) + } + 2 => { + + @types.InputEvent::PointerUp(@types.Point::{x : p2, y : p3}) + } + 3 => { + + @types.InputEvent::PointerLeave + } + 4 => { + + @types.InputEvent::FocusLost + } + 5 => { + + let result = mbt_ffi_ptr2str(p2, p3) + + @types.InputEvent::KeyDown(result) + } + _ => panic() + } + + let (result0) : (Bool) = on_event(Surface::from(p0), lifted); + let ret = (if result0 { 1 } else { 0 }) + return ret + +} + +///| +extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = +#|(func (param i32) (result i32) local.get 0 i32.load8_u) + +///| +extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) = +#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store) + +///| +extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) = +#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8) + +///| +extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = +#|(func (param i32) (result i32) (local i32) +#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc +#| local.tee 1 i32.const 0 call $moonbit.init_array8 +#| local.get 1) + +///| +extern "wasm" fn mbt_ffi_free(position : Int) = +#|(func (param i32) local.get 0 call $moonbit.decref) + +///| +extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = +#|(func (param i32) (param i32) (result i32) +#| local.get 0 +#| local.get 1 call $moonbit.init_array16 +#| local.get 0) + +///| +extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = +#|(func (param i32) (result i32) local.get 0 i32.load) + +///| +#owned(str) +extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = +#|(func (param i32) (result i32) local.get 0) + diff --git a/components/gamerig-library/gen/interface/chandra/desktop/plasmoid/moon.pkg b/components/gamerig-library/gen/interface/chandra/desktop/plasmoid/moon.pkg new file mode 100644 index 0000000..451db26 --- /dev/null +++ b/components/gamerig-library/gen/interface/chandra/desktop/plasmoid/moon.pkg @@ -0,0 +1,8 @@ +import { + "chandra/desktop/interface/chandra/desktop/types" @types, + "chandra/desktop/interface/chandra/desktop/theme" @theme, + "chandra/desktop/interface/chandra/desktop/game-library" @game_library, + "chandra/desktop/lib/gamelib" @logic, +} + +warnings = "-44" diff --git a/components/gamerig-library/gen/interface/chandra/desktop/plasmoid/stub.mbt b/components/gamerig-library/gen/interface/chandra/desktop/plasmoid/stub.mbt new file mode 100644 index 0000000..dec21ef --- /dev/null +++ b/components/gamerig-library/gen/interface/chandra/desktop/plasmoid/stub.mbt @@ -0,0 +1,66 @@ +///| The Gamerig Library's `plasmoid` export: a desktop module (it also exports desktop-module), so +/// `render` gets the whole output. The data comes from the `game-library` capability (the shell +/// polls gamerig's library daemon); all logic lives in lib/gamelib. + +///| +pub fn info() -> PlasmoidInfo { + { id: "org.chandra.gamerig-library", name: "Gamerig Library", preferred: { w: 0, h: 0 }, min_width: 0, stretch: false } +} + +///| +fn games() -> Array[@logic.Game] { + @game_library.games().map(g => { + id: g.id, + name: g.name, + category: g.category, + description: g.description, + icon: g.icon, + install_hint: g.install_hint, + featured: g.featured, + installed: g.installed, + running: g.running, + }) +} + +///| +fn modes() -> Array[@logic.Mode] { + @game_library.launch_modes().map(m => { game: m.game, id: m.id, label: m.label }) +} + +///| +fn rig() -> @logic.Rig { + let s = @game_library.status() + { + connected: s.connected, + error: s.error, + gpu: s.gpu, + resolution: s.resolution, + display: s.display, + audio: s.audio, + audio_ok: s.audio_ok, + hostname: s.hostname, + } +} + +///| +pub fn render(size : @types.Size) -> Array[@types.DrawOp] { + @logic.state.render(games(), modes(), rig(), size, @theme.get_tokens()) +} + +///| Desktop modules have no popup. +pub fn popup() -> PopupSurface? { + None +} + +///| +pub fn on_event(_target : Surface, event : @types.InputEvent) -> Bool { + let (redraw, action) = @logic.state.handle(event) + match action { + Launch(id, mode) => @game_library.launch(id, mode) + Stop(id) => @game_library.stop(id) + Focus(id) => @game_library.focus(id) + Refresh => @game_library.refresh() + NoAction => () + } + redraw +} diff --git a/components/gamerig-library/gen/interface/chandra/desktop/plasmoid/top.mbt b/components/gamerig-library/gen/interface/chandra/desktop/plasmoid/top.mbt new file mode 100644 index 0000000..24d7d0e --- /dev/null +++ b/components/gamerig-library/gen/interface/chandra/desktop/plasmoid/top.mbt @@ -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 + diff --git a/components/gamerig-library/gen/moon.pkg b/components/gamerig-library/gen/moon.pkg new file mode 100644 index 0000000..f86df81 --- /dev/null +++ b/components/gamerig-library/gen/moon.pkg @@ -0,0 +1,34 @@ +import { + "chandra/desktop/components/gamerig-library/gen/interface/chandra/desktop/desktop-module" @desktop-module, + "chandra/desktop/components/gamerig-library/gen/interface/chandra/desktop/module-config" @module-config, + "chandra/desktop/components/gamerig-library/gen/interface/chandra/desktop/plasmoid" @plasmoid, +} + +warnings = "-44" + +pkgtype(kind: "foreign_library") + +options( + link: { + "wasm": { + "export-memory-name": "memory", + "heap-start-address": 16, + "exports": [ + "mbt_ffi_cabi_realloc:cabi_realloc", + "wasmExportBackdrop:chandra:desktop/desktop-module@0.1.0#backdrop", + "wasmExportConfigItems:chandra:desktop/module-config@0.1.0#config-items", + "wasmExportConfigItemsPostReturn:cabi_post_chandra:desktop/module-config@0.1.0#config-items", + "wasmExportInfo:chandra:desktop/plasmoid@0.1.0#info", + "wasmExportInfoPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#info", + "wasmExportOnEvent:chandra:desktop/plasmoid@0.1.0#on-event", + "wasmExportOnScroll:chandra:desktop/desktop-module@0.1.0#on-scroll", + "wasmExportPopup:chandra:desktop/plasmoid@0.1.0#popup", + "wasmExportPopupPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#popup", + "wasmExportRender:chandra:desktop/plasmoid@0.1.0#render", + "wasmExportRenderPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#render", + "wasmExportSetConfig:chandra:desktop/module-config@0.1.0#set-config", + "wasmExportTick:chandra:desktop/desktop-module@0.1.0#tick" + ], + }, + }, +) diff --git a/compositor/app/app.mbt b/compositor/app/app.mbt index ae53bde..64a51cc 100644 --- a/compositor/app/app.mbt +++ b/compositor/app/app.mbt @@ -63,6 +63,7 @@ pub fn run(args : Array[String]) -> Int { let mut restore = true let mut kiosk : String? = None let mut kiosk_hybrid = false + let mut desktop = "" let mut app_id = "chandra" let mut width = 1280 let mut height = 720 @@ -98,6 +99,9 @@ pub fn run(args : Array[String]) -> Int { kiosk = Some(args[i + 1]) // one fullscreen app, locked down restore = false i = i + 2 + } else if a == "--desktop" && i + 1 < args.length() { + desktop = args[i + 1] // what fills the desktop: a desktop module's id, "wallpaper" or "clock-card" + i = i + 2 } else if a == "--kiosk-hybrid" { kiosk_hybrid = true // with --kiosk: keep the panel and the desktop, lock only leaving if kiosk is None { @@ -263,6 +267,9 @@ pub fn run(args : Array[String]) -> Int { } None => () } + if desktop != "" && !comp.shell.set_desktop(desktop) { + @sys.log("--desktop " + desktop + ": no such desktop module") + } if login { comp.start_auth_agent() // polkit's password prompts (run0, pkexec): Chandra's dialog } diff --git a/compositor/bin/main.mbt b/compositor/bin/main.mbt index 6f696e6..5e0dc30 100644 --- a/compositor/bin/main.mbt +++ b/compositor/bin/main.mbt @@ -14,6 +14,7 @@ fn main { let mut restore = true let mut kiosk : String? = None let mut kiosk_hybrid = false + let mut desktop = "" let mut app_id = "chandra" let mut width = 1280 let mut height = 720 @@ -43,6 +44,9 @@ fn main { kiosk = Some(args[i + 1]) // one fullscreen app, locked down (docs/kiosk.md) restore = false i = i + 2 + } else if a == "--desktop" && i + 1 < args.length() { + desktop = args[i + 1] // what fills the desktop: a desktop module's id, "wallpaper" or "clock-card" + i = i + 2 } else if a == "--kiosk-hybrid" { kiosk_hybrid = true // with --kiosk: keep the panel and the desktop, lock only leaving if kiosk is None { @@ -173,6 +177,9 @@ fn main { Some(cmd) => comp.start_kiosk(cmd, hybrid=kiosk_hybrid) None => () } + if desktop != "" && !comp.shell.set_desktop(desktop) { + @sys.log("--desktop " + desktop + ": no such desktop module") + } if drm { comp.login_session = true comp.start_auth_agent() // polkit's password prompts (run0, pkexec): Chandra's dialog diff --git a/compositor/host/compositor.mbt b/compositor/host/compositor.mbt index 3aa07b3..84dbe41 100644 --- a/compositor/host/compositor.mbt +++ b/compositor/host/compositor.mbt @@ -720,13 +720,17 @@ pub fn ChandraCompositor::has_timed_work(self : ChandraCompositor) -> Bool { self.overview_animating() || self.shell.animating() || self.shell.face_busy() || + self.shell.gamelib_busy() || self.kiosk_waiting() } ///| How long an idle main loop may sleep: `idle_ms` (until the wall clock's next second), or /// less when a desktop module's next animation frame is due sooner. pub fn ChandraCompositor::wake_timeout(self : ChandraCompositor, idle_ms : Int) -> Int { - let d = self.shell.desktop_wake_ms(@sys.monotonic_ms()) + let now = @sys.monotonic_ms() + let d = self.shell.desktop_wake_ms(now) + let g = self.shell.gamelib_wake_ms(now) + let d = if g >= 0 && (d < 0 || g < d) { g } else { d } if d >= 0 && d < idle_ms { d } else { diff --git a/compositor/host/gamelib_test.mbt b/compositor/host/gamelib_test.mbt new file mode 100644 index 0000000..11213de --- /dev/null +++ b/compositor/host/gamelib_test.mbt @@ -0,0 +1,112 @@ +///| The Gamerig Library desktop module and the `game-library` capability (compositor/shell/ +/// gamelib.mbt), against a state file standing in for gamerig's library daemon. Needs the module +/// built: scripts/build-modules.sh. + +///| +let gamelib_state_idle : String = + #|{"system": {"gpu": "NVIDIA GeForce GTX 1650", "resolution": "1280x720", "display": ":0", + #| "audio": "PulseAudio", "audio_ok": true, "hostname": "rig"}, + #| "apps": [ + #| {"id": "steam", "name": "Steam", "category": "games", "featured": true, "icon": "Play", + #| "description": "Your Steam library.", "installed": true, "running": false, + #| "modes": [{"id": "default", "label": "Launch"}, {"id": "bigpicture", "label": "Big Picture"}]}, + #| {"id": "terminal", "name": "Terminal", "category": "tools", "icon": "Terminal", + #| "description": "Interactive shell inside the rig.", "installed": true} + #| ]} + +///| +fn gamelib_file(tag : String, body : String) -> String { + let path = "/tmp/chandra-gamelib-" + tag + "-" + @sys.getpid().to_string() + ".json" + ignore(@sys.write_file_bytes(path, @sys.str_to_utf8_bytes(body))) + path +} + +///| The desktop module's texts and where each is drawn. +fn gamelib_texts(comp : @host.ChandraCompositor) -> Array[(String, Int, Int)] { + let out : Array[(String, Int, Int)] = [] + for op in comp.shell.slot_ops("desktop") { + if op is Text(t) { + out.push((t.text, t.origin.x, t.origin.y)) + } + } + out +} + +///| +fn gamelib_has(comp : @host.ChandraCompositor, s : String) -> Bool { + gamelib_texts(comp).iter().any(t => t.0 == s) +} + +///| Click the first text `label` the module drew. +fn gamelib_click(comp : @host.ChandraCompositor, label : String, t : UInt) -> Unit { + for tx in gamelib_texts(comp) { + if tx.0 == label { + comp.handle_input(@nested.InputEvent::PointerMove((tx.1 + 4).to_double(), tx.2.to_double()), t) + comp.handle_input(@nested.InputEvent::PointerButton(272U, true), t + 1U) + comp.handle_input(@nested.InputEvent::PointerButton(272U, false), t + 2U) + ignore(comp.compose_frame()) + return + } + } + abort("no " + label) +} + +///| +test "the Gamerig Library shows the daemon's games and rig, and sends launch / stop / focus" { + let comp = desk_comp("gamelib") + let path = gamelib_file("a", gamelib_state_idle) + comp.shell.set_gamelib_base("file://" + path) + assert_true(comp.shell.desktop_modules().contains(("gamerig-library", "Gamerig Library"))) + assert_true(comp.shell.set_desktop("gamerig-library")) + ignore(comp.compose_frame()) + ignore(comp.compose_frame()) + for want in ["Gamerig", "Steam", "Terminal", "Big Picture", "Rig Status", "Games", "Running Apps"] { + assert_true(gamelib_has(comp, want), msg="missing " + want) + } + // Launch Big Picture, then plain Launch on the first card (Steam, featured). + gamelib_click(comp, "Big Picture", 100U) + gamelib_click(comp, "Launch", 110U) + ignore(comp.compose_frame()) + assert_eq(comp.shell.gamelib.sent, ["launch steam bigpicture", "launch steam default"]) + // The daemon says it runs now: the card offers Switch to and Stop, the sidebar lists it. + ignore(@sys.write_file_bytes(path, @sys.str_to_utf8_bytes(gamelib_state_idle.replace(old="\"running\": false", new="\"running\": true")))) + comp.shell.gamelib.next_poll = 0UL + ignore(comp.compose_frame()) + ignore(comp.compose_frame()) + assert_true(gamelib_has(comp, "Switch to")) + gamelib_click(comp, "Stop", 120U) + gamelib_click(comp, "Switch to", 130U) + ignore(comp.compose_frame()) + assert_eq(comp.shell.gamelib.sent[2:].to_owned(), ["stop steam default", "focus steam default"]) + // The daemon goes away: the library says so. + @sys.unlink(path) + comp.shell.gamelib.next_poll = 0UL + ignore(comp.compose_frame()) + ignore(comp.compose_frame()) + assert_true(gamelib_texts(comp).iter().any(t => t.0.has_prefix("Library daemon not reachable"))) +} + +///| +test "typing on the focused library filters its cards" { + let comp = desk_comp("gamelib-type") + let path = gamelib_file("b", gamelib_state_idle) + comp.shell.set_gamelib_base("file://" + path) + assert_true(comp.shell.set_desktop("gamerig-library")) + ignore(comp.compose_frame()) + ignore(comp.compose_frame()) + // A click on the empty grid gives the desktop the keyboard. + comp.handle_input(@nested.InputEvent::PointerMove(900.0, 600.0), 10U) + comp.handle_input(@nested.InputEvent::PointerButton(272U, true), 11U) + comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 12U) + ignore(comp.compose_frame()) + for k in [20U, 18U, 19U, 50U] { // t e r m (evdev codes) + comp.handle_input(@nested.InputEvent::Key(k, true), 20U) + comp.handle_input(@nested.InputEvent::Key(k, false), 21U) + } + ignore(comp.compose_frame()) + assert_true(gamelib_has(comp, "term")) + assert_true(gamelib_has(comp, "Terminal")) + assert_false(gamelib_has(comp, "Steam")) + @sys.unlink(path) +} + diff --git a/compositor/host/input_test.mbt b/compositor/host/input_test.mbt index 555394c..0d7a0a4 100644 --- a/compositor/host/input_test.mbt +++ b/compositor/host/input_test.mbt @@ -1689,9 +1689,9 @@ test "open_settings opens the settings module on the tab asked for" { assert_true(comp.shell.open_settings(Desktop)) ignore(comp.compose_frame()) let pr = comp.shell.slot_popup_rect(slot) - // "On the desktop" and its choices (wallpaper only, clock card, the two desktop modules), then - // the Wallpaper heading and the five wallpapers. - assert_eq(pr.h, 40 + (1 + 4 + 6) * 28 + 6) + // "On the desktop" and its choices (wallpaper only, clock card, the three desktop modules), + // then the Wallpaper heading and the five wallpapers. + assert_eq(pr.h, 40 + (1 + 5 + 6) * 28 + 6) assert_true(comp.shell.open_settings(Session)) ignore(comp.compose_frame()) // The five settings, then Face unlock (a heading; chandra-face isn't installed in tests). diff --git a/compositor/shell/gamelib.mbt b/compositor/shell/gamelib.mbt new file mode 100644 index 0000000..ec3122c --- /dev/null +++ b/compositor/shell/gamelib.mbt @@ -0,0 +1,341 @@ +///| The `game-library` capability (docs/gamerig-library.md): what the Gamerig Library desktop +/// module shows. The shell polls gamerig's library daemon (server.py, `GET /api/state` on +/// 127.0.0.1:8091; GAMERIG_DESKTOP_API sets another base URL) about every two seconds while a +/// module with the capability is loaded, and sends the module's launch / stop / focus back as +/// `POST /api/apps//`. Both run curl on a socket (`spawn_socket`), so the compositor +/// never waits on the daemon. A `file://` base reads a state file instead (tests, demos) and only +/// records the actions. + +///| How often the daemon is asked, and how soon after an action. +let gamelib_poll_ms : UInt64 = 2000UL + +///| +let gamelib_after_action_ms : UInt64 = 250UL + +///| An action's error stays in the status this long. +let gamelib_error_ms : UInt64 = 8000UL + +///| A curl run in progress: our end of its socket and what it has said. +pub(all) struct CurlRun { + fd : Int + buf : Array[Byte] +} + +///| What the shell knows of the library, and the daemon calls in flight. +pub(all) struct GameLib { + /// Base URL without a trailing slash ("http://127.0.0.1:8091" or "file:///path/state.json"). + mut base : String + /// curl's path ("" when there is none: every poll fails with a message). + curl : String + mut state : @gamelib.State + mut get : CurlRun? + mut post : CurlRun? + /// Actions waiting for the one in flight: (verb, game, mode). + queue : Array[(String, String, String)] + /// Actions done against a file:// base, as "verb game mode" (tests read them). + sent : Array[String] + mut next_poll : UInt64 + /// What the last action said went wrong, until `error_until`. + mut action_error : String + mut error_until : UInt64 + mut dirty : Bool +} + +///| curl, where the rig's image has it. +fn find_curl() -> String { + let env = @sys.getenv("GAMERIG_CURL") + if env != "" { + return env + } + for p in ["/usr/bin/curl", "/bin/curl", "/usr/local/bin/curl"] { + if @sys.has_exe(p) { + return p + } + } + "" +} + +///| +pub fn GameLib::new() -> GameLib { + let env = @sys.getenv("GAMERIG_DESKTOP_API") + let base = if env != "" { env } else { "http://127.0.0.1:8091" } + { + base: trim_slash(base), + curl: find_curl(), + state: { rig: @gamelib.Rig::unknown(), games: [], modes: [] }, + get: None, + post: None, + queue: [], + sent: [], + next_poll: 0UL, + action_error: "", + error_until: 0UL, + dirty: true, + } +} + +///| +fn trim_slash(s : String) -> String { + if s.has_suffix("/") { + s[:s.length() - 1].to_string() + } else { + s + } +} + +///| Point the library at another daemon (or a state file) and poll it now. +pub fn DesktopShell::set_gamelib_base(self : DesktopShell, base : String) -> Unit { + self.gamelib.base = trim_slash(base) + self.gamelib.next_poll = 0UL + self.gamelib.sent.clear() +} + +///| A module asked for something (`game-library` launch / stop / focus / refresh). +pub fn GameLib::request(self : GameLib, code : Int, game : String, mode : String) -> Unit { + let verb = match code { + 0 => "launch" + 1 => "stop" + 2 => "focus" + _ => { + self.next_poll = 0UL + return + } + } + if game == "" || game.contains("/") || game.contains("\n") || mode.contains("\n") { + return + } + self.queue.push((verb, game, if mode == "" { "default" } else { mode })) +} + +///| Start curl with `args`; None when it can't run. +fn GameLib::curl_run(self : GameLib, args : Array[String]) -> CurlRun? { + if self.curl == "" { + return None + } + // argv goes to the child one per line, so the -w newline is curl's own "\n" escape; the daemon + // is local, so no proxy. At most 15 arguments (spawn_socket). + let argv = [self.curl, "-sS", "--noproxy", "*", "-m5", "-w", "\\n%{http_code}"] + argv.append(args) + let fd = @sys.spawn_socket(argv) + if fd < 0 { + None + } else { + Some({ fd, buf: [] }) + } +} + +///| Read what `run` has said, without waiting. Some((body, http status)) once it is done. +fn read_run(run : CurlRun) -> (String, Int)? { + let chunk : FixedArray[Byte] = FixedArray::make(8192, b'\x00') + let mut eof = false + while @sys.poll_read(run.fd, 0) > 0 { + let (n, extra) = @sys.recvmsg_fd(run.fd, chunk, chunk.length()) + if extra >= 0 { + @sys.close_fd(extra) + } + if n == -1 { + break + } + if n <= 0 { + eof = true + break + } + for i = 0; i < n; i = i + 1 { + run.buf.push(chunk[i]) + } + if run.buf.length() > 4 * 1024 * 1024 { + eof = true // a runaway answer: stop reading + break + } + } + if !eof { + return None + } + @sys.close_fd(run.fd) + let text = @utf8.decode_lossy(Bytes::from_array(run.buf)) + // curl -w appended "\n"; 000 when it couldn't connect. + match text.rev_find("\n") { + Some(i) => { + let code = @gamelib.parse_int(text[i + 1:].to_string()) + Some((text[:i].to_string(), code)) + } + None => Some((text, 0)) + } +} + +///| Take a new state (or say why there is none). +fn GameLib::take(self : GameLib, body : String, code : Int, now : UInt64) -> Unit { + let err = if code == 200 { + match @gamelib.parse_state(body) { + Ok(s) => { + self.state = s + "" + } + Err(e) => e + } + } else if code == 0 { + "Library daemon not reachable at " + self.base + } else { + "Library daemon answered HTTP " + code.to_string() + ": " + @gamelib.error_message(body) + } + let rig = self.state.rig + let rig = if err != "" { + { ..rig, connected: false, error: err } + } else if now < self.error_until { + { ..rig, connected: true, error: self.action_error } + } else { + { ..rig, connected: true, error: "" } + } + if rig != self.state.rig || err == "" { + self.state = { ..self.state, rig, } + self.dirty = true + } +} + +///| One step: collect answers, start the next poll or action when due. Call it before modules +/// read the tables. +pub fn GameLib::poll(self : GameLib, now : UInt64) -> Unit { + let before = self.state + // The poll in flight. + match self.get { + Some(run) => + match read_run(run) { + Some((body, code)) => { + self.get = None + self.take(body, code, now) + self.next_poll = now + gamelib_poll_ms + } + None => () + } + None => () + } + // The action in flight. + match self.post { + Some(run) => + match read_run(run) { + Some((body, code)) => { + self.post = None + if code < 200 || code >= 300 { + self.action_error = if code == 0 { + "Library daemon not reachable at " + self.base + } else { + @gamelib.error_message(body) + } + self.error_until = now + gamelib_error_ms + } + self.next_poll = now + gamelib_after_action_ms + } + None => () + } + None => () + } + // Next action. + if self.post is None && self.queue.length() > 0 { + let (verb, game, mode) = self.queue.remove(0) + if self.base.has_prefix("file://") { + self.sent.push(verb + " " + game + " " + mode) + self.next_poll = 0UL + } else { + let url = self.base + "/api/apps/" + game + "/" + verb + let body = if verb == "launch" { "{\"mode\":\"" + mode.replace_all(old="\"", new="") + "\"}" } else { "{}" } + match self.curl_run(["-H", "Content-Type: application/json", "--data-binary", body, url]) { + Some(run) => self.post = Some(run) + None => { + self.action_error = "curl is not installed: can't reach the library daemon" + self.error_until = now + gamelib_error_ms + } + } + } + } + // Next poll. + if self.get is None && now >= self.next_poll { + self.next_poll = now + gamelib_poll_ms + if self.base.has_prefix("file://") { + let path = self.base[7:].to_string() + let bytes = @sys.read_file_bytes(path) + if bytes.length() == 0 { + self.take("", 0, now) + } else { + self.take(@utf8.decode_lossy(bytes), 200, now) + } + } else { + match self.curl_run([self.base + "/api/state"]) { + Some(run) => self.get = Some(run) + None => self.take("", 0, now) + } + } + } + if self.state != before { + self.dirty = true + } +} + +///| A daemon call is in flight (the main loop keeps its pace so the answer shows soon). +pub fn GameLib::busy(self : GameLib) -> Bool { + self.get is Some(_) || self.post is Some(_) || self.queue.length() > 0 +} + +///| Milliseconds until the next poll is due, -1 when no module uses the library. +pub fn DesktopShell::gamelib_wake_ms(self : DesktopShell, now : UInt64) -> Int { + if !self.any_cap("game-library") { + return -1 + } + if self.gamelib.next_poll <= now { + 0 + } else { + (self.gamelib.next_poll - now).to_int() + } +} + +///| Whether a library daemon call is in flight. +pub fn DesktopShell::gamelib_busy(self : DesktopShell) -> Bool { + self.any_cap("game-library") && self.gamelib.busy() +} + +///| Publish tables 26-28 for modules with the capability (and redraw the desktop on news). +fn DesktopShell::publish_gamelib(self : DesktopShell) -> Unit { + if !self.any_cap("game-library") { + return + } + let g = self.gamelib + g.poll(@sys.monotonic_ms()) + if !g.dirty { + return + } + g.dirty = false + let r = g.state.rig + let st = @wasm.Table::new() + st.str(r.error) + st.str(r.gpu) + st.str(r.resolution) + st.str(r.display) + st.str(r.audio) + st.str(r.hostname) + st.int(if r.connected { 1 } else { 0 }) + st.int(if r.audio_ok { 1 } else { 0 }) + st.end_row() + @wasm.publish(GameStatus, st) + let gt = @wasm.Table::new() + for x in g.state.games { + gt.str(x.id) + gt.str(x.name) + gt.str(x.category) + gt.str(x.description) + gt.str(x.icon) + gt.str(x.install_hint) + gt.int(if x.featured { 1 } else { 0 }) + gt.int(if x.installed { 1 } else { 0 }) + gt.int(if x.running { 1 } else { 0 }) + gt.end_row() + } + @wasm.publish(Games, gt) + let mt = @wasm.Table::new() + for m in g.state.modes { + mt.str(m.game) + mt.str(m.id) + mt.str(m.label) + mt.end_row() + } + @wasm.publish(GameModes, mt) + self.desk_dirty = true +} diff --git a/compositor/shell/moon.pkg b/compositor/shell/moon.pkg index 861421a..7d055ad 100644 --- a/compositor/shell/moon.pkg +++ b/compositor/shell/moon.pkg @@ -11,6 +11,7 @@ import { "chandra/desktop/lib/timefmt" @timefmt, "chandra/desktop/lib/launcher" @launcher, "chandra/desktop/lib/dock" @dock, + "chandra/desktop/lib/gamelib" @gamelib, "chandra/desktop/compositor/scene" @scene, "jqlssg/moonedn" @edn, "chandra/desktop/compositor/sys" @sys, diff --git a/compositor/shell/shell.mbt b/compositor/shell/shell.mbt index 222ad40..5bd19a9 100644 --- a/compositor/shell/shell.mbt +++ b/compositor/shell/shell.mbt @@ -311,6 +311,8 @@ pub(all) struct DesktopShell { mut default_apps_dirty : Bool /// Face unlock (face.mbt): what `chandra-face` said, for Settings > Session. face : FaceUnlock + /// The game library (gamelib.mbt): gamerig's library daemon, for the `game-library` capability. + gamelib : GameLib /// The terminal chosen in the Apps tab (desktop id; "" for none), saved as state.edn :terminal. mut terminal : String /// Desktop ids of Terminal=true apps, started inside the terminal. @@ -473,6 +475,7 @@ pub fn DesktopShell::new(display : String) -> DesktopShell { default_apps: [], default_apps_dirty: true, face: FaceUnlock::new(), + gamelib: GameLib::new(), terminal: "", terminal_apps, desk_set: false, diff --git a/compositor/shell/widgets.mbt b/compositor/shell/widgets.mbt index 12a7040..1cfb79a 100644 --- a/compositor/shell/widgets.mbt +++ b/compositor/shell/widgets.mbt @@ -701,6 +701,7 @@ fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit { self.publish_default_apps() } self.publish_face_unlock() + self.publish_gamelib() if self.any_cap("screenshot") { @wasm.publish_screenshot(self.screenshot_state) } @@ -854,6 +855,7 @@ fn DesktopShell::process_requests(self : DesktopShell) -> Unit { Some(Shortcut(code)) => self.shortcut_request(code) Some(DefaultApp(code)) => self.default_app_request(code) Some(FaceUnlock(code)) => self.face.request(code) + Some(GameLibrary(code, game, mode)) => self.gamelib.request(code, game, mode) Some(PowerAction(a)) => if a >= 0 && a <= 2 { self.actions.push(SystemPower(a)) } Some(Network(code, ssid, password)) => self.network_request(code, ssid, password) Some(SetInspector(on)) => self.set_inspecting(on) diff --git a/compositor/wasm/wasm_host.mbt b/compositor/wasm/wasm_host.mbt index 453c4a7..1e17f7a 100644 --- a/compositor/wasm/wasm_host.mbt +++ b/compositor/wasm/wasm_host.mbt @@ -335,6 +335,13 @@ pub(all) enum HostTable { FaceStatus /// Enrolled faces (ss: label added). Faces + /// Game library status (ssssssii: error gpu resolution display audio hostname connected + /// audio-ok; one row), served by `game-library.status`. + GameStatus + /// Games (ssssssiii: id name category description icon install-hint featured installed running). + Games + /// Extra launch modes (sss: game id label). + GameModes } ///| @@ -365,6 +372,9 @@ pub fn publish(which : HostTable, t : Table) -> Unit { Desktops => 20U FaceStatus => 24U Faces => 25U + GameStatus => 26U + Games => 27U + GameModes => 28U } // Most tables are republished every frame unchanged: skip the copy into the host then. let slot = id.reinterpret_as_int() @@ -455,6 +465,8 @@ pub(all) enum HostRequest { /// The face-unlock capability: a face index removes it; -1 refresh, -2 enroll, -3 / -4 stop / /// start using it for the password dialog and sudo. FaceUnlock(Int) + /// The game-library capability: 0 launch (game, mode), 1 stop, 2 focus (game), 3 refresh. + GameLibrary(Int, String, String) } derive(Eq, Debug) ///| @@ -482,6 +494,7 @@ pub fn next_request() -> HostRequest? { Some(ReloadSession) => Some(ReloadSession) Some(SetDesktop(i)) => Some(SetDesktop(i)) Some(FaceUnlock(i)) => Some(FaceUnlock(i)) + Some(GameLibrary(r)) => Some(GameLibrary(r.action, r.game, r.mode)) } } diff --git a/compositor/wasm/wasm_native.mbt b/compositor/wasm/wasm_native.mbt index 14171af..0afd4e2 100644 --- a/compositor/wasm/wasm_native.mbt +++ b/compositor/wasm/wasm_native.mbt @@ -743,6 +743,13 @@ pub(all) enum HostTable { FaceStatus /// Enrolled faces (ss: label added). Faces + /// Game library status (ssssssii: error gpu resolution display audio hostname connected + /// audio-ok; one row), served by `game-library.status`. + GameStatus + /// Games (ssssssiii: id name category description icon install-hint featured installed running). + Games + /// Extra launch modes (sss: game id label). + GameModes } ///| Publish `t` as the data behind `which` for every module's next call. @@ -764,6 +771,9 @@ pub fn publish(which : HostTable, t : Table) -> Unit { Desktops => 20 FaceStatus => 24 Faces => 25 + GameStatus => 26 + Games => 27 + GameModes => 28 } let out : Array[Byte] = [] for k = 0; k < 4; k = k + 1 { @@ -853,6 +863,8 @@ pub(all) enum HostRequest { /// The face-unlock capability: a face index removes it; -1 refresh, -2 enroll, -3 / -4 stop / /// start using it for the password dialog and sudo. FaceUnlock(Int) + /// The game-library capability: 0 launch (game, mode), 1 stop, 2 focus (game), 3 refresh. + GameLibrary(Int, String, String) } derive(Eq, Debug) ///| @@ -896,6 +908,14 @@ pub fn next_request() -> HostRequest? { 19 => Some(DefaultApp(c_host_req_int())) 40 => Some(SetDesktop(c_host_req_int())) 44 => Some(FaceUnlock(c_host_req_int())) + 45 => { + let code = c_host_req_int() + let s = req_str() + match s.find("\u{1f}") { + Some(i) => Some(GameLibrary(code, s[:i].to_string(), s[i + 1:].to_string())) + None => Some(GameLibrary(code, s, "")) + } + } _ => None } } diff --git a/compositor/wasm/wasm_stub.c b/compositor/wasm/wasm_stub.c index fd56bc7..f9b4bac 100644 --- a/compositor/wasm/wasm_stub.c +++ b/compositor/wasm/wasm_stub.c @@ -67,7 +67,8 @@ enum { K_SC_LIST, K_SC_CAPTURE, K_SC_CANCEL, K_SC_RESET, K_SC_RESET_ALL, K_DA_CATS, K_DA_APPS, K_DA_SET, K_DA_REFRESH, K_DESKTOPS, K_DESKTOP_CUR, K_SET_DESKTOP, - K_FU_STATUS, K_FU_FACES, K_FU_ENROLL, K_FU_REMOVE, K_FU_SET_IN_USE, K_FU_REFRESH + K_FU_STATUS, K_FU_FACES, K_FU_ENROLL, K_FU_REMOVE, K_FU_SET_IN_USE, K_FU_REFRESH, + K_GL_STATUS, K_GL_GAMES, K_GL_MODES, K_GL_LAUNCH, K_GL_STOP, K_GL_FOCUS, K_GL_REFRESH }; typedef struct Env { Inst *inst; int kind; } Env; @@ -76,7 +77,8 @@ 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_NET_STATUS, T_NET_NETWORKS, T_SHORTCUTS, T_APP_CATS, T_APP_CHOICES, /* fixed numbers from here (wit/host/plasmoids.wit publish-table) */ - T_DESKTOPS = 20, T_FACE_STATUS = 24, T_FACES = 25, T_N = 32 }; + T_DESKTOPS = 20, T_FACE_STATUS = 24, T_FACES = 25, + T_GL_STATUS = 26, T_GL_GAMES = 27, T_GL_MODES = 28, T_N = 32 }; typedef struct { uint8_t *data; size_t len; } Blob; static Blob tables[T_N]; static int32_t host_ints[24] = {[7] = -1}; /* 0 layout mode, 1 inspector on, 2 current wallpaper, 3 session settings on (bit i: row i), @@ -397,6 +399,29 @@ static wasm_trap_t *host_import(void *env, const wasm_val_vec_t *args, wasm_val_ case K_FU_REMOVE: if (a0 >= 0 && a0 < 1000) push_req(44, a0, NULL); break; case K_FU_SET_IN_USE: push_req(44, a0 ? -4 : -3, NULL); break; case K_FU_REFRESH: push_req(44, -1, NULL); break; + /* Game library: status from table 26 (error gpu resolution display audio hostname connected + * audio-ok), games from 27 (id name category description icon install-hint featured installed + * running), launch modes from 28 (game id label); request 45 is 0 launch / 1 stop / 2 focus / + * 3 refresh, with "game\x1fmode". */ + case K_GL_STATUS: build_record(in, T_GL_STATUS, "ssssssbb", a0); break; + case K_GL_GAMES: build_list(in, T_GL_GAMES, "ssssssbbb", a0); break; + case K_GL_MODES: build_list(in, T_GL_MODES, "sss", a0); break; + case K_GL_REFRESH: push_req(45, 3, NULL); break; + case K_GL_LAUNCH: + case K_GL_STOP: + case K_GL_FOCUS: { + int32_t a3 = args->size >= 4 ? args->data[3].of.i32 : 0; + char *game = guest_str(in, a0, a1); + char *mode = e->kind == K_GL_LAUNCH ? guest_str(in, a2, a3) : strdup(""); + size_t lg = strlen(game), lm = strlen(mode); + char *both = (char *)malloc(lg + lm + 2); + memcpy(both, game, lg); + both[lg] = 0x1f; + memcpy(both + lg + 1, mode, lm + 1); + push_req(45, e->kind == K_GL_LAUNCH ? 0 : e->kind == K_GL_STOP ? 1 : 2, both); + free(game); free(mode); free(both); + break; + } case K_SESSION_SET: push_req(a1 ? 11 : 10, a0, NULL); break; /* 10 off, 11 on */ /* Request 12 carries the screenshot code: 0-3 take, 10-12 record, 20 stop, 30/31 pointer. */ case K_SHOT_TAKE: if (a0 >= 0 && a0 <= 3) push_req(12, a0, NULL); break; @@ -620,6 +645,13 @@ static int classify_import(const wasm_name_t *m, const wasm_name_t *f) { if (!strcmp(iface, "face-unlock") && !strcmp(fn, "remove")) return K_FU_REMOVE; if (!strcmp(iface, "face-unlock") && !strcmp(fn, "set-in-use")) return K_FU_SET_IN_USE; if (!strcmp(iface, "face-unlock") && !strcmp(fn, "refresh")) return K_FU_REFRESH; + if (!strcmp(iface, "game-library") && !strcmp(fn, "status")) return K_GL_STATUS; + if (!strcmp(iface, "game-library") && !strcmp(fn, "games")) return K_GL_GAMES; + if (!strcmp(iface, "game-library") && !strcmp(fn, "launch-modes")) return K_GL_MODES; + if (!strcmp(iface, "game-library") && !strcmp(fn, "launch")) return K_GL_LAUNCH; + if (!strcmp(iface, "game-library") && !strcmp(fn, "stop")) return K_GL_STOP; + if (!strcmp(iface, "game-library") && !strcmp(fn, "focus")) return K_GL_FOCUS; + if (!strcmp(iface, "game-library") && !strcmp(fn, "refresh")) return K_GL_REFRESH; if (!strcmp(iface, "session-settings") && !strcmp(fn, "settings")) return K_SESSION_SETTINGS; if (!strcmp(iface, "session-settings") && !strcmp(fn, "is-on")) return K_SESSION_IS_ON; if (!strcmp(iface, "session-settings") && !strcmp(fn, "set-setting")) return K_SESSION_SET; diff --git a/docs/desktop-modules.md b/docs/desktop-modules.md index 3b4ddde..c005ac4 100644 --- a/docs/desktop-modules.md +++ b/docs/desktop-modules.md @@ -5,7 +5,7 @@ instead of a box in the panel. Use it for interactive desktops (an icon launcher wallpaper, a game, a dashboard). It runs in the same sandbox as a panel module, draws with the same draw ops and asks for the same capabilities; only the way the shell drives it differs. -Two samples ship with Chandra: +Three ship with Chandra: * **Icon Desktop** (`components/icon-desktop`, logic in `lib/icondesk`): a grid of app icons on the wallpaper. Click to launch, drag to move (dropping on another icon swaps them), arrow keys @@ -16,8 +16,14 @@ Two samples ship with Chandra: wheel changes speed. Module settings: speed, density, and Moving or Still (Still draws one frame and then costs nothing). +* **Gamerig Library** (`components/gamerig-library`, logic in `lib/gamelib`): gamerig's game + library (categories, search, cards with Launch / Big Picture / Stop, running apps, rig status), + fed by gamerig's library daemon through the `game-library` capability. See + [gamerig-library.md](gamerig-library.md). + ![Icon Desktop](screenshots/desktop-icons.png) ![Live Starfield](screenshots/desktop-starfield.png) +![Gamerig Library](screenshots/desktop-gamerig-library.png) ## Choosing what fills the desktop diff --git a/docs/gamerig-library.md b/docs/gamerig-library.md new file mode 100644 index 0000000..cf895d3 --- /dev/null +++ b/docs/gamerig-library.md @@ -0,0 +1,64 @@ +# Gamerig Library desktop module + +The Gamerig Library is gamerig's library window (the WebKit page in `desktop/ui`, served by +`server.py`) rebuilt as a Chandra desktop module: the same layout, colours and actions, drawn with +Chandra's draw ops, with no browser engine. On a rig it is the desktop of a hybrid kiosk: the +panel, the dock and Alt+Tab work, the library fills the desktop, and leaving the session is +locked. + +![Gamerig Library](screenshots/desktop-gamerig-library.png) + +``` +GAMERIG_DESKTOP_API=http://127.0.0.1:8091 \ + build/wasmhost build/compositor.wasm --x11 --fullscreen --app-id gamerig-desktop \ + --kiosk-hybrid --desktop gamerig-library +``` + +or pick **Gamerig Library** in Settings > Desktop. + +## What it shows + +* **Top bar:** the Gamerig mark, "Library" with the app count, the Alt Tab hint and the search + box (typing filters while the desktop has the keyboard; every word must match the name, id, + category or description). +* **Sidebar:** Library categories (All, Games, Launchers, Tools, Running) with their counts; + Running Apps (click one to bring its window forward, × stops it); Rig Status at the bottom + (GPU, display, audio with its dot; an orange dot while the daemon can't be reached). +* **Cards:** featured games two columns wide; icon tile (gamerig's lucide icon names: Play, + Sparkles, Folder, Star, Square, Terminal, Settings, ExternalLink), name, category and status + badges (Ready, Running, Not installed), description, the install hint for what isn't installed, + and the buttons: **Launch** (gold when it can start), extra modes such as **Big Picture**, and + **Switch to** / **Stop** while it runs. What the daemon refuses ("lutris is not installed") + shows under the title for a few seconds. +* Keyboard: arrows move the selection, Enter launches it (or switches to it), Backspace and + Escape edit the search; the wheel scrolls the grid. +* Module settings (right-click the desktop): Colours, *Follow desktop* (gamerig dark or light + after the desktop theme), *Dark* or *Light*. + +Not there yet: the Add App dialog and the per-app logs view (both are in the web library), and +gamepad navigation (gap G4 in [kiosk-gamerig.md](kiosk-gamerig.md)). + +## How it gets its data + +The module can't reach the network. The shell does it for it, through the `game-library` +capability (`wit/capabilities.wit`): + +* `compositor/shell/gamelib.mbt` polls `GET /api/state` every 2 s while a module with the + capability is loaded (and 250 ms after an action), with curl on a socket (`spawn_socket`), so + the compositor never waits. `` is `GAMERIG_DESKTOP_API`, default + `http://127.0.0.1:8091`. A `file://` base reads a state file instead (tests, demos) and only + records the actions. +* The JSON is parsed by `lib/gamelib` (`parse_state`, the same rules as gamerig's + `desktop/ui/library`) and published as host tables 26 (status), 27 (games) and 28 (extra + launch modes). +* `launch(game, mode)`, `stop`, `focus` become request 45 and then + `POST /api/apps//launch|stop|focus` (`{"mode": ...}` for launch). Games start on the + rig's X server through server.py, exactly as from the web library, and Openbox stacks them over + Chandra's window. + +Served by every host: the wasmer/wasmtime stub (`compositor/wasm/wasm_stub.c`), the MoonBit +wasmhost and the Rust `host-wasm`. + +Code: `components/gamerig-library` (bindings and a thin stub), `lib/gamelib` (model, JSON, +layout, drawing, input; tests in `lib/gamelib/gamelib_test.mbt`), `compositor/shell/gamelib.mbt` +(the poller), host tests in `compositor/host/gamelib_test.mbt`. diff --git a/docs/kiosk-gamerig.md b/docs/kiosk-gamerig.md index ebb728e..d903c5b 100644 --- a/docs/kiosk-gamerig.md +++ b/docs/kiosk-gamerig.md @@ -86,7 +86,7 @@ NVIDIA Xorg :0 ─────────────── Selkies (ximagesrc | # | Gap | Effort | Risk | Status | | --- | --- | --- | --- | --- | | G1 | Kiosk profile: no panel, shortcuts off, desktop menus off, focused window fullscreen, app restarted with backoff, admin escape, `chandra-ctl kiosk`; `--app-id` for the X window's class; `scripts/gamerig-kiosk.sh` | 1 day | low | **done** (d521d0d), rig test pending | -| G2 | **Native launcher module**: the calm library as a Chandra desktop module (desktop modules exist since 0f71779): grid, categories, search, running apps, rig status, logs, add app. Needs a capability for modules to call server.py's HTTP API (or the daemon's catalog/launch logic as a host capability) | 1-2 weeks | medium (UI parity; no HTML/CSS engine, so it is a re-implementation sharing calm's tokens) | to do; removes WebKit (≈ 67 MiB) | +| G2 | **Native launcher module**: the calm library as a Chandra desktop module (desktop modules exist since 0f71779): grid, categories, search, running apps, rig status, logs, add app. Needs a capability for modules to call server.py's HTTP API (or the daemon's catalog/launch logic as a host capability) | 1-2 weeks | medium (UI parity; no HTML/CSS engine, so it is a re-implementation sharing calm's tokens) | **library done**: `gamerig-library` desktop module + `game-library` capability (the shell polls server.py), [gamerig-library.md](gamerig-library.md); Add App and logs still to do; removes WebKit (≈ 67 MiB) | | G3 | **Chandra as the X11 window manager** (replaces Openbox and the fullscreen watcher): `SubstructureRedirect` on the root, map games fullscreen and borderless, leave dialogs (Steam login, file pickers) floating, focus, stacking, `_NET_ACTIVE_WINDOW` / `_NET_CLIENT_LIST` so `wmctrl`/`xdotool` keep working, follow `xrandr`, Ctrl+Alt+L / Super+Space / Alt+Tab across X and Wayland windows. Chandra already speaks the X11 protocol in MoonBit (`compositor/x11`); this is gamerig's own M3 "MoonBit X11 WM" | 1-2 weeks | medium (Steam's odd windows) | to do; removes Openbox (≈ 52 MiB) | | G4 | Gamepad navigation for modules: read the joystick evdev devices Selkies creates (libinput ignores pads; on `--x11` there is no libinput at all), a WIT gamepad event, focus movement in the launcher | 2-4 days | low | to do | | G5 | Clipboard bridge between X (Selkies) and Chandra's Wayland clients | 1-2 days | low | to do, only for apps inside Chandra | @@ -111,7 +111,9 @@ Xorg itself stays (≈ 50 MiB est.); replacing it is the Wayland route below and 1. **Stage 1 (built): Chandra as the library window.** `scripts/gamerig-kiosk.sh` on a running rig, or G6 in onstart. Same library (WebKit inside Chandra), same everything else. Proves the X path on NVIDIA: capture, XTest input, resize, Ctrl+Alt+L, game on top, back to the library. -2. **Stage 2: native launcher module** (G2 + G4). Drops WebKit from the image. The library becomes +2. **Stage 2: native launcher module** (G2 + G4). Built as a hybrid kiosk: `gamerig-kiosk.sh` + now runs `--kiosk-hybrid --desktop gamerig-library` (panel, dock and Alt+Tab work; Log out and + power are locked), so the library needs no WebKit. Drops WebKit from the image. The library becomes gamepad-navigable inside the stream. 3. **Stage 3: Chandra as the window manager** (G3). Drops Openbox and the watcher; the Alt+Tab and "back to library" logic moves into one place. diff --git a/docs/kiosk.md b/docs/kiosk.md index 438b4c5..219deb4 100644 --- a/docs/kiosk.md +++ b/docs/kiosk.md @@ -30,9 +30,14 @@ are refused with a notice. `CMD`, if given, is started and restarted as above (w all is left). ``` -build/wasmhost build/compositor.wasm --x11 --fullscreen --app-id gamerig-desktop --kiosk-hybrid +build/wasmhost build/compositor.wasm --x11 --fullscreen --app-id gamerig-desktop --kiosk-hybrid \ + --desktop gamerig-library ``` +`--desktop NAME` (any mode) picks what fills the desktop at start, as Settings > Desktop does: a +desktop module's id, `wallpaper` or `clock-card`. On a rig that is the +[Gamerig Library](gamerig-library.md). + **Admin escape:** Ctrl+Alt+Shift+Escape unlocks the kiosk (panel, shortcuts and menus come back, windows leave fullscreen) and locks it again. From a script: `chandra-ctl kiosk unlock`, `chandra-ctl kiosk lock`, `chandra-ctl kiosk status`. diff --git a/docs/screenshots/desktop-gamerig-library.png b/docs/screenshots/desktop-gamerig-library.png new file mode 100644 index 0000000..8d4d6ea Binary files /dev/null and b/docs/screenshots/desktop-gamerig-library.png differ diff --git a/host-wasm/src/main.rs b/host-wasm/src/main.rs index 58c452e..d970da3 100644 --- a/host-wasm/src/main.rs +++ b/host-wasm/src/main.rs @@ -296,6 +296,9 @@ impl chandra::host::plasmoids::Host for State { Req::DefaultApp(code) => R::DefaultApp(code), Req::SetDesktop(i) => R::SetDesktop(i), Req::FaceUnlock(code) => R::FaceUnlock(code), + Req::GameLibrary(action, game, mode) => { + R::GameLibrary(chandra::host::plasmoids::GameRequest { action, game, mode }) + } }) } diff --git a/host-wasm/src/plasmoid.rs b/host-wasm/src/plasmoid.rs index 986aa90..0f927e4 100644 --- a/host-wasm/src/plasmoid.rs +++ b/host-wasm/src/plasmoid.rs @@ -76,6 +76,8 @@ pub enum Req { /// A face-unlock request: a face index removes it; -1 refresh, -2 enroll, -3 / -4 stop / /// start using it. FaceUnlock(i32), + /// A game-library action (0 launch, 1 stop, 2 focus, 3 refresh), the game and the mode. + GameLibrary(i32, String, String), } pub const T_APPS: usize = 0; @@ -103,11 +105,18 @@ pub const T_DESKTOPS: usize = 20; pub const T_FACE_STATUS: usize = 24; /// Enrolled faces (ss): label added. pub const T_FACES: usize = 25; +/// Game library status, one row (ssssssii): error gpu resolution display audio hostname connected +/// audio-ok. +pub const T_GL_STATUS: usize = 26; +/// Games (ssssssiii): id name category description icon install-hint featured installed running. +pub const T_GL_GAMES: usize = 27; +/// Extra launch modes (sss): game id label. +pub const T_GL_MODES: usize = 28; /// Host data every module reads from, shared by all loaded modules. #[derive(Default)] pub struct Shared { - pub tables: [Vec; 26], + pub tables: [Vec; 29], pub layout_mode: i32, pub wallpaper: i32, /// What fills the desktop (an index into the desktops table). @@ -418,6 +427,70 @@ impl d::face_unlock::Host for PState { } } +impl d::game_library::Host for PState { + fn status(&mut self) -> d::game_library::RigStatus { + let rows = self.rows(T_GL_STATUS, "ssssssii"); + match rows.first() { + Some(r) if r.len() == 8 => d::game_library::RigStatus { + error: s(&r[0]), + gpu: s(&r[1]), + resolution: s(&r[2]), + display: s(&r[3]), + audio: s(&r[4]), + hostname: s(&r[5]), + connected: i(&r[6]) != 0, + audio_ok: i(&r[7]) != 0, + }, + _ => d::game_library::RigStatus { + error: String::new(), + gpu: String::new(), + resolution: String::new(), + display: String::new(), + audio: String::new(), + hostname: String::new(), + connected: false, + audio_ok: false, + }, + } + } + fn games(&mut self) -> Vec { + self.rows(T_GL_GAMES, "ssssssiii") + .iter() + .filter(|r| r.len() == 9) + .map(|r| d::game_library::Game { + id: s(&r[0]), + name: s(&r[1]), + category: s(&r[2]), + description: s(&r[3]), + icon: s(&r[4]), + install_hint: s(&r[5]), + featured: i(&r[6]) != 0, + installed: i(&r[7]) != 0, + running: i(&r[8]) != 0, + }) + .collect() + } + fn launch_modes(&mut self) -> Vec { + self.rows(T_GL_MODES, "sss") + .iter() + .filter(|r| r.len() == 3) + .map(|r| d::game_library::LaunchMode { game: s(&r[0]), id: s(&r[1]), label: s(&r[2]) }) + .collect() + } + fn launch(&mut self, game: String, mode: String) { + self.shared.borrow_mut().requests.push_back(Req::GameLibrary(0, game, mode)); + } + fn stop(&mut self, game: String) { + self.shared.borrow_mut().requests.push_back(Req::GameLibrary(1, game, String::new())); + } + fn focus(&mut self, game: String) { + self.shared.borrow_mut().requests.push_back(Req::GameLibrary(2, game, String::new())); + } + fn refresh(&mut self) { + self.shared.borrow_mut().requests.push_back(Req::GameLibrary(3, String::new(), String::new())); + } +} + impl d::power::Host for PState { fn screen_off_minutes(&mut self) -> u32 { self.shared.borrow().screen_off_min @@ -1210,4 +1283,58 @@ mod tests { assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Network(2, _, _)))); rt.unload(h); } -} + + #[test] + fn gamerig_library_shows_the_daemons_games_and_launches_big_picture() { + let mut rt = runtime(); + let l = rt.load(&module("gamerig-library")).expect("gamerig-library loads"); + assert!(l.imports.contains(&"game-library".to_string())); + let h = l.handle; + { + let mut sh = rt.shared.borrow_mut(); + sh.tables[T_GL_STATUS] = rows_table(&[vec![ + F::S(""), + F::S("NVIDIA GeForce GTX 1650"), + F::S("1280x720"), + F::S(":0"), + F::S("PulseAudio"), + F::S("rig"), + F::I(1), + F::I(1), + ]]); + sh.tables[T_GL_GAMES] = rows_table(&[vec![ + F::S("steam"), + F::S("Steam"), + F::S("games"), + F::S("Your Steam library."), + F::S("Play"), + F::S(""), + F::I(1), + F::I(1), + F::I(0), + ]]); + sh.tables[T_GL_MODES] = rows_table(&[vec![F::S("steam"), F::S("bigpicture"), F::S("Big Picture")]]); + } + let ops = rt.render(h, Size { w: 1280, h: 720 }); + let t = texts(&ops); + for n in ["Gamerig", "Steam", "Big Picture", "Rig Status", "PulseAudio"] { + assert!(t.contains(&n.to_string()), "{n} shown"); + } + // Click Big Picture: a launch request with its mode. + let at = ops + .iter() + .find_map(|o| match o { + d::types::DrawOp::Text(t) if t.text == "Big Picture" => Some(t.origin), + _ => None, + }) + .expect("Big Picture button"); + let p = Point { x: at.x + 4, y: at.y }; + rt.on_event(h, false, InputEvent::PointerDown(p)); + rt.on_event(h, false, InputEvent::PointerUp(p)); + match rt.shared.borrow_mut().requests.pop_front() { + Some(Req::GameLibrary(0, game, mode)) => assert_eq!((game.as_str(), mode.as_str()), ("steam", "bigpicture")), + other => panic!("expected a launch, got {:?}", other.is_some()), + } + rt.unload(h); + } +} \ No newline at end of file diff --git a/interface/chandra/desktop/game-library/README.md b/interface/chandra/desktop/game-library/README.md new file mode 100644 index 0000000..3ce1241 --- /dev/null +++ b/interface/chandra/desktop/game-library/README.md @@ -0,0 +1,5 @@ +A game library (docs/gamerig-library.md): the games and apps a game-streaming rig offers, what +runs, and the rig's GPU, display and audio. The host gets all of it from gamerig's library +daemon (`GET /api/state` on 127.0.0.1:8091, or GAMERIG_DESKTOP_API), polled every couple of +seconds; the module never talks to the network itself. Launch, stop and focus go back to the +daemon, which starts games on the rig's X server. \ No newline at end of file diff --git a/interface/chandra/desktop/game-library/ffi.mbt b/interface/chandra/desktop/game-library/ffi.mbt new file mode 100644 index 0000000..33b8830 --- /dev/null +++ b/interface/chandra/desktop/game-library/ffi.mbt @@ -0,0 +1,54 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + +///| +fn wasmImportStatus(p0 : Int) = "chandra:desktop/game-library@0.1.0" "status" + +///| +fn wasmImportGames(p0 : Int) = "chandra:desktop/game-library@0.1.0" "games" + +///| +fn wasmImportLaunchModes(p0 : Int) = "chandra:desktop/game-library@0.1.0" "launch-modes" + +///| +fn wasmImportLaunch(p0 : Int, p1 : Int, p2 : Int, p3 : Int) = "chandra:desktop/game-library@0.1.0" "launch" + +///| +fn wasmImportStop(p0 : Int, p1 : Int) = "chandra:desktop/game-library@0.1.0" "stop" + +///| +fn wasmImportFocus(p0 : Int, p1 : Int) = "chandra:desktop/game-library@0.1.0" "focus" + +///| +fn wasmImportRefresh() = "chandra:desktop/game-library@0.1.0" "refresh" + +///| +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_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_ptr2str(ptr : Int, len : Int) -> String = +#|(func (param i32) (param i32) (result i32) +#| local.get 0 +#| local.get 1 call $moonbit.init_array16 +#| local.get 0) + +///| +extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = +#|(func (param i32) (result i32) (local i32) +#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc +#| local.tee 1 i32.const 0 call $moonbit.init_array8 +#| local.get 1) + diff --git a/interface/chandra/desktop/game-library/moon.pkg b/interface/chandra/desktop/game-library/moon.pkg new file mode 100644 index 0000000..e2a6033 --- /dev/null +++ b/interface/chandra/desktop/game-library/moon.pkg @@ -0,0 +1 @@ +warnings = "-44" diff --git a/interface/chandra/desktop/game-library/top.mbt b/interface/chandra/desktop/game-library/top.mbt new file mode 100644 index 0000000..4f49008 --- /dev/null +++ b/interface/chandra/desktop/game-library/top.mbt @@ -0,0 +1,129 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! +///| +pub(all) struct RigStatus { + error : String; gpu : String; resolution : String; display : String; audio : String; hostname : String; connected : Bool; audio_ok : Bool +} +///| +pub(all) struct Game { + id : String; name : String; category : String; description : String; icon : String; install_hint : String; featured : Bool; installed : Bool; running : Bool +} +///| +/// A way to start a game other than plain Launch (Steam's Big Picture). +pub(all) struct LaunchMode { + game : String; id : String; label : String +} +///| +pub fn status() -> RigStatus { + + let return_area = mbt_ffi_malloc(52) + wasmImportStatus(return_area); + + let result = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 0), mbt_ffi_load32((return_area) + 4)) + + let result0 = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 8), mbt_ffi_load32((return_area) + 12)) + + let result1 = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 16), mbt_ffi_load32((return_area) + 20)) + + let result2 = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 24), mbt_ffi_load32((return_area) + 28)) + + let result3 = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 32), mbt_ffi_load32((return_area) + 36)) + + let result4 = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 40), mbt_ffi_load32((return_area) + 44)) + let ret = RigStatus::{error : result, gpu : result0, resolution : result1, display : result2, audio : result3, hostname : result4, connected : (mbt_ffi_load8_u((return_area) + 48) != 0), audio_ok : (mbt_ffi_load8_u((return_area) + 49) != 0)} + mbt_ffi_free(return_area) + return ret + +} +///| +/// In catalog order. +pub fn games() -> Array[Game] { + + let return_area = mbt_ffi_malloc(8) + wasmImportGames(return_area); + + let array : Array[Game] = []; + for index = 0; index < (mbt_ffi_load32((return_area) + 4)); index = index + 1 { + let iter_base = (mbt_ffi_load32((return_area) + 0)) + (index * 52) + + 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 result1 = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 16), mbt_ffi_load32((iter_base) + 20)) + + let result2 = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 24), mbt_ffi_load32((iter_base) + 28)) + + let result3 = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 32), mbt_ffi_load32((iter_base) + 36)) + + let result4 = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 40), mbt_ffi_load32((iter_base) + 44)) + + array.push(Game::{id : result, name : result0, category : result1, description : result2, icon : result3, install_hint : result4, featured : (mbt_ffi_load8_u((iter_base) + 48) != 0), installed : (mbt_ffi_load8_u((iter_base) + 49) != 0), running : (mbt_ffi_load8_u((iter_base) + 50) != 0)}) + } + mbt_ffi_free(mbt_ffi_load32((return_area) + 0)) + let ret = array + mbt_ffi_free(return_area) + return ret + +} +///| +pub fn launch_modes() -> Array[LaunchMode] { + + let return_area = mbt_ffi_malloc(8) + wasmImportLaunchModes(return_area); + + let array : Array[LaunchMode] = []; + for index = 0; index < (mbt_ffi_load32((return_area) + 4)); index = index + 1 { + let iter_base = (mbt_ffi_load32((return_area) + 0)) + (index * 24) + + 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 result1 = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 16), mbt_ffi_load32((iter_base) + 20)) + + array.push(LaunchMode::{game : result, id : result0, label : result1}) + } + mbt_ffi_free(mbt_ffi_load32((return_area) + 0)) + let ret = array + mbt_ffi_free(return_area) + return ret + +} +///| +/// Start `game` (`mode` "default", or one of its launch modes). +pub fn launch(game : String, mode : String) -> Unit { + + let ptr = mbt_ffi_str2ptr(game) + + let ptr0 = mbt_ffi_str2ptr(mode) + wasmImportLaunch(ptr, game.length(), ptr0, mode.length()); + mbt_ffi_free(ptr) + mbt_ffi_free(ptr0) + +} +///| +/// Stop it (SIGTERM, then SIGKILL). +pub fn stop(game : String) -> Unit { + + let ptr = mbt_ffi_str2ptr(game) + wasmImportStop(ptr, game.length()); + mbt_ffi_free(ptr) + +} +///| +/// Raise its window over the desktop. +pub fn focus(game : String) -> Unit { + + let ptr = mbt_ffi_str2ptr(game) + wasmImportFocus(ptr, game.length()); + mbt_ffi_free(ptr) + +} +///| +/// Poll the daemon again now. +pub fn refresh() -> Unit { + + wasmImportRefresh(); + +} + diff --git a/interface/chandra/host/plasmoids/pkg.generated.mbti b/interface/chandra/host/plasmoids/pkg.generated.mbti index e5260dc..590859c 100644 --- a/interface/chandra/host/plasmoids/pkg.generated.mbti +++ b/interface/chandra/host/plasmoids/pkg.generated.mbti @@ -69,6 +69,12 @@ pub(all) struct ConfigItem { value : String } +pub(all) struct GameRequest { + action : Int32 + game : String + mode : String +} + pub(all) struct InstanceMove { slot : String delta : Int32 @@ -123,6 +129,7 @@ pub(all) enum Request { DefaultApp(Int32) SetDesktop(Int32) FaceUnlock(Int32) + GameLibrary(GameRequest) } pub(all) struct SettingChange { diff --git a/interface/chandra/host/plasmoids/top.mbt b/interface/chandra/host/plasmoids/top.mbt index a6853ed..c342260 100644 --- a/interface/chandra/host/plasmoids/top.mbt +++ b/interface/chandra/host/plasmoids/top.mbt @@ -30,6 +30,11 @@ pub(all) struct NetworkRequest { action : Int; ssid : String; password : String } ///| +/// A game library action: 0 launch (game, mode), 1 stop, 2 focus (game), 3 poll again. +pub(all) struct GameRequest { + action : Int; game : String; mode : String +} +///| /// A module moving a panel instance `delta` places (negative: towards the start). pub(all) struct InstanceMove { slot : String; delta : Int @@ -63,6 +68,7 @@ pub(all) enum Request { DefaultApp(Int) SetDesktop(Int) FaceUnlock(Int) + GameLibrary(GameRequest) } ///| /// A native file-chooser dialog (zenity on the host session) for "Add widget". @@ -428,7 +434,11 @@ pub fn desktop_tick(handle : UInt, now_ms : UInt) -> UInt { /// can-manage has-wifi), 9 Wi-Fi networks (siiii: ssid signal secured active saved), 10 keyboard /// shortcuts (ssssi: name binding default-binding conflict capturing), 11 default-app /// categories (sss: name current missing), 12 default-app choices (issii: category id name icon current), -/// 20 desktops (s: name) served by `wallpaper.desktops`. +/// 20 desktops (s: name) served by `wallpaper.desktops`, 24 face unlock status (sssiii: problem howdy +/// message installed in-use busy; one row), 25 enrolled faces (ss: label added), 26 game library status (one row, +/// ssssssii: error gpu resolution display audio hostname connected audio-ok), +/// 27 games (ssssssiii: id name category description icon install-hint featured installed running), +/// 28 launch modes (sss: game id label). pub fn publish_table(which : UInt, rows : FixedArray[Byte]) -> Unit { let ptr = mbt_ffi_bytes2ptr(rows) @@ -528,7 +538,7 @@ pub fn next_request() -> Request? { let return_area = mbt_ffi_malloc(28) wasmImportNextRequest(return_area); - let lifted5 : Request? = match mbt_ffi_load8_u((return_area) + 0) { + let lifted7 : Request? = match mbt_ffi_load8_u((return_area) + 0) { 0 => Option::None 1 => { @@ -629,6 +639,14 @@ pub fn next_request() -> Request? { Request::FaceUnlock(mbt_ffi_load32((return_area) + 8)) } + 21 => { + + let result5 = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 12), mbt_ffi_load32((return_area) + 16)) + + let result6 = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 20), mbt_ffi_load32((return_area) + 24)) + + Request::GameLibrary(GameRequest::{action : mbt_ffi_load32((return_area) + 8), game : result5, mode : result6}) + } _ => panic() } @@ -636,7 +654,7 @@ pub fn next_request() -> Request? { } _ => panic() } - let ret = lifted5 + let ret = lifted7 mbt_ffi_free(return_area) return ret diff --git a/lib/gamelib/gamelib_test.mbt b/lib/gamelib/gamelib_test.mbt new file mode 100644 index 0000000..589fce1 --- /dev/null +++ b/lib/gamelib/gamelib_test.mbt @@ -0,0 +1,171 @@ +///| A /api/state answer like gamerig's server.py gives. +let sample : String = + #|{"system": {"gpu": "NVIDIA GeForce GTX 1650", "resolution": "1920x1080", "display": ":0", + #| "audio": "PulseAudio (Selkies)", "audio_ok": true, "hostname": "rig"}, + #| "apps": [ + #| {"id": "steam", "name": "Steam", "category": "games", "featured": true, "icon": "Play", + #| "description": "Your Steam library, store and friends.", "installed": true, "running": false, + #| "modes": [{"id": "default", "label": "Launch"}, {"id": "bigpicture", "label": "Big Picture"}]}, + #| {"id": "lutris", "name": "Lutris", "category": "launchers", "icon": "Folder", + #| "description": "Open gaming platform.", "installed": false, "install_hint": "apt-get install lutris"}, + #| {"id": "terminal", "name": "Terminal", "category": "tools", "icon": "Terminal", + #| "description": "Interactive shell inside the rig.", "installed": true, "running": true, "pid": 42}, + #| {"name": "no id"} + #| ]} + +///| +fn sample_state() -> @gamelib.State { + match @gamelib.parse_state(sample) { + Ok(s) => s + Err(e) => abort(e) + } +} + +///| +fn tokens() -> @theme.Tokens { + let c = @ui.color(230, 230, 230, 255) + { + name: "dark", + 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: 8, + spacing: 8, + panel_height: 40, + } +} + +///| +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 +} + +///| +test "parse_state reads the rig, the games and their extra modes" { + let s = sample_state() + assert_eq(s.rig.gpu, "NVIDIA GeForce GTX 1650") + assert_true(s.rig.connected) + assert_true(s.rig.audio_ok) + assert_eq(s.games.map(g => g.id), ["steam", "lutris", "terminal"]) + assert_eq(s.modes, [{ game: "steam", id: "bigpicture", label: "Big Picture" }]) + assert_eq(s.games[1].install_hint, "apt-get install lutris") + assert_eq(s.games[2].status(), Running) + assert_true(@gamelib.parse_state("nope") is Err(_)) + assert_eq(@gamelib.error_message("{\"error\": \"unknown app\"}"), "unknown app") +} + +///| +test "filtering: categories, running, search words, featured first" { + let g = sample_state().games + assert_eq(@gamelib.count_in(g, All), 3) + assert_eq(@gamelib.count_in(g, Games), 1) + assert_eq(@gamelib.count_in(g, Running), 1) + assert_eq(@gamelib.filter_games(g, All, "shell rig").map(x => x.id), ["terminal"]) + assert_eq(@gamelib.filter_games(g, All, "").map(x => x.id), ["steam", "lutris", "terminal"]) + assert_eq(@gamelib.filter_games(g, Tools, "steam").length(), 0) +} + +///| +test "wrap and ellipsize keep to the width" { + let lines = @gamelib.wrap("one two three four five six seven", 60, 10, 2) + assert_eq(lines.length(), 2) + for l in lines { + assert_true(@gamelib.approx_width(l, 10) <= 60) + } + assert_true(lines[1].has_suffix("…")) + assert_eq(@gamelib.ellipsize("short", 100, 10), "short") +} + +///| +test "grid: featured cards span two columns, rows wrap" { + let g = sample_state().games + let (cells, total, cols) = @gamelib.grid_layout(g, 900) + assert_eq(cols, 3) + // steam (featured) two columns, lutris next to it, terminal on the next row. + assert_eq(cells[0].3 > cells[1].3, true) + assert_eq(cells[1].2, 0) + assert_true(cells[2].2 > 0) + assert_true(total >= cells[2].2 + cells[2].4) + // One column: nothing spans. + let (one, _, c1) = @gamelib.grid_layout(g, 300) + assert_eq(c1, 1) + assert_eq(one[0].3, one[1].3) +} + +///| +test "render shows the sidebar, the cards and the rig; clicks launch, stop and filter" { + let lib = @gamelib.Library::new() + let s = sample_state() + let size : @types.Size = { w: 1600, h: 1000 } + let ops = lib.render(s.games, s.modes, s.rig, size, tokens()) + let t = texts(ops) + for want in ["Gamerig", "Library", "Games", "Running Apps", "Rig Status", "Steam", "Big Picture", "Switch to", "Stop", "Not installed", "All apps"] { + assert_true(t.contains(want), msg="missing " + want) + } + assert_true(t.iter().any(x => x.has_prefix("NVIDIA GeForce"))) + let click = (h : @gamelib.Hit) => { + for reg in lib.regions { + if reg.1 == h { + let p : @types.Point = { x: reg.0.x + 2, y: reg.0.y + 2 } + ignore(lib.handle(PointerDown(p))) + return lib.handle(PointerUp(p)).1 + } + } + abort("no region") + } + assert_eq(click(Button("steam", "bigpicture")), Launch("steam", "bigpicture")) + assert_eq(click(Button("steam", "default")), Launch("steam", "default")) + assert_eq(click(StopButton("terminal")), Stop("terminal")) + assert_eq(click(RunningRow("terminal")), Focus("terminal")) + assert_eq(click(RefreshButton), Refresh) + assert_eq(click(Cat(Tools)), NoAction) + assert_eq(lib.category, Tools) + let t = texts(lib.render(s.games, s.modes, s.rig, size, tokens())) + assert_false(t.contains("Steam")) + assert_true(t.contains("Terminal")) +} + +///| +test "typing filters, Enter launches the selection, Escape clears" { + let lib = @gamelib.Library::new() + let s = sample_state() + let size : @types.Size = { w: 1280, h: 720 } + ignore(lib.render(s.games, s.modes, s.rig, size, tokens())) + for k in ["l", "u", "t"] { + ignore(lib.handle(KeyDown(k))) + } + assert_eq(lib.query, "lut") + ignore(lib.render(s.games, s.modes, s.rig, size, tokens())) + ignore(lib.handle(KeyDown("Right"))) + assert_eq(lib.selected, "lutris") + assert_eq(lib.handle(KeyDown("Enter")).1, Launch("lutris", "default")) + ignore(lib.handle(KeyDown("Backspace"))) + assert_eq(lib.query, "lu") + ignore(lib.handle(KeyDown("Escape"))) + assert_eq(lib.query, "") +} + +///| +test "disconnected: says it is waiting, and the error" { + let lib = @gamelib.Library::new() + let rig = { ..@gamelib.Rig::unknown(), error: "Library daemon not reachable" } + let t = texts(lib.render([], [], rig, { w: 1280, h: 720 }, tokens())) + assert_true(t.contains("Waiting for the library daemon…")) + assert_true(t.contains("Library daemon not reachable")) +} diff --git a/lib/gamelib/model.mbt b/lib/gamelib/model.mbt new file mode 100644 index 0000000..8bcd9d5 --- /dev/null +++ b/lib/gamelib/model.mbt @@ -0,0 +1,319 @@ +///| The Gamerig Library desktop module's data (components/gamerig-library): what gamerig's library +/// daemon reports at `GET /api/state` (gamerig docker/desktop/server.py), and how the library +/// sorts it into categories and searches it. The same types serve the shell, which polls the daemon +/// and parses its JSON here (`parse_state`), and the module, which gets them back through the +/// `game-library` capability. + +///| A sidebar filter. `Running` is not a category of the catalog but a view of what runs now. +#derive(Eq, Debug) +pub(all) enum Category { + All + Games + Launchers + Tools + Running +} + +///| +pub let categories : Array[Category] = [All, Games, Launchers, Tools, Running] + +///| +pub fn Category::key(self : Category) -> String { + match self { + All => "all" + Games => "games" + Launchers => "launchers" + Tools => "tools" + Running => "running" + } +} + +///| +pub fn Category::label(self : Category) -> String { + match self { + All => "All" + Games => "Games" + Launchers => "Launchers" + Tools => "Tools" + Running => "Running" + } +} + +///| The heading over the grid ("All apps", "Games" ...). +pub fn Category::title(self : Category) -> String { + match self { + All => "All apps" + Running => "Running now" + c => c.label() + } +} + +///| +pub fn Category::parse(key : String) -> Category { + match key.trim().to_owned().to_lower() { + "games" | "game" => Games + "launchers" | "launcher" => Launchers + "tools" | "tool" => Tools + "running" => Running + _ => All + } +} + +///| The singular label of a game's own category, for its badge. +pub fn category_badge(key : String) -> String { + match Category::parse(key) { + Games => "Game" + Launchers => "Launcher" + Tools => "Tool" + _ => "App" + } +} + +///| One game or app of the library. +#derive(Eq, Debug) +pub(all) struct Game { + id : String + name : String + category : String + description : String + icon : String + install_hint : String + featured : Bool + installed : Bool + running : Bool +} + +///| A way to start `game` other than plain Launch (Steam's Big Picture). +#derive(Eq, Debug) +pub(all) struct Mode { + game : String + id : String + label : String +} + +///| The rig, as the library daemon describes it. +#derive(Eq, Debug) +pub(all) struct Rig { + connected : Bool + error : String + gpu : String + resolution : String + display : String + audio : String + audio_ok : Bool + hostname : String +} + +///| Before the daemon first answered. +pub fn Rig::unknown() -> Rig { + { + connected: false, + error: "", + gpu: "Detecting GPU…", + resolution: "—", + display: "—", + audio: "Detecting audio…", + audio_ok: false, + hostname: "", + } +} + +///| What a card says about its game. +#derive(Eq, Debug) +pub(all) enum Status { + Running + Ready + NotInstalled +} + +///| +pub fn Game::status(self : Game) -> Status { + if self.running { + Running + } else if self.installed { + Ready + } else { + NotInstalled + } +} + +///| +pub fn Status::label(self : Status) -> String { + match self { + Running => "Running" + Ready => "Ready" + NotInstalled => "Not installed" + } +} + +///| Everything `GET /api/state` says. +#derive(Eq, Debug) +pub(all) struct State { + rig : Rig + games : Array[Game] + modes : Array[Mode] +} + +// --------------------------------------------------------------------------- +// JSON (gamerig desktop/ui/library parse_state, in Chandra's types) + +///| +fn str_field(obj : Map[String, Json], key : String, fallback : String) -> String { + match obj.get(key) { + Some(String(s)) => s + Some(Number(n, ..)) => n.to_int().to_string() + _ => fallback + } +} + +///| +fn bool_field(obj : Map[String, Json], key : String) -> Bool { + match obj.get(key) { + Some(True) => true + Some(String("true")) => true + Some(Number(n, ..)) => n != 0.0 + _ => false + } +} + +///| One game from its JSON, and its extra launch modes. Without an id there is nothing to act on. +fn parse_game(j : Json, modes : Array[Mode]) -> Game? { + guard j is Object(m) else { return None } + let id = str_field(m, "id", "") + if id == "" { + return None + } + if m.get("modes") is Some(Array(items)) { + for item in items { + if item is Object(md) { + let mid = str_field(md, "id", "") + if mid != "" && mid != "default" { + modes.push({ game: id, id: mid, label: str_field(md, "label", mid) }) + } + } + } + } + Some({ + id, + name: str_field(m, "name", id), + category: str_field(m, "category", "tools").to_lower(), + description: str_field(m, "description", ""), + icon: str_field(m, "icon", ""), + install_hint: str_field(m, "install_hint", ""), + featured: bool_field(m, "featured"), + installed: bool_field(m, "installed"), + running: bool_field(m, "running"), + }) +} + +///| +fn parse_rig(v : Json?) -> Rig { + let base = Rig::unknown() + guard v is Some(Object(m)) else { return { ..base, connected: true } } + { + connected: true, + error: "", + gpu: str_field(m, "gpu", base.gpu), + resolution: str_field(m, "resolution", base.resolution), + display: str_field(m, "display", base.display), + audio: str_field(m, "audio", base.audio), + audio_ok: bool_field(m, "audio_ok"), + hostname: str_field(m, "hostname", ""), + } +} + +///| Parse the body of `GET /api/state`. +pub fn parse_state(body : String) -> Result[State, String] { + let j = @json.parse(body) catch { + e => return Err("Invalid answer from the library daemon: \{e}") + } + guard j is Object(m) else { + return Err("The library daemon answered with something other than an object") + } + let games : Array[Game] = [] + let modes : Array[Mode] = [] + if m.get("apps") is Some(Array(items)) { + for item in items { + if parse_game(item, modes) is Some(g) { + games.push(g) + } + } + } + Ok({ rig: parse_rig(m.get("system")), games, modes }) +} + +///| The daemon's `{"error": "..."}`, or the body itself when it is not one. +pub fn error_message(body : String) -> String { + let j = @json.parse(body) catch { _ => return body.trim().to_owned() } + match j { + Object(m) => + match m.get("error") { + Some(String(s)) => s + _ => body + } + _ => body + } +} + +// --------------------------------------------------------------------------- +// Filtering + +///| +fn in_category(g : Game, cat : Category) -> Bool { + match cat { + All => true + Running => g.running + c => g.category == c.key() + } +} + +///| +fn matches_query(g : Game, query : String) -> Bool { + let q = query.trim().to_owned().to_lower() + if q == "" { + return true + } + let hay = "\{g.name} \{g.id} \{g.category} \{g.description}".to_lower() + for word in q.split(" ") { + let w = word.to_owned() + if w != "" && hay.find(w) is None { + return false + } + } + true +} + +///| The cards to show: in the category, matching every word of the search, featured games first +/// and otherwise in catalog order. +pub fn filter_games(games : Array[Game], category : Category, query : String) -> Array[Game] { + let picked = games.filter(g => in_category(g, category) && matches_query(g, query)) + let featured = picked.filter(g => g.featured) + let rest = picked.filter(g => !g.featured) + [..featured, ..rest] +} + +///| +pub fn count_in(games : Array[Game], category : Category) -> Int { + games.filter(g => in_category(g, category)).length() +} + +///| `game`'s extra launch modes. +pub fn modes_of(modes : Array[Mode], game : String) -> Array[Mode] { + modes.filter(m => m.game == game) +} + +///| A non-negative decimal number (an HTTP status), 0 when `s` isn't one. +pub fn parse_int(s : String) -> Int { + let t = s.trim() + if t.length() == 0 || t.length() > 9 { + return 0 + } + let mut v = 0 + for ch in t { + if ch < '0' || ch > '9' { + return 0 + } + v = v * 10 + (ch.to_int() - '0'.to_int()) + } + v +} diff --git a/lib/gamelib/moon.pkg b/lib/gamelib/moon.pkg new file mode 100644 index 0000000..ad53d05 --- /dev/null +++ b/lib/gamelib/moon.pkg @@ -0,0 +1,6 @@ +import { + "moonbitlang/core/json", + "chandra/desktop/interface/chandra/desktop/types" @types, + "chandra/desktop/interface/chandra/desktop/theme" @theme, + "chandra/desktop/lib/ui" @ui, +} diff --git a/lib/gamelib/view.mbt b/lib/gamelib/view.mbt new file mode 100644 index 0000000..2846c94 --- /dev/null +++ b/lib/gamelib/view.mbt @@ -0,0 +1,997 @@ +///| The Gamerig Library desktop: gamerig's library window (desktop/ui, the WebKit page) drawn as +/// Chandra draw ops. The layout follows it: a top bar with the Gamerig mark, the title and the +/// search box; a sidebar with the categories and their counts, the running games and the rig's +/// status; and a grid of cards, featured games two columns wide, each with its icon, name, +/// category and status badges, description, install hint and buttons (Launch, the extra modes such +/// as Big Picture; Switch to and Stop while it runs). +/// +/// Input: a click on a button acts on its card; a click on a card selects it. Typing filters +/// (while the desktop has the keyboard), Backspace and Escape edit the search, arrows move the +/// selection, Enter launches it (or switches to it when it runs), the wheel scrolls the grid. +/// +/// Pure: the component hands in the data, the size, the theme and the events, and carries out the +/// `Action` this returns. + +///| What the module asks of the host after an event. +#derive(Eq, Debug) +pub(all) enum Action { + NoAction + Launch(String, String) + Stop(String) + Focus(String) + Refresh +} + +///| What is under the pointer. +#derive(Eq, Debug) +pub(all) enum Hit { + NoHit + Cat(Category) + Search + ClearSearch + RefreshButton + Card(String) + Button(String, String) + StopButton(String) + FocusButton(String) + RunningRow(String) + RunningStop(String) +} + +///| One item of the module's right-click settings (the `module-config` record). +#derive(Eq, Debug) +pub(all) struct ConfigEntry { + key : String + label : String + choices : Array[String] + value : String +} + +///| +pub let colors_choices : Array[String] = ["Follow desktop", "Dark", "Light"] + +///| Gamerig's colours. +pub(all) struct Pal { + bg : @types.Color + panel : @types.Color + card : @types.Color + card_hover : @types.Color + row_sel : @types.Color + border : @types.Color + fg : @types.Color + muted : @types.Color + faint : @types.Color + accent : @types.Color + accent_fg : @types.Color + ok : @types.Color + ok_bg : @types.Color + badge_bg : @types.Color + badge_fg : @types.Color + warn : @types.Color + dark : Bool +} + +///| +fn c(r : Int, g : Int, b : Int) -> @types.Color { + @ui.color(r, g, b, 255) +} + +///| +pub fn Pal::dark() -> Pal { + { + bg: c(24, 26, 35), + panel: c(33, 35, 47), + card: c(41, 43, 58), + card_hover: c(48, 51, 68), + row_sel: c(49, 52, 70), + border: c(52, 55, 74), + fg: c(234, 235, 241), + muted: c(156, 159, 178), + faint: c(118, 121, 140), + accent: c(246, 183, 46), + accent_fg: c(27, 29, 38), + ok: c(74, 222, 128), + ok_bg: c(30, 58, 46), + badge_bg: c(54, 57, 75), + badge_fg: c(188, 191, 206), + warn: c(251, 146, 60), + dark: true, + } +} + +///| +pub fn Pal::light() -> Pal { + { + bg: c(236, 238, 244), + panel: c(247, 248, 251), + card: c(255, 255, 255), + card_hover: c(244, 246, 251), + row_sel: c(228, 231, 240), + border: c(221, 224, 233), + fg: c(29, 32, 46), + muted: c(103, 108, 126), + faint: c(140, 145, 160), + accent: c(246, 183, 46), + accent_fg: c(27, 29, 38), + ok: c(21, 128, 61), + ok_bg: c(220, 252, 231), + badge_bg: c(236, 238, 243), + badge_fg: c(75, 80, 96), + warn: c(194, 65, 12), + dark: false, + } +} + +///| The library's state between calls. +pub(all) struct Library { + mut category : Category + mut query : String + /// Pixels the grid is scrolled down. + mut scroll : Int + mut hover : Hit + mut press : Hit + /// The selected card (keyboard), by game id; "" none. + mut selected : String + mut focused : Bool + mut colors : String + /// From the last render: where things are, the cards in order with their columns, and the + /// grid's height and viewport (for the wheel). + regions : Array[(@types.Rect, Hit)] + mut shown : Array[(String, Int, Int)] + mut content_h : Int + mut view_h : Int + mut games : Array[Game] +} + +///| +pub fn Library::new() -> Library { + { + category: All, + query: "", + scroll: 0, + hover: NoHit, + press: NoHit, + selected: "", + focused: false, + colors: "Follow desktop", + regions: [], + shown: [], + content_h: 0, + view_h: 0, + games: [], + } +} + +///| The one instance the component drives. +pub let state : Library = Library::new() + +///| Text sizes. +let fs : Int = 14 + +///| +let fs_small : Int = 12 + +///| +let top_h : Int = 56 + +///| +let card_min_w : Int = 280 + +///| +let gap : Int = 16 + +///| Roughly how wide `s` is in the desktop's proportional UI font: about 0.53 em a character +/// (the 0.6 em of `@ui.text_width` is the monospace upper bound and leaves lines half empty). +pub fn approx_width(s : String, size : Int) -> Int { + s.length() * size * 53 / 100 +} + +///| Narrower than `w` at `size`? +fn fits(s : String, w : Int, size : Int) -> Bool { + approx_width(s, size) <= w +} + +///| `s` cut to `w` pixels with an ellipsis. +pub fn ellipsize(s : String, w : Int, size : Int) -> String { + if fits(s, w, size) { + return s + } + let chars = s.to_array() + let mut n = chars.length() + while n > 0 && !fits(String::from_array(chars[:n].to_owned()) + "…", w, size) { + n = n - 1 + } + String::from_array(chars[:n].to_owned()).trim_end().to_owned() + "…" +} + +///| `s` broken into lines of at most `w` pixels, at most `max` lines (the last one ellipsized). +pub fn wrap(s : String, w : Int, size : Int, max : Int) -> Array[String] { + let out : Array[String] = [] + let mut line = "" + let words = s.split(" ").map(x => x.to_owned()).filter(x => x != "").collect() + let mut i = 0 + while i < words.length() { + let word = words[i] + let cand = if line == "" { word } else { line + " " + word } + if fits(cand, w, size) || line == "" { + line = cand + i = i + 1 + } else { + out.push(line) + line = "" + if out.length() == max { + break + } + } + } + if line != "" && out.length() < max { + out.push(line) + } else if out.length() == max && i < words.length() { + // More left: say so on the last line. + out[max - 1] = ellipsize(out[max - 1] + " " + words[i], w, size) + } + out.map(l => ellipsize(l, w, size)) +} + +///| The palette for the colours setting and the desktop theme. +fn Library::pal(self : Library, tokens : @theme.Tokens) -> Pal { + match self.colors { + "Dark" => Pal::dark() + "Light" => Pal::light() + _ => { + let f = tokens.palette.foreground + if f.r.to_int() + f.g.to_int() + f.b.to_int() > 384 { + Pal::dark() + } else { + Pal::light() + } + } + } +} + +///| (background, glyph colour) of an icon tile, after gamerig's tinted tiles. +fn tile_colors(icon : String, p : Pal) -> (@types.Color, @types.Color) { + let (r, g, b) = match icon { + "Play" => (251, 113, 133) + "Sparkles" | "Star" | "ExternalLink" => (167, 139, 250) + "Settings" => (96, 165, 250) + "Folder" | "Square" | "Terminal" => (251, 146, 60) + _ => (45, 212, 191) + } + if p.dark { + (@ui.color(r / 4 + 22, g / 4 + 22, b / 4 + 30, 255), c(r, g, b)) + } else { + (@ui.color(255 - (255 - r) / 6, 255 - (255 - g) / 6, 255 - (255 - b) / 6, 255), @ui.color(r * 3 / 4, g * 3 / 4, b * 3 / 4, 255)) + } +} + +///| A line-drawn icon in the square at (x, y) of side `s`, after the lucide icons gamerig uses. +pub fn draw_glyph(ops : Array[@types.DrawOp], name : String, x : Int, y : Int, s : Int, col : @types.Color, letter~ : String = "") -> Unit { + let w = if s >= 24 { 2 } else { 1 } + let l = (x0, y0, x1, y1) => ops.push(@ui.line(x + x0 * s / 24, y + y0 * s / 24, x + x1 * s / 24, y + y1 * s / 24, col, width=w)) + match name { + "Play" => { + l(7, 4, 7, 20) + l(7, 4, 19, 12) + l(7, 20, 19, 12) + } + "Sparkles" => { + l(10, 3, 10, 17) + l(3, 10, 17, 10) + l(10, 3, 12, 8) + l(12, 8, 17, 10) + l(17, 10, 12, 12) + l(12, 12, 10, 17) + l(10, 17, 8, 12) + l(8, 12, 3, 10) + l(3, 10, 8, 8) + l(8, 8, 10, 3) + l(19, 3, 19, 7) + l(17, 5, 21, 5) + l(5, 18, 5, 21) + } + "Folder" => { + l(3, 6, 3, 19) + l(3, 19, 21, 19) + l(21, 19, 21, 8) + l(21, 8, 12, 8) + l(12, 8, 10, 5) + l(10, 5, 3, 5) + l(3, 5, 3, 6) + } + "Star" => { + let pts = [(12, 2), (14, 9), (22, 9), (16, 14), (18, 21), (12, 17), (6, 21), (8, 14), (2, 9), (10, 9)] + for i in 0.. + ops.push(@ui.stroke_rect(@ui.rect(x + s * 4 / 24, y + s * 4 / 24, s * 16 / 24, s * 16 / 24), col, width=w, radius=s / 10)) + "Terminal" => { + l(4, 7, 10, 12) + l(10, 12, 4, 17) + l(12, 18, 20, 18) + } + "Settings" => { + ops.push(@ui.circle(x + s / 2, y + s / 2, s * 8 / 24, col, filled=false)) + ops.push(@ui.circle(x + s / 2, y + s / 2, s * 3 / 24, col, filled=false)) + for d in [(12, 1, 12, 4), (12, 20, 12, 23), (1, 12, 4, 12), (20, 12, 23, 12)] { + l(d.0, d.1, d.2, d.3) + } + } + "ExternalLink" => { + l(4, 7, 4, 20) + l(4, 20, 17, 20) + l(17, 20, 17, 13) + l(4, 7, 11, 7) + l(13, 4, 20, 4) + l(20, 4, 20, 11) + l(20, 4, 10, 14) + } + "Home" => { + l(3, 11, 12, 3) + l(12, 3, 21, 11) + l(5, 9, 5, 21) + l(5, 21, 19, 21) + l(19, 21, 19, 9) + l(10, 21, 10, 14) + l(10, 14, 14, 14) + l(14, 14, 14, 21) + } + "Wrench" => { + ops.push(@ui.circle(x + s * 16 / 24, y + s * 8 / 24, s * 5 / 24, col, filled=false)) + l(13, 11, 4, 20) + l(4, 20, 6, 22) + l(6, 22, 15, 13) + } + "Running" => { + ops.push(@ui.circle(x + s / 2, y + s / 2, s * 9 / 24, col, filled=false)) + ops.push(@ui.circle(x + s / 2, y + s / 2, s * 3 / 24, col)) + } + "Search" => { + ops.push(@ui.circle(x + s * 10 / 24, y + s * 10 / 24, s * 7 / 24, col, filled=false)) + l(15, 15, 21, 21) + } + "Refresh" => { + ops.push(@ui.circle(x + s / 2, y + s / 2, s * 8 / 24, col, filled=false)) + l(16, 3, 20, 5) + l(20, 5, 18, 9) + } + "Monitor" => { + ops.push(@ui.stroke_rect(@ui.rect(x + s * 2 / 24, y + s * 3 / 24, s * 20 / 24, s * 14 / 24), col, width=w, radius=s / 12)) + l(8, 21, 16, 21) + l(12, 17, 12, 21) + } + "Speaker" => { + l(3, 9, 3, 15) + l(3, 9, 7, 9) + l(3, 15, 7, 15) + l(7, 9, 12, 4) + l(7, 15, 12, 20) + l(12, 4, 12, 20) + l(16, 9, 18, 12) + l(18, 12, 16, 15) + } + "Info" => { + ops.push(@ui.circle(x + s / 2, y + s / 2, s * 9 / 24, col, filled=false)) + l(12, 11, 12, 17) + ops.push(@ui.circle(x + s / 2, y + s * 8 / 24, 1, col)) + } + "Stop" => ops.push(@ui.fill_rect(@ui.rect(x + s * 6 / 24, y + s * 6 / 24, s * 12 / 24, s * 12 / 24), col, radius=2)) + "Close" => { + l(6, 6, 18, 18) + l(18, 6, 6, 18) + } + _ => { + let t = if letter == "" { "?" } else { letter } + ops.push(@ui.text(x + s / 2, y + s / 2, t, s * 2 / 3, col, align=CENTER, bold=true)) + } + } +} + +///| A rounded pill badge at (x, y) (its left edge, top); returns its width. +fn badge(ops : Array[@types.DrawOp], x : Int, y : Int, label : String, bg : @types.Color, fg : @types.Color) -> Int { + let w = approx_width(label, fs_small) * 12 / 10 + 18 + ops.push(@ui.fill_rect(@ui.rect(x, y, w, 22), bg, radius=11)) + ops.push(@ui.text(x + 8, y + 11, label, fs_small, fg, bold=true)) + w +} + +///| A button: (x, y) its top-left; returns its width. `primary` is gamerig's gold Launch. +fn Library::button( + self : Library, + ops : Array[@types.DrawOp], + x : Int, + y : Int, + label : String, + glyph : String, + primary : Bool, + hit : Hit, + p : Pal, +) -> Int { + let w = approx_width(label, fs_small + 1) * 11 / 10 + 42 + let r = @ui.rect(x, y, w, 30) + let hov = self.hover == hit + let (bg, fg) = if primary { + (if hov { @ui.lerp_color(p.accent, c(255, 255, 255), 2, 10) } else { p.accent }, p.accent_fg) + } else { + (if hov { p.row_sel } else { @ui.with_alpha(p.badge_bg, 0) }, p.fg) + } + ops.push(@ui.fill_rect(r, bg, radius=15)) + if !primary { + ops.push(@ui.stroke_rect(r, p.border, radius=15)) + } + draw_glyph(ops, glyph, x + 10, y + 7, 16, fg) + ops.push(@ui.text(x + 32, y + 15, label, fs_small + 1, fg, bold=true)) + self.regions.push((r, hit)) + w +} + +///| Height of a card `w` wide: header, description, hint and buttons. +fn card_height(g : Game, w : Int) -> Int { + let inner = w - 40 + let desc = wrap(g.description, inner, fs, 3).length() + let hint = if g.installed || g.install_hint == "" { 0 } else { wrap(g.install_hint, inner - 20, fs_small, 3).length() } + 20 + 48 + 14 + desc * 22 + (if hint > 0 { 10 + hint * 18 } else { 0 }) + 20 + 30 + 20 +} + +///| Place the cards: (game index, x, y, w, h) in grid coordinates (0, 0 at the grid's top-left), +/// featured games two columns wide when there are two, rows as tall as their tallest card. +pub fn grid_layout(games : Array[Game], inner_w : Int) -> (Array[(Int, Int, Int, Int, Int)], Int, Int) { + let cols = { + let n = (inner_w + gap) / (card_min_w + gap) + if n < 1 { 1 } else { n } + } + let col_w = (inner_w - gap * (cols - 1)) / cols + let out : Array[(Int, Int, Int, Int, Int)] = [] + let mut col = 0 + let mut y = 0 + let mut row : Array[Int] = [] + let flush = (row : Array[Int], y : Int) => { + let mut h = 0 + for k in row { + if out[k].4 > h { + h = out[k].4 + } + } + for k in row { + let (i, x, ry, w, _) = out[k] + out[k] = (i, x, ry, w, h) + } + y + h + gap + } + for i, g in games { + let span = if g.featured && cols >= 2 { 2 } else { 1 } + if col + span > cols { + y = flush(row, y) + row = [] + col = 0 + } + let w = col_w * span + gap * (span - 1) + out.push((i, col * (col_w + gap), y, w, card_height(g, w))) + row.push(out.length() - 1) + col = col + span + } + let total = if row.length() > 0 { flush(row, y) - gap } else { 0 } + (out, total, cols) +} + +///| Draw the whole library for an output `size`. +pub fn Library::render( + self : Library, + games : Array[Game], + modes : Array[Mode], + rig : Rig, + size : @types.Size, + tokens : @theme.Tokens, +) -> Array[@types.DrawOp] { + let p = self.pal(tokens) + let w = size.w.reinterpret_as_int() + let h = size.h.reinterpret_as_int() + let bottom = tokens.panel_height.reinterpret_as_int() + self.regions.clear() + self.games = games + let ops : Array[@types.DrawOp] = [] + ops.push(@ui.fill_rect(@ui.rect(0, 0, w, h), p.bg)) + let side_w = if w >= 1100 { 272 } else if w >= 700 { 220 } else { 0 } + let main_x = if side_w > 0 { side_w + 16 } else { 8 } + let body_h = h - top_h - bottom - 8 + // ---- top bar ---- + ops.push(@ui.fill_rect(@ui.rect(20, 14, 28, 28), p.accent, radius=7)) + draw_glyph(ops, "Monitor", 25, 19, 18, p.accent_fg) + ops.push(@ui.text(58, 28, "Gamerig", 16, p.fg, bold=true)) + ops.push(@ui.text(main_x + 12, 20, "Library", fs, p.fg, bold=true)) + let n = games.length() + ops.push(@ui.text(main_x + 12, 38, n.to_string() + (if n == 1 { " app" } else { " apps" }), fs_small, p.muted)) + let sw = if w - main_x > 700 { 288 } else { 200 } + let sx = w - 20 - sw + let sr = @ui.rect(sx, 10, sw, 36) + ops.push(@ui.fill_rect(sr, p.panel, radius=8)) + ops.push(@ui.stroke_rect(sr, if self.focused { p.accent } else { p.border }, radius=8)) + draw_glyph(ops, "Search", sx + 12, 20, 16, p.muted) + if self.query == "" { + ops.push(@ui.text(sx + 36, 28, if self.focused { "Type to filter apps…" } else { "Filter apps…" }, fs, p.faint)) + } else { + let shown = ellipsize(self.query, sw - 76, fs) + ops.push(@ui.text(sx + 36, 28, shown, fs, p.fg)) + let cx = sx + 36 + approx_width(shown, fs) + 1 + if self.focused { + ops.push(@ui.line(cx, 19, cx, 37, p.accent, width=2)) + } + let cr = @ui.rect(sx + sw - 30, 16, 24, 24) + draw_glyph(ops, "Close", sx + sw - 26, 20, 16, if self.hover == ClearSearch { p.fg } else { p.muted }) + self.regions.push((cr, ClearSearch)) + } + self.regions.push((sr, Search)) + // Hints, left of the search box, when there is room. + let hx = sx - 16 + if hx - (main_x + 140) > 220 { + let mut x = hx + for part in [("Switch", ["Alt", "Tab"])] { + let (label, keys) = part + x = x - approx_width(label, fs_small) + ops.push(@ui.text(x, 28, label, fs_small, p.muted)) + x = x - 6 + for k in keys.rev() { + let kw = approx_width(k, fs_small) + 10 + x = x - kw + ops.push(@ui.fill_rect(@ui.rect(x, 18, kw, 20), p.badge_bg, radius=4)) + ops.push(@ui.text(x + 5, 28, k, fs_small, p.badge_fg, bold=true)) + x = x - 4 + } + } + } + // ---- sidebar ---- + if side_w > 0 { + self.render_sidebar(ops, games, rig, 8, top_h, side_w, body_h, p) + } + // ---- main ---- + let mw = w - main_x - 8 + let mr = @ui.rect(main_x, top_h, mw, body_h) + ops.push(@ui.fill_rect(mr, p.panel, radius=12)) + let shown = filter_games(games, self.category, self.query) + ops.push(@ui.text(main_x + 24, top_h + 32, self.category.title(), 16, p.fg, bold=true)) + let sub = if rig.error != "" { + rig.error + } else { + shown.length().to_string() + " of " + count_in(games, self.category).to_string() + " apps" + + (if self.query != "" { " matching “" + self.query + "”" } else { "" }) + } + ops.push(@ui.text(main_x + 24, top_h + 58, ellipsize(sub, mw - 160, fs), fs, if rig.error != "" { p.warn } else { p.muted })) + let rr = @ui.rect(main_x + mw - 104, top_h + 18, 84, 28) + if self.hover == RefreshButton { + ops.push(@ui.fill_rect(rr, p.row_sel, radius=8)) + } + draw_glyph(ops, "Refresh", main_x + mw - 96, top_h + 24, 16, p.muted) + ops.push(@ui.text(main_x + mw - 74, top_h + 32, "Refresh", fs_small + 1, p.muted, bold=true)) + self.regions.push((rr, RefreshButton)) + let gx = main_x + 24 + let gy = top_h + 88 + let gw = mw - 48 + let gh = body_h - 88 - 16 + let (cells, total, cols) = grid_layout(shown, gw) + self.content_h = total + self.view_h = gh + self.clamp_scroll() + self.shown = cells.map(cell => (shown[cell.0].id, cell.1 / ((gw - gap * (cols - 1)) / cols + gap), cell.2)) + if self.selected != "" && !shown.iter().any(g => g.id == self.selected) { + self.selected = "" + } + ops.push(@types.DrawOp::PushClip(@ui.rect(gx - 4, gy - 4, gw + 8, gh + 8))) + if shown.length() == 0 { + let msg = if games.length() == 0 { + if rig.connected { "The library is empty." } else { "Waiting for the library daemon…" } + } else if self.category == Running && self.query == "" { + "Nothing running. Launch something!" + } else { + "No apps match." + } + ops.push(@ui.text(gx + gw / 2, gy + 60, msg, fs, p.muted, align=CENTER)) + } + for cell in cells { + let (i, x, y, cw, ch) = cell + let y = gy + y - self.scroll + if y + ch < gy - 8 || y > gy + gh + 8 { + continue + } + self.render_card(ops, shown[i], modes_of(modes, shown[i].id), gx + x, y, cw, ch, p, gy, gh) + } + ops.push(@types.DrawOp::PopClip) + // A scrollbar when the grid is taller than its view. + if total > gh && gh > 0 { + let th = if gh * gh / total < 32 { 32 } else { gh * gh / total } + let ty = gy + (gh - th) * self.scroll / (total - gh) + ops.push(@ui.fill_rect(@ui.rect(main_x + mw - 10, ty, 4, th), @ui.with_alpha(p.muted, 120), radius=2)) + } + ops +} + +///| +fn Library::render_sidebar( + self : Library, + ops : Array[@types.DrawOp], + games : Array[Game], + rig : Rig, + x : Int, + y : Int, + w : Int, + h : Int, + p : Pal, +) -> Unit { + ops.push(@ui.fill_rect(@ui.rect(x, y, w, h), p.panel, radius=12)) + ops.push(@ui.text(x + 16, y + 18, "Library", fs_small, p.muted, bold=true)) + let mut ry = y + 32 + for cat in categories { + let r = @ui.rect(x + 8, ry, w - 16, 36) + let sel = self.category == cat + if sel { + ops.push(@ui.fill_rect(r, p.row_sel, radius=8)) + } else if self.hover == Cat(cat) { + ops.push(@ui.fill_rect(r, @ui.with_alpha(p.row_sel, 140), radius=8)) + } + let glyph = match cat { + All => "Home" + Games => "Play" + Launchers => "Folder" + Tools => "Wrench" + Running => "Running" + } + let fg = if sel { p.fg } else { p.muted } + draw_glyph(ops, glyph, x + 18, ry + 9, 18, fg) + ops.push(@ui.text(x + 46, ry + 18, cat.label(), fs + 1, if sel { p.fg } else { @ui.lerp_color(p.muted, p.fg, 1, 2) }, bold=sel)) + ops.push(@ui.text(x + w - 18, ry + 18, count_in(games, cat).to_string(), fs_small, p.muted, align=RIGHT)) + self.regions.push((r, Cat(cat))) + ry = ry + 38 + } + ry = ry + 14 + ops.push(@ui.text(x + 16, ry, "Running Apps", fs_small, p.muted, bold=true)) + ry = ry + 16 + let running = games.filter(g => g.running) + if running.length() == 0 { + ops.push(@ui.text(x + 18, ry + 14, "Nothing running. Launch something!", fs_small, p.muted)) + ry = ry + 30 + } + let status_top = y + h - 108 + for g in running { + if ry + 32 > status_top - 8 { + break + } + let r = @ui.rect(x + 8, ry, w - 16, 32) + if self.hover == RunningRow(g.id) || self.hover == RunningStop(g.id) { + ops.push(@ui.fill_rect(r, p.row_sel, radius=8)) + } + ops.push(@ui.circle(x + 22, ry + 16, 4, p.ok)) + ops.push(@ui.text(x + 34, ry + 16, ellipsize(g.name, w - 90, fs), fs, p.fg)) + let sr = @ui.rect(x + w - 40, ry + 4, 24, 24) + draw_glyph(ops, "Close", x + w - 36, ry + 8, 16, if self.hover == RunningStop(g.id) { p.warn } else { p.muted }) + self.regions.push((sr, RunningStop(g.id))) + self.regions.push((r, RunningRow(g.id))) + ry = ry + 34 + } + // Rig status, at the bottom. + let sy = status_top + ops.push(@ui.text(x + 12, sy + 12, "Rig Status", fs_small, p.muted, bold=true)) + let rows = [ + ("Monitor", "GPU", rig.gpu), + ("Monitor", "Display", rig.resolution + (if rig.display != "" && rig.display != "—" { " on " + rig.display } else { "" })), + ("Speaker", "Audio", rig.audio), + ] + for k, row in rows { + let (g, label, value) = row + let yy = sy + 38 + k * 26 + draw_glyph(ops, g, x + 12, yy - 7, 14, p.muted) + ops.push(@ui.text(x + 34, yy, label, fs_small, p.muted)) + let vx = x + 96 + if label == "Audio" { + ops.push(@ui.circle(vx + 3, yy, 3, if rig.audio_ok { p.ok } else { p.faint })) + ops.push(@ui.text(vx + 14, yy, ellipsize(value, w - 124, fs_small), fs_small, p.fg)) + } else { + ops.push(@ui.text(vx, yy, ellipsize(value, w - 110, fs_small), fs_small, p.fg)) + } + } + if !rig.connected { + ops.push(@ui.circle(x + w - 20, sy + 12, 4, p.warn)) + } +} + +///| +fn Library::render_card( + self : Library, + ops : Array[@types.DrawOp], + g : Game, + modes : Array[Mode], + x : Int, + y : Int, + w : Int, + h : Int, + p : Pal, + clip_y : Int, + clip_h : Int, +) -> Unit { + let r = @ui.rect(x, y, w, h) + let hov = match self.hover { + Card(id) | Button(id, _) | StopButton(id) | FocusButton(id) => id == g.id + _ => false + } + ops.push(@ui.fill_rect(r, if hov { p.card_hover } else { p.card }, radius=14)) + if self.selected == g.id { + ops.push(@ui.stroke_rect(r, p.accent, width=2, radius=14)) + } + // Icon tile, name and badges. + let (tbg, tfg) = tile_colors(g.icon, p) + ops.push(@ui.fill_rect(@ui.rect(x + 20, y + 20, 44, 44), tbg, radius=10)) + draw_glyph(ops, g.icon, x + 30, y + 30, 24, tfg, letter=g.name.to_array()[:1].to_owned() |> String::from_array) + ops.push(@ui.text(x + 78, y + 32, ellipsize(g.name, w - 98, 16), 16, p.fg, bold=true)) + let bx = x + 76 + let bw = badge(ops, bx, y + 48, category_badge(g.category), p.badge_bg, p.badge_fg) + let st = g.status() + let (sbg, sfg) = match st { + Ready | Running => (p.ok_bg, p.ok) + NotInstalled => (p.badge_bg, p.badge_fg) + } + ignore(badge(ops, bx + bw + 6, y + 48, st.label(), sbg, sfg)) + // Description and hint. + let mut ty = y + 20 + 48 + 14 + 11 + for line in wrap(g.description, w - 40, fs, 3) { + ops.push(@ui.text(x + 20, ty, line, fs, p.fg)) + ty = ty + 22 + } + if !g.installed && g.install_hint != "" { + ty = ty + 10 - 2 + draw_glyph(ops, "Info", x + 20, ty - 7, 14, p.muted) + for line in wrap(g.install_hint, w - 60, fs_small, 3) { + ops.push(@ui.text(x + 40, ty, line, fs_small, p.muted)) + ty = ty + 18 + } + } + // Buttons, at the bottom. + let by = y + h - 20 - 30 + let mut bx = x + 20 + if g.running { + bx = bx + self.button(ops, bx, by, "Switch to", "ExternalLink", true, FocusButton(g.id), p) + 8 + bx = bx + self.button(ops, bx, by, "Stop", "Stop", false, StopButton(g.id), p) + 8 + } else { + bx = bx + self.button(ops, bx, by, "Launch", "Play", g.installed, Button(g.id, "default"), p) + 8 + for m in modes { + if bx + approx_width(m.label, fs_small + 1) + 42 > x + w - 12 { + break + } + bx = bx + self.button(ops, bx, by, m.label, "Monitor", false, Button(g.id, m.id), p) + 8 + } + } + // The card itself (after the buttons, so they win), only where it shows. + let top = if y < clip_y { clip_y } else { y } + let bot = if y + h > clip_y + clip_h { clip_y + clip_h } else { y + h } + if bot > top { + self.regions.push((@ui.rect(x, top, w, bot - top), Card(g.id))) + } +} + +///| +fn Library::clamp_scroll(self : Library) -> Unit { + let max = self.content_h - self.view_h + let max = if max < 0 { 0 } else { max } + if self.scroll > max { + self.scroll = max + } + if self.scroll < 0 { + self.scroll = 0 + } +} + +///| What is at `p` (from the last render; buttons before the cards under them). +pub fn Library::hit(self : Library, p : @types.Point) -> Hit { + // The grid is clipped: a button scrolled out of view is not there. + for reg in self.regions { + if @ui.contains(reg.0, p) { + return reg.1 + } + } + NoHit +} + +///| Wheel over the desktop: scroll the grid. True when it moved. +pub fn Library::scroll_by(self : Library, dy : Int) -> Bool { + let before = self.scroll + self.scroll = self.scroll + dy * 4 + self.clamp_scroll() + self.scroll != before +} + +///| The game with `id` from the last render. +fn Library::game(self : Library, id : String) -> Game? { + for g in self.games { + if g.id == id { + return Some(g) + } + } + None +} + +///| What a click on `hit` does. +fn Library::activate(self : Library, hit : Hit) -> Action { + match hit { + Cat(cat) => { + self.category = cat + self.scroll = 0 + NoAction + } + ClearSearch => { + self.query = "" + self.scroll = 0 + NoAction + } + RefreshButton => Refresh + Card(id) => { + self.selected = id + NoAction + } + Button(id, mode) => { + self.selected = id + Launch(id, mode) + } + StopButton(id) | RunningStop(id) => Stop(id) + FocusButton(id) | RunningRow(id) => Focus(id) + Search | NoHit => NoAction + } +} + +///| Move the keyboard selection by `dx` cards / `dy` rows. +fn Library::step(self : Library, dx : Int, dy : Int) -> Unit { + let cards = self.shown + if cards.length() == 0 { + return + } + let mut at = -1 + for i, cd in cards { + if cd.0 == self.selected { + at = i + } + } + if at < 0 { + self.selected = cards[0].0 + return + } + if dx != 0 { + let n = at + dx + let n = if n < 0 { 0 } else if n >= cards.length() { cards.length() - 1 } else { n } + self.selected = cards[n].0 + } else { + // The card in the next / previous row nearest in column. + let (_, col, y) = cards[at] + let mut best = -1 + let mut best_d = 0 + for i, cd in cards { + let ok = if dy > 0 { cd.2 > y } else { cd.2 < y } + if ok { + let d = (cd.2 - y).abs() * 100 + (cd.1 - col).abs() + if best < 0 || d < best_d { + best = i + best_d = d + } + } + } + if best >= 0 { + self.selected = cards[best].0 + } + } + self.reveal() +} + +///| Scroll so the selected card shows. +fn Library::reveal(self : Library) -> Unit { + for cd in self.shown { + if cd.0 == self.selected { + if cd.2 < self.scroll { + self.scroll = cd.2 + } else if cd.2 + 160 > self.scroll + self.view_h { + self.scroll = cd.2 + 160 - self.view_h + } + } + } + self.clamp_scroll() +} + +///| One input event; (redraw, what to do). +pub fn Library::handle(self : Library, ev : @types.InputEvent) -> (Bool, Action) { + match ev { + PointerMove(pt) => { + let h = self.hit(pt) + if h != self.hover { + self.hover = h + (true, NoAction) + } else { + (false, NoAction) + } + } + PointerDown(pt) => { + self.press = self.hit(pt) + let was = self.focused + self.focused = true + (!was, NoAction) + } + PointerUp(pt) => { + let h = self.hit(pt) + let pressed = self.press + self.press = NoHit + if h == pressed && h != NoHit { + (true, self.activate(h)) + } else { + (false, NoAction) + } + } + PointerLeave => { + let changed = self.hover != NoHit + self.hover = NoHit + (changed, NoAction) + } + FocusLost => { + let was = self.focused + self.focused = false + (was, NoAction) + } + KeyDown(k) => self.key(k) + } +} + +///| +fn Library::key(self : Library, k : String) -> (Bool, Action) { + match k { + "ArrowLeft" | "Left" => self.step(-1, 0) + "ArrowRight" | "Right" => self.step(1, 0) + "ArrowUp" | "Up" => self.step(0, -1) + "ArrowDown" | "Down" => self.step(0, 1) + "Enter" | "Return" => + match self.game(self.selected) { + Some(g) if g.running => return (true, Focus(g.id)) + Some(g) => return (true, Launch(g.id, "default")) + None => { + self.step(0, 0) + return (true, NoAction) + } + } + "Backspace" => { + let a = self.query.to_array() + if a.length() == 0 { + return (false, NoAction) + } + self.query = String::from_array(a[:a.length() - 1].to_owned()) + self.scroll = 0 + } + "Escape" => { + if self.query == "" && self.selected == "" { + return (false, NoAction) + } + self.query = "" + self.selected = "" + self.scroll = 0 + } + _ => + if k.length() == 1 && k.to_array()[0] >= ' ' && self.query.length() < 64 { + self.query = self.query + k + self.scroll = 0 + self.selected = "" + } else { + return (false, NoAction) + } + } + (true, NoAction) +} + +///| The right-click settings. +pub fn Library::config_items(self : Library) -> Array[ConfigEntry] { + [{ key: "colors", label: "Colours", choices: colors_choices, value: self.colors }] +} + +///| Set one; true when it changed something on screen. +pub fn Library::set_config(self : Library, key : String, value : String) -> Bool { + match key { + "colors" if colors_choices.contains(value) => { + self.colors = value + true + } + _ => false + } +} diff --git a/scripts/components.txt b/scripts/components.txt index 27ebfdc..7ab7d79 100644 --- a/scripts/components.txt +++ b/scripts/components.txt @@ -12,3 +12,4 @@ battery battery-widget network network-widget icon-desktop icon-desktop-widget starfield starfield-widget +gamerig-library gamerig-library-widget diff --git a/scripts/gamerig-kiosk.sh b/scripts/gamerig-kiosk.sh index c9e9ad1..2e62ddb 100755 --- a/scripts/gamerig-kiosk.sh +++ b/scripts/gamerig-kiosk.sh @@ -8,9 +8,11 @@ # * Chandra is one X client: a fullscreen window under Openbox whose WM_CLASS is gamerig-desktop, # so gamerig's Openbox rules, Ctrl+Alt+L / Super+Space ("back to the library", wmctrl -xa) and # server.py's focus calls find it exactly as they found the old window. -# * Inside it, Chandra runs in kiosk mode: no panel, no shortcuts, the library app fullscreen and -# restarted when it exits. Until there is a native launcher module the library app is the same -# shell_window.py, now a Wayland client of Chandra (GTK + WebKit on wl_shm). +# * Inside it, Chandra runs as a hybrid kiosk (the default, CHANDRA_KIOSK_MODE=hybrid): panel, +# dock and Alt+Tab work, the desktop is the Gamerig Library module (docs/gamerig-library.md), +# which reads and drives server.py through the shell; Log out and power are locked. No WebKit. +# CHANDRA_KIOSK_MODE=strict runs the old single-app kiosk instead: no panel, no shortcuts, the +# library app (shell_window.py as a Wayland client of Chandra) fullscreen and restarted. # * Games and Steam don't go through Chandra: server.py starts them on Xorg with the NVIDIA # driver, Openbox stacks them above Chandra, Selkies captures and injects input (XTest) as before. # @@ -20,13 +22,14 @@ # # Environment: CHANDRA_DIR (default /opt/chandra: wasmhost, compositor.wasm, components/, wit/, # config/, assets/, lib/), GAMERIG_DESKTOP_DIR (default /opt/gamerig-desktop), GAMERIG_DESKTOP_PORT -# (8091), DISPLAY (default: the first X socket), CHANDRA_KIOSK_APP (the app run in the kiosk; -# default gamerig's library window). +# (8091), DISPLAY (default: the first X socket), CHANDRA_KIOSK_MODE (hybrid or strict), +# CHANDRA_KIOSK_APP (strict: the app run in the kiosk; default gamerig's library window). set -u CHANDRA_DIR=${CHANDRA_DIR:-/opt/chandra} GAMERIG_DESKTOP_DIR=${GAMERIG_DESKTOP_DIR:-/opt/gamerig-desktop} PORT=${GAMERIG_DESKTOP_PORT:-8091} +MODE=${CHANDRA_KIOSK_MODE:-hybrid} LOG=${CHANDRA_KIOSK_LOG:-/var/log/chandra-kiosk.log} if [ -z "${DISPLAY:-}" ]; then @@ -44,8 +47,13 @@ mkdir -p "$XDG_RUNTIME_DIR" && chmod 700 "$XDG_RUNTIME_DIR" # so GTK picks Wayland. WebKit gets no DMA-BUF renderer and no sandbox in a container (as onstart.sh). APP=${CHANDRA_KIOSK_APP:-"env WEBKIT_DISABLE_DMABUF_RENDERER=1 WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS=1 NO_AT_BRIDGE=1 python3 $GAMERIG_DESKTOP_DIR/shell_window.py --url http://127.0.0.1:$PORT/"} -echo "chandra: $CHANDRA_DIR DISPLAY=$DISPLAY XDG_RUNTIME_DIR=$XDG_RUNTIME_DIR" -echo "kiosk app: $APP" +export GAMERIG_DESKTOP_API=${GAMERIG_DESKTOP_API:-http://127.0.0.1:$PORT} +case "$MODE" in + strict) KIOSK_ARGS="--kiosk"; echo "kiosk app: $APP" ;; + *) MODE=hybrid; KIOSK_ARGS="--kiosk-hybrid --desktop gamerig-library"; APP="" ;; +esac +echo "chandra: $CHANDRA_DIR DISPLAY=$DISPLAY XDG_RUNTIME_DIR=$XDG_RUNTIME_DIR mode=$MODE" +echo "library daemon: $GAMERIG_DESKTOP_API" [ "${1:-}" = "--check" ] && exit 0 if [ ! -x "$CHANDRA_DIR/wasmhost" ] || [ ! -f "$CHANDRA_DIR/compositor.wasm" ]; then @@ -73,9 +81,15 @@ export LD_LIBRARY_PATH="$CHANDRA_DIR/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" delay=1 while true; do start=$(date +%s) - echo "$(date -u +%FT%TZ) starting chandra (kiosk)" >>"$LOG" - ./wasmhost compositor.wasm --x11 --fullscreen --app-id gamerig-desktop \ - --socket "$XDG_RUNTIME_DIR/wayland-chandra" --kiosk "$APP" >>"$LOG" 2>&1 + echo "$(date -u +%FT%TZ) starting chandra (kiosk, $MODE)" >>"$LOG" + if [ "$MODE" = strict ]; then + ./wasmhost compositor.wasm --x11 --fullscreen --app-id gamerig-desktop \ + --socket "$XDG_RUNTIME_DIR/wayland-chandra" --kiosk "$APP" >>"$LOG" 2>&1 + else + # shellcheck disable=SC2086 + ./wasmhost compositor.wasm --x11 --fullscreen --app-id gamerig-desktop \ + --socket "$XDG_RUNTIME_DIR/wayland-chandra" $KIOSK_ARGS >>"$LOG" 2>&1 + fi rc=$? [ $(( $(date +%s) - start )) -ge 30 ] && delay=1 echo "$(date -u +%FT%TZ) chandra exited ($rc); again in ${delay}s" >>"$LOG" diff --git a/wasmhost/bin/plasmoids.mbt b/wasmhost/bin/plasmoids.mbt index 424bbf5..c9fce6f 100644 --- a/wasmhost/bin/plasmoids.mbt +++ b/wasmhost/bin/plasmoids.mbt @@ -264,6 +264,11 @@ fn request_val(r : @wasm.HostRequest) -> @wt.Val { DefaultApp(n) => Variant("default-app", Some(S32(n))) SetDesktop(n) => Variant("set-desktop", Some(S32(n))) FaceUnlock(n) => Variant("face-unlock", Some(S32(n))) + GameLibrary(action, game, mode) => + Variant( + "game-library", + Some(Record([("action", S32(action)), ("game", Str(game)), ("mode", Str(mode))])), + ) } } diff --git a/wit/capabilities.wit b/wit/capabilities.wit index 46e5b19..53475b4 100644 --- a/wit/capabilities.wit +++ b/wit/capabilities.wit @@ -373,3 +373,57 @@ interface face-unlock { /// Read the status and the faces again. refresh: func(); } + +/// A game library (docs/gamerig-library.md): the games and apps a game-streaming rig offers, what +/// runs, and the rig's GPU, display and audio. The host gets all of it from gamerig's library +/// daemon (`GET /api/state` on 127.0.0.1:8091, or GAMERIG_DESKTOP_API), polled every couple of +/// seconds; the module never talks to the network itself. Launch, stop and focus go back to the +/// daemon, which starts games on the rig's X server. +interface game-library { + record rig-status { + /// Why the daemon can't be reached ("Library daemon not reachable"), or what the last action + /// said went wrong; empty when all is well. + error: string, + gpu: string, + resolution: string, + display: string, + audio: string, + hostname: string, + /// The daemon answered the last poll. + connected: bool, + audio-ok: bool, + } + record game { + id: string, + name: string, + /// games, launchers or tools. + category: string, + description: string, + /// An icon name from gamerig's catalog (Play, Sparkles, Folder, Star, Box, Terminal, + /// Settings, ExternalLink ...). + icon: string, + /// What to do when it can't start (not installed). + install-hint: string, + featured: bool, + installed: bool, + running: bool, + } + /// A way to start a game other than plain Launch (Steam's Big Picture). + record launch-mode { + game: string, + id: string, + label: string, + } + status: func() -> rig-status; + /// In catalog order. + games: func() -> list; + launch-modes: func() -> list; + /// Start `game` (`mode` "default", or one of its launch modes). + launch: func(game: string, mode: string); + /// Stop it (SIGTERM, then SIGKILL). + stop: func(game: string); + /// Raise its window over the desktop. + focus: func(game: string); + /// Poll the daemon again now. + refresh: func(); +} diff --git a/wit/host/plasmoids.wit b/wit/host/plasmoids.wit index 1deecd2..22c6b3f 100644 --- a/wit/host/plasmoids.wit +++ b/wit/host/plasmoids.wit @@ -70,7 +70,10 @@ interface plasmoids { /// shortcuts (ssssi: name binding default-binding conflict capturing), 11 default-app /// categories (sss: name current missing), 12 default-app choices (issii: category id name icon current), /// 20 desktops (s: name) served by `wallpaper.desktops`, 24 face unlock status (sssiii: problem howdy - /// message installed in-use busy; one row), 25 enrolled faces (ss: label added). + /// message installed in-use busy; one row), 25 enrolled faces (ss: label added), 26 game library status (one row, + /// ssssssii: error gpu resolution display audio hostname connected audio-ok), + /// 27 games (ssssssiii: id name category description icon install-hint featured installed running), + /// 28 launch modes (sss: game id label). publish-table: func(which: u32, rows: list); /// Layout mode (0 tiling, 1 monocle, 2 floating) and whether the Interface Explorer is on. publish-state: func(layout-mode: s32, inspector-on: bool); @@ -117,6 +120,13 @@ interface plasmoids { password: string, } + /// A game library action: 0 launch (game, mode), 1 stop, 2 focus (game), 3 poll again. + record game-request { + action: s32, + game: string, + mode: string, + } + /// A module moving a panel instance `delta` places (negative: towards the start). record instance-move { slot: string, @@ -165,6 +175,8 @@ interface plasmoids { /// The face-unlock capability: an index removes that face; -1 reads the status again, -2 /// enrolls a face, -3 / -4 stop / start using it for the password dialog and sudo. face-unlock(s32), + /// The game-library capability: launch, stop, focus or refresh. + game-library(game-request), } /// The next pending request, oldest first. next-request: func() -> option; diff --git a/wit/worlds.wit b/wit/worlds.wit index 374fad8..937af00 100644 --- a/wit/worlds.wit +++ b/wit/worlds.wit @@ -103,6 +103,7 @@ world plasmoid-host { import shortcuts; import default-apps; import face-unlock; + import game-library; export plasmoid; } @@ -168,3 +169,12 @@ world starfield-widget { include desktop-widget; export module-config; } + +/// Desktop module: gamerig's library as the desktop. A sidebar with the categories and their +/// counts, what is running and the rig's status; a search box; cards for each game with Launch, +/// Big Picture, Stop and Switch to. Built for a game-streaming rig in a hybrid kiosk. +world gamerig-library-widget { + include desktop-widget; + import game-library; + export module-config; +} diff --git a/world/gamerig-library-widget/README.md b/world/gamerig-library-widget/README.md new file mode 100644 index 0000000..8478e99 --- /dev/null +++ b/world/gamerig-library-widget/README.md @@ -0,0 +1,3 @@ +Desktop module: gamerig's library as the desktop. A sidebar with the categories and their +counts, what is running and the rig's status; a search box; cards for each game with Launch, +Big Picture, Stop and Switch to. Built for a game-streaming rig in a hybrid kiosk. \ No newline at end of file diff --git a/world/gamerig-library-widget/ffi_import.mbt b/world/gamerig-library-widget/ffi_import.mbt new file mode 100644 index 0000000..cdedbce --- /dev/null +++ b/world/gamerig-library-widget/ffi_import.mbt @@ -0,0 +1,2 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + diff --git a/world/gamerig-library-widget/import.mbt b/world/gamerig-library-widget/import.mbt new file mode 100644 index 0000000..cdedbce --- /dev/null +++ b/world/gamerig-library-widget/import.mbt @@ -0,0 +1,2 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + diff --git a/world/gamerig-library-widget/moon.pkg b/world/gamerig-library-widget/moon.pkg new file mode 100644 index 0000000..e2a6033 --- /dev/null +++ b/world/gamerig-library-widget/moon.pkg @@ -0,0 +1 @@ +warnings = "-44"