Wasm panel modules, widget host, merged plasmoid host design, and shell/UI work

Panel and wasm host
- The panel is built from wasm plasmoid modules (compositor/wasm: wasmer-backed host).
  Modules get capabilities by importing host interfaces; the host publishes data tables
  and serves a request queue (launch, focus window, set layout, inspector, load/unload
  modules). New WIT: windows, layout-control, inspector, modules, system.
- Merged two competing host designs: generic tables + requests are the base; the
  `system` snapshot and the id-stable `windows.all/focus` (Desktop Pulse) run on top of it.
- Panel widgets: load a .wasm from a path or file chooser, reorder by dragging,
  right-click replace/remove/add, saved to panel.edn.
- Desktop widget, system sampler (sysinfo), app catalog/humanised names, Interface
  Explorer (inspector), real font rendering (compositor/font, assets/fonts).

Compositor
- Drag the divider between tiled windows; lower tiled rows leave room for the title bar.
- Title-bar buttons, 12-hour clock, truncated titles, task-list/layout menus.
- DRM/KMS session, tcc debug builds (vendored tinycc incl. conftest.c), justfile
  recipes (modules, run, test), pixi.toml.

Known gaps
- The sources for the pulse, tasks, layout, inspector, module-manager, moon-* and
  clock-digital12 modules are not in the tree yet, so `just modules` stops at pulse and
  the host tests that load those modules fail until they land.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
nandiandClaude Sonnet 5.5 committed 2026-11-24 23:38:05 -08:00
1 parent 080377fd79
commit 0145981c6a
57 files changed
+11447 -207

No files matched your search

+1
View File
@@ -6,3 +6,4 @@ node_modules/
.mooncakes/ .mooncakes/
*.log *.log
host-native/target/ host-native/target/
.pixi/
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+96
View File
@@ -0,0 +1,96 @@
Copyright (c) 2016, The Inter Project Authors (https://github.com/rsms/inter)
Copyright (c) 2015-2025, Renzhi Li (aka. Belleve Invis, belleve@typeof.net)
Copyright (c) 2025, Jamie Gravendeel (https://jamie.garden)
Copyright (c) 2025, Florian Müllner
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+12
View File
@@ -6,6 +6,7 @@ fn main {
let mut socket_path = "/tmp/wayland-moon-0" let mut socket_path = "/tmp/wayland-moon-0"
let mut theme_path = "config/themes/moon-night.json" let mut theme_path = "config/themes/moon-night.json"
let mut gfx_out = "" let mut gfx_out = ""
let widgets : Array[String] = []
let mut windowed = false let mut windowed = false
let mut drm = false let mut drm = false
let mut width = 1280 let mut width = 1280
@@ -26,6 +27,9 @@ fn main {
} else if a == "--drm" { } else if a == "--drm" {
drm = true drm = true
i = i + 1 i = i + 1
} else if a == "--widget" && i + 1 < args.length() {
widgets.push(args[i + 1])
i = i + 2
} else if a == "--gfx-out" && i + 1 < args.length() { } else if a == "--gfx-out" && i + 1 < args.length() {
gfx_out = args[i + 1] gfx_out = args[i + 1]
i = i + 2 i = i + 2
@@ -71,6 +75,14 @@ fn main {
match @host.MoonPlasmaCompositor::new(socket_path, theme, width, height) { match @host.MoonPlasmaCompositor::new(socket_path, theme, width, height) {
Some(comp) => { Some(comp) => {
comp.shell.persist = true // remember which modules are loaded in the panel
comp.shell.screen_w = width // the panel can't place widgets before it knows its width
if widgets.length() > 0 {
ignore(comp.compose_frame()) // boots the panel and sets the theme tokens modules are loaded with
for path in widgets {
ignore(comp.shell.load_path(path))
}
}
if gfx_out.length() > 0 { if gfx_out.length() > 0 {
let pixmap = comp.present_to_gfx(gfx_ctx) let pixmap = comp.present_to_gfx(gfx_ctx)
let png = @renderer.encode_png(pixmap) let png = @renderer.encode_png(pixmap)
+1 -1
View File
@@ -18,7 +18,7 @@ pkgtype(kind: "executable")
options( options(
link: { link: {
"native": { "native": {
"cc-link-flags": "-ldrm -linput -lseat -lxkbcommon -ludev", "cc-link-flags": "-ldrm -linput -lseat -lxkbcommon -ludev -lwasmer",
}, },
}, },
) )
+142
View File
@@ -0,0 +1,142 @@
///| Real text rendering for the native compositor: Adwaita Mono rasterised with
/// stb_truetype, plugged into the renderer's glyph hook. The pure-MoonBit
/// renderer (also built for wasm) keeps its bitmap font when no hook is set.
///|
#borrow(path)
extern "C" fn c_font_load(slot : Int, path : Bytes) -> Int = "mp_font_load"
///|
extern "C" fn c_font_metrics(
slot : Int,
cp : Int,
size : Int,
info : FixedArray[Int],
) = "mp_font_metrics"
///|
#borrow(buf)
extern "C" fn c_font_bitmap(
slot : Int,
cp : Int,
size : Int,
w : Int,
h : Int,
buf : Bytes,
) = "mp_font_bitmap"
///|
fn utf8(s : String) -> Bytes {
let out : Array[Byte] = []
for ch in s {
let c = ch.to_int()
if c < 0x80 {
out.push(c.to_byte())
} else if c < 0x800 {
out.push((0xC0 | (c >> 6)).to_byte())
out.push((0x80 | (c & 0x3F)).to_byte())
} else if c < 0x10000 {
out.push((0xE0 | (c >> 12)).to_byte())
out.push((0x80 | ((c >> 6) & 0x3F)).to_byte())
out.push((0x80 | (c & 0x3F)).to_byte())
} else {
out.push((0xF0 | (c >> 18)).to_byte())
out.push((0x80 | ((c >> 12) & 0x3F)).to_byte())
out.push((0x80 | ((c >> 6) & 0x3F)).to_byte())
out.push((0x80 | (c & 0x3F)).to_byte())
}
}
Bytes::from_array(out)
}
///| Where to look for each face: bundled copy first, then the system one.
let regular_paths : Array[String] = [
"assets/fonts/AdwaitaMono-Regular.ttf",
"/usr/share/fonts/Adwaita/AdwaitaMono-Regular.ttf",
]
///|
let sans_paths : Array[String] = [
"assets/fonts/AlloVariable.ttf",
"/usr/local/share/fonts/a/AlloVariable.ttf",
"assets/fonts/AdwaitaSans-Regular.ttf",
"/usr/share/fonts/Adwaita/AdwaitaSans-Regular.ttf",
]
///|
let bold_paths : Array[String] = [
"assets/fonts/AdwaitaMono-Bold.ttf",
"/usr/share/fonts/Adwaita/AdwaitaMono-Bold.ttf",
]
///|
fn load_first(slot : Int, paths : Array[String]) -> Bool {
for p in paths {
if c_font_load(slot, utf8(p)) == 0 {
return true
}
}
false
}
///|
let cache : Map[Int, @renderer.Glyph] = {}
///|
fn rasterise(slot : Int, cp : Int, size : Int, embolden : Bool) -> @renderer.Glyph {
let key = cp + 0x110000 * (size + 256 * (slot * 2 + (if embolden { 1 } else { 0 })))
match cache.get(key) {
Some(g) => g
None => {
let info : FixedArray[Int] = FixedArray::make(5, 0)
c_font_metrics(slot, cp, size, info)
let w = info[0]
let h = info[1]
let buf = if w > 0 && h > 0 {
let b = Bytes::make(w * h, b'\x00')
c_font_bitmap(slot, cp, size, w, h, b)
b
} else {
Bytes::make(0, b'\x00')
}
let g : @renderer.Glyph = {
w,
h,
xoff: info[2],
yoff: info[3],
advance: info[4],
coverage: buf,
embolden,
}
cache.set(key, g)
g
}
}
}
///| Install Allo Variable (UI text, falling back to Adwaita Sans) and Adwaita Mono (code) as the renderer's
/// faces. Returns false (keeping the bitmap font) when no face can be found.
/// Slots: 0 mono, 1 mono bold, 2 sans. Sans is a variable font whose bold
/// instance stb_truetype can't select, so bold sans is emboldened.
pub fn install() -> Bool {
let has_mono = load_first(0, regular_paths)
let has_sans = load_first(2, sans_paths)
if !has_mono && !has_sans {
return false
}
let has_bold = has_mono && load_first(1, bold_paths)
@renderer.set_glyph_source(fn(cp, size, bold, mono) {
if mono && has_mono {
if bold && has_bold {
rasterise(1, cp, size, false)
} else {
rasterise(0, cp, size, bold)
}
} else if has_sans {
rasterise(2, cp, size, bold)
} else {
rasterise(0, cp, size, bold)
}
})
true
}
+63
View File
@@ -0,0 +1,63 @@
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "moonbit.h"
#define STB_TRUETYPE_IMPLEMENTATION
#define STBTT_STATIC
#include "stb_truetype.h"
#define MAX_SLOTS 4
static stbtt_fontinfo fonts[MAX_SLOTS];
static unsigned char *font_data[MAX_SLOTS];
/* Load a TTF file into `slot`. Returns 0 on success. */
MOONBIT_FFI_EXPORT
int32_t mp_font_load(int32_t slot, moonbit_bytes_t path_bytes) {
char path[512];
int32_t len = Moonbit_array_length(path_bytes);
size_t n = (size_t)len < sizeof(path) - 1 ? (size_t)len : sizeof(path) - 1;
memcpy(path, path_bytes, n);
path[n] = '\0';
if (slot < 0 || slot >= MAX_SLOTS) return -1;
FILE *f = fopen(path, "rb");
if (!f) return -1;
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
if (sz <= 0) { fclose(f); return -1; }
unsigned char *buf = (unsigned char *)malloc((size_t)sz);
if (!buf || fread(buf, 1, (size_t)sz, f) != (size_t)sz) { fclose(f); free(buf); return -1; }
fclose(f);
if (!stbtt_InitFont(&fonts[slot], buf, stbtt_GetFontOffsetForIndex(buf, 0))) { free(buf); return -1; }
free(font_data[slot]);
font_data[slot] = buf;
return 0;
}
/* info = [w, h, xoff, yoff (top-left of bitmap relative to pen/baseline), advance] in pixels. */
MOONBIT_FFI_EXPORT
void mp_font_metrics(int32_t slot, int32_t cp, int32_t size, int32_t *info) {
stbtt_fontinfo *fi = &fonts[slot];
float scale = stbtt_ScaleForMappingEmToPixels(fi, (float)size);
int adv, lsb, x0, y0, x1, y1;
int g = stbtt_FindGlyphIndex(fi, cp);
stbtt_GetGlyphHMetrics(fi, g, &adv, &lsb);
stbtt_GetGlyphBitmapBox(fi, g, scale, scale, &x0, &y0, &x1, &y1);
info[0] = x1 - x0;
info[1] = y1 - y0;
info[2] = x0;
info[3] = y0;
info[4] = (int32_t)(adv * scale + 0.5f);
}
/* Render the 8-bit coverage bitmap (w*h bytes, w/h from mp_font_metrics) into buf. */
MOONBIT_FFI_EXPORT
void mp_font_bitmap(int32_t slot, int32_t cp, int32_t size, int32_t w, int32_t h, moonbit_bytes_t buf) {
stbtt_fontinfo *fi = &fonts[slot];
float scale = stbtt_ScaleForMappingEmToPixels(fi, (float)size);
if (w <= 0 || h <= 0 || Moonbit_array_length(buf) < w * h) return;
stbtt_MakeGlyphBitmap(fi, (unsigned char *)buf, w, h, w, scale, scale, stbtt_FindGlyphIndex(fi, cp));
}
+10
View File
@@ -0,0 +1,10 @@
import {
"moonbitlang/core/builtin",
"moonplasma/desktop/compositor/renderer" @renderer,
}
supported_targets = "-all+native"
options(
"native-stub": [ "font_stub.c" ],
)
File diff suppressed because it is too large. Load diff
+265 -18
View File
@@ -10,6 +10,8 @@ pub(all) struct HostWindow {
mut maximized : Bool mut maximized : Bool
mut fullscreen : Bool mut fullscreen : Bool
mut surface : @scene.ShmBufferSnapshot? mut surface : @scene.ShmBufferSnapshot?
/// A size change still to be sent to the client (coalesced while dragging a divider).
mut cfg_dirty : Bool
} }
///| ///|
@@ -32,6 +34,8 @@ pub(all) struct MoonPlasmaCompositor {
mut press_fwd : Bool mut press_fwd : Bool
mut kbd_win : UInt64? mut kbd_win : UInt64?
mut mods : UInt mut mods : UInt
/// A Super key is down and nothing else was pressed since: releasing it opens the launcher.
mut super_solo : Bool
mut layout_mode : @wm.LayoutMode mut layout_mode : @wm.LayoutMode
} }
@@ -42,6 +46,7 @@ pub fn MoonPlasmaCompositor::new(
output_w : Int, output_w : Int,
output_h : Int, output_h : Int,
) -> MoonPlasmaCompositor? { ) -> MoonPlasmaCompositor? {
ignore(@font.install()) // Adwaita Mono; keeps the bitmap font if it's missing
let server = match @wayland.WaylandServer::listen(socket_path, output_w, output_h) { let server = match @wayland.WaylandServer::listen(socket_path, output_w, output_h) {
Some(s) => s Some(s) => s
None => return None None => return None
@@ -58,6 +63,8 @@ pub fn MoonPlasmaCompositor::new(
excl_top=32, // room for the server-side title bar drawn above each client excl_top=32, // room for the server-side title bar drawn above each client
excl_bottom=theme.panel_height, excl_bottom=theme.panel_height,
) )
let shell = @shell.DesktopShell::new(socket_path)
shell.set_output(theme, output_w, output_h)
Some({ Some({
server, server,
wm, wm,
@@ -67,7 +74,7 @@ pub fn MoonPlasmaCompositor::new(
work_area, work_area,
windows: {}, windows: {},
damage: @scene.DamageTracker::new(), damage: @scene.DamageTracker::new(),
shell: @shell.DesktopShell::new(socket_path), shell,
ptr_x: 0.0, ptr_x: 0.0,
ptr_y: 0.0, ptr_y: 0.0,
ptr_win: None, ptr_win: None,
@@ -75,12 +82,14 @@ pub fn MoonPlasmaCompositor::new(
press_fwd: false, press_fwd: false,
kbd_win: None, kbd_win: None,
mods: 0U, mods: 0U,
super_solo: false,
layout_mode: @wm.LayoutMode::Tiling, layout_mode: @wm.LayoutMode::Tiling,
}) })
} }
///| ///|
pub fn MoonPlasmaCompositor::close(self : MoonPlasmaCompositor) -> Unit { pub fn MoonPlasmaCompositor::close(self : MoonPlasmaCompositor) -> Unit {
self.shell.shutdown()
self.server.close() self.server.close()
} }
@@ -95,6 +104,11 @@ fn MoonPlasmaCompositor::apply_actions(
match self.windows.get(wid) { match self.windows.get(wid) {
Some(win) => { Some(win) => {
win.geometry = @scene.Rect::new(r.x, r.y, r.w, r.h) win.geometry = @scene.Rect::new(r.x, r.y, r.w, r.h)
if self.split_drag is Some(_) {
// Dragging: send one configure per frame, not one per mouse event.
win.cfg_dirty = true
} else {
win.cfg_dirty = false
self.server.send_toplevel_configure( self.server.send_toplevel_configure(
wid, wid,
r.w, r.w,
@@ -103,6 +117,7 @@ fn MoonPlasmaCompositor::apply_actions(
win.maximized, win.maximized,
win.fullscreen, win.fullscreen,
) )
}
self.damage.mark_full() self.damage.mark_full()
} }
None => () None => ()
@@ -130,8 +145,26 @@ fn MoonPlasmaCompositor::apply_actions(
} }
} }
///| Send the size changes coalesced during a divider drag.
fn MoonPlasmaCompositor::flush_configures(self : MoonPlasmaCompositor) -> Unit {
for wid, win in self.windows {
if win.cfg_dirty {
win.cfg_dirty = false
self.server.send_toplevel_configure(
wid,
win.geometry.w,
win.geometry.h,
win.focused,
win.maximized,
win.fullscreen,
)
}
}
}
///| ///|
pub fn MoonPlasmaCompositor::step(self : MoonPlasmaCompositor) -> Unit { pub fn MoonPlasmaCompositor::step(self : MoonPlasmaCompositor) -> Unit {
self.flush_configures()
let events = self.server.poll_events() let events = self.server.poll_events()
for ev in events { for ev in events {
match ev { match ev {
@@ -145,6 +178,7 @@ pub fn MoonPlasmaCompositor::step(self : MoonPlasmaCompositor) -> Unit {
maximized: false, maximized: false,
fullscreen: false, fullscreen: false,
surface: None, surface: None,
cfg_dirty: false,
} }
self.windows.set(wid, win) self.windows.set(wid, win)
let rec : @wm.WindowRecord = { let rec : @wm.WindowRecord = {
@@ -250,15 +284,13 @@ pub fn MoonPlasmaCompositor::set_layout_mode(
pub fn MoonPlasmaCompositor::compose_frame( pub fn MoonPlasmaCompositor::compose_frame(
self : MoonPlasmaCompositor, self : MoonPlasmaCompositor,
) -> @renderer.Pixmap { ) -> @renderer.Pixmap {
self.flush_configures()
let scene = @scene.SceneGraph::new(self.output_w, self.output_h) let scene = @scene.SceneGraph::new(self.output_w, self.output_h)
let order = self.wm.stacking_order() let order = self.wm.stacking_order()
let titles : Array[String] = []
for wid in order { for wid in order {
match self.windows.get(wid) { match self.windows.get(wid) {
Some(win) => { Some(win) => {
let label = if win.title.length() > 0 { win.title } else { win.app_id }
titles.push(label)
let (insets, deco_ops) = @scene.build_breeze_decoration( let (insets, deco_ops) = @scene.build_breeze_decoration(
win.title, win.title,
win.app_id, win.app_id,
@@ -284,18 +316,51 @@ pub fn MoonPlasmaCompositor::compose_frame(
} }
} }
let layout_label = match self.layout_mode { self.shell.layout_sel = match self.layout_mode {
@wm.LayoutMode::Tiling => "BSP Tiling" @wm.LayoutMode::Tiling => 0
@wm.LayoutMode::Floating => "Floating" @wm.LayoutMode::Monocle => 1
@wm.LayoutMode::Monocle => "Monocle" @wm.LayoutMode::Floating => 2
} }
let (bg_ops, panel_ops) = self.shell.render( // The task list shows every window, minimized ones too (so they can be restored).
self.output_w, let wins : Array[@shell.WinInfo] = []
self.output_h, for wid in order {
self.theme, match self.windows.get(wid) {
layout_label, Some(win) =>
titles, wins.push({
) id: win.id,
title: if win.title.length() > 0 { win.title } else { win.app_id },
focused: win.focused,
minimized: false,
})
None => ()
}
}
for id, r in self.wm.windows {
if r.minimized {
match self.windows.get(id) {
Some(win) =>
wins.push({
id,
title: if win.title.length() > 0 { win.title } else { win.app_id },
focused: false,
minimized: true,
})
None => ()
}
}
}
self.shell.windows = wins
// The window list the `windows` interface serves to wasm widgets (task-bar order).
let entries : Array[@wasm.WindowEntry] = []
for w in wins {
match self.windows.get(w.id) {
Some(win) => entries.push({ id: w.id, title: w.title, app_id: win.app_id, focused: w.focused })
None => ()
}
}
self.shell.win_list = entries
let (bg_ops, panel_ops) = self.shell.render(self.output_w, self.output_h, self.theme)
self.run_shell_actions()
scene.background_ops = bg_ops scene.background_ops = bg_ops
scene.panel_ops = panel_ops scene.panel_ops = panel_ops
ignore(self.damage.take_damage(self.output_w, self.output_h)) ignore(self.damage.take_damage(self.output_w, self.output_h))
@@ -390,6 +455,104 @@ fn MoonPlasmaCompositor::window_at(self : MoonPlasmaCompositor, x : Int, y : Int
None None
} }
///| Title-bar button under (x, y) for window `wid`: 1 minimize, 2 maximize, 3 close, 0 none.
/// Mirrors the layout in `build_breeze_decoration` (18px buttons, 8px apart, 10px from the right edge).
fn MoonPlasmaCompositor::title_button_at(
self : MoonPlasmaCompositor,
wid : UInt64,
x : Int,
y : Int,
) -> Int {
match self.windows.get(wid) {
None => 0
Some(win) => {
let g = win.geometry
let outer_w = g.w + 4
let lx = x - (g.x - 2)
let ly = y - (g.y - 32)
let size = 18
let by = (32 - size) / 2
if ly < by - 3 || ly >= by + size + 3 {
return 0
}
let close_x = outer_w - 10 - size
let max_x = close_x - 8 - size
let min_x = max_x - 8 - size
if lx >= close_x - 3 && lx < close_x + size + 3 {
3
} else if lx >= max_x - 3 && lx < max_x + size + 3 {
2
} else if lx >= min_x - 3 && lx < min_x + size + 3 {
1
} else {
0
}
}
}
}
///| Activate the title-bar button `btn` of window `wid`.
fn MoonPlasmaCompositor::press_title_button(
self : MoonPlasmaCompositor,
wid : UInt64,
btn : Int,
) -> Unit {
self.leave_pointer()
let req = match btn {
1 => @wm.WindowRequest::Minimize(true)
2 => {
let maxed = match self.wm.windows.get(wid) {
Some(r) => r.maximized
None => false
}
@wm.WindowRequest::Maximize(!maxed)
}
_ => @wm.WindowRequest::Close
}
self.apply_actions(self.wm.handle_request(wid, req, self.work_area))
if btn == 1 {
// Hand focus to the top-most remaining window.
let order = self.wm.stacking_order()
if order.length() > 0 {
let top = order[order.length() - 1]
self.apply_actions([@wm.WmAction::Focus(top), @wm.WmAction::Raise(top)])
} else {
self.set_kbd_focus(None)
}
}
self.damage.mark_full()
}
///| Restore a minimized window (or focus a visible one) from its task-bar pill.
fn MoonPlasmaCompositor::activate_task(self : MoonPlasmaCompositor, wid : UInt64) -> Unit {
let minimized = match self.wm.windows.get(wid) {
Some(r) => r.minimized
None => return
}
if minimized {
self.apply_actions(
self.wm.handle_request(wid, @wm.WindowRequest::Minimize(false), self.work_area),
)
}
self.apply_actions([@wm.WmAction::Focus(wid), @wm.WmAction::Raise(wid)])
}
///| Carry out what panel modules asked for: focus a window, switch layout.
fn MoonPlasmaCompositor::run_shell_actions(self : MoonPlasmaCompositor) -> Unit {
for a in self.shell.take_actions() {
match a {
@shell.ShellAction::FocusWindow(wid) => self.activate_task(wid)
@shell.ShellAction::SetLayout(m) =>
match m {
0 => self.set_layout_mode(@wm.LayoutMode::Tiling)
1 => self.set_layout_mode(@wm.LayoutMode::Monocle)
2 => self.set_layout_mode(@wm.LayoutMode::Floating)
_ => ()
}
}
}
}
///| Tiling divider under (x, y), with a few pixels of slack either side. ///| Tiling divider under (x, y), with a few pixels of slack either side.
fn MoonPlasmaCompositor::handle_at( fn MoonPlasmaCompositor::handle_at(
self : MoonPlasmaCompositor, self : MoonPlasmaCompositor,
@@ -467,6 +630,20 @@ pub fn MoonPlasmaCompositor::handle_input(
self.ptr_y = y self.ptr_y = y
let xi = x.to_int() let xi = x.to_int()
let yi = y.to_int() let yi = y.to_int()
if self.shell.inspecting() {
self.leave_pointer()
let id = match self.shell.component_at(xi, yi) {
"" =>
match self.window_at(xi, yi) {
Some((_, true)) => "window-surface"
Some((_, false)) => "window-decoration"
None => "desktop"
}
sid => sid
}
self.shell.set_hover(id, xi, yi)
return
}
if self.shell.pointer_move(xi, yi) || self.shell.hit(xi, yi) { if self.shell.pointer_move(xi, yi) || self.shell.hit(xi, yi) {
self.leave_pointer() self.leave_pointer()
return return
@@ -482,6 +659,17 @@ pub fn MoonPlasmaCompositor::handle_input(
self.leave_pointer() self.leave_pointer()
return return
} }
match self.split_drag {
Some(h) => {
self.apply_actions(self.wm.drag_split(h, xi, yi, self.work_area))
return
}
None => ()
}
if self.handle_at(xi, yi) is Some(_) {
self.leave_pointer()
return
}
match self.window_at(xi, yi) { match self.window_at(xi, yi) {
Some((wid, true)) => Some((wid, true)) =>
match self.windows.get(wid) { match self.windows.get(wid) {
@@ -500,17 +688,50 @@ pub fn MoonPlasmaCompositor::handle_input(
_ => self.leave_pointer() _ => self.leave_pointer()
} }
} }
Scroll(v) => {
// ~10 units per wheel notch -> 3 lines.
let lines = if v > 0.0 { (v / 10.0).to_int() + 1 } else { (v / 10.0).to_int() - 1 }
ignore(self.shell.scroll_inspector(lines))
}
PointerButton(button, pressed) => { PointerButton(button, pressed) => {
let xi = self.ptr_x.to_int() let xi = self.ptr_x.to_int()
let yi = self.ptr_y.to_int() let yi = self.ptr_y.to_int()
if !pressed && self.shell.pointer_up() {
self.run_shell_actions()
return
}
if !pressed && self.split_drag is Some(_) { if !pressed && self.split_drag is Some(_) {
self.split_drag = None self.split_drag = None
return return
} }
if pressed { // Right button over a swappable panel widget opens its alternatives menu.
if self.shell.pointer_down(xi, yi) { if button == 273U && pressed && self.shell.right_click(xi, yi) {
return return
} }
if pressed {
self.super_solo = false
if button != 273U && self.shell.pointer_down(xi, yi) {
self.run_shell_actions()
return
}
match self.window_at(xi, yi) {
Some((wid, false)) => {
let btn = self.title_button_at(wid, xi, yi)
if btn != 0 {
self.press_title_button(wid, btn)
return
}
}
_ => ()
}
match self.handle_at(xi, yi) {
Some(h) => {
self.split_drag = Some(h)
self.leave_pointer()
return
}
None => ()
}
match self.handle_at(xi, yi) { match self.handle_at(xi, yi) {
Some(h) => { Some(h) => {
self.split_drag = Some(h) self.split_drag = Some(h)
@@ -542,7 +763,24 @@ pub fn MoonPlasmaCompositor::handle_input(
} }
} }
Key(code, pressed) => Key(code, pressed) =>
if self.shell.popup_open() { if code == 125U || code == 126U {
// Super (left/right): a bare tap toggles the launcher search; never reaches clients.
if pressed {
self.super_solo = true
} else if self.super_solo {
self.super_solo = false
if !self.shell.inspecting() {
self.shell.toggle_launcher()
}
}
} else if self.shell.inspecting() {
self.super_solo = false
// Escape leaves inspect mode; other keys are not forwarded while inspecting.
if code == 1U && pressed {
self.shell.set_inspecting(false)
}
} else if self.shell.popup_open() {
self.super_solo = false
if pressed { if pressed {
let name = key_name(code, (self.mods & 1U) != 0U) let name = key_name(code, (self.mods & 1U) != 0U)
if name.length() > 0 { if name.length() > 0 {
@@ -550,6 +788,7 @@ pub fn MoonPlasmaCompositor::handle_input(
} }
} }
} else { } else {
self.super_solo = false
match self.kbd_win { match self.kbd_win {
Some(w) => self.server.keyboard_key(w, time_ms, code, pressed) Some(w) => self.server.keyboard_key(w, time_ms, code, pressed)
None => () None => ()
@@ -580,6 +819,14 @@ pub fn MoonPlasmaCompositor::desired_cursor(self : MoonPlasmaCompositor) -> UInt
Some(h) => return if h.horizontal { 26U } else { 27U } // ew-resize / ns-resize Some(h) => return if h.horizontal { 26U } else { 27U } // ew-resize / ns-resize
None => () None => ()
} }
let handle = match self.split_drag {
Some(h) => Some(h)
None => self.handle_at(self.ptr_x.to_int(), self.ptr_y.to_int())
}
match handle {
Some(h) => return if h.horizontal { 26U } else { 27U } // ew-resize / ns-resize
None => ()
}
match self.ptr_win { match self.ptr_win {
Some(w) => self.server.client_cursor_shape(w) Some(w) => self.server.client_cursor_shape(w)
None => 1U None => 1U
+400 -15
View File
@@ -1,5 +1,41 @@
///| Input routing: host pointer/keyboard events reach the focused client window, ///| Input routing: host pointer/keyboard events reach the focused client window, and the
/// and the launcher button opens the shell's launcher popup. /// panel (made entirely of wasm modules) responds to the mouse and keyboard.
/// Needs the modules: run scripts/build-modules.sh (just test does).
///| Rectangle of the panel module `id` (file stem), as last drawn.
fn rect_of(comp : @host.MoonPlasmaCompositor, id : String) -> @scene.Rect {
comp.shell.slot_rect(comp.shell.slot_of(id))
}
///| Centre of the panel module `id`.
fn center_of(comp : @host.MoonPlasmaCompositor, id : String) -> (Double, Double) raise {
let r = rect_of(comp, id)
assert_true(r.w > 0)
((r.x + r.w / 2).to_double(), (r.y + r.h / 2).to_double())
}
///| Move to (x, y), press and release `btn`, then draw a frame.
fn click_at(comp : @host.MoonPlasmaCompositor, x : Int, y : Int, t : UInt, btn? : UInt = 272U) -> Unit {
comp.handle_input(@nested.InputEvent::PointerMove(x.to_double(), y.to_double()), t)
comp.handle_input(@nested.InputEvent::PointerButton(btn, true), t + 1U)
comp.handle_input(@nested.InputEvent::PointerButton(btn, false), t + 2U)
ignore(comp.compose_frame())
}
///| Click the centre of panel module `id`.
fn click_module(comp : @host.MoonPlasmaCompositor, id : String, t : UInt) -> Unit raise {
let (x, y) = center_of(comp, id)
click_at(comp, x.to_int(), y.to_int(), t)
}
///| A fresh compositor with the default panel and a first frame drawn.
fn new_comp(tag : String) -> @host.MoonPlasmaCompositor {
let socket_path = "/tmp/wayland-moon-" + tag + "-" + @sys.getpid().to_string() + ".sock"
let theme = @scene.ThemeTokens::moon_night()
let comp = @host.MoonPlasmaCompositor::new(socket_path, theme, 1280, 720).unwrap()
ignore(comp.compose_frame())
comp
}
///| Drain everything the compositor sent this client as (object, opcode) pairs. ///| Drain everything the compositor sent this client as (object, opcode) pairs.
fn drain_msgs(c : TestWaylandClient) -> Array[(UInt, UInt)] { fn drain_msgs(c : TestWaylandClient) -> Array[(UInt, UInt)] {
@@ -37,6 +73,7 @@ fn has_msg(msgs : Array[(UInt, UInt)], obj : UInt, op : UInt) -> Bool {
msgs.iter().any(m => m.0 == obj && m.1 == op) msgs.iter().any(m => m.0 == obj && m.1 == op)
} }
///| ///|
test "host input reaches the focused client and the launcher popup opens" { test "host input reaches the focused client and the launcher popup opens" {
let socket_path = "/tmp/wayland-moon-input-" + let socket_path = "/tmp/wayland-moon-input-" +
@@ -95,22 +132,16 @@ test "host input reaches the focused client and the launcher popup opens" {
} }
assert_eq(comp.desired_cursor(), 9U) assert_eq(comp.desired_cursor(), 9U)
// Launcher: click the button -> popup opens and swallows keys. // Launcher module: click the button -> its popup opens and swallows keys.
ignore(comp.compose_frame()) // lays out the panel ignore(comp.compose_frame()) // lays out the panel
comp.handle_input(@nested.InputEvent::PointerMove(60.0, 700.0), 20U) let (lx, ly) = center_of(comp, "launcher")
assert_eq(comp.desired_cursor(), 4U) // ...but the launcher button always shows a hand comp.handle_input(@nested.InputEvent::PointerMove(lx, ly), 20U)
comp.handle_input(@nested.InputEvent::PointerButton(0x110U, true), 21U) assert_eq(comp.desired_cursor(), 4U) // ...but panel modules always show a hand
comp.handle_input(@nested.InputEvent::PointerButton(0x110U, false), 22U) click_at(comp, lx.to_int(), ly.to_int(), 21U)
assert_true(comp.shell.popup_open()) assert_true(comp.shell.popup_open())
assert_true(comp.shell.slot_popup_rect(comp.shell.slot_of("launcher")).w > 0)
comp.handle_input(@nested.InputEvent::Key(30U, true), 23U) comp.handle_input(@nested.InputEvent::Key(30U, true), 23U)
let after = drain_msgs(c) assert_false(has_msg(drain_msgs(c), kbd_id, 3U)) // swallowed by the launcher
assert_false(has_msg(after, kbd_id, 3U)) // swallowed by the launcher
// Typing fills the search field: evdev 20 = t, 18 = e (key 30 = a was typed above).
comp.handle_input(@nested.InputEvent::Key(20U, true), 26U)
comp.handle_input(@nested.InputEvent::Key(18U, true), 27U)
assert_eq(comp.shell.launcher_state.query, "ate")
comp.handle_input(@nested.InputEvent::Key(14U, true), 28U)
assert_eq(comp.shell.launcher_state.query, "at")
// Off the shell and off any window: default arrow. // Off the shell and off any window: default arrow.
comp.handle_input(@nested.InputEvent::PointerMove(1270.0, 5.0), 25U) comp.handle_input(@nested.InputEvent::PointerMove(1270.0, 5.0), 25U)
assert_eq(comp.desired_cursor(), 1U) assert_eq(comp.desired_cursor(), 1U)
@@ -146,3 +177,357 @@ test "dragging the divider between two tiled windows resizes them" {
assert_true(right2.w > right.w + 200) assert_true(right2.w > right.w + 200)
assert_true(right2.x > left2.x + left2.w) assert_true(right2.x > left2.x + left2.w)
} }
///|
test "the layout module opens a popup to pick Tiling, Monocle or Floating" {
let socket_path = "/tmp/wayland-moon-layout-" +
@sys.getpid().to_string() +
".sock"
let theme = @scene.ThemeTokens::moon_night()
let comp = @host.MoonPlasmaCompositor::new(socket_path, theme, 1280, 720).unwrap()
let _a = open_and_configure_client(comp, socket_path, "A", "a")
let _b = open_and_configure_client(comp, socket_path, "B", "b")
ignore(comp.compose_frame())
let slot = comp.shell.slot_of("layout")
let (cx, cy) = center_of(comp, "layout")
comp.handle_input(@nested.InputEvent::PointerMove(cx, cy), 1U)
assert_eq(comp.desired_cursor(), 4U) // it is a button: hand cursor
// Pick row `i` from the popup the button opens.
let pick = fn(i : Int, t : UInt) raise {
click_at(comp, cx.to_int(), cy.to_int(), t) // open
let pr = comp.shell.slot_popup_rect(slot)
assert_true(pr.w > 0)
click_at(comp, pr.x + pr.w / 2, pr.y + 4 + i * 28 + 14, t + 3U)
assert_eq(comp.shell.slot_popup_rect(slot).w, 0)
}
assert_eq(comp.layout_mode, @wm.LayoutMode::Tiling)
let tiled_w = comp.windows.get(1UL).unwrap().geometry.w
// Opening alone changes nothing.
click_at(comp, cx.to_int(), cy.to_int(), 2U)
assert_true(comp.shell.slot_popup_rect(slot).w > 0)
assert_eq(comp.layout_mode, @wm.LayoutMode::Tiling)
// Escape closes without picking.
comp.handle_input(@nested.InputEvent::Key(1U, true), 3U)
assert_eq(comp.shell.slot_popup_rect(slot).w, 0)
pick(1, 10U)
assert_eq(comp.layout_mode, @wm.LayoutMode::Monocle)
assert_true(comp.windows.get(1UL).unwrap().geometry.w > tiled_w + 100)
pick(2, 20U)
assert_eq(comp.layout_mode, @wm.LayoutMode::Floating)
pick(0, 30U)
assert_eq(comp.layout_mode, @wm.LayoutMode::Tiling)
assert_eq(comp.windows.get(1UL).unwrap().geometry.w, tiled_w)
}
///|
test "title-bar buttons minimize, maximize and close windows" {
let socket_path = "/tmp/wayland-moon-btn-" +
@sys.getpid().to_string() +
".sock"
let theme = @scene.ThemeTokens::moon_night()
let comp = @host.MoonPlasmaCompositor::new(socket_path, theme, 1280, 720).unwrap()
let (c, _shm, _surf, _xdg, tl, _deco) = open_and_configure_client(comp, socket_path, "A", "a")
let _b = open_and_configure_client(comp, socket_path, "B", "b")
ignore(comp.compose_frame())
// Button centres, from the decoration layout (18px buttons, 10px from the right edge).
let btn = fn(wid : UInt64, n : Int) {
let g = comp.windows.get(wid).unwrap().geometry
let outer_w = g.w + 4
let x = g.x - 2 + outer_w - 10 - 9 - (3 - n) * 26
let y = g.y - 32 + 16
(x, y)
}
let click = fn(p : (Int, Int), t : UInt) {
click_at(comp, p.0, p.1, t)
}
// Maximize window 1: it grows.
let w0 = comp.windows.get(1UL).unwrap().geometry.w
click(btn(1UL, 2), 1U)
assert_true(comp.windows.get(1UL).unwrap().geometry.w > w0)
click(btn(1UL, 2), 10U)
assert_eq(comp.windows.get(1UL).unwrap().geometry.w, w0)
// Minimize window 1: it leaves the stacking order, then its pill in the task list restores it.
click(btn(1UL, 1), 20U)
assert_true(comp.wm.windows.get(1UL).unwrap().minimized)
assert_true(!comp.wm.stacking_order().contains(1UL))
let tasks = rect_of(comp, "tasks")
// pills: the visible window first, the minimized one second (140 wide, 6 apart)
click((tasks.x + 146 + 20, tasks.y + tasks.h / 2), 30U)
assert_true(!comp.wm.windows.get(1UL).unwrap().minimized)
// Close window 2: the client receives xdg_toplevel.close (opcode 1 on its toplevel).
ignore(drain_msgs(c))
click(btn(1UL, 3), 40U)
for _i = 0; _i < 5; _i = _i + 1 {
comp.step()
@sys.sleep_ms(2)
}
assert_true(has_msg(drain_msgs(c), tl, 1U))
}
///|
test "the task list module focuses the window whose pill is clicked" {
let socket_path = "/tmp/wayland-moon-tasks-" +
@sys.getpid().to_string() +
".sock"
let theme = @scene.ThemeTokens::moon_night()
let comp = @host.MoonPlasmaCompositor::new(socket_path, theme, 1280, 720).unwrap()
let _a = open_and_configure_client(comp, socket_path, "A", "a")
let _b = open_and_configure_client(comp, socket_path, "B", "b")
ignore(comp.compose_frame())
let focused = fn() {
let mut f = 0UL
for id, w in comp.windows {
if w.focused {
f = id
}
}
f
}
let tasks = rect_of(comp, "tasks")
assert_true(tasks.w > 300) // the stretching module takes the free space
let first = comp.wm.stacking_order()[0]
click_at(comp, tasks.x + 20, tasks.y + tasks.h / 2, 1U) // pill 0
assert_eq(focused(), first)
let other = comp.wm.stacking_order()
click_at(comp, tasks.x + 146 + 20, tasks.y + tasks.h / 2, 10U) // pill 1
assert_true(focused() != first || other.length() == 1)
}
///|
test "right-click a panel module to replace it in place, or remove it" {
let comp = new_comp("swap")
let before = comp.shell.slots()
let clock = rect_of(comp, "clock-digital12")
assert_true(clock.w > 0)
let find_row = fn(label : String) {
let mut i = -1
for k = 0; k < comp.shell.menu_rows.length(); k = k + 1 {
if comp.shell.menu_rows[k].label == label {
i = k
}
}
i
}
click_at(comp, clock.x + clock.w / 2, clock.y + clock.h / 2, 1U, btn=273U)
assert_true(comp.shell.menu_open)
let m = comp.shell.menu_rect
assert_true(m.w > 0 && m.y + m.h <= clock.y) // above the panel, not off-screen
let bin = find_row("Replace with Binary Clock")
assert_true(bin >= 0)
assert_true(find_row("Remove widget") >= 0)
assert_true(find_row("Module manager...") >= 0)
// Hover the row (hand cursor), click it: the binary clock takes the digital clock's place.
let ix = m.x + m.w / 2
let iy = m.y + 26 + 28 * bin + 14
comp.handle_input(@nested.InputEvent::PointerMove(ix.to_double(), iy.to_double()), 10U)
assert_eq(comp.desired_cursor(), 4U)
click_at(comp, ix, iy, 11U)
assert_true(!comp.shell.menu_open)
assert_eq(comp.shell.slot_of("clock-digital12"), "")
let after = comp.shell.slots()
assert_eq(after.length(), before.length())
assert_eq(after[after.length() - 1], comp.shell.slot_of("clock-binary")) // same place in the panel
assert_true(rect_of(comp, "clock-binary").w > 0)
// Escape dismisses the menu; "Remove widget" unloads the module.
let moon = rect_of(comp, "moon-disc")
click_at(comp, moon.x + moon.w / 2, moon.y + moon.h / 2, 20U, btn=273U)
assert_true(comp.shell.menu_open)
comp.handle_input(@nested.InputEvent::Key(1U, true), 30U)
assert_true(!comp.shell.menu_open)
click_at(comp, moon.x + moon.w / 2, moon.y + moon.h / 2, 40U, btn=273U)
let m2 = comp.shell.menu_rect
click_at(comp, m2.x + m2.w / 2, m2.y + 26 + 28 * find_row("Remove widget") + 14, 50U)
assert_eq(comp.shell.slot_of("moon-disc"), "")
assert_eq(comp.shell.slots().length(), before.length() - 1)
}
///|
test "tapping Super toggles the launcher; Super+key does not" {
let comp = new_comp("super")
let tap = fn(t : UInt) {
comp.handle_input(@nested.InputEvent::Key(125U, true), t)
comp.handle_input(@nested.InputEvent::Key(125U, false), t + 1U)
}
assert_false(comp.shell.popup_open())
tap(1U)
assert_true(comp.shell.popup_open())
tap(3U)
assert_false(comp.shell.popup_open())
// Super held while another key is pressed: not a tap.
comp.handle_input(@nested.InputEvent::Key(125U, true), 5U)
comp.handle_input(@nested.InputEvent::Key(30U, true), 6U)
comp.handle_input(@nested.InputEvent::Key(30U, false), 7U)
comp.handle_input(@nested.InputEvent::Key(125U, false), 8U)
assert_false(comp.shell.popup_open())
}
///|
test "the panel is saved to panel.edn and restored" {
// Never touch the user's real config: only run when a scratch dir is provided.
if @sys.getenv("MOON_PLASMA_TEST_CONFIG") == "1" {
let theme = @scene.ThemeTokens::moon_night()
let a = @shell.DesktopShell::new("x")
a.persist = true
a.set_output(theme, 1280, 720)
assert_true(a.unload_slot(a.slot_of("moon-disc")))
assert_true(a.load_module("clock-binary"))
let b = @shell.DesktopShell::new("x")
b.persist = true
b.set_output(theme, 1280, 720)
assert_eq(b.slot_of("moon-disc"), "")
assert_true(b.slot_of("clock-binary") != "")
assert_eq(b.slots().length(), a.slots().length())
}
}
///|
test "the wasm picker opens the module manager, which loads and unloads modules" {
let comp = new_comp("manager")
// The manager is not in the default panel: the picker loads it on demand.
assert_eq(comp.shell.slot_of("module-manager"), "")
let n0 = comp.shell.slots().length()
// Right-click empty panel space (the margin): the menu offers the module manager.
let panel = comp.shell.panel_rect
click_at(comp, 1, panel.y + 5, 1U, btn=273U)
assert_true(comp.shell.menu_open)
assert_eq(comp.shell.menu_rows[0].label, "Module manager...")
let m = comp.shell.menu_rect
click_at(comp, m.x + m.w / 2, m.y + 26 + 14, 10U)
assert_eq(comp.shell.slots().length(), n0 + 1)
let mgr = comp.shell.slot_of("module-manager")
assert_true(mgr != "")
ignore(comp.compose_frame())
let pr = comp.shell.slot_popup_rect(mgr)
assert_true(pr.w > 0) // the picker opened the app's popup
// Rows: header(24), one per loaded module (28), header(24), one per available module (28), browse.
let loaded = comp.shell.slots().length()
let avail_y = fn(k : Int) { pr.y + 4 + 24 + loaded * 28 + 24 + k * 28 + 14 }
let mut k_bin = -1
for k = 0; k < comp.shell.catalog.length(); k = k + 1 {
if comp.shell.catalog[k].id == "clock-binary" {
k_bin = k
}
}
assert_true(k_bin >= 0)
assert_eq(comp.shell.slot_of("clock-binary"), "")
click_at(comp, pr.x + 40, avail_y(k_bin), 20U) // select it: it is loaded into the panel
assert_true(comp.shell.slot_of("clock-binary") != "")
assert_eq(comp.shell.slots().length(), loaded + 1)
// The popup stays open; click the loaded module's row to unload it again.
let pr2 = comp.shell.slot_popup_rect(mgr)
assert_true(pr2.w > 0)
let slots = comp.shell.slots()
let mut idx = -1
for i = 0; i < slots.length(); i = i + 1 {
if slots[i] == comp.shell.slot_of("clock-binary") {
idx = i
}
}
click_at(comp, pr2.x + 40, pr2.y + 4 + 24 + idx * 28 + 14, 30U)
assert_eq(comp.shell.slot_of("clock-binary"), "")
assert_eq(comp.shell.slots().length(), loaded)
// The manager is just another module: it can be removed too, and the picker brings it back.
assert_true(comp.shell.unload_slot(mgr))
assert_eq(comp.shell.slot_of("module-manager"), "")
assert_true(comp.shell.open_module_manager())
assert_true(comp.shell.slot_of("module-manager") != "")
}
///|
test "dragging a panel module reorders it" {
let comp = new_comp("wdrag")
let order0 = comp.shell.slots()
let moon = rect_of(comp, "moon-disc")
let clock = rect_of(comp, "clock-digital12")
assert_true(moon.x < clock.x)
let cy = (clock.y + clock.h / 2).to_double()
comp.handle_input(@nested.InputEvent::PointerMove((clock.x + clock.w / 2).to_double(), cy), 1U)
assert_eq(comp.desired_cursor(), 4U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, true), 2U)
// Drag the clock left past the moon.
comp.handle_input(@nested.InputEvent::PointerMove((moon.x + 2).to_double(), cy), 3U)
assert_eq(comp.desired_cursor(), 17U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 4U)
ignore(comp.compose_frame())
let order1 = comp.shell.slots()
assert_eq(order1.length(), order0.length())
assert_true(order1 != order0)
assert_eq(order1[order1.length() - 2], comp.shell.slot_of("clock-digital12"))
assert_true(rect_of(comp, "clock-digital12").x < rect_of(comp, "moon-disc").x)
assert_true(comp.desired_cursor() != 17U)
}
///|
test "any .wasm plasmoid can be loaded from a path and unloaded again" {
let comp = new_comp("path")
let n0 = comp.shell.slots().length()
let theme = @scene.ThemeTokens::moon_night()
ignore(theme)
assert_true(comp.shell.load_path("compositor/wasm/testdata/clock-digital.component.wasm") is Some(_))
assert_eq(comp.shell.slots().length(), n0 + 1)
ignore(comp.compose_frame())
let slot = comp.shell.slots()[n0]
assert_true(comp.shell.slot_rect(slot).w > 0) // it got a panel placement and was drawn
assert_true(comp.shell.load_path("compositor/wasm/testdata/missing.wasm") is None)
assert_eq(comp.shell.slots().length(), n0 + 1)
// It unloads like any module.
assert_true(comp.shell.unload_slot(slot))
ignore(comp.compose_frame())
assert_eq(comp.shell.slot_rect(slot).w, 0)
}
///|
test "modules are added until the panel is full" {
let comp = new_comp("full")
let n0 = comp.shell.slots().length()
let mut added = 0
for _i = 0; _i < 40; _i = _i + 1 {
if comp.shell.load_module("moon-disc") {
added = added + 1
}
}
assert_true(added > 2 && added < 40)
assert_eq(comp.shell.slots().length(), n0 + added)
ignore(comp.compose_frame())
assert_true(rect_of(comp, "moon-disc").w > 0)
}
///|
test "Desktop Pulse reads live machine and window state through its granted interfaces and can raise a window" {
let socket_path = "/tmp/wayland-moon-pulse-" +
@sys.getpid().to_string() +
".sock"
let theme = @scene.ThemeTokens::moon_night()
let comp = @host.MoonPlasmaCompositor::new(socket_path, theme, 1280, 720).unwrap()
let _a = open_and_configure_client(comp, socket_path, "A", "a")
let _b = open_and_configure_client(comp, socket_path, "B", "b")
ignore(comp.compose_frame())
let n0 = comp.shell.slots().length()
assert_true(comp.shell.load_path("compositor/wasm/testdata/pulse.component.wasm") is Some(_))
// Its capability grant is exactly what the component imports; nothing else is reachable.
let slot = comp.shell.slots()[n0]
let w = comp.shell.widgets[n0]
assert_eq(w.slot, slot)
assert_eq(w.caps.length(), 3)
assert_true(w.caps.contains("system") && w.caps.contains("theme") && w.caps.contains("windows"))
ignore(comp.compose_frame())
// The host provider fed it real numbers and the window list.
assert_true(comp.shell.sampler.cur.mem_total_kib > 0L)
assert_true(comp.shell.sampler.cur.uptime_secs > 0L)
assert_eq(comp.shell.win_list.length(), 2)
let r = comp.shell.slot_rect(slot)
assert_true(r.w >= 300)
// Clicking each window's chip raises that window (first chip starts at x = 280).
for i = 0; i < 2; i = i + 1 {
let id = comp.shell.win_list[i].id
let cx = r.x + 280 + i * 23 + 10
let cy = r.y + r.h / 2
comp.handle_input(@nested.InputEvent::PointerMove(cx.to_double(), cy.to_double()), (10 + i * 4).reinterpret_as_uint())
comp.handle_input(@nested.InputEvent::PointerButton(272U, true), (11 + i * 4).reinterpret_as_uint())
comp.handle_input(@nested.InputEvent::PointerButton(272U, false), (12 + i * 4).reinterpret_as_uint())
ignore(comp.compose_frame())
assert_true(comp.windows.get(id).unwrap().focused)
let others_focused = comp.windows.iter().filter(kv => kv.0 != id && kv.1.focused).count()
assert_eq(others_focused, 0)
}
}
+58
View File
@@ -0,0 +1,58 @@
///| Interface Explorer: toggle from the panel, hover components, see their WIT.
///|
test "inspector shows the WIT interface of the hovered component" {
let socket_path = "/tmp/wayland-moon-inspect-" +
@sys.getpid().to_string() +
".sock"
let theme = @scene.ThemeTokens::moon_night()
let comp = @host.MoonPlasmaCompositor::new(socket_path, theme, 1280, 720).unwrap()
let (c, shm, surf, xdg, _tl, _deco) = open_and_configure_client(
comp, socket_path, "T", "t",
)
commit_shm_frame(comp, c, shm, surf, xdg, 1UL)
ignore(comp.compose_frame()) // lays out the panel
assert_false(comp.shell.inspecting())
// Open the apps popup first; turning the explorer on must not close it.
let (lx, ly) = center_of(comp, "launcher")
click_at(comp, lx.to_int(), ly.to_int(), 0U)
assert_true(comp.shell.popup_open())
// Click the Interface Explorer button to turn inspect mode on.
let (bx, by) = center_of(comp, "inspector")
click_at(comp, bx.to_int(), by.to_int(), 1U)
assert_true(comp.shell.inspecting())
assert_true(comp.shell.popup_open())
assert_eq(comp.desired_cursor(), 4U)
// Hover the launcher.
let (lx, ly) = center_of(comp, "launcher")
comp.handle_input(@nested.InputEvent::PointerMove(lx, ly), 4U)
let lslot = comp.shell.slot_of("launcher")
assert_eq(comp.shell.hover_id, lslot)
assert_eq(comp.desired_cursor(), 3U)
// The explorer describes the module's real binary: what it exports and which capabilities it imports.
let lines = comp.shell.inspector_lines_for(lslot)
assert_true(lines.iter().any(l => l.has_prefix("# plasmoid")))
assert_true(lines.iter().any(l => l.has_prefix("# app launch")))
assert_true(lines.iter().any(l => l.has_prefix("# app catalog")))
let frame = comp.compose_frame()
let png = @renderer.encode_png(frame)
ignore(@sys.write_file_bytes("_build/inspector_launcher.png", png))
// Clock, panel, window title bar and desktop resolve to their own components.
let (cx, cy) = center_of(comp, "clock-digital12")
comp.handle_input(@nested.InputEvent::PointerMove(cx, cy), 5U)
assert_eq(comp.shell.hover_id, comp.shell.slot_of("clock-digital12"))
comp.handle_input(@nested.InputEvent::PointerMove(1270.0, 5.0), 6U)
assert_eq(comp.shell.hover_id, "desktop")
// Clicks are swallowed while inspecting; Escape leaves the mode.
comp.handle_input(@nested.InputEvent::PointerButton(0x110U, true), 7U)
assert_true(comp.shell.popup_open()) // unchanged: the click was swallowed
comp.handle_input(@nested.InputEvent::Key(1U, true), 8U)
assert_false(comp.shell.inspecting())
comp.close()
}
+10
View File
@@ -4,10 +4,20 @@ import {
"moonplasma/desktop/compositor/sys" @sys, "moonplasma/desktop/compositor/sys" @sys,
"moonplasma/desktop/compositor/scene" @scene, "moonplasma/desktop/compositor/scene" @scene,
"moonplasma/desktop/compositor/shell" @shell, "moonplasma/desktop/compositor/shell" @shell,
"moonplasma/desktop/compositor/wasm" @wasm,
"moonplasma/desktop/compositor/nested" @nested, "moonplasma/desktop/compositor/nested" @nested,
"moonplasma/desktop/compositor/font" @font,
"moonplasma/desktop/compositor/renderer" @renderer, "moonplasma/desktop/compositor/renderer" @renderer,
"moonplasma/desktop/compositor/wayland" @wayland, "moonplasma/desktop/compositor/wayland" @wayland,
"moonplasma/desktop/compositor/gfx" @gfx, "moonplasma/desktop/compositor/gfx" @gfx,
} }
supported_targets = "-all+native" supported_targets = "-all+native"
options(
link: {
"native": {
"cc-link-flags": "-lwasmer",
},
},
)
+10
View File
@@ -7,6 +7,8 @@
pub(all) enum InputEvent { pub(all) enum InputEvent {
PointerMove(Double, Double) PointerMove(Double, Double)
PointerButton(UInt, Bool) PointerButton(UInt, Bool)
/// Vertical wheel scroll in wl_fixed units / 256 (positive = down).
Scroll(Double)
Key(UInt, Bool) Key(UInt, Bool)
Modifiers(UInt, UInt, UInt, UInt) Modifiers(UInt, UInt, UInt, UInt)
} }
@@ -241,6 +243,14 @@ fn NestedWindow::dispatch(
let state = r.u32() let state = r.u32()
self.input.push(PointerButton(button, state == 1U)) self.input.push(PointerButton(button, state == 1U))
} }
4U => {
let _time = r.u32()
let axis = r.u32()
let value = r.i32().to_double() / 256.0
if axis == 0U {
self.input.push(Scroll(value))
}
}
_ => () _ => ()
} }
} else if self.live_buffers.contains(obj) { } else if self.live_buffers.contains(obj) {
+14
View File
@@ -16,9 +16,23 @@ pub fn encode_ppm(Pixmap) -> Bytes
pub fn render_scene(@scene.SceneGraph) -> Pixmap pub fn render_scene(@scene.SceneGraph) -> Pixmap
pub fn set_glyph_source((Int32, Int32, Bool, Bool) -> Glyph) -> Unit
pub fn text_width(String, Int32, Bool, Bool) -> Int32
// Errors // Errors
// Types and methods // Types and methods
pub(all) struct Glyph {
w : Int32
h : Int32
xoff : Int32
yoff : Int32
advance : Int32
coverage : Bytes
embolden : Bool
}
pub(all) struct Pixmap { pub(all) struct Pixmap {
width : Int32 width : Int32
height : Int32 height : Int32
+136 -8
View File
@@ -259,13 +259,22 @@ fn draw_circle(
let cg = color.g.to_int() let cg = color.g.to_int()
let cb = color.b.to_int() let cb = color.b.to_int()
let ca = color.a.to_int() let ca = color.a.to_int()
let r2 = radius * radius // Antialiased: per-pixel coverage from the distance to the edge (1px wide ring when unfilled).
let inner_r2 = if radius > 1 { (radius - 1) * (radius - 1) } else { 0 } let rad = radius.to_double()
for dy = -radius; dy <= radius; dy = dy + 1 { for dy = -radius - 1; dy <= radius + 1; dy = dy + 1 {
for dx = -radius; dx <= radius; dx = dx + 1 { for dx = -radius - 1; dx <= radius + 1; dx = dx + 1 {
let d2 = dx * dx + dy * dy let d = (dx * dx + dy * dy).to_double().sqrt()
if d2 <= r2 && (filled || d2 >= inner_r2) { let outer = rad + 0.5 - d
blend_pixel(dst, cx + dx, cy + dy, cr, cg, cb, ca, clip) let mut cov = if outer > 1.0 { 1.0 } else { outer }
if !filled {
let inner = d - (rad - 1.0 - 0.5)
let ic = if inner > 1.0 { 1.0 } else { inner }
if ic < cov {
cov = ic
}
}
if cov > 0.02 {
blend_pixel(dst, cx + dx, cy + dy, cr, cg, cb, (ca.to_double() * cov).round().to_int(), clip)
} }
} }
} }
@@ -378,8 +387,98 @@ fn glyph_rows(ch : Int) -> Array[Int] {
} }
} }
///| A rasterised glyph: 8-bit coverage `w`x`h`, top-left at (xoff, yoff)
/// relative to the pen position on the baseline.
pub(all) struct Glyph {
w : Int
h : Int
xoff : Int
yoff : Int
advance : Int
coverage : Bytes
/// Draw twice, 1px apart (faces without a real bold).
embolden : Bool
}
///| Optional real-font glyph source: (codepoint, pixel size, bold) -> glyph.
/// Unset (e.g. in wasm builds), text uses the built-in 5x7 bitmap font.
let glyph_source : Ref[((Int, Int, Bool, Bool) -> Glyph)?] = { val: None }
///|
pub fn set_glyph_source(f : (Int, Int, Bool, Bool) -> Glyph) -> Unit {
glyph_source.val = Some(f)
}
///| Pixel width `text` would occupy when drawn with the given face.
pub fn text_width(text : String, size : Int, bold : Bool, mono : Bool) -> Int {
match glyph_source.val {
Some(src) => {
let mut w = 0
for ch in text {
let g = src(ch.to_int(), size, bold, mono)
w = w + g.advance + (if g.embolden { 1 } else { 0 })
}
w
}
None => text.length() * (if size >= 14 { 12 } else { 6 })
}
}
///|
fn draw_text_font(
dst : Pixmap,
src : (Int, Int, Bool, Bool) -> Glyph,
mono : Bool,
x : Int,
y : Int,
text : String,
size : Int,
color : @scene.Rgba,
align : @scene.TextAlign,
bold : Bool,
clip : @scene.Rect?,
) -> Unit {
let glyphs : Array[Glyph] = []
let mut total_w = 0
for ch in text {
let g = src(ch.to_int(), size, bold, mono)
glyphs.push(g)
total_w = total_w + g.advance + (if g.embolden { 1 } else { 0 })
}
let start_x = match align {
Left => x
Center => x - total_w / 2
Right => x - total_w
}
// `y` is the vertical centre of the text; centre the capital height on it.
let cap = src(72, size, false, mono) // 'H'
let baseline = y + (-cap.yoff) / 2
let cr = color.r.to_int()
let cg = color.g.to_int()
let cb = color.b.to_int()
let ca = color.a.to_int()
let mut pen = start_x
for g in glyphs {
for row = 0; row < g.h; row = row + 1 {
for col = 0; col < g.w; col = col + 1 {
let cov = g.coverage[row * g.w + col].to_int()
if cov > 0 {
let px = pen + g.xoff + col
let py = baseline + g.yoff + row
blend_pixel(dst, px, py, cr, cg, cb, ca * cov / 255, clip)
if g.embolden {
blend_pixel(dst, px + 1, py, cr, cg, cb, ca * cov / 255, clip)
}
}
}
}
pen = pen + g.advance + (if g.embolden { 1 } else { 0 })
}
}
///| ///|
fn draw_text( fn draw_text(
mono : Bool,
dst : Pixmap, dst : Pixmap,
x : Int, x : Int,
y : Int, y : Int,
@@ -393,6 +492,13 @@ fn draw_text(
if text.length() == 0 || color.a.to_int() == 0 { if text.length() == 0 || color.a.to_int() == 0 {
return return
} }
match glyph_source.val {
Some(src) => {
draw_text_font(dst, src, mono, x, y, text, size, color, align, bold, clip)
return
}
None => ()
}
let scale = if size >= 14 { 2 } else { 1 } let scale = if size >= 14 { 2 } else { 1 }
let char_w = 6 * scale let char_w = 6 * scale
let total_w = text.length() * char_w let total_w = text.length() * char_w
@@ -469,7 +575,9 @@ pub fn draw_ops(
Circle(cx, cy, rad, col, filled) => Circle(cx, cy, rad, col, filled) =>
draw_circle(dst, cx + ox, cy + oy, rad, col, filled, cur_clip) draw_circle(dst, cx + ox, cy + oy, rad, col, filled, cur_clip)
Text(x, y, txt, sz, col, align, bold) => Text(x, y, txt, sz, col, align, bold) =>
draw_text(dst, x + ox, y + oy, txt, sz, col, align, bold, cur_clip) draw_text(false, dst, x + ox, y + oy, txt, sz, col, align, bold, cur_clip)
MonoText(x, y, txt, sz, col, align, bold) =>
draw_text(true, dst, x + ox, y + oy, txt, sz, col, align, bold, cur_clip)
PushClip(r) => PushClip(r) =>
clip_stack.push(@scene.Rect::new(r.x + ox, r.y + oy, r.w, r.h)) clip_stack.push(@scene.Rect::new(r.x + ox, r.y + oy, r.w, r.h))
PopClip => if clip_stack.length() > 0 { ignore(clip_stack.pop()) } PopClip => if clip_stack.length() > 0 { ignore(clip_stack.pop()) }
@@ -486,6 +594,26 @@ pub fn blit_shm_surface(
if buf.width <= 0 || buf.height <= 0 || dst_rect.w <= 0 || dst_rect.h <= 0 { if buf.width <= 0 || buf.height <= 0 || dst_rect.w <= 0 || dst_rect.h <= 0 {
return return
} }
// While the client catches up with a resize, its buffer is smaller than the window:
// extend the buffer's bottom-right colour over the rest instead of showing the wallpaper.
if (buf.width < dst_rect.w || buf.height < dst_rect.h) &&
buf.stride * buf.height <= buf.bytes.length() &&
buf.width > 0 {
let o = (buf.height - 1) * buf.stride + (buf.width - 1) * 4
let a = if buf.format == 1 { 255 } else { buf.bytes[o + 3].to_int() }
fill_rounded_rect(
dst,
dst_rect,
@scene.Rgba::new(
buf.bytes[o + 2].to_int(),
buf.bytes[o + 1].to_int(),
buf.bytes[o].to_int(),
a,
),
0,
None,
)
}
let copy_w = if buf.width < dst_rect.w { buf.width } else { dst_rect.w } let copy_w = if buf.width < dst_rect.w { buf.width } else { dst_rect.w }
let copy_h = if buf.height < dst_rect.h { buf.height } else { dst_rect.h } let copy_h = if buf.height < dst_rect.h { buf.height } else { dst_rect.h }
let is_xrgb = buf.format == 1 let is_xrgb = buf.format == 1
+1
View File
@@ -28,6 +28,7 @@ pub(all) enum DrawOp {
Line(Int32, Int32, Int32, Int32, Rgba, Int32) Line(Int32, Int32, Int32, Int32, Rgba, Int32)
Circle(Int32, Int32, Int32, Rgba, Bool) Circle(Int32, Int32, Int32, Rgba, Bool)
Text(Int32, Int32, String, Int32, Rgba, TextAlign, Bool) Text(Int32, Int32, String, Int32, Rgba, TextAlign, Bool)
MonoText(Int32, Int32, String, Int32, Rgba, TextAlign, Bool)
PushClip(Rect) PushClip(Rect)
PopClip PopClip
} }
+2
View File
@@ -224,6 +224,8 @@ pub(all) enum DrawOp {
Line(Int, Int, Int, Int, Rgba, Int) Line(Int, Int, Int, Int, Rgba, Int)
Circle(Int, Int, Int, Rgba, Bool) Circle(Int, Int, Int, Rgba, Bool)
Text(Int, Int, String, Int, Rgba, TextAlign, Bool) Text(Int, Int, String, Int, Rgba, TextAlign, Bool)
/// Same as Text but in the monospace face (code listings).
MonoText(Int, Int, String, Int, Rgba, TextAlign, Bool)
PushClip(Rect) PushClip(Rect)
PopClip PopClip
} }
+166
View File
@@ -0,0 +1,166 @@
///| Installed desktop applications, discovered from freedesktop `.desktop` files
/// (XDG data dirs + flatpak exports). Feeds the launcher's search.
///|
priv struct DesktopApp {
id : String
name : String
comment : String
category : String
command : String
}
///| Directories scanned, lowest priority first (later ones override by file name).
fn app_dirs() -> Array[String] {
let home = @sys.getenv("HOME")
let data_home = {
let x = @sys.getenv("XDG_DATA_HOME")
if x.length() > 0 { x } else { home + "/.local/share" }
}
let dirs : Array[String] = []
let xdg = @sys.getenv("XDG_DATA_DIRS")
let list = if xdg.length() > 0 { xdg } else { "/usr/local/share:/usr/share" }
let parts : Array[String] = list.split(":").map(x => x.to_string()).collect()
// XDG_DATA_DIRS is highest priority first; we want lowest first.
for i = parts.length() - 1; i >= 0; i = i - 1 {
if parts[i].length() > 0 {
dirs.push(parts[i] + "/applications")
}
}
dirs.push("/var/lib/flatpak/exports/share/applications")
dirs.push(home + "/.local/share/flatpak/exports/share/applications")
dirs.push(data_home + "/applications")
dirs
}
///| Drop Exec field codes (%f %U ...), keep a literal %%.
fn clean_exec(exec : String) -> String {
let sb = StringBuilder::new()
let chars = exec.to_array()
let mut i = 0
while i < chars.length() {
if chars[i] == '%' && i + 1 < chars.length() {
if chars[i + 1] == '%' {
sb.write_char('%')
}
i = i + 2
} else {
sb.write_char(chars[i])
i = i + 1
}
}
sb.to_string().trim(chars=" ").to_string()
}
///| Parse one .desktop file; None when it should not be listed.
fn parse_desktop(id : String, text : String, have_terminal : Bool) -> DesktopApp? {
let mut in_entry = false
let mut name = ""
let mut generic = ""
let mut comment = ""
let mut exec = ""
let mut cats = ""
let mut hidden = false
let mut terminal = false
let mut kind = "Application"
for raw in text.split("\n") {
let line = raw.trim(chars=" \r\t").to_string()
if line.length() == 0 || line.has_prefix("#") {
continue
}
if line.has_prefix("[") {
in_entry = line == "[Desktop Entry]"
continue
}
if !in_entry {
continue
}
match line.find("=") {
None => ()
Some(eq) => {
let key = line[:eq].trim(chars=" ").to_string()
let val = line[eq + 1:].trim(chars=" ").to_string()
match key {
"Name" => name = val
"GenericName" => generic = val
"Comment" => comment = val
"Exec" => exec = val
"Categories" => cats = val
"Type" => kind = val
"NoDisplay" | "Hidden" => if val == "true" { hidden = true }
"Terminal" => terminal = val == "true"
_ => ()
}
}
}
}
if hidden || kind != "Application" || name.length() == 0 || exec.length() == 0 {
return None
}
if terminal && !have_terminal {
return None
}
let mut command = clean_exec(exec)
if terminal {
command = "foot -e " + command
}
let category = match cats.split(";").next() {
Some(c) if c.length() > 0 => c.to_string()
_ => "Other"
}
let comment = if comment.length() > 0 { comment } else { generic }
Some({ id, name, comment, category, command })
}
///| Scan every applications dir; later dirs override earlier ones, result sorted by name.
fn scan_desktop_apps() -> Array[DesktopApp] {
let have_terminal = @sys.has_exe("foot")
let by_id : Map[String, DesktopApp] = {}
let removed : Map[String, Bool] = {}
for dir in app_dirs() {
for file in @sys.list_desktop_files(dir) {
let bytes = @sys.read_file_bytes(dir + "/" + file)
let id = file[:file.length() - 8].to_string()
match parse_desktop(id, @utf8.decode_lossy(bytes), have_terminal) {
Some(app) => {
by_id.set(id, app)
removed.remove(id)
}
None => {
by_id.remove(id)
}
}
}
}
let apps : Array[DesktopApp] = []
for _, a in by_id {
apps.push(a)
}
apps.sort_by(fn(a, b) {
let x = a.name.to_lower()
let y = b.name.to_lower()
if x < y { -1 } else if x > y { 1 } else { 0 }
})
apps
}
///|
test "parse_desktop reads a normal entry and strips field codes" {
let t = "[Desktop Entry]\nType=Application\nName=Firefox\nName[de]=Feuerfuchs\nComment=Browse\nExec=firefox %u\nCategories=Network;WebBrowser;\n[Desktop Action x]\nName=Nope\n"
match parse_desktop("firefox", t, true) {
Some(a) => {
assert_eq(a.name, "Firefox")
assert_eq(a.command, "firefox")
assert_eq(a.category, "Network")
assert_eq(a.comment, "Browse")
}
None => fail("expected entry")
}
}
///|
test "parse_desktop hides NoDisplay entries" {
let t = "[Desktop Entry]\nType=Application\nName=X\nExec=x\nNoDisplay=true\n"
assert_true(parse_desktop("x", t, true) is None)
}
+44
View File
@@ -0,0 +1,44 @@
///| Desktop widget: a card on the wallpaper (below all windows, top-right) showing
/// the time, the date and the current moon phase. Built from the same pure lib/*
/// renderers as the panel widgets.
///|
let desktop_widget_w : Int = 260
///|
let desktop_widget_h : Int = 120
///|
fn render_desktop_widget(
screen_w : Int,
tokens : @theme.Tokens,
at : @types.Datetime,
out : Array[@scene.DrawOp],
) -> Unit {
let r = tokens.radius.reinterpret_as_int()
let hour = at.hour.to_int()
let minute = at.minute.to_int()
let time = @timefmt.hhmm12(hour, minute)
let date = @timefmt.weekday_short(at.weekday.to_int()) +
", " +
at.day.to_int().to_string() +
" " +
@timefmt.month_short(at.month.to_int())
let p = @moon.phase(at.year.reinterpret_as_int(), at.month.to_int(), at.day.to_int())
let ops : Array[@types.DrawOp] = [
@ui.fill_rect(@ui.rect(0, 0, desktop_widget_w, desktop_widget_h), tokens.palette.surface, radius=r),
@ui.stroke_rect(@ui.rect(0, 0, desktop_widget_w, desktop_widget_h), tokens.palette.border, width=1, radius=r),
@ui.text(18, 38, time, 32, tokens.palette.foreground, bold=true),
@ui.text(18, 74, date, tokens.font_size.reinterpret_as_int(), tokens.palette.foreground),
@ui.text(
18,
98,
@moon.phase_name(p) + " " + @moon.illumination(p).to_string() + "%",
tokens.font_size.reinterpret_as_int() - 2,
tokens.palette.foreground,
),
]
let x0 = screen_w - desktop_widget_w - 24
translate(ops, x0, 24, out)
translate(@moon.render_disc(@ui.size(56, 56), tokens, p), x0 + desktop_widget_w - 56 - 18, 24 + 18, out)
}
+429
View File
@@ -0,0 +1,429 @@
///| Turns WIT source into narrative prose for the Interface Explorer.
///
/// Output is one paragraph per line (the renderer word-wraps), with `""` between
/// paragraphs. A `# ` prefix marks a heading. Terms are wrapped in `**bold**`.
///|
fn trim(s : String) -> String {
s.trim(chars=" \t\r").to_string()
}
///| "window-state" -> "window state"
fn dashes(s : String) -> String {
let sb = StringBuilder::new()
for ch in s {
sb.write_char(if ch == '-' { ' ' } else { ch })
}
sb.to_string()
}
///|
fn pad(n : Int) -> String {
let sb = StringBuilder::new()
for _i = 0; _i < n; _i = _i + 1 {
sb.write_char(' ')
}
sb.to_string()
}
///| Split on `sep` outside <...>, (...) and {...}.
fn split_top(s : String, sep : Char) -> Array[String] {
let out : Array[String] = []
let mut depth = 0
let mut start = 0
for i = 0; i < s.length(); i = i + 1 {
let ch = s[i]
if ch == '<' || ch == '(' || ch == '{' {
depth = depth + 1
} else if ch == '>' || ch == ')' || ch == '}' {
depth = depth - 1
} else if ch == sep.to_int().to_uint16() && depth == 0 {
out.push(trim(s[start:i].to_string()))
start = i + 1
}
}
let last = trim(s[start:].to_string())
if last.length() > 0 {
out.push(last)
}
out
}
///| Index of `ch` in `s`, or -1.
fn index_of(s : String, ch : Char) -> Int {
for i = 0; i < s.length(); i = i + 1 {
if s[i] == ch.to_int().to_uint16() {
return i
}
}
-1
}
///| Index of the last `ch` in `s`, or -1.
fn last_index_of(s : String, ch : Char) -> Int {
for i = s.length() - 1; i >= 0; i = i - 1 {
if s[i] == ch.to_int().to_uint16() {
return i
}
}
-1
}
///| A WIT type in words.
fn ty(t0 : String) -> String {
let t = trim(t0)
match t {
"string" => "text"
"bool" => "yes/no"
"u8" | "u16" | "u32" | "u64" | "s8" | "s16" | "s32" | "s64" | "f32" | "f64" =>
"number"
"char" => "a character"
"_" => "nothing"
_ => {
let lt = index_of(t, '<')
if lt > 0 && t.has_suffix(">") {
let head = t[:lt].to_string()
let args = split_top(t[lt + 1:t.length() - 1].to_string(), ',')
let a0 = if args.length() > 0 { ty(args[0]) } else { "" }
match head {
"list" => "list of " + a0
"option" => "optional " + a0
"borrow" | "own" => a0
"tuple" => "(" + args.map(ty).join(", ") + ")"
"result" => {
let err = if args.length() > 1 { ty(args[1]) } else { "" }
let ok = if a0 == "nothing" { "success" } else { a0 }
if err == "" || err == "nothing" {
ok + ", or failure"
} else {
ok + ", or an error (" + err + ")"
}
}
_ => dashes(t)
}
} else {
dashes(t)
}
}
}
}
///| Strip "///" and one space.
fn doc_text(l : String) -> String {
trim(trim(l)[3:].to_string())
}
///|
fn bold(s : String) -> String {
"**" + s + "**"
}
///| Join with commas and a final "and".
fn and_list(items : Array[String]) -> String {
if items.length() == 0 {
"nothing"
} else if items.length() == 1 {
items[0]
} else {
items[:items.length() - 1].to_array().join(", ") +
" and " +
items[items.length() - 1]
}
}
///| Docs as running text, with a trailing space if non-empty.
fn doc_prose(docs : Array[String]) -> String {
if docs.length() == 0 {
""
} else {
let t = docs.join(" ")
(if t.has_suffix(".") { t } else { t + "." }) + " "
}
}
///| "name: func(a: t, b: t) -> r" as one sentence.
fn func_sentence(entry : String) -> String {
let c = index_of(entry, ':')
let name = dashes(trim(entry[:c].to_string()))
let rest = entry[c + 1:].to_string()
let open = index_of(rest, '(')
let mut depth = 0
let mut close = -1
for i = open; i >= 0 && i < rest.length(); i = i + 1 {
if rest[i] == '(' {
depth = depth + 1
} else if rest[i] == ')' {
depth = depth - 1
if depth == 0 {
close = i
break
}
}
}
let params = if open >= 0 && close > open {
split_top(rest[open + 1:close].to_string(), ',')
} else {
[]
}
let after = if close >= 0 { rest[close + 1:].to_string() } else { "" }
let arrow = after.find("->")
let ret = match arrow {
Some(i) => trim(after[i + 2:].to_string())
None => ""
}
let gives = if ret == "" { "returns nothing" } else { "returns " + ty(ret) }
if params.length() == 0 {
bold(name) + " " + gives + "."
} else {
let ps = params.map(fn(p) {
let pc = index_of(p, ':')
if pc < 0 {
bold(dashes(p))
} else {
bold(dashes(trim(p[:pc].to_string()))) +
" (" +
ty(p[pc + 1:].to_string()) +
")"
}
})
bold(name) + " takes " + and_list(ps) + " and " + gives + "."
}
}
///| One field / case / call as a clause, plus its docs.
fn entry_sentence(kind : String, entry : String, docs : Array[String]) -> String {
let e = trim(entry)
let body = if e.contains(": func(") {
func_sentence(e)
} else if kind == "record" {
let c = index_of(e, ':')
if c >= 0 {
bold(dashes(trim(e[:c].to_string()))) + " is " + ty(e[c + 1:].to_string()) + "."
} else {
bold(dashes(e)) + "."
}
} else if kind == "variant" {
let p = index_of(e, '(')
if p > 0 && e.has_suffix(")") {
bold(dashes(e[:p].to_string())) +
" carries " +
ty(e[p + 1:e.length() - 1].to_string()) +
"."
} else {
bold(dashes(e)) + " carries nothing."
}
} else {
bold(dashes(e)) + "."
}
body + (if docs.length() > 0 { " " + doc_prose(docs).trim(chars=" ").to_string() } else { "" })
}
///| Plain-English rendering of a `interface <name> { ... }` block (as returned by extract_block).
fn humanise_interface(name : String, block : Array[String]) -> Array[String] {
let out : Array[String] = []
let mut i = 0
let head_docs : Array[String] = []
while i < block.length() && trim(block[i]).has_prefix("///") {
head_docs.push(doc_text(block[i]))
i = i + 1
}
out.push("# " + dashes(name) + " (interface)")
if head_docs.length() > 0 {
out.push(doc_prose(head_docs).trim(chars=" ").to_string())
}
i = i + 1 // header line
let mut pending : Array[String] = []
let mut calls_shown = false
let kinds = ["record", "enum", "variant", "flags", "resource"]
while i < block.length() {
let l = trim(block[i])
i = i + 1
if l.has_prefix("///") {
pending.push(doc_text(l))
continue
}
if l == "" || l == "}" {
continue
}
if l.has_prefix("use ") {
pending = []
continue
}
let kw = first_word(l)
if kinds.contains(kw) {
let nm = dashes(first_word(trim(l[kw.length():].to_string())))
let entries : Array[(Array[String], String)] = []
let lb = index_of(l, '{')
let rb = last_index_of(l, '}')
if lb >= 0 && rb > lb {
for e in split_top(l[lb + 1:rb].to_string(), ',') {
entries.push(([], e))
}
} else {
let mut ed : Array[String] = []
while i < block.length() {
let el = trim(block[i])
i = i + 1
if el.has_prefix("}") {
break
}
if el.has_prefix("///") {
ed.push(doc_text(el))
} else if el != "" {
let clean = if el.has_suffix(",") || el.has_suffix(";") {
el[:el.length() - 1].to_string()
} else {
el
}
entries.push((ed, clean))
ed = []
}
}
}
out.push("")
let intro = match kw {
"record" => "A " + bold(nm) + " is a group of fields. "
"enum" => "A " + bold(nm) + " is exactly one of " + and_list(entries.map(fn(e) { bold(dashes(e.1)) })) + ". "
"variant" => "A " + bold(nm) + " is one of several cases, some carrying data. "
"flags" => "A " + bold(nm) + " is any combination of " + and_list(entries.map(fn(e) { bold(dashes(e.1)) })) + ". "
_ => "A " + bold(nm) + " is a handle owned by the host. "
}
let sb = StringBuilder::new()
sb.write_string(intro + doc_prose(pending))
if kw == "record" || kw == "variant" {
let parts = entries.map(fn(e) { entry_sentence(kw, e.1, e.0) })
sb.write_string(parts.join(" "))
}
out.push(sb.to_string().trim(chars=" ").to_string())
} else if kw == "type" && l.contains("=") {
let eq = index_of(l, '=')
let nm = dashes(first_word(trim(l[kw.length():].to_string())))
let tgt = trim(l[eq + 1:].to_string())
let tgt = if tgt.has_suffix(";") { tgt[:tgt.length() - 1].to_string() } else { tgt }
out.push("")
out.push(bold(nm) + " is just another name for " + ty(tgt) + ". " + doc_prose(pending).trim(chars=" ").to_string())
} else if l.contains(": func(") {
if !calls_shown {
out.push("")
out.push("What it can do:")
calls_shown = true
out.push("")
}
let clean = if l.has_suffix(";") { l[:l.length() - 1].to_string() } else { l }
out.push(entry_sentence("func", clean, pending))
}
pending = []
}
out
}
///| "moonplasma:desktop/theme@0.1.0;" -> "theme" (raw WIT identifier, dashes kept)
fn ref_name(s : String) -> String {
let mut r = trim(s)
if r.has_suffix(";") {
r = r[:r.length() - 1].to_string()
}
let sl = last_index_of(r, '/')
if sl >= 0 {
r = r[sl + 1:].to_string()
}
let at = index_of(r, '@')
if at >= 0 {
r = r[:at].to_string()
}
r
}
///| "moonplasma:desktop/app-catalog@0.1.0" -> "app catalog"
fn short_ref(s : String) -> String {
dashes(ref_name(s))
}
///| Interfaces a world uses, resolved through `include`: exports first, then imports.
fn world_interfaces(text : String, name : String) -> Array[String] {
let imports : Array[String] = []
let exports : Array[String] = []
collect_world_raw(text, name, imports, exports, 0)
let out : Array[String] = []
for e in exports {
if !out.contains(e) {
out.push(e)
}
}
for i in imports {
if !out.contains(i) {
out.push(i)
}
}
out
}
///|
fn collect_world_raw(
text : String,
name : String,
imports : Array[String],
exports : Array[String],
depth : Int,
) -> Unit {
if depth > 3 {
return
}
for l in extract_block(text, "world", name) {
let t = trim(l)
if t.has_prefix("import ") {
imports.push(ref_name(t[7:].to_string()))
} else if t.has_prefix("export ") {
exports.push(ref_name(t[7:].to_string()))
} else if t.has_prefix("include ") {
collect_world_raw(text, ref_name(t[8:].to_string()), imports, exports, depth + 1)
}
}
}
///|
fn collect_world(
text : String,
name : String,
imports : Array[String],
exports : Array[String],
depth : Int,
) -> Unit {
if depth > 3 {
return
}
for l in extract_block(text, "world", name) {
let t = trim(l)
if t.has_prefix("import ") {
imports.push(short_ref(t[7:].to_string()))
} else if t.has_prefix("export ") {
exports.push(short_ref(t[7:].to_string()))
} else if t.has_prefix("include ") {
collect_world(text, trim(short_ref(t[8:].to_string())).replace_all(old=" ", new="-"), imports, exports, depth + 1)
}
}
}
///| Plain-English rendering of a world: what it provides and what it needs.
fn humanise_world(text : String, name : String) -> Array[String] {
let out : Array[String] = []
let block = extract_block(text, "world", name)
let docs : Array[String] = []
for l in block {
if trim(l).has_prefix("///") {
docs.push(doc_text(l))
} else {
break
}
}
out.push("# " + dashes(name) + " (component)")
if docs.length() > 0 {
out.push(doc_prose(docs).trim(chars=" ").to_string())
}
let imports : Array[String] = []
let exports : Array[String] = []
collect_world(text, name, imports, exports, 0)
out.push("")
out.push("It provides " + and_list(exports.map(bold)) + ", and needs " + and_list(imports.map(bold)) + " from the host.")
out
}
+396
View File
@@ -0,0 +1,396 @@
///| Interface Explorer: a shell tool. Toggle it from the panel's "Interface Explorer" button, then
/// hover any system component (launcher, clock, panel, window title bar, ...)
/// to see the WIT interface that component implements in a dialog.
/// WIT text is read from the repo's `wit/` directory at runtime, so the dialog
/// always shows what is on disk.
///| A system component the inspector knows about.
priv struct Component {
id : String
title : String
note : String
/// (file, world name)
world : (String, String)?
/// (file, interface name) pairs, in display order.
ifaces : Array[(String, String)]
}
///|
let components : Array[Component] = [
{
id: "panel",
title: "Panel",
note: "containment: places widgets and draws the panel frame",
world: Some(("wit/worlds.wit", "panel")),
ifaces: [],
},
{
id: "desktop",
title: "Desktop surface",
note: "wallpaper / desktop containment",
world: Some(("wit/worlds.wit", "shell")),
ifaces: [],
},
{
id: "window-decoration",
title: "Window decoration",
note: "server-side title bar and buttons",
world: Some(("wit/wm/worlds.wit", "decoration-provider")),
ifaces: [],
},
{
id: "window-surface",
title: "Client surface",
note: "a client's committed buffer, composited by the host",
world: None,
ifaces: [("wit/compositor/surface.wit", "surface")],
},
]
///| The component behind `id`: a loaded panel module (described from its real binary:
/// the plasmoid contract it exports and the capability interfaces it imports) or one
/// of the fixed shell parts (panel, desktop, window decoration, client surface).
fn DesktopShell::find_component(self : DesktopShell, id : String) -> Component? {
match self.widget_by_slot(id) {
Some(w) => {
let ifaces : Array[(String, String)] = [("", "plasmoid")]
for c in w.caps {
ifaces.push(("", c))
}
Some({
id,
title: w.pl.name,
note: "wasm module " + w.module_id + ", imports: " + (if w.caps.length() == 0 { "nothing" } else { w.caps.join(", ") }),
world: None,
ifaces,
})
}
None => {
for c in components {
if c.id == id {
return Some(c)
}
}
None
}
}
}
///| Read a file under the repo's wit/ directory (cached); "" when missing.
fn DesktopShell::wit_file(self : DesktopShell, path : String) -> String {
match self.wit_cache.get(path) {
Some(t) => t
None => {
let bytes = @sys.read_file_bytes(path)
let text = if bytes.length() == 0 {
""
} else {
@utf8.decode_lossy(bytes)
}
self.wit_cache.set(path, text)
text
}
}
}
///| The `kind name { ... }` block (with its leading /// docs), one line per entry.
fn extract_block(text : String, kind : String, name : String) -> Array[String] {
let lines : Array[String] = []
for l in text.split("\n") {
lines.push(l.to_string())
}
let head = kind + " " + name + " {"
let out : Array[String] = []
let mut start = -1
for i = 0; i < lines.length(); i = i + 1 {
if lines[i].has_prefix(head) {
start = i
break
}
}
if start < 0 {
return out
}
// leading doc comments
let mut s = start
while s > 0 && lines[s - 1].has_prefix("///") {
s = s - 1
}
for i = s; i < lines.length(); i = i + 1 {
out.push(lines[i])
if i >= start && (lines[i] == "}" || (i == start && lines[i].has_suffix("}"))) {
break
}
}
out
}
///| WIT files searched for interface/world definitions.
let wit_sources : Array[String] = [
"wit/worlds.wit", "wit/plasmoid.wit", "wit/capabilities.wit", "wit/shell.wit",
"wit/theme.wit", "wit/types.wit", "wit/wm/worlds.wit", "wit/wm/policy.wit",
"wit/wm/decoration.wit", "wit/compositor/surface.wit",
]
///| Interface block `name` from whichever WIT file defines it.
fn DesktopShell::find_interface(self : DesktopShell, name : String) -> Array[String] {
for f in wit_sources {
let b = extract_block(self.wit_file(f), "interface", name)
if b.length() > 0 {
return b
}
}
[]
}
///| All dialog lines for a component (blank line between blocks).
fn DesktopShell::inspector_lines(self : DesktopShell, c : Component) -> Array[String] {
let out : Array[String] = []
match c.world {
Some((file, name)) => {
for l in humanise_world(self.wit_file(file), name) {
out.push(l)
}
out.push("")
}
None => ()
}
// Interfaces come from the world (exports + imports) unless listed explicitly.
let names : Array[String] = []
match c.world {
Some((file, wname)) if c.ifaces.length() == 0 =>
for n in world_interfaces(self.wit_file(file), wname) {
names.push(n)
}
_ => for fi in c.ifaces { names.push(fi.1) }
}
for name in names {
let b = self.find_interface(name)
if b.length() == 0 {
out.push("(interface " + name + " not found - run from the repo root)")
} else {
for l in humanise_interface(name, b) {
out.push(l)
}
}
out.push("")
}
if names.length() == 0 && c.world is None {
out.push("(no WIT: not a component)")
}
// drop trailing blank
while out.length() > 0 && out[out.length() - 1] == "" {
ignore(out.pop())
}
out
}
///| Word length at the start of `s` (letters, digits, '-').
fn first_word(s : String) -> String {
let mut n = 0
while n < s.length() {
let ch = s[n]
let ok = (ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') ||
ch == '-'
if !ok {
break
}
n = n + 1
}
s[:n].to_string()
}
///| Draw the dialog for the hovered component into `ops`.
fn DesktopShell::render_inspector(
self : DesktopShell,
w : Int,
h : Int,
tokens : @theme.Tokens,
ops : Array[@scene.DrawOp],
) -> Unit {
match self.find_component(self.hover_id) {
None => ()
Some(c) => {
let p = tokens.palette
let line_h = 18
let body_sz = 12
let header_h = 22 + 16 + 10
let text_w = 400
let dw = text_w + 28
// Word-wrap each paragraph to `text_w` using real glyph widths. A row is
// a list of (word, bold) runs; `**term**` in the prose marks bold terms.
let rows_all : Array[(Int, Array[(String, Bool, Bool)])] = [] // (kind: 0 body, 1 heading, 2 blank)
for para in self.inspector_lines(c) {
if para == "" {
rows_all.push((2, []))
} else if para.has_prefix("# ") {
rows_all.push((1, [(para[2:].to_string(), true, false)]))
} else {
// (word, bold, glued to the previous word: no space between)
let words : Array[(String, Bool, Bool)] = []
let mut is_bold = false
let mut prev_space = true
for seg in para.split("**") {
let sg = seg.to_string()
let mut first_word = true
for wd in sg.split(" ") {
let wd = wd.to_string()
if wd.length() > 0 {
words.push((wd, is_bold, first_word && !sg.has_prefix(" ") && !prev_space))
}
first_word = false
}
if sg.length() > 0 {
prev_space = sg.has_suffix(" ")
}
is_bold = !is_bold
}
let space = @renderer.text_width(" ", body_sz, false, false)
let mut cur : Array[(String, Bool, Bool)] = []
let mut cw = 0
for wv in words {
let ww = @renderer.text_width(wv.0, body_sz, wv.1, false)
if cur.length() > 0 && !wv.2 && cw + space + ww > text_w {
rows_all.push((0, cur))
cur = []
cw = 0
}
cw = cw + (if cur.length() > 0 && !wv.2 { space } else { 0 }) + ww
cur.push(wv)
}
if cur.length() > 0 {
rows_all.push((0, cur))
}
}
}
// Compact dialog: at most ~14 visible rows (or what fits the screen),
// the rest scrolls with the mouse wheel.
let fit = (h - 16 - header_h - 12) / line_h
let max_rows = if fit < 14 { fit } else { 14 }
let max_rows = if max_rows < 1 { 1 } else { max_rows }
let rows = if rows_all.length() < max_rows { rows_all.length() } else { max_rows }
let max_scroll = rows_all.length() - rows
if self.inspect_scroll > max_scroll {
self.inspect_scroll = max_scroll
}
if self.inspect_scroll < 0 {
self.inspect_scroll = 0
}
let first = self.inspect_scroll
let dh = header_h + rows * line_h + 12
let mut dx = self.hover_x + 18
let mut dy = self.hover_y + 18
if dx + dw > w {
dx = w - dw - 4
}
if dx < 4 {
dx = 4
}
if dy + dh > h {
dy = self.hover_y - dh - 12
}
if dy < 4 {
dy = 4
}
let local : Array[@types.DrawOp] = []
let r = tokens.radius.reinterpret_as_int()
local.push(@ui.fill_rect(@ui.rect(0, 0, dw, dh), p.surface_popup, radius=r + 4))
local.push(@ui.stroke_rect(@ui.rect(0, 0, dw, dh), p.accent, radius=r + 4))
local.push(@ui.text(14, 16, c.title, 14, p.foreground, bold=true))
local.push(@ui.text(14, 34, c.note, 11, p.foreground_muted))
local.push(@ui.fill_rect(@ui.rect(10, 46, dw - 20, 1), p.border))
let mut y = 58 + line_h / 2
let space = @renderer.text_width(" ", body_sz, false, false)
for i = first; i < rows_all.length() && i < first + rows; i = i + 1 {
let (kind, runs) = rows_all[i]
if kind == 1 {
local.push(@ui.text(14, y, runs[0].0, 13, p.accent, bold=true))
} else if kind == 0 {
let mut x = 14
for run in runs {
let (wd, b, glued) = run
if glued {
x = x - space
}
local.push(@ui.text(x, y, wd, body_sz, if b { p.accent } else { p.foreground }, bold=b))
x = x + @renderer.text_width(wd, body_sz, b, false) + space
}
}
y = y + line_h
}
if max_scroll > 0 {
// Scrollbar track + thumb on the right edge, plus a hint.
let th = rows * line_h
let thumb = if th * rows / rows_all.length() < 12 { 12 } else { th * rows / rows_all.length() }
let ty = 52 + (th - thumb) * first / max_scroll
local.push(@ui.fill_rect(@ui.rect(dw - 8, 52, 3, th), p.border))
local.push(@ui.fill_rect(@ui.rect(dw - 8, ty, 3, thumb), p.accent))
local.push(@ui.text(dw - 24 - 90, 34, "scroll for more", 11, p.foreground_muted))
}
let scene_ops : Array[@scene.DrawOp] = []
translate(local, dx, dy, scene_ops)
for op in scene_ops {
ops.push(op)
}
}
}
}
///| True while inspect mode is on.
pub fn DesktopShell::inspecting(self : DesktopShell) -> Bool {
self.inspect_on
}
///| Turn inspect mode on/off. The launcher popup is left as it is.
pub fn DesktopShell::set_inspecting(self : DesktopShell, on : Bool) -> Unit {
self.inspect_on = on
self.hover_id = ""
}
///| Shell component under (x, y): a panel widget id, "panel" for bare panel,
/// "" for anything else (windows or the desktop - the compositor resolves those).
pub fn DesktopShell::component_at(self : DesktopShell, x : Int, y : Int) -> String {
for entry in self.comps {
let (id, r) = entry
if inside(r, x, y) {
return id
}
}
if inside(self.panel_rect, x, y) {
"panel"
} else {
""
}
}
///| Record what the pointer is over while inspecting.
pub fn DesktopShell::set_hover(self : DesktopShell, id : String, x : Int, y : Int) -> Unit {
if id != self.hover_id {
self.inspect_scroll = 0
}
self.hover_id = id
self.hover_x = x
self.hover_y = y
}
///| Dialog lines for component `id` (for tests and tooling).
pub fn DesktopShell::inspector_lines_for(self : DesktopShell, id : String) -> Array[String] {
match self.find_component(id) {
Some(c) => self.inspector_lines(c)
None => []
}
}
///| Mouse-wheel scroll of the explorer dialog (lines, + = down). True if consumed.
pub fn DesktopShell::scroll_inspector(self : DesktopShell, lines : Int) -> Bool {
if !self.inspect_on || self.hover_id == "" {
return false
}
self.inspect_scroll = self.inspect_scroll + lines
if self.inspect_scroll < 0 {
self.inspect_scroll = 0
}
true
}
+13
View File
@@ -1,14 +1,27 @@
import { import {
"moonbitlang/core/builtin", "moonbitlang/core/builtin",
"moonbitlang/core/encoding/utf8" @utf8,
"moonplasma/desktop/interface/moonplasma/desktop/types" @types, "moonplasma/desktop/interface/moonplasma/desktop/types" @types,
"moonplasma/desktop/interface/moonplasma/desktop/theme" @theme, "moonplasma/desktop/interface/moonplasma/desktop/theme" @theme,
"moonplasma/desktop/lib/ui" @ui, "moonplasma/desktop/lib/ui" @ui,
"moonplasma/desktop/lib/shell" @libshell, "moonplasma/desktop/lib/shell" @libshell,
"moonplasma/desktop/lib/panel" @panel, "moonplasma/desktop/lib/panel" @panel,
"moonplasma/desktop/lib/clock" @clock, "moonplasma/desktop/lib/clock" @clock,
"moonplasma/desktop/lib/moon" @moon,
"moonplasma/desktop/lib/timefmt" @timefmt,
"moonplasma/desktop/lib/launcher" @launcher, "moonplasma/desktop/lib/launcher" @launcher,
"moonplasma/desktop/compositor/scene" @scene, "moonplasma/desktop/compositor/scene" @scene,
"moonplasma/desktop/compositor/sys" @sys, "moonplasma/desktop/compositor/sys" @sys,
"moonplasma/desktop/compositor/renderer" @renderer,
"moonplasma/desktop/compositor/wasm" @wasm,
} }
supported_targets = "-all+native" supported_targets = "-all+native"
options(
link: {
"native": {
"cc-link-flags": "-lwasmer",
},
},
)
+530 -138
View File
@@ -125,59 +125,279 @@ fn now() -> @types.Datetime {
} }
} }
///| The desktop shell: wallpaper + bottom panel with launcher, task list and clock. ///| A window as the panel's task list sees it (handed to modules through the `windows` capability).
pub(all) struct WinInfo {
id : UInt64
title : String
focused : Bool
minimized : Bool
}
///| Something a panel module asked the compositor to do.
pub(all) enum ShellAction {
SetLayout(Int)
FocusWindow(UInt64)
} derive(Eq, Debug)
///| One wasm module loaded into the panel.
pub(all) struct Widget {
/// Panel slot id ("w1", "w2", ...): one per loaded instance.
slot : String
/// The module's file stem ("clock-digital"), or its path for modules loaded from elsewhere.
module_id : String
path : String
pl : @wasm.Plasmoid
/// Host interfaces the module imports (its capabilities).
caps : Array[String]
mut rect : @scene.Rect
/// Where its popup is on screen (w == 0 while closed), and what to draw there.
mut popup_rect : @scene.Rect
mut popup_ops : Array[@types.DrawOp]
mut popup_hot : Bool
}
///| A wasm module file found on the module path.
pub(all) struct CatalogEntry {
id : String
path : String
/// Filled in (by loading the module once) the first time names are needed; "" until then.
mut name : String
}
///| One row of the right-click menu: kind 0 replace with module `arg` (a path), 1 remove, 2 open the module manager.
pub(all) struct MenuRow {
label : String
kind : Int
arg : String
}
///| The desktop shell: wallpaper + a bottom panel made entirely of wasm modules
/// (application menu, Interface Explorer, layout switcher, task list, moon, clock ...).
/// Nothing on the panel is built in: every element is a plasmoid component loaded
/// from a `.wasm` file and can be unloaded or replaced while the compositor runs.
pub(all) struct DesktopShell { pub(all) struct DesktopShell {
launcher_state : @launcher.State
apps : Array[@types.AppEntry] apps : Array[@types.AppEntry]
exec : Map[String, String] exec : Map[String, String]
/// Wayland socket handed to launched apps as WAYLAND_DISPLAY. /// Wayland socket handed to launched apps as WAYLAND_DISPLAY.
display : String display : String
/// Panel modules in panel order; a module with `stretch` splits the panel into a left and a right group.
widgets : Array[Widget]
mut next_slot : Int
/// Module files on the search path (see `module_dirs`).
catalog : Array[CatalogEntry]
mut catalog_named : Bool
mut booted : Bool
/// Read and write panel.edn (the compositor binary turns this on; tests leave it off).
mut persist : Bool
mut tokens : @theme.Tokens
mut screen_w : Int mut screen_w : Int
mut launcher_rect : @scene.Rect mut screen_h : Int
mut popup_rect : @scene.Rect mut panel_h : Int
/// Window list + layout mode, set by the compositor before each frame.
mut windows : Array[WinInfo]
mut layout_sel : Int
mut layout_names : Array[String]
/// Things modules asked for (focus a window, switch layout), drained by the compositor.
actions : Array[ShellAction]
mut apps_dirty : Bool
/// The native file chooser opened by the module manager's "Browse" row, and a transient notice.
mut picker : @wasm.Picker?
/// Machine-state provider behind the `system` interface, and the window list behind `windows`.
sampler : SysSampler
mut win_list : Array[@wasm.WindowEntry]
mut notice : String
mut notice_frames : Int
mut notice_start : Int
/// Right-click menu.
mut menu_open : Bool
mut menu_rect : @scene.Rect
mut menu_title : String
mut menu_rows : Array[MenuRow]
mut menu_hover : Int
mut menu_anchor_x : Int
mut menu_slot : String
/// Panel widget being dragged (slot id, "" if none), press point, and whether it moved past the click threshold.
mut drag_slot : String
mut drag_x0 : Int
mut drag_y0 : Int
mut drag_active : Bool
// WIT inspector state (see inspector.mbt)
mut inspect_on : Bool
mut hover_id : String
mut hover_x : Int
mut inspect_scroll : Int
mut hover_y : Int
mut panel_rect : @scene.Rect
comps : Array[(String, @scene.Rect)]
wit_cache : Map[String, String]
/// Most-recently-launched app ids, newest first (persisted).
recents : Array[String]
} }
///| Apps the launcher offers, kept only if their executable exists.
/// (id, name, comment, category, glyph, executable)
let candidates : Array[(String, String, String, String, String, String)] = [
("org.moonplasma.terminal", "Terminal", "Command-line shell", "System", ">_", "foot"),
("org.moonplasma.konsole", "Konsole", "KDE terminal", "System", ">_", "konsole"),
("org.moonplasma.files", "Files", "Browse folders and files", "Utilities", "F", "dolphin"),
("org.moonplasma.browser", "Web Browser", "Browse the web", "Internet", "W", "firefox"),
("org.moonplasma.editor", "Text Editor", "Edit plain text files", "Utilities", "T", "kate"),
("org.moonplasma.settings", "System Settings", "Configure the desktop", "System", "S", "systemsettings"),
]
///| ///|
pub fn DesktopShell::new(display : String) -> DesktopShell { pub fn DesktopShell::new(display : String) -> DesktopShell {
let apps : Array[@types.AppEntry] = [] let apps : Array[@types.AppEntry] = []
let exec : Map[String, String] = {} let exec : Map[String, String] = {}
for c in candidates { for a in scan_desktop_apps() {
let (id, name, comment, category, glyph, bin) = c let glyph = match a.name.to_array().get(0) {
if @sys.has_exe(bin) { Some(c) => c.to_string().to_upper()
apps.push({ id, name, comment, category, glyph }) None => "?"
exec.set(id, bin)
} }
apps.push({ id: a.id, name: a.name, comment: a.comment, category: a.category, glyph })
exec.set(a.id, a.command)
} }
{ let zero : @scene.Rect = { x: 0, y: 0, w: 0, h: 0 }
launcher_state: @launcher.State::new(), let sh : DesktopShell = {
apps, apps,
exec, exec,
display, display,
widgets: [],
next_slot: 1,
catalog: [],
catalog_named: false,
booted: false,
persist: false,
tokens: conv_theme(@scene.ThemeTokens::moon_night()),
screen_w: 0, screen_w: 0,
launcher_rect: { x: 0, y: 0, w: 0, h: 0 }, screen_h: 0,
popup_rect: { x: 0, y: 0, w: 0, h: 0 }, panel_h: 40,
windows: [],
layout_sel: 0,
layout_names: ["Tiling (BSP)", "Monocle", "Floating"],
actions: [],
apps_dirty: true,
sampler: SysSampler::new(),
win_list: [],
picker: None,
notice: "",
notice_frames: 0,
notice_start: 0,
menu_open: false,
menu_rect: zero,
menu_title: "",
menu_rows: [],
menu_hover: -1,
menu_anchor_x: 0,
menu_slot: "",
drag_slot: "",
drag_x0: 0,
drag_y0: 0,
drag_active: false,
inspect_on: false,
hover_id: "",
hover_x: 0,
inspect_scroll: 0,
hover_y: 0,
panel_rect: zero,
comps: [],
wit_cache: {},
recents: load_recents(),
}
sh.order_apps()
sh
}
///| Tell the shell the theme and output size it will first be drawn with (modules are loaded
/// against these); the panel itself is loaded on first use.
pub fn DesktopShell::set_output(self : DesktopShell, theme : @scene.ThemeTokens, w : Int, h : Int) -> Unit {
self.tokens = conv_theme(theme)
self.screen_w = w
self.screen_h = h
self.panel_h = theme.panel_height
}
///| Default launcher entries, in order: each group is matched against app ids (first hit wins).
let default_groups : Array[Array[String]] = [
["foot", "konsole", "terminal", "kitty", "alacritty"],
["dolphin", "nautilus", "thunar", "files"],
["firefox", "chromium", "chrome", "browser"],
["kate", "gedit", "texteditor", "code", "editor"],
["systemsettings", "settings", "control"],
]
///|
let max_recents : Int = 8
///|
fn recents_path() -> String {
let c = @sys.getenv("XDG_CACHE_HOME")
(if c.length() > 0 { c } else { @sys.getenv("HOME") + "/.cache" }) +
"/moon-plasma-recent"
}
///|
fn load_recents() -> Array[String] {
let out : Array[String] = []
let text = @utf8.decode_lossy(@sys.read_file_bytes(recents_path()))
for l in text.split("\n") {
let id = l.trim(chars=" \r").to_string()
if id.length() > 0 {
out.push(id)
}
}
out
}
///| Reorder the launcher: defaults first, then recents (newest first), then the rest A-Z.
fn DesktopShell::order_apps(self : DesktopShell) -> Unit {
let by_id : Map[String, @types.AppEntry] = {}
for a in self.apps {
by_id.set(a.id, a)
}
let out : Array[@types.AppEntry] = []
let seen : Map[String, Bool] = {}
fn take(a : @types.AppEntry, out : Array[@types.AppEntry], seen : Map[String, Bool]) -> Unit {
if !seen.contains(a.id) {
seen.set(a.id, true)
out.push(a)
}
}
for g in default_groups {
let mut found = false
for key in g {
if !found {
for a in self.apps {
if !found && a.id.to_lower().contains(key) {
take(a, out, seen)
found = true
}
}
}
}
}
for id in self.recents {
match by_id.get(id) {
Some(a) => take(a, out, seen)
None => ()
}
}
for a in self.apps {
take(a, out, seen) // already A-Z from the scan
}
self.apps.clear()
for a in out {
self.apps.push(a)
} }
} }
///| Truncate `s` with ".." so it fits `width` px (the renderer's small text is 6 px per char). ///| Remember `id` as the most recent launch and persist the list.
fn fit_title(s : String, width : Int) -> String { fn DesktopShell::note_recent(self : DesktopShell, id : String) -> Unit {
let max_chars = width / 6 let next : Array[String] = [id]
if s.length() <= max_chars { for r in self.recents {
s if r != id && next.length() < max_recents {
} else { next.push(r)
s[:max_chars - 2].to_string() + ".."
} }
}
self.recents.clear()
for r in next {
self.recents.push(r)
}
let sb = StringBuilder::new()
for r in self.recents {
sb.write_string(r + "\n")
}
ignore(@sys.write_file_bytes(recents_path(), @utf8.encode(sb.to_string())))
self.order_apps()
} }
///| ///|
@@ -185,43 +405,122 @@ fn inside(r : @scene.Rect, x : Int, y : Int) -> Bool {
r.w > 0 && x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h r.w > 0 && x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h
} }
///| True while the launcher popup is open (it then owns keyboard input). ///| The launcher module (the Super key opens it).
let launcher_module : String = "launcher"
///| True while any panel popup or the right-click menu is open (it then owns keyboard input).
pub fn DesktopShell::popup_open(self : DesktopShell) -> Bool { pub fn DesktopShell::popup_open(self : DesktopShell) -> Bool {
self.launcher_state.open self.menu_open || self.open_popup_widget() is Some(_)
} }
///| True if (x, y) is over the launcher button or its open popup. ///| The widget whose popup is open, if any.
pub fn DesktopShell::hit(self : DesktopShell, x : Int, y : Int) -> Bool { fn DesktopShell::open_popup_widget(self : DesktopShell) -> Widget? {
inside(self.launcher_rect, x, y) || for w in self.widgets {
(self.launcher_state.open && inside(self.popup_rect, x, y)) if w.popup_rect.w > 0 {
return Some(w)
}
}
None
} }
///| ///|
fn DesktopShell::launch(self : DesktopShell, id : String) -> Result[Unit, String] { fn DesktopShell::widget_at(self : DesktopShell, x : Int, y : Int) -> Widget? {
match self.exec.get(id) { for w in self.widgets {
None => Err("no executable for " + id) if inside(w.rect, x, y) {
Some(bin) => return Some(w)
if @sys.spawn(bin, self.display) { }
Ok(()) }
} else { None
Err("could not start " + bin) }
///|
fn DesktopShell::widget_by_slot(self : DesktopShell, slot : String) -> Widget? {
for w in self.widgets {
if w.slot == slot {
return Some(w)
}
}
None
}
///| Widget whose popup contains (x, y).
fn DesktopShell::popup_at(self : DesktopShell, x : Int, y : Int) -> Widget? {
for w in self.widgets {
if inside(w.popup_rect, x, y) {
return Some(w)
}
}
None
}
///| Does the widget import host interface `cap`?
fn Widget::has_cap(self : Widget, cap : String) -> Bool {
self.caps.contains(cap)
}
///| Hand an event to a module, then carry out whatever it asked of the host.
fn DesktopShell::deliver(self : DesktopShell, w : Widget, popup : Bool, ev : @wasm.PlasmoidEvent) -> Bool {
self.publish_host_data()
let changed = w.pl.on_event(popup, ev)
self.process_requests()
// The module may have unloaded itself (or been replaced) while handling the event.
if self.widget_by_slot(w.slot) is Some(_) {
self.refresh_popup(w)
}
changed
}
///| Close every popup except `keep`'s (a press elsewhere dismisses them).
fn DesktopShell::dismiss_popups(self : DesktopShell, keep : String) -> Unit {
for w in self.widgets.copy() {
if w.slot != keep && w.popup_rect.w > 0 {
ignore(self.deliver(w, false, FocusLost))
} }
} }
} }
///| wp_cursor_shape_v1 value for the shell UI under (x, y): 4 pointer (hand) over the ///| Open the launcher module's popup, or close it if already open (the Super-key tap).
/// launcher button and popup entries, 9 text over the search field, else 0 (not shell-specific). pub fn DesktopShell::toggle_launcher(self : DesktopShell) -> Unit {
pub fn DesktopShell::cursor_at(self : DesktopShell, x : Int, y : Int) -> UInt { self.ensure_booted()
if inside(self.launcher_rect, x, y) { self.menu_open = false
4U for w in self.widgets {
} else if self.launcher_state.open && inside(self.popup_rect, x, y) { if w.module_id == launcher_module {
if self.launcher_state.hover >= 0 { if w.popup_rect.w > 0 {
4U ignore(self.deliver(w, false, FocusLost))
} else if y - self.popup_rect.y < 52 {
9U
} else { } else {
1U self.dismiss_popups(w.slot)
ignore(self.deliver(w, false, PointerDown(0, 0)))
} }
return
}
}
}
///| True if (x, y) is over the panel, an open popup or the menu (so windows don't see it).
pub fn DesktopShell::hit(self : DesktopShell, x : Int, y : Int) -> Bool {
inside(self.panel_rect, x, y) ||
(self.menu_open && inside(self.menu_rect, x, y)) ||
self.popup_at(x, y) is Some(_)
}
///| wp_cursor_shape_v1 value for the shell UI under (x, y): hand over panel modules, grabbing
/// while one is dragged, 0 when (x, y) is not shell UI.
pub fn DesktopShell::cursor_at(self : DesktopShell, x : Int, y : Int) -> UInt {
if self.inspect_on {
// help cursor everywhere while inspecting; hand over the Interface Explorer toggle itself
return match self.widget_at(x, y) {
Some(w) if w.has_cap("inspector") => 4U
_ => 3U
}
}
if self.drag_active {
17U // grabbing
} else if self.menu_open && inside(self.menu_rect, x, y) {
if self.menu_hover >= 0 { 4U } else { 1U }
} else if self.popup_at(x, y) is Some(_) {
1U
} else if self.widget_at(x, y) is Some(_) {
4U
} else { } else {
0U 0U
} }
@@ -229,47 +528,139 @@ pub fn DesktopShell::cursor_at(self : DesktopShell, x : Int, y : Int) -> UInt {
///| Pointer press at (x, y). Returns true when the shell consumed it. ///| Pointer press at (x, y). Returns true when the shell consumed it.
pub fn DesktopShell::pointer_down(self : DesktopShell, x : Int, y : Int) -> Bool { pub fn DesktopShell::pointer_down(self : DesktopShell, x : Int, y : Int) -> Bool {
let launch = fn(id : String) { self.launch(id) } self.ensure_booted()
if inside(self.launcher_rect, x, y) { if self.menu_open {
ignore( // A press outside the menu dismisses it and goes through.
@launcher.handle_event(self.apps, self.launcher_state, Widget, PointerDown({ x: x - self.launcher_rect.x, y: y - self.launcher_rect.y }), launch), return self.menu_pointer_down(x, y)
)
true
} else if self.launcher_state.open {
if inside(self.popup_rect, x, y) {
ignore(
@launcher.handle_event(self.apps, self.launcher_state, Popup, PointerDown({ x: x - self.popup_rect.x, y: y - self.popup_rect.y }), launch),
)
true
} else {
// Click outside: dismiss, and let the click through.
ignore(@launcher.handle_event(self.apps, self.launcher_state, Popup, FocusLost, launch))
false
} }
} else { if self.inspect_on {
false // Inspecting: clicks reach only modules that hold the `inspector` capability (the toggle).
match self.widget_at(x, y) {
Some(w) if w.has_cap("inspector") =>
ignore(self.deliver(w, false, PointerDown(x - w.rect.x, y - w.rect.y)))
_ => ()
} }
}
///| Pointer motion; returns true when over the popup (so windows don't see it).
pub fn DesktopShell::pointer_move(self : DesktopShell, x : Int, y : Int) -> Bool {
if self.launcher_state.open {
let launch = fn(id : String) { self.launch(id) }
if inside(self.popup_rect, x, y) {
ignore(
@launcher.handle_event(self.apps, self.launcher_state, Popup, PointerMove({ x: x - self.popup_rect.x, y: y - self.popup_rect.y }), launch),
)
return true return true
} }
ignore(@launcher.handle_event(self.apps, self.launcher_state, Popup, PointerLeave, launch)) match self.popup_at(x, y) {
Some(w) => {
ignore(self.deliver(w, true, PointerDown(x - w.popup_rect.x, y - w.popup_rect.y)))
return true
}
None => ()
}
match self.widget_at(x, y) {
Some(w) => {
// A click (delivered on release) or the start of a drag that reorders the panel.
// The Interface Explorer toggle leaves open popups alone.
if !w.has_cap("inspector") {
self.dismiss_popups(w.slot)
}
self.drag_slot = w.slot
self.drag_x0 = x
self.drag_y0 = y
self.drag_active = false
true
}
None => {
// Click elsewhere: dismiss any popup and let the click through.
self.dismiss_popups("")
inside(self.panel_rect, x, y)
}
} }
false
} }
///| Key name as used by lib/launcher ("Escape", "Backspace", "Enter" or one character). ///| Move the dragged widget in panel order to where the pointer is: it lands after every
/// other widget whose centre is left of `x`.
fn DesktopShell::reorder_dragged(self : DesktopShell, x : Int) -> Unit {
match self.widget_by_slot(self.drag_slot) {
None => ()
Some(dragged) => {
let others = self.widgets.filter(w => w.slot != self.drag_slot)
let mut idx = 0
for w in others {
if w.rect.x + w.rect.w / 2 < x {
idx = idx + 1
}
}
others.insert(idx, dragged)
self.widgets.clear()
for w in others {
self.widgets.push(w)
}
}
}
}
///| Pointer release: ends a widget drag, or clicks the widget if it never moved. True when a press was pending.
pub fn DesktopShell::pointer_up(self : DesktopShell) -> Bool {
let slot = self.drag_slot
let was_drag = self.drag_active
self.drag_slot = ""
self.drag_active = false
if slot == "" {
return false
}
if was_drag {
self.save_panel_config()
} else {
match self.widget_by_slot(slot) {
Some(w) => ignore(self.deliver(w, false, PointerDown(self.drag_x0 - w.rect.x, self.drag_y0 - w.rect.y)))
None => ()
}
}
true
}
///| Pointer motion; returns true when over a popup or the menu (so windows don't see it).
pub fn DesktopShell::pointer_move(self : DesktopShell, x : Int, y : Int) -> Bool {
if self.drag_slot != "" {
if !self.drag_active && (x - self.drag_x0 > 4 || self.drag_x0 - x > 4) {
self.drag_active = true
}
if self.drag_active {
self.reorder_dragged(x)
}
return true
}
if self.menu_open {
return self.menu_pointer_move(x, y)
}
let mut over = false
for w in self.widgets.copy() {
if w.popup_rect.w > 0 {
if inside(w.popup_rect, x, y) {
w.popup_hot = true
over = true
ignore(self.deliver(w, true, PointerMove(x - w.popup_rect.x, y - w.popup_rect.y)))
} else if w.popup_hot {
w.popup_hot = false
ignore(self.deliver(w, true, PointerLeave))
}
}
}
over
}
///| Key name as used by the plasmoid contract ("Escape", "Backspace", "Enter" or one character).
pub fn DesktopShell::key_down(self : DesktopShell, name : String) -> Unit { pub fn DesktopShell::key_down(self : DesktopShell, name : String) -> Unit {
let launch = fn(id : String) { self.launch(id) } if self.menu_open {
ignore(@launcher.handle_event(self.apps, self.launcher_state, Popup, KeyDown(name), launch)) if name == "Escape" {
self.menu_open = false
}
return
}
match self.open_popup_widget() {
Some(w) => ignore(self.deliver(w, true, KeyDown(name)))
None => ()
}
}
///| Things panel modules asked the compositor to do since the last call (focus a window, switch layout).
pub fn DesktopShell::take_actions(self : DesktopShell) -> Array[ShellAction] {
let out = self.actions.copy()
self.actions.clear()
out
} }
///| Build the (background, panel) render-lists for the current frame. ///| Build the (background, panel) render-lists for the current frame.
@@ -278,72 +669,73 @@ pub fn DesktopShell::render(
w : Int, w : Int,
h : Int, h : Int,
theme : @scene.ThemeTokens, theme : @scene.ThemeTokens,
layout_label : String,
window_titles : Array[String],
) -> (Array[@scene.DrawOp], Array[@scene.DrawOp]) { ) -> (Array[@scene.DrawOp], Array[@scene.DrawOp]) {
let tokens = conv_theme(theme) let tokens = conv_theme(theme)
self.tokens = tokens
self.screen_w = w self.screen_w = w
self.screen_h = h
self.panel_h = theme.panel_height
self.ensure_booted()
self.poll_picker()
self.publish_host_data()
// Machine state and the rich window list only matter to modules that import them.
if self.widgets.iter().any(w => w.has_cap("system") || w.has_cap("windows")) {
self.sampler.refresh()
@wasm.set_windows(self.win_list)
}
let bg : Array[@scene.DrawOp] = [] let bg : Array[@scene.DrawOp] = []
translate(@libshell.render_background(@ui.size(w, h), tokens), 0, 0, bg) translate(@libshell.render_background(@ui.size(w, h), tokens), 0, 0, bg)
render_desktop_widget(w, tokens, now(), bg)
let (_, _, clock_w, clock_h, clock_min) = @clock.digital_info()
let slots : Array[@panel.SlotIn] = [
{ id: "launcher", pref_w: 190, pref_h: 36, min_w: 170, stretch: false, end_align: false },
{ id: "layout", pref_w: 96, pref_h: 36, min_w: 80, stretch: false, end_align: false },
{ id: "tasks", pref_w: 100, pref_h: 36, min_w: 0, stretch: true, end_align: false },
{ id: "clock", pref_w: clock_w, pref_h: clock_h, min_w: clock_min, stretch: false, end_align: true },
]
let panel_ops : Array[@scene.DrawOp] = [] let panel_ops : Array[@scene.DrawOp] = []
match @panel.layout(w, h, theme.panel_height, 4, tokens.spacing.reinterpret_as_int(), slots) { self.comps.clear()
self.panel_rect = { x: 0, y: 0, w: 0, h: 0 }
match @panel.layout(w, h, theme.panel_height, 4, tokens.spacing.reinterpret_as_int(), self.panel_slots()) {
Err(_) => () Err(_) => ()
Ok(pl) => { Ok(pl) => {
let pr = @ui.rect(pl.x, pl.y, pl.w, pl.h) self.panel_rect = { x: pl.x, y: pl.y, w: pl.w, h: pl.h }
translate(@libshell.render_panel(pr, tokens), 0, 0, panel_ops) translate(@libshell.render_panel(@ui.rect(pl.x, pl.y, pl.w, pl.h), tokens), 0, 0, panel_ops)
for p in pl.placements { for i = 0; i < pl.placements.length() && i < self.widgets.length(); i = i + 1 {
let size = @ui.size(p.w, p.h) let p = pl.placements[i]
let local : Array[@types.DrawOp] = match p.id { let wd = self.widgets[i]
"launcher" => @launcher.render_button(size, tokens, self.launcher_state) translate(wd.pl.render(p.w, p.h, tokens), p.x, p.y, panel_ops)
"clock" => @clock.render_digital(size, tokens, now(), hour12=true) wd.rect = { x: p.x, y: p.y, w: p.w, h: p.h }
"layout" => [ self.comps.push((wd.slot, wd.rect))
@ui.fill_rect(@ui.rect(0, 0, p.w, p.h), tokens.palette.surface_hover, radius=tokens.radius.reinterpret_as_int()),
@ui.text(p.w / 2, p.h / 2, layout_label, tokens.font_size.reinterpret_as_int() - 2, tokens.palette.foreground, align=CENTER),
]
_ => []
} }
translate(local, p.x, p.y, panel_ops)
if p.id == "launcher" {
self.launcher_rect = { x: p.x, y: p.y, w: p.w, h: p.h }
} }
if p.id == "tasks" { }
let mut tx = 0 // Popups sit above the panel, left-aligned with their widget.
for title in window_titles { for wd in self.widgets {
let pill_w = 140 self.refresh_popup(wd)
if tx + pill_w <= p.w { if wd.popup_rect.w > 0 {
translate(wd.popup_ops, wd.popup_rect.x, wd.popup_rect.y, panel_ops)
}
}
if self.menu_open {
self.render_menu(w, tokens, panel_ops)
} else {
self.menu_rect = { x: 0, y: 0, w: 0, h: 0 }
}
if self.notice_frames > 0 {
if (wall_secs() - self.notice_start + 86400) % 86400 >= 4 {
self.notice_frames = 0
}
}
if self.notice_frames > 0 {
let nw = self.notice.length() * 7 + 24
translate( translate(
[ [
@ui.fill_rect(@ui.rect(tx, 0, pill_w, p.h), tokens.palette.surface_hover, radius=tokens.radius.reinterpret_as_int()), @ui.fill_rect(@ui.rect(0, 0, nw, 28), tokens.palette.surface_popup, radius=tokens.radius.reinterpret_as_int()),
@ui.text(tx + 10, p.h / 2, fit_title(title, pill_w - 20), tokens.font_size.reinterpret_as_int() - 2, tokens.palette.foreground), @ui.stroke_rect(@ui.rect(0, 0, nw, 28), tokens.palette.border, radius=tokens.radius.reinterpret_as_int()),
@ui.text(12, 14, self.notice, tokens.font_size.reinterpret_as_int() - 3, tokens.palette.foreground),
], ],
p.x, w - nw - 12,
p.y, self.panel_rect.y - 40,
panel_ops, panel_ops,
) )
tx = tx + pill_w + 6
} }
} if self.inspect_on {
} self.render_inspector(w, h, tokens, panel_ops)
}
}
}
if self.launcher_state.open {
let size = @launcher.popup_size(self.apps, self.launcher_state)
let pw = size.w.reinterpret_as_int()
let ph = size.h.reinterpret_as_int()
let (px, py) = @panel.popup_position(w, h - theme.panel_height, self.launcher_rect.x, pw, ph, 6)
self.popup_rect = { x: px, y: py, w: pw, h: ph }
translate(@launcher.render_popup(self.apps, tokens, self.launcher_state), px, py, panel_ops)
} else {
self.popup_rect = { x: 0, y: 0, w: 0, h: 0 }
} }
(bg, panel_ops) (bg, panel_ops)
} }
+199
View File
@@ -0,0 +1,199 @@
///| Linux provider for the `system` interface: samples /proc and /sys about once a second
/// and hands widgets a `SystemSnapshot`. Widgets never see these paths; swapping this file
/// for another provider (a VM, a remote host, a mock) changes nothing for them.
///|
pub(all) struct SysSampler {
mut last_secs : Int
mut prev_busy : Int64
mut prev_total : Int64
mut prev_rx : Int64
mut prev_tx : Int64
mut primed : Bool
mut cur : @wasm.SystemSnapshot
}
///|
fn SysSampler::new() -> SysSampler {
{
last_secs: -1,
prev_busy: 0L,
prev_total: 0L,
prev_rx: 0L,
prev_tx: 0L,
primed: false,
cur: {
cpu_permille: 0,
mem_used_kib: 0L,
mem_total_kib: 0L,
battery_percent: -1,
charging: false,
uptime_secs: 0L,
rx_bps: 0L,
tx_bps: 0L,
load_centi: 0,
},
}
}
///|
fn proc_text(path : String) -> String {
@utf8.decode_lossy(@sys.read_proc_bytes(path))
}
///| Leading unsigned integer of `s` (0 if none).
fn parse_i64(s : String) -> Int64 {
let mut v = 0L
for ch in s {
let c = ch.to_int()
if c >= 48 && c <= 57 {
v = v * 10L + (c - 48).to_int64()
} else {
break
}
}
v
}
///| Whitespace-separated fields.
fn fields(s : String) -> Array[String] {
let out : Array[String] = []
let mut cur = ""
for ch in s {
if ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' {
if cur.length() > 0 {
out.push(cur)
cur = ""
}
} else {
cur = cur + ch.to_string()
}
}
if cur.length() > 0 {
out.push(cur)
}
out
}
///| "0.52" -> 52 (hundredths).
fn parse_centi(s : String) -> Int {
let parts = s.split(".").collect()
let whole = parse_i64(parts[0].to_string()).to_int()
let frac = if parts.length() > 1 {
let f = parts[1].to_string()
let two = if f.length() >= 2 { f[:2].to_string() } else { f + "0" }
parse_i64(two).to_int()
} else {
0
}
whole * 100 + frac
}
///| (busy, total) jiffies from the aggregate "cpu" line of /proc/stat.
fn cpu_times() -> (Int64, Int64) {
let text = proc_text("/proc/stat")
for line in text.split("\n") {
let f = fields(line.to_string())
if f.length() > 5 && f[0] == "cpu" {
let mut total = 0L
for i = 1; i < f.length() && i <= 8; i = i + 1 {
total = total + parse_i64(f[i])
}
let idle = parse_i64(f[4]) + parse_i64(f[5])
return (total - idle, total)
}
}
(0L, 0L)
}
///| (rx, tx) bytes summed over every interface but loopback.
fn net_bytes() -> (Int64, Int64) {
let mut rx = 0L
let mut tx = 0L
for line in proc_text("/proc/net/dev").split("\n") {
let l = line.to_string()
match l.find(":") {
None => ()
Some(i) => {
let name = l[:i].to_string().trim(chars=" ").to_string()
if name != "lo" {
let f = fields(l[i + 1:].to_string())
if f.length() > 8 {
rx = rx + parse_i64(f[0])
tx = tx + parse_i64(f[8])
}
}
}
}
}
(rx, tx)
}
///| (total, available) KiB from /proc/meminfo.
fn mem_kib() -> (Int64, Int64) {
let mut total = 0L
let mut avail = 0L
for line in proc_text("/proc/meminfo").split("\n") {
let f = fields(line.to_string())
if f.length() >= 2 {
if f[0] == "MemTotal:" {
total = parse_i64(f[1])
} else if f[0] == "MemAvailable:" {
avail = parse_i64(f[1])
}
}
}
(total, avail)
}
///| (percent, plugged-in) for the first battery, or (-1, true) without one.
fn battery() -> (Int, Bool) {
for name in ["BAT0", "BAT1", "BATT"] {
let base = "/sys/class/power_supply/" + name
let cap = proc_text(base + "/capacity")
if cap.length() > 0 {
let status = proc_text(base + "/status").trim(chars=" \n").to_string()
return (parse_i64(cap).to_int(), status != "Discharging")
}
}
(-1, true)
}
///| Re-sample if a wall-clock second passed since the last call; cheap otherwise.
fn SysSampler::refresh(self : SysSampler) -> Unit {
let now = wall_secs()
if now == self.last_secs {
return
}
let dt = if self.last_secs < 0 {
1
} else {
let d = now - self.last_secs
if d <= 0 { d + 86400 } else { d }
}
self.last_secs = now
let (busy, total) = cpu_times()
let (rx, tx) = net_bytes()
let (mt, ma) = mem_kib()
let (pct, plugged) = battery()
let dtotal = total - self.prev_total
let cpu = if self.primed && dtotal > 0L { ((busy - self.prev_busy) * 1000L / dtotal).to_int() } else { 0 }
let load = parse_centi(fields(proc_text("/proc/loadavg")).get(0).unwrap_or("0"))
self.cur = {
cpu_permille: if cpu < 0 { 0 } else if cpu > 1000 { 1000 } else { cpu },
mem_used_kib: mt - ma,
mem_total_kib: mt,
battery_percent: pct,
charging: plugged,
uptime_secs: parse_i64(fields(proc_text("/proc/uptime")).get(0).unwrap_or("0")),
rx_bps: if self.primed && rx >= self.prev_rx { (rx - self.prev_rx) / dt.to_int64() } else { 0L },
tx_bps: if self.primed && tx >= self.prev_tx { (tx - self.prev_tx) / dt.to_int64() } else { 0L },
load_centi: load,
}
self.prev_busy = busy
self.prev_total = total
self.prev_rx = rx
self.prev_tx = tx
self.primed = true
@wasm.set_system(self.cur)
}
+724
View File
@@ -0,0 +1,724 @@
///| The panel's modules: finding them on disk, loading, unloading and replacing them
/// while the compositor runs, the capabilities (host data + requests) they use, the
/// right-click menu, and the saved panel layout.
///
/// A module is a wasm plasmoid component (`moonplasma:desktop/plasmoid`). Its imports
/// are the capabilities it was granted: `theme` and `clock` always, `app-catalog` /
/// `app-launch` for the application menu, `windows` for the task list, `layout-control`
/// for the layout switcher, `inspector` for the Interface Explorer button and `modules`
/// for the module manager. The manager is itself just a module: the wasm picker
/// ("Module manager..." in the panel menu) loads it on demand and opens it.
///| Modules loaded into a fresh panel, in order. `tasks` stretches, so what follows it packs right.
let default_panel : Array[String] = [
"launcher", "inspector", "layout", "tasks", "moon-disc", "clock-digital12",
]
///| The module whose popup is the wasm picker.
let manager_module : String = "module-manager"
///| Directories searched for `*.wasm` modules, highest priority first.
fn module_dirs() -> Array[String] {
let dirs : Array[String] = []
let env = @sys.getenv("MOON_PLASMA_MODULES")
if env.length() > 0 {
for d in env.split(":") {
if d.length() > 0 {
dirs.push(d.to_string())
}
}
}
let data_home = {
let x = @sys.getenv("XDG_DATA_HOME")
if x.length() > 0 { x } else { @sys.getenv("HOME") + "/.local/share" }
}
dirs.push(data_home + "/moon-plasma/modules")
dirs.push("/usr/local/share/moon-plasma/modules")
dirs.push("/usr/share/moon-plasma/modules")
dirs.push("modules") // the login session runs from /usr/local/share/moon-plasma
// In a source checkout (and from a package directory when running its tests).
dirs.push("build/components")
dirs.push("../build/components")
dirs.push("../../build/components")
dirs
}
///| "/a/b/clock.wasm" -> "clock"
fn stem(path : String) -> String {
let mut start = 0
for i = 0; i < path.length(); i = i + 1 {
if path[i] == '/' {
start = i + 1
}
}
let name = path[start:].to_string()
if name.has_suffix(".wasm") {
name[:name.length() - 5].to_string()
} else {
name
}
}
///| Find every module file on the search path (earlier directories win on the same name).
fn DesktopShell::scan_catalog(self : DesktopShell) -> Unit {
self.catalog.clear()
self.catalog_named = false
let seen : Map[String, Bool] = {}
for dir in module_dirs() {
for f in @wasm.list_wasm_files(dir) {
let id = stem(f)
if !seen.contains(id) {
seen.set(id, true)
self.catalog.push({ id, path: dir + "/" + f, name: "" })
}
}
}
}
///| Learn each module's display name by loading it once; files that are not plasmoids
/// (the shell, window-manager and gfx components live in the same directory) drop out.
fn DesktopShell::name_catalog(self : DesktopShell) -> Unit {
if self.catalog_named {
return
}
self.catalog_named = true
let keep : Array[CatalogEntry] = []
for e in self.catalog {
match @wasm.load(e.path, self.tokens) {
Ok(pl) => {
e.name = pl.name
pl.unload()
keep.push(e)
}
Err(_) => ()
}
}
self.catalog.clear()
for e in keep {
self.catalog.push(e)
}
}
///| Catalog entry for module id `id`.
fn DesktopShell::find_module(self : DesktopShell, id : String) -> CatalogEntry? {
for e in self.catalog {
if e.id == id {
return Some(e)
}
}
None
}
///| Panel slot descriptions for every loaded module, in panel order. A stretching module
/// (the task list) splits the panel: modules after it pack against the right edge.
fn DesktopShell::panel_slots(self : DesktopShell) -> Array[@panel.SlotIn] {
let mut first_stretch = -1
for i = 0; i < self.widgets.length(); i = i + 1 {
if first_stretch < 0 && self.widgets[i].pl.stretch {
first_stretch = i
}
}
let out : Array[@panel.SlotIn] = []
for i = 0; i < self.widgets.length(); i = i + 1 {
let w = self.widgets[i]
out.push({
id: w.slot,
pref_w: w.pl.pref_w,
pref_h: w.pl.pref_h,
min_w: w.pl.min_w,
stretch: w.pl.stretch,
end_align: first_stretch >= 0 && i > first_stretch,
})
}
out
}
///| Would the panel still fit on screen with the current modules?
fn DesktopShell::panel_fits(self : DesktopShell) -> Bool {
match @panel.layout(self.screen_w, 100000, 40, 4, 6, self.panel_slots()) {
Ok(_) => true
Err(_) => false
}
}
///| Show a short message above the panel for a few seconds.
fn DesktopShell::say(self : DesktopShell, msg : String) -> Unit {
self.notice = msg
self.notice_frames = 1
self.notice_start = wall_secs()
}
///| Seconds since local midnight (wall clock).
fn wall_secs() -> Int {
@sys.wall_time_field(3) * 3600 + @sys.wall_time_field(4) * 60 + @sys.wall_time_field(5)
}
///| Load the panel on first use: the saved layout if there is one, else the default modules.
fn DesktopShell::ensure_booted(self : DesktopShell) -> Unit {
if self.booted {
return
}
self.booted = true
self.scan_catalog()
let entries = match self.load_panel_config() {
Some(e) => e
None => default_panel
}
for e in entries {
let path = if e.has_prefix("/") {
e
} else {
match self.find_module(e) {
Some(c) => c.path
None => {
self.say("Module '" + e + "' not found (build it with scripts/build-modules.sh)")
""
}
}
}
if path != "" {
ignore(self.load_path(path))
}
}
}
///| Load the module file at `path` into the panel (any number of instances may be loaded).
/// None, with a notice, when it is not a plasmoid or the panel has no room for it.
pub fn DesktopShell::load_path(self : DesktopShell, path : String) -> Widget? {
match @wasm.load(path, self.tokens) {
Err(e) => {
self.say("Can't load module: " + e)
None
}
Ok(pl) => {
let id = stem(path)
let known = match self.find_module(id) {
Some(c) => c.path == path
None => false
}
let w : Widget = {
slot: "w" + self.next_slot.to_string(),
module_id: if known { id } else { path },
path,
pl,
caps: pl.imports(),
rect: { x: 0, y: 0, w: 0, h: 0 },
popup_rect: { x: 0, y: 0, w: 0, h: 0 },
popup_ops: [],
popup_hot: false,
}
self.next_slot = self.next_slot + 1
self.widgets.push(w)
if self.screen_w > 0 && !self.panel_fits() {
self.widgets.retain(x => x.slot != w.slot)
pl.unload()
self.say("No room in the panel for " + pl.name)
None
} else {
Some(w)
}
}
}
}
///| Load module `id` (a file stem from the catalog, or a path) and persist the panel.
pub fn DesktopShell::load_module(self : DesktopShell, id : String) -> Bool {
self.ensure_booted()
let path = match self.find_module(id) {
Some(c) => c.path
None => id
}
match self.load_path(path) {
Some(w) => {
self.say("Loaded " + w.pl.name)
self.save_panel_config()
true
}
None => false
}
}
///| Unload the module in `slot`, freeing its panel space. False if there is none.
pub fn DesktopShell::unload_slot(self : DesktopShell, slot : String) -> Bool {
match self.widget_by_slot(slot) {
None => false
Some(w) => {
self.widgets.retain(x => x.slot != slot)
w.pl.unload()
if self.drag_slot == slot {
self.drag_slot = ""
self.drag_active = false
}
self.save_panel_config()
true
}
}
}
///| Replace the module in `slot` with the module file at `path`, keeping its place in the panel.
pub fn DesktopShell::replace_slot(self : DesktopShell, slot : String, path : String) -> Bool {
let mut idx = -1
for i = 0; i < self.widgets.length(); i = i + 1 {
if self.widgets[i].slot == slot {
idx = i
}
}
if idx < 0 {
return false
}
let old = self.widgets[idx]
self.widgets.remove(idx) |> ignore
match self.load_path(path) {
None => {
self.widgets.insert(idx, old)
false
}
Some(nw) => {
// load_path appended it; move it into the old module's place, then drop the old one.
self.widgets.retain(x => x.slot != nw.slot)
self.widgets.insert(idx, nw)
old.pl.unload()
self.save_panel_config()
true
}
}
}
///| Unload every module (the compositor is closing).
pub fn DesktopShell::shutdown(self : DesktopShell) -> Unit {
for w in self.widgets {
w.pl.unload()
}
self.widgets.clear()
}
///| Slot ids of the loaded modules, in panel order.
pub fn DesktopShell::slots(self : DesktopShell) -> Array[String] {
self.ensure_booted()
self.widgets.map(w => w.slot)
}
///| Module id of the module in `slot` ("" if none).
pub fn DesktopShell::slot_module(self : DesktopShell, slot : String) -> String {
match self.widget_by_slot(slot) {
Some(w) => w.module_id
None => ""
}
}
///| Slot of the first loaded instance of module `id` ("" if none).
pub fn DesktopShell::slot_of(self : DesktopShell, id : String) -> String {
self.ensure_booted()
for w in self.widgets {
if w.module_id == id {
return w.slot
}
}
""
}
///| Panel rectangle of the module in `slot` as last drawn.
pub fn DesktopShell::slot_rect(self : DesktopShell, slot : String) -> @scene.Rect {
match self.widget_by_slot(slot) {
Some(w) => w.rect
None => { x: 0, y: 0, w: 0, h: 0 }
}
}
///| Rectangle of the module's open popup (w == 0 when closed).
pub fn DesktopShell::slot_popup_rect(self : DesktopShell, slot : String) -> @scene.Rect {
match self.widget_by_slot(slot) {
Some(w) => w.popup_rect
None => { x: 0, y: 0, w: 0, h: 0 }
}
}
///| Publish what modules can read through their capabilities (apps, windows, layout, loaded modules).
fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit {
if self.apps_dirty {
self.apps_dirty = false
let t = @wasm.Table::new()
for a in self.apps {
t.str(a.id)
t.str(a.name)
t.str(a.comment)
t.str(a.category)
t.str(a.glyph)
t.end_row()
}
@wasm.publish(Apps, t)
}
let wt = @wasm.Table::new()
for win in self.windows {
wt.int(win.id.to_int())
wt.str(win.title)
wt.int(if win.focused { 1 } else { 0 })
wt.int(if win.minimized { 1 } else { 0 })
wt.end_row()
}
@wasm.publish(Windows, wt)
let lt = @wasm.Table::new()
for n in self.layout_names {
lt.str(n)
lt.end_row()
}
@wasm.publish(Layouts, lt)
@wasm.publish_state(self.layout_sel, self.inspect_on)
let it = @wasm.Table::new()
for w in self.widgets {
it.str(w.slot)
it.str(w.module_id)
it.str(w.pl.name)
it.end_row()
}
@wasm.publish(Instances, it)
let mut wants_modules = false
for w in self.widgets {
if w.has_cap("modules") {
wants_modules = true
}
}
if wants_modules {
self.name_catalog()
let mt = @wasm.Table::new()
for e in self.catalog {
let mut n = 0
for w in self.widgets {
if w.path == e.path {
n = n + 1
}
}
mt.str(e.id)
mt.str(e.name)
mt.str(e.path)
mt.int(n)
mt.end_row()
}
@wasm.publish(Modules, mt)
}
}
///| Carry out what modules asked of the host during their last calls.
fn DesktopShell::process_requests(self : DesktopShell) -> Unit {
while true {
match @wasm.next_request() {
None => break
Some(Launch(id)) => {
match self.exec.get(id) {
Some(bin) =>
if @sys.spawn(bin, self.display) {
self.note_recent(id)
self.apps_dirty = true
} else {
self.say("Could not start " + bin)
}
None => self.say("No executable for " + id)
}
}
Some(FocusWindow(n)) => self.actions.push(FocusWindow(n.to_int64().to_uint64()))
Some(SetLayout(m)) => self.actions.push(SetLayout(m))
Some(SetInspector(on)) => self.set_inspecting(on)
Some(LoadModule(path)) => {
match self.load_path(path) {
Some(w) => {
self.say("Loaded " + w.pl.name)
self.save_panel_config()
}
None => ()
}
}
Some(UnloadInstance(slot)) => ignore(self.unload_slot(slot))
Some(Browse) =>
if self.picker is None {
self.picker = @wasm.Picker::start()
if self.picker is None {
self.say("No file chooser available (install zenity)")
}
}
}
}
// A module that imports `windows.focus` (the 64-bit-id form) asks through its own slot.
match @wasm.take_focus_request() {
Some(id) => self.actions.push(FocusWindow(id))
None => ()
}
}
///| Re-read the module's popup (size and drawing) and place it above the panel.
fn DesktopShell::refresh_popup(self : DesktopShell, w : Widget) -> Unit {
if self.widget_by_slot(w.slot) is None {
return
}
match w.pl.popup() {
None => {
w.popup_rect = { x: 0, y: 0, w: 0, h: 0 }
w.popup_ops = []
w.popup_hot = false
}
Some(ps) => {
let (px, py) = @panel.popup_position(self.screen_w, self.screen_h - self.panel_h, w.rect.x, ps.w, ps.h, 6)
w.popup_rect = { x: px, y: py, w: ps.w, h: ps.h }
w.popup_ops = ps.ops
}
}
}
///| Check the open file dialog; load the chosen .wasm into the panel.
fn DesktopShell::poll_picker(self : DesktopShell) -> Unit {
match self.picker {
None => ()
Some(pk) =>
match pk.poll() {
None => ()
Some(None) => self.picker = None
Some(Some(path)) => {
self.picker = None
match self.load_path(path) {
Some(w) => {
self.say("Loaded " + w.pl.name)
self.save_panel_config()
}
None => ()
}
}
}
}
}
///| The wasm picker: open the module manager app to choose what to load, loading the
/// manager itself first if it is not in the panel.
pub fn DesktopShell::open_module_manager(self : DesktopShell) -> Bool {
self.ensure_booted()
let mut mgr : Widget? = None
for w in self.widgets {
if mgr is None && w.module_id == manager_module {
mgr = Some(w)
}
}
if mgr is None {
match self.find_module(manager_module) {
None => {
self.say("Module manager not found (build it with scripts/build-modules.sh)")
return false
}
Some(c) => mgr = self.load_path(c.path)
}
}
match mgr {
None => false
Some(w) => {
self.dismiss_popups(w.slot)
if w.popup_rect.w == 0 {
ignore(self.deliver(w, false, PointerDown(0, 0)))
}
self.save_panel_config()
true
}
}
}
// ---------------------------------------------------------------- right-click menu
///| Title row height and item row height of the menu.
let menu_title_h : Int = 26
///|
let menu_item_h : Int = 28
///|
let menu_w : Int = 250
///| Most "Replace with" rows listed.
let max_replace_rows : Int = 8
///| Right-click: on a module its replace/remove menu, on empty panel space the picker entry.
/// True when consumed.
pub fn DesktopShell::right_click(self : DesktopShell, x : Int, y : Int) -> Bool {
self.ensure_booted()
if self.inspect_on {
return false
}
let was_open = self.menu_open
self.menu_open = false
self.dismiss_popups("")
match self.widget_at(x, y) {
Some(w) => {
self.name_catalog()
let rows : Array[MenuRow] = []
for e in self.catalog {
if e.id != w.module_id && e.path != w.path && rows.length() < max_replace_rows {
rows.push({ label: "Replace with " + e.name, kind: 0, arg: e.path })
}
}
rows.push({ label: "Remove widget", kind: 1, arg: "" })
rows.push({ label: "Module manager...", kind: 2, arg: "" })
self.open_menu(w.pl.name, rows, w.slot, x)
true
}
None =>
if inside(self.panel_rect, x, y) {
self.open_menu("Add widget", [{ label: "Module manager...", kind: 2, arg: "" }], "", x)
true
} else {
was_open
}
}
}
///|
fn DesktopShell::open_menu(self : DesktopShell, title : String, rows : Array[MenuRow], slot : String, x : Int) -> Unit {
self.menu_open = true
self.menu_title = title
self.menu_rows = rows
self.menu_slot = slot
self.menu_hover = -1
self.menu_anchor_x = x
}
///|
fn DesktopShell::menu_item_at(self : DesktopShell, x : Int, y : Int) -> Int {
if !self.menu_open || !inside(self.menu_rect, x, y) {
return -1
}
let i = (y - self.menu_rect.y - menu_title_h) / menu_item_h
if y - self.menu_rect.y >= menu_title_h && i >= 0 && i < self.menu_rows.length() {
i
} else {
-1
}
}
///| Left press while the menu is open: choose a row or dismiss. True when consumed.
fn DesktopShell::menu_pointer_down(self : DesktopShell, x : Int, y : Int) -> Bool {
let i = self.menu_item_at(x, y)
let over = inside(self.menu_rect, x, y)
self.menu_open = false
if i >= 0 {
let row = self.menu_rows[i]
let slot = self.menu_slot
match row.kind {
0 => ignore(self.replace_slot(slot, row.arg))
1 => ignore(self.unload_slot(slot))
_ => ignore(self.open_module_manager())
}
}
over
}
///|
fn DesktopShell::menu_pointer_move(self : DesktopShell, x : Int, y : Int) -> Bool {
self.menu_hover = self.menu_item_at(x, y)
inside(self.menu_rect, x, y)
}
///|
fn DesktopShell::render_menu(
self : DesktopShell,
w : Int,
tokens : @theme.Tokens,
out : Array[@scene.DrawOp],
) -> Unit {
let n = self.menu_rows.length()
let mh = menu_title_h + n * menu_item_h + 6
let mx = clamp_menu(self.menu_anchor_x - menu_w / 2, 4, w - menu_w - 4)
let my = self.panel_rect.y - mh - 6
self.menu_rect = { x: mx, y: my, w: menu_w, h: mh }
let fs = tokens.font_size.reinterpret_as_int()
let r = tokens.radius.reinterpret_as_int()
let ops : Array[@types.DrawOp] = [
@ui.fill_rect(@ui.rect(0, 0, menu_w, mh), tokens.palette.surface_popup, radius=r),
@ui.stroke_rect(@ui.rect(0, 0, menu_w, mh), tokens.palette.border, radius=r),
@ui.text(12, menu_title_h / 2 + 2, self.menu_title, fs - 3, tokens.palette.foreground_muted),
]
for i = 0; i < n; i = i + 1 {
let top = menu_title_h + i * menu_item_h
let hot = i == self.menu_hover
if hot {
ops.push(@ui.fill_rect(@ui.rect(4, top, menu_w - 8, menu_item_h - 2), tokens.palette.surface_hover, radius=r))
}
ops.push(@ui.text(14, top + menu_item_h / 2, self.menu_rows[i].label, fs - 2, tokens.palette.foreground))
}
translate(ops, mx, my, out)
}
///|
fn clamp_menu(v : Int, lo : Int, hi : Int) -> Int {
if v > hi { hi } else if v < lo { lo } else { v }
}
// ---------------------------------------------------------------- saved panel
///| Panel config lives in $XDG_CONFIG_HOME/moon-plasma/panel.edn (default ~/.config).
fn panel_config_dir() -> String {
let c = @sys.getenv("XDG_CONFIG_HOME")
(if c.length() > 0 { c } else { @sys.getenv("HOME") + "/.config" }) +
"/moon-plasma"
}
///| Write the loaded modules, in panel order, as EDN:
/// {:panel ["launcher" "layout" "tasks" "/home/me/my-widget.wasm"]}
/// (catalog modules by name, others by path). A no-op unless `persist` is on.
pub fn DesktopShell::save_panel_config(self : DesktopShell) -> Unit {
if !self.persist || !self.booted {
return
}
let sb = StringBuilder::new()
sb.write_string(";; Moon Plasma panel: the wasm modules loaded into it, in order\n")
sb.write_string("{:panel [")
let mut first = true
for w in self.widgets {
if !first {
sb.write_string("\n ")
}
first = false
sb.write_string("\"" + w.module_id + "\"")
}
sb.write_string("]}\n")
let dir = panel_config_dir()
if @sys.mkdir_p(dir) {
ignore(@sys.write_file_bytes(dir + "/panel.edn", @utf8.encode(sb.to_string())))
}
}
///| The module list saved in panel.edn; None when persistence is off or there is no saved panel.
fn DesktopShell::load_panel_config(self : DesktopShell) -> Array[String]? {
if !self.persist {
return None
}
let text = @utf8.decode_lossy(@sys.read_file_bytes(panel_config_dir() + "/panel.edn"))
let lines : Array[String] = []
for l in text.split("\n") {
if !l.trim(chars=" \t\r").to_string().has_prefix(";") {
lines.push(l.to_string())
}
}
let body = lines.join("\n")
match body.find(":panel") {
None => None
Some(i) => {
let rest = body[i:].to_string()
match (rest.find("["), rest.find("]")) {
(Some(a), Some(b)) if b > a => {
let out : Array[String] = []
for part in rest[a + 1:b].to_string().split("\"") {
// quoted strings are the odd-numbered parts
out.push(part.to_string())
}
let names : Array[String] = []
for k = 1; k < out.length(); k = k + 2 {
if out[k].length() > 0 {
names.push(out[k])
}
}
Some(names)
}
_ => None
}
}
}
}
///| Theme tokens in the WIT shape the plasmoids expect.
pub fn DesktopShell::tokens_for(_self : DesktopShell, theme : @scene.ThemeTokens) -> @theme.Tokens {
conv_theme(theme)
}
+52
View File
@@ -194,3 +194,55 @@ pub fn has_exe(name : String) -> Bool {
pub fn spawn(cmd : String, display : String) -> Bool { pub fn spawn(cmd : String, display : String) -> Bool {
c_spawn(str_to_utf8_bytes(cmd), str_to_utf8_bytes(display)) == 0 c_spawn(str_to_utf8_bytes(cmd), str_to_utf8_bytes(display)) == 0
} }
///|
extern "C" fn c_list_desktop(dir : Bytes) -> Bytes = "mp_list_desktop"
///|
extern "C" fn c_getenv(name : Bytes) -> Bytes = "mp_getenv"
///| Newline-separated names of the `*.desktop` files directly in `dir`.
pub fn list_desktop_files(dir : String) -> Array[String] {
let raw = c_list_desktop(str_to_utf8_bytes(dir))
let out : Array[String] = []
let sb = StringBuilder::new()
let mut i = 0
while i < raw.length() {
if raw[i] == b'\n' {
out.push(sb.to_string())
sb.reset()
} else {
sb.write_char(Int::unsafe_to_char(raw[i].to_int()))
}
i = i + 1
}
out
}
///| Environment variable, or "" when unset.
pub fn getenv(name : String) -> String {
let raw = c_getenv(str_to_utf8_bytes(name))
let sb = StringBuilder::new()
for i = 0; i < raw.length(); i = i + 1 {
sb.write_char(Int::unsafe_to_char(raw[i].to_int()))
}
sb.to_string()
}
///|
extern "C" fn c_mkdir_p(path : Bytes) -> Int = "mp_mkdir_p"
///| Create `path` and any missing parents; true when it exists afterwards.
pub fn mkdir_p(path : String) -> Bool {
c_mkdir_p(str_to_utf8_bytes(path)) == 0
}
///|
#borrow(path)
extern "C" fn c_read_proc(path : Bytes) -> Bytes = "mp_read_proc"
///| Contents of a small /proc or /sys file ("" when unreadable). Unlike `read_file_bytes`
/// this works on files that report size 0.
pub fn read_proc_bytes(path : String) -> Bytes {
c_read_proc(str_to_utf8_bytes(path))
}
+116 -2
View File
@@ -12,7 +12,10 @@
#include <sys/un.h> #include <sys/un.h>
#include <time.h> #include <time.h>
#include <signal.h> #include <signal.h>
#include <sys/prctl.h>
#include <dirent.h>
#include <unistd.h> #include <unistd.h>
#include <limits.h>
#include "moonbit.h" #include "moonbit.h"
@@ -332,22 +335,133 @@ int32_t mp_has_exe(moonbit_bytes_t name_bytes) {
return found; return found;
} }
/* Private session bus for launched apps, so single-instance apps (Firefox, Kate,
* Dolphin...) don't forward the launch to an instance on the host session.
* Started lazily; dies with the compositor. */
static char private_bus[256];
static int private_bus_tried = 0;
static void start_private_bus(void) {
if (private_bus_tried) return;
private_bus_tried = 1;
int fds[2];
if (pipe(fds) != 0) return;
pid_t pid = fork();
if (pid < 0) { close(fds[0]); close(fds[1]); return; }
if (pid == 0) {
prctl(PR_SET_PDEATHSIG, SIGTERM);
close(fds[0]);
char arg[64];
snprintf(arg, sizeof(arg), "--print-address=%d", fds[1]);
execlp("dbus-daemon", "dbus-daemon", "--session", "--nofork", arg, (char *)NULL);
_exit(127);
}
close(fds[1]);
ssize_t n = read(fds[0], private_bus, sizeof(private_bus) - 1);
close(fds[0]);
if (n > 0) {
private_bus[n] = 0;
char *nl = strchr(private_bus, '\n');
if (nl) *nl = 0;
} else {
private_bus[0] = 0;
}
}
/* Launch `cmd` detached, with WAYLAND_DISPLAY pointing at our socket. Returns 0 on fork success. */ /* Launch `cmd` detached, with WAYLAND_DISPLAY pointing at our socket. Returns 0 on fork success. */
MOONBIT_FFI_EXPORT MOONBIT_FFI_EXPORT
int32_t mp_spawn(moonbit_bytes_t cmd_bytes, moonbit_bytes_t display_bytes) { int32_t mp_spawn(moonbit_bytes_t cmd_bytes, moonbit_bytes_t display_bytes) {
char cmd[256]; char cmd[2048];
char display[512]; char display[512];
bytes_to_cstr(cmd_bytes, cmd, sizeof(cmd)); bytes_to_cstr(cmd_bytes, cmd, sizeof(cmd));
bytes_to_cstr(display_bytes, display, sizeof(display)); bytes_to_cstr(display_bytes, display, sizeof(display));
signal(SIGCHLD, SIG_IGN); /* no zombies */ signal(SIGCHLD, SIG_IGN); /* no zombies */
start_private_bus();
pid_t pid = fork(); pid_t pid = fork();
if (pid < 0) return -1; if (pid < 0) return -1;
if (pid == 0) { if (pid == 0) {
setsid(); setsid();
if (private_bus[0]) setenv("DBUS_SESSION_BUS_ADDRESS", private_bus, 1);
setenv("WAYLAND_DISPLAY", display, 1); setenv("WAYLAND_DISPLAY", display, 1);
unsetenv("DISPLAY"); unsetenv("DISPLAY");
execlp(cmd, cmd, (char *)NULL); /* Make toolkits pick our Wayland socket, not X11 or the host session. */
setenv("XDG_SESSION_TYPE", "wayland", 1);
setenv("QT_QPA_PLATFORM", "wayland", 1);
setenv("GDK_BACKEND", "wayland", 1);
setenv("SDL_VIDEODRIVER", "wayland", 1);
setenv("MOZ_ENABLE_WAYLAND", "1", 1);
setenv("ELECTRON_OZONE_PLATFORM_HINT", "wayland", 1);
setenv("CLUTTER_BACKEND", "wayland", 1);
execl("/bin/sh", "sh", "-c", cmd, (char *)NULL);
_exit(127); _exit(127);
} }
return 0; return 0;
} }
/* Names of "*.desktop" files in `dir`, newline-separated. */
MOONBIT_FFI_EXPORT
moonbit_bytes_t mp_list_desktop(moonbit_bytes_t dir_bytes) {
char dir[512];
bytes_to_cstr(dir_bytes, dir, sizeof(dir));
DIR *d = opendir(dir);
if (!d) return moonbit_make_bytes_raw(0);
size_t cap = 4096, len = 0;
char *buf = malloc(cap);
struct dirent *e;
while ((e = readdir(d)) != NULL) {
size_t n = strlen(e->d_name);
if (n < 9 || strcmp(e->d_name + n - 8, ".desktop") != 0) continue;
if (len + n + 2 > cap) { cap = (len + n + 2) * 2; buf = realloc(buf, cap); }
memcpy(buf + len, e->d_name, n);
len += n;
buf[len++] = '\n';
}
closedir(d);
moonbit_bytes_t out = moonbit_make_bytes_raw((int32_t)len);
memcpy(out, buf, len);
free(buf);
return out;
}
MOONBIT_FFI_EXPORT
moonbit_bytes_t mp_getenv(moonbit_bytes_t name_bytes) {
char name[128];
bytes_to_cstr(name_bytes, name, sizeof(name));
const char *v = getenv(name);
if (!v) return moonbit_make_bytes_raw(0);
size_t n = strlen(v);
moonbit_bytes_t out = moonbit_make_bytes_raw((int32_t)n);
memcpy(out, v, n);
return out;
}
/* mkdir -p; returns 0 when the directory exists afterwards. */
MOONBIT_FFI_EXPORT
int32_t mp_mkdir_p(moonbit_bytes_t path_bytes) {
char path[512];
bytes_to_cstr(path_bytes, path, sizeof(path));
for (char *p = path + 1; *p; p++) {
if (*p == '/') {
*p = 0;
mkdir(path, 0755);
*p = '/';
}
}
if (mkdir(path, 0755) != 0 && errno != EEXIST) return -1;
return 0;
}
/* Read a small /proc or /sys file (they report size 0, so read until EOF; capped at 64 KiB). */
MOONBIT_FFI_EXPORT
moonbit_bytes_t mp_read_proc(moonbit_bytes_t path_bytes) {
char path[512];
bytes_to_cstr(path_bytes, path, sizeof(path));
FILE *f = fopen(path, "rb");
if (!f) return moonbit_make_bytes_raw(0);
static char buf[65536];
size_t n = fread(buf, 1, sizeof(buf), f);
fclose(f);
moonbit_bytes_t out = moonbit_make_bytes_raw((int32_t)n);
memcpy(out, buf, n);
return out;
}
+16
View File
@@ -0,0 +1,16 @@
import {
"moonbitlang/core/builtin",
"moonplasma/desktop/interface/moonplasma/desktop/types" @types,
"moonplasma/desktop/interface/moonplasma/desktop/theme" @theme,
}
supported_targets = "-all+native"
options(
"native-stub": [ "wasm_stub.c" ],
link: {
"native": {
"cc-link-flags": "-lwasmer",
},
},
)
Binary file not shown.
Binary file not shown.
Binary file not shown.
+723
View File
@@ -0,0 +1,723 @@
///| Loads plasmoid components (.wasm) into the native compositor. The core module
/// is run with wasmer (see wasm_stub.c); this file does the canonical-ABI marshalling
/// of the `plasmoid` interface: info, render and the draw-op list, UTF-16 strings.
///|
#borrow(path, tokens)
extern "C" fn c_wasm_load(path : Bytes, tokens : Bytes) -> Int = "mp_wasm_load"
///|
#borrow(tokens)
extern "C" fn c_wasm_set_tokens(h : Int, tokens : Bytes) = "mp_wasm_set_tokens"
///|
extern "C" fn c_wasm_unload(h : Int) = "mp_wasm_unload"
///|
extern "C" fn c_wasm_call(h : Int, which : Int, a0 : Int, a1 : Int, a2 : Int, a3 : Int) -> Int = "mp_wasm_call"
///|
#borrow(out)
extern "C" fn c_wasm_read(h : Int, off : Int, len : Int, out : Bytes) -> Int = "mp_wasm_read"
///|
#borrow(b)
extern "C" fn c_wasm_set_system(b : Bytes) = "mp_wasm_set_system"
///|
#borrow(b)
extern "C" fn c_wasm_set_windows(b : Bytes) = "mp_wasm_set_windows"
///|
extern "C" fn c_wasm_take_focus() -> Int = "mp_wasm_take_focus"
///|
#borrow(src)
extern "C" fn c_wasm_write(h : Int, off : Int, src : Bytes, len : Int) -> Int = "mp_wasm_write"
///|
#borrow(out)
extern "C" fn c_wasm_imports(h : Int, out : Bytes) -> Int = "mp_wasm_imports"
///|
#borrow(data)
extern "C" fn c_host_set_table(which : Int, data : Bytes) = "mp_host_set_table"
///|
extern "C" fn c_host_set_int(which : Int, v : Int) = "mp_host_set_int"
///|
extern "C" fn c_host_req_pop() -> Int = "mp_host_req_pop"
///|
extern "C" fn c_host_req_int() -> Int = "mp_host_req_int"
///|
#borrow(out)
extern "C" fn c_host_req_str(out : Bytes) -> Int = "mp_host_req_str"
///|
#borrow(dir)
extern "C" fn c_list_wasm(dir : Bytes) -> Bytes = "mp_list_wasm"
///|
extern "C" fn c_pick_start() -> Int = "mp_pick_start"
///|
#borrow(out)
extern "C" fn c_fd_read(fd : Int, out : Bytes) -> Int = "mp_fd_read"
///|
extern "C" fn c_fd_close(fd : Int) = "mp_fd_close"
///|
fn utf8(s : String) -> Bytes {
let out : Array[Byte] = []
for ch in s {
let c = ch.to_int()
if c < 0x80 {
out.push(c.to_byte())
} else if c < 0x800 {
out.push((0xC0 | (c >> 6)).to_byte())
out.push((0x80 | (c & 0x3F)).to_byte())
} else if c < 0x10000 {
out.push((0xE0 | (c >> 12)).to_byte())
out.push((0x80 | ((c >> 6) & 0x3F)).to_byte())
out.push((0x80 | (c & 0x3F)).to_byte())
} else {
out.push((0xF0 | (c >> 18)).to_byte())
out.push((0x80 | ((c >> 12) & 0x3F)).to_byte())
out.push((0x80 | ((c >> 6) & 0x3F)).to_byte())
out.push((0x80 | (c & 0x3F)).to_byte())
}
}
Bytes::from_array(out)
}
///| Decode UTF-8 bytes (file-picker output).
fn from_utf8(b : Bytes, len : Int) -> String {
let sb = StringBuilder::new()
let mut i = 0
while i < len {
let c = b[i].to_int()
if c < 0x80 {
sb.write_char(c.unsafe_to_char())
i = i + 1
} else if c < 0xE0 && i + 1 < len {
sb.write_char((((c & 0x1F) << 6) | (b[i + 1].to_int() & 0x3F)).unsafe_to_char())
i = i + 2
} else if c < 0xF0 && i + 2 < len {
sb.write_char((((c & 0x0F) << 12) | ((b[i + 1].to_int() & 0x3F) << 6) | (b[i + 2].to_int() & 0x3F)).unsafe_to_char())
i = i + 3
} else if i + 3 < len {
sb.write_char((((c & 0x07) << 18) | ((b[i + 1].to_int() & 0x3F) << 12) | ((b[i + 2].to_int() & 0x3F) << 6) | (b[i + 3].to_int() & 0x3F)).unsafe_to_char())
i = i + 4
} else {
i = len
}
}
sb.to_string()
}
///| Export indices in wasm_stub.c.
let ex_info : Int = 0
///|
let ex_render : Int = 1
///|
let ex_onevent : Int = 2
///|
let ex_popup : Int = 3
///|
let ex_post_info : Int = 4
///|
let ex_post_render : Int = 5
///|
let ex_post_popup : Int = 6
///|
let ex_realloc : Int = 7
///| The 64-byte `theme.tokens` record (name left empty) the guest reads through get-tokens.
pub fn pack_tokens(t : @theme.Tokens) -> Bytes {
let b = FixedArray::make(64, b'\x00')
let mut off = 8
let col = fn(c : @types.Color) {
b[off] = c.r
b[off + 1] = c.g
b[off + 2] = c.b
b[off + 3] = c.a
off = off + 4
}
let p = t.palette
col(p.desktop_top)
col(p.desktop_bottom)
col(p.surface)
col(p.surface_hover)
col(p.surface_popup)
col(p.foreground)
col(p.foreground_muted)
col(p.accent)
col(p.accent_foreground)
col(p.border)
let put32 = fn(o : Int, v : UInt) {
for k = 0; k < 4; k = k + 1 {
b[o + k] = ((v >> (8 * k)) & 0xFFU).to_int().to_byte()
}
}
put32(48, t.font_size)
put32(52, t.radius)
put32(56, t.spacing)
put32(60, t.panel_height)
Bytes::from_fixedarray(b)
}
///| A loaded plasmoid instance.
pub(all) struct Plasmoid {
handle : Int
id : String
name : String
pref_w : Int
pref_h : Int
min_w : Int
stretch : Bool
/// The host interfaces this widget imports, i.e. what it was granted (e.g. "system,windows").
imports : Array[String]
}
///|
fn Plasmoid::mem(self : Plasmoid, off : Int, len : Int) -> Bytes? {
if len < 0 || off < 0 {
return None
}
let buf = Bytes::make(len, b'\x00')
if len == 0 || c_wasm_read(self.handle, off, len, buf) == 0 {
Some(buf)
} else {
None
}
}
///|
fn rd32(b : Bytes, o : Int) -> Int {
b[o].to_int() | (b[o + 1].to_int() << 8) | (b[o + 2].to_int() << 16) | (b[o + 3].to_int() << 24)
}
///| UTF-16LE string of `len` code units at `ptr` in guest memory.
fn Plasmoid::str(self : Plasmoid, ptr : Int, len : Int) -> String {
if len <= 0 || len > 4096 {
return ""
}
match self.mem(ptr, len * 2) {
None => ""
Some(b) => {
let sb = StringBuilder::new()
for i = 0; i < len; i = i + 1 {
sb.write_char((b[2 * i].to_int() | (b[2 * i + 1].to_int() << 8)).unsafe_to_char())
}
sb.to_string()
}
}
}
///| Load a plasmoid component or core module. Err carries a short reason.
pub fn load(path : String, tokens : @theme.Tokens) -> Result[Plasmoid, String] {
let h = c_wasm_load(utf8(path), pack_tokens(tokens))
if h < 0 {
return Err(
match h {
-1 => "not a wasm file"
-2 => "cannot read file"
-3 | -4 => "no plasmoid (moonplasma:desktop/plasmoid) in this module"
_ => "wasm runtime error"
},
)
}
let p0 : Plasmoid = { handle: h, id: "", name: "", pref_w: 0, pref_h: 0, min_w: 0, stretch: false, imports: [] }
let ra = c_wasm_call(h, ex_info, 0, 0, 0, 0)
if ra < 0 {
c_wasm_unload(h)
return Err("widget trapped in info()")
}
match p0.mem(ra, 32) {
None => {
c_wasm_unload(h)
Err("bad info() result")
}
Some(b) => {
let p = {
..p0,
id: p0.str(rd32(b, 0), rd32(b, 4)),
name: p0.str(rd32(b, 8), rd32(b, 12)),
pref_w: rd32(b, 16),
pref_h: rd32(b, 20),
min_w: rd32(b, 24),
stretch: b[28].to_int() != 0,
imports: read_imports(h),
}
ignore(c_wasm_call(h, ex_post_info, ra, 0, 0, 0))
Ok(p)
}
}
}
///| Names of the moonplasma interfaces (besides types/theme) the widget at `h` imports.
fn read_imports(h : Int) -> Array[String] {
let buf = Bytes::make(512, b'\x00')
let n = c_wasm_imports(h, buf)
let out : Array[String] = []
if n > 0 {
for part in from_utf8(buf, n).split("\n") {
if part.length() > 0 && part.to_string() != "theme" {
out.push(part.to_string())
}
}
}
out
}
///| Machine state served to widgets through `system.read`.
pub(all) struct SystemSnapshot {
cpu_permille : Int
mem_used_kib : Int64
mem_total_kib : Int64
battery_percent : Int
charging : Bool
uptime_secs : Int64
rx_bps : Int64
tx_bps : Int64
load_centi : Int
}
///| One window served to widgets through `windows.all`.
pub(all) struct WindowEntry {
id : UInt64
title : String
app_id : String
focused : Bool
}
///| Publish the machine state widgets will read (canonical-ABI layout of `system.snapshot`).
pub fn set_system(s : SystemSnapshot) -> Unit {
let b = FixedArray::make(64, b'\x00')
let put = fn(o : Int, v : Int64, n : Int) {
for k = 0; k < n; k = k + 1 {
b[o + k] = ((v >> (8 * k)) & 0xFFL).to_int().to_byte()
}
}
put(0, s.cpu_permille.to_int64(), 4)
put(8, s.mem_used_kib, 8)
put(16, s.mem_total_kib, 8)
put(24, s.battery_percent.to_int64(), 4)
put(28, if s.charging { 1L } else { 0L }, 1)
put(32, s.uptime_secs, 8)
put(40, s.rx_bps, 8)
put(48, s.tx_bps, 8)
put(56, s.load_centi.to_int64(), 4)
c_wasm_set_system(Bytes::from_fixedarray(b))
}
///| Publish the window list widgets will read.
pub fn set_windows(wins : Array[WindowEntry]) -> Unit {
let out : Array[Byte] = []
let u32 = fn(v : Int) {
for k = 0; k < 4; k = k + 1 {
out.push(((v >> (8 * k)) & 0xFF).to_byte())
}
}
let units = fn(str : String) {
u32(str.length())
for i = 0; i < str.length(); i = i + 1 {
let c = str[i].to_int()
out.push((c & 0xFF).to_byte())
out.push(((c >> 8) & 0xFF).to_byte())
}
}
let n = if wins.length() > 64 { 64 } else { wins.length() }
u32(n)
for i = 0; i < n; i = i + 1 {
let w = wins[i]
u32((w.id & 0xFFFFFFFFUL).to_int())
u32((w.id >> 32).to_int())
u32(if w.focused { 1 } else { 0 })
// titles are capped so one huge title cannot crowd out the rest of the list
units(if w.title.length() > 200 { w.title[:200].to_string() } else { w.title })
units(if w.app_id.length() > 200 { w.app_id[:200].to_string() } else { w.app_id })
}
c_wasm_set_windows(Bytes::from_array(out))
}
///| Window a widget asked to focus (via `windows.focus`) since the last call.
pub fn take_focus_request() -> UInt64? {
let id = c_wasm_take_focus()
if id < 0 { None } else { Some(id.to_uint64()) }
}
///| Forward a press at widget-local (x, y) to the widget's `on-event`. True when it asked for a redraw.
pub fn Plasmoid::pointer_down(self : Plasmoid, x : Int, y : Int) -> Bool {
c_wasm_call(self.handle, ex_onevent, 0, 1, x, y) == 1
}
///|
pub fn Plasmoid::unload(self : Plasmoid) -> Unit {
c_wasm_unload(self.handle)
}
///|
fn col(b : Bytes, o : Int) -> @types.Color {
{ r: b[o], g: b[o + 1], b: b[o + 2], a: b[o + 3] }
}
///| Decode `n` draw-ops at guest address `base` (the canonical-ABI list<draw-op> layout).
fn Plasmoid::decode_ops(self : Plasmoid, base : Int, n : Int, out : Array[@types.DrawOp]) -> Unit {
if n >= 0 && n <= 4096 {
match self.mem(base, n * 32) {
None => ()
Some(b) =>
for i = 0; i < n; i = i + 1 {
let o = i * 32
let rect = fn(o2 : Int) -> @types.Rect {
{ x: rd32(b, o2), y: rd32(b, o2 + 4), w: rd32(b, o2 + 8).reinterpret_as_uint(), h: rd32(b, o2 + 12).reinterpret_as_uint() }
}
match b[o].to_int() {
0 =>
out.push(
FillRect({ rect: rect(o + 4), color: col(b, o + 20), radius: rd32(b, o + 24).reinterpret_as_uint() }),
)
1 =>
out.push(
StrokeRect({
rect: rect(o + 4),
color: col(b, o + 20),
width: rd32(b, o + 24).reinterpret_as_uint(),
radius: rd32(b, o + 28).reinterpret_as_uint(),
}),
)
2 =>
out.push(
Line({
start: { x: rd32(b, o + 4), y: rd32(b, o + 8) },
end: { x: rd32(b, o + 12), y: rd32(b, o + 16) },
color: col(b, o + 20),
width: rd32(b, o + 24).reinterpret_as_uint(),
}),
)
3 =>
out.push(
Circle({
center: { x: rd32(b, o + 4), y: rd32(b, o + 8) },
radius: rd32(b, o + 12).reinterpret_as_uint(),
color: col(b, o + 16),
filled: b[o + 20].to_int() != 0,
}),
)
4 =>
out.push(
Text({
origin: { x: rd32(b, o + 4), y: rd32(b, o + 8) },
text: self.str(rd32(b, o + 12), rd32(b, o + 16)),
style: {
size: rd32(b, o + 20).reinterpret_as_uint(),
color: col(b, o + 24),
align: match b[o + 28].to_int() {
1 => CENTER
2 => RIGHT
_ => LEFT
},
bold: b[o + 29].to_int() != 0,
},
}),
)
5 => out.push(PushClip(rect(o + 4)))
_ => out.push(PopClip)
}
}
}
}
}
///| Draw ops of the widget at `size`, with the theme tokens refreshed first.
/// A trapping or malformed widget yields no ops.
pub fn Plasmoid::render(
self : Plasmoid,
w : Int,
h : Int,
tokens : @theme.Tokens,
) -> Array[@types.DrawOp] {
c_wasm_set_tokens(self.handle, pack_tokens(tokens))
let ra = c_wasm_call(self.handle, ex_render, w, h, 0, 0)
let out : Array[@types.DrawOp] = []
if ra < 0 {
return out
}
match self.mem(ra, 8) {
None => ()
Some(hdr) => self.decode_ops(rd32(hdr, 0), rd32(hdr, 4), out)
}
ignore(c_wasm_call(self.handle, ex_post_render, ra, 0, 0, 0))
out
}
///| A popup surface a plasmoid wants shown next to its panel widget.
pub(all) struct PopupSurface {
w : Int
h : Int
ops : Array[@types.DrawOp]
}
///| `popup()`: the widget's open popup, or None. Local coordinates, origin top-left.
pub fn Plasmoid::popup(self : Plasmoid) -> PopupSurface? {
let ra = c_wasm_call(self.handle, ex_popup, 0, 0, 0, 0)
if ra < 0 {
return None
}
let mut res : PopupSurface? = None
match self.mem(ra, 20) {
None => ()
Some(b) =>
if b[0].to_int() != 0 {
let ops : Array[@types.DrawOp] = []
self.decode_ops(rd32(b, 12), rd32(b, 16), ops)
res = Some({ w: rd32(b, 4), h: rd32(b, 8), ops })
}
}
ignore(c_wasm_call(self.handle, ex_post_popup, ra, 0, 0, 0))
res
}
///| An input event for a plasmoid (mirrors the WIT `input-event`).
pub(all) enum PlasmoidEvent {
PointerMove(Int, Int)
PointerDown(Int, Int)
PointerUp(Int, Int)
PointerLeave
FocusLost
KeyDown(String)
}
///| Deliver an event to the widget (`popup` = its popup surface, else the panel widget).
/// True when the widget says its visuals changed. A trapping widget yields false.
pub fn Plasmoid::on_event(self : Plasmoid, popup : Bool, ev : PlasmoidEvent) -> Bool {
let target = if popup { 1 } else { 0 }
let r = match ev {
PointerMove(x, y) => c_wasm_call(self.handle, ex_onevent, target, 0, x, y)
PointerDown(x, y) => c_wasm_call(self.handle, ex_onevent, target, 1, x, y)
PointerUp(x, y) => c_wasm_call(self.handle, ex_onevent, target, 2, x, y)
PointerLeave => c_wasm_call(self.handle, ex_onevent, target, 3, 0, 0)
FocusLost => c_wasm_call(self.handle, ex_onevent, target, 4, 0, 0)
KeyDown(k) => {
// The guest owns a UTF-16 copy of the key name.
let b : Array[Byte] = []
let mut units = 0
for ch in k {
let c = ch.to_int()
if c >= 0x10000 {
let v = c - 0x10000
let hi = 0xD800 + (v >> 10)
let lo = 0xDC00 + (v & 0x3FF)
b.push((hi & 0xFF).to_byte())
b.push((hi >> 8).to_byte())
b.push((lo & 0xFF).to_byte())
b.push((lo >> 8).to_byte())
units = units + 2
} else {
b.push((c & 0xFF).to_byte())
b.push((c >> 8).to_byte())
units = units + 1
}
}
let ptr = c_wasm_call(self.handle, ex_realloc, 0, 0, 2, if units * 2 < 4 { 4 } else { units * 2 })
if ptr < 0 {
-1
} else {
ignore(c_wasm_write(self.handle, ptr, Bytes::from_array(b), b.length()))
c_wasm_call(self.handle, ex_onevent, target, 5, ptr, units)
}
}
}
r == 1
}
///| Host interfaces (capabilities) the module's binary imports, e.g. ["theme", "clock"].
pub fn Plasmoid::imports(self : Plasmoid) -> Array[String] {
let buf = Bytes::make(512, b'\x00')
let n = c_wasm_imports(self.handle, buf)
let out : Array[String] = []
let sb = StringBuilder::new()
for i = 0; i < n; i = i + 1 {
if buf[i] == b'\n' {
out.push(sb.to_string())
sb.reset()
} else {
sb.write_char(buf[i].to_int().unsafe_to_char())
}
}
out
}
///| Rows of host data a module can read through its capability imports (apps, windows, ...).
/// Fields are i32 or strings; see `build_list` in wasm_stub.c for the per-table row shapes.
pub(all) struct Table {
rows : Array[Byte]
mut n : Int
}
///|
pub fn Table::new() -> Table {
{ rows: [], n: 0 }
}
///|
fn Table::push32(self : Table, v : Int) -> Unit {
for k = 0; k < 4; k = k + 1 {
self.rows.push(((v >> (8 * k)) & 0xFF).to_byte())
}
}
///| An i32 field.
pub fn Table::int(self : Table, v : Int) -> Unit {
self.push32(v)
}
///| A string field.
pub fn Table::str(self : Table, s : String) -> Unit {
let b = utf8(s)
self.push32(b.length())
for i = 0; i < b.length(); i = i + 1 {
self.rows.push(b[i])
}
}
///| Finish one row.
pub fn Table::end_row(self : Table) -> Unit {
self.n = self.n + 1
}
///|
pub(all) enum HostTable {
Apps
Windows
Layouts
Modules
Instances
}
///| Publish `t` as the data behind `which` for every module's next call.
pub fn publish(which : HostTable, t : Table) -> Unit {
let w = match which {
Apps => 0
Windows => 1
Layouts => 2
Modules => 3
Instances => 4
}
let out : Array[Byte] = []
for k = 0; k < 4; k = k + 1 {
out.push(((t.n >> (8 * k)) & 0xFF).to_byte())
}
for b in t.rows {
out.push(b)
}
c_host_set_table(w, Bytes::from_array(out))
}
///| Publish the current layout mode (0 tiling, 1 monocle, 2 floating) and whether the Interface Explorer is on.
pub fn publish_state(layout_mode : Int, inspector_on : Bool) -> Unit {
c_host_set_int(0, layout_mode)
c_host_set_int(1, if inspector_on { 1 } else { 0 })
}
///| Something a module asked the host to do during a call.
pub(all) enum HostRequest {
Launch(String)
FocusWindow(Int)
SetLayout(Int)
SetInspector(Bool)
LoadModule(String)
UnloadInstance(String)
Browse
} derive(Eq, Debug)
///|
fn req_str() -> String {
let buf = Bytes::make(1024, b'\x00')
let n = c_host_req_str(buf)
from_utf8(buf, n)
}
///| The next pending request, oldest first.
pub fn next_request() -> HostRequest? {
match c_host_req_pop() {
1 => Some(Launch(req_str()))
2 => Some(FocusWindow(c_host_req_int()))
3 => Some(SetLayout(c_host_req_int()))
4 => Some(SetInspector(c_host_req_int() != 0))
5 => Some(LoadModule(req_str()))
6 => Some(UnloadInstance(req_str()))
7 => Some(Browse)
_ => None
}
}
///| Names of the `*.wasm` files directly in `dir`, sorted.
pub fn list_wasm_files(dir : String) -> Array[String] {
let raw = c_list_wasm(utf8(dir))
let out : Array[String] = []
let sb = StringBuilder::new()
for i = 0; i < raw.length(); i = i + 1 {
if raw[i] == b'\n' {
out.push(sb.to_string())
sb.reset()
} else {
sb.write_char(raw[i].to_int().unsafe_to_char())
}
}
out
}
///| An in-flight native file-chooser dialog (zenity on the host session).
pub(all) struct Picker {
fd : Int
buf : Array[Byte]
}
///| Open the file chooser; None when it can't be started.
pub fn Picker::start() -> Picker? {
let fd = c_pick_start()
if fd < 0 {
None
} else {
Some({ fd, buf: [] })
}
}
///| Poll the dialog: None while it is open, Some(None) if cancelled, Some(Some(path)) when chosen.
pub fn Picker::poll(self : Picker) -> String?? {
let chunk = Bytes::make(512, b'\x00')
while true {
let n = c_fd_read(self.fd, chunk)
if n > 0 {
for i = 0; i < n; i = i + 1 {
self.buf.push(chunk[i])
}
} else if n == 0 {
c_fd_close(self.fd)
let bytes = Bytes::from_array(self.buf)
let mut len = bytes.length()
while len > 0 && (bytes[len - 1] == b'\n' || bytes[len - 1] == b'\r') {
len = len - 1
}
return if len == 0 { Some(None) } else { Some(Some(from_utf8(bytes, len))) }
} else {
break
}
}
None
}
+747
View File
@@ -0,0 +1,747 @@
/* Wasm plasmoid host: runs the core module of a moonplasma plasmoid component
* (or a bare core module) with wasmer's C API. Canonical-ABI marshalling stays in
* MoonBit; this file instantiates, provides the host imports (theme, clock) and
* exposes raw calls plus guest-memory reads. */
#include <fcntl.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <dirent.h>
#include <wasm.h>
#include "moonbit.h"
#define MAX_INST 512
enum { EX_INFO, EX_RENDER, EX_ONEVENT, EX_POPUP, EX_POST_INFO, EX_POST_RENDER, EX_POST_POPUP, EX_REALLOC, EX_N };
static const char *ex_names[EX_N] = {
"moonplasma:desktop/plasmoid@0.1.0#info",
"moonplasma:desktop/plasmoid@0.1.0#render",
"moonplasma:desktop/plasmoid@0.1.0#on-event",
"moonplasma:desktop/plasmoid@0.1.0#popup",
"cabi_post_moonplasma:desktop/plasmoid@0.1.0#info",
"cabi_post_moonplasma:desktop/plasmoid@0.1.0#render",
"cabi_post_moonplasma:desktop/plasmoid@0.1.0#popup",
"cabi_realloc",
};
typedef struct Inst {
int used;
wasm_module_t *module;
wasm_instance_t *instance;
wasm_memory_t *memory;
wasm_func_t *ex[EX_N];
uint8_t tokens[64];
int kind_n;
char imports[512]; /* newline-separated host interfaces this module imports (capabilities it uses) */
} Inst;
static wasm_engine_t *engine;
static wasm_store_t *store;
static Inst insts[MAX_INST];
/* Host imports a module can call. */
enum {
K_OTHER, K_TOKENS, K_CLOCK, K_APPS, K_LAUNCH, K_WINDOWS, K_FOCUS, K_LAYOUTS, K_LAYOUT_CUR, K_SET_LAYOUT,
K_INSPECT_IS_ON, K_INSPECT_SET, K_MOD_AVAILABLE, K_MOD_LOADED, K_MOD_LOAD, K_MOD_UNLOAD, K_MOD_BROWSE,
K_SYSTEM_READ, K_WIN_ALL, K_WIN_FOCUS_ID
};
typedef struct Env { Inst *inst; int kind; } Env;
/* ---- host data the shell publishes before calling a guest ----
* A table is [u32 rows] then rows of fields, each field a LE i32 ('i') or a u32 byte length + UTF-8 ('s'). */
enum { T_APPS, T_WINDOWS, T_LAYOUTS, T_MODULES, T_INSTANCES, T_N };
typedef struct { uint8_t *data; size_t len; } Blob;
static Blob tables[T_N];
static int32_t host_ints[4]; /* 0 layout mode, 1 inspector on */
/* ---- requests a guest made of the host (launch, focus, ...) ; drained by the shell after each call ---- */
typedef struct { int kind; int32_t n; char *s; } Req;
#define MAX_REQ 64
static Req reqs[MAX_REQ];
static int req_head, req_tail;
static Req cur_req;
static void push_req(int kind, int32_t n, const char *s) {
if (req_tail - req_head >= MAX_REQ) return;
Req *r = &reqs[req_tail % MAX_REQ];
r->kind = kind;
r->n = n;
r->s = s ? strdup(s) : NULL;
req_tail++;
}
/* Host state a widget may read through its granted interfaces. The compositor refreshes
* these (mp_wasm_set_system / mp_wasm_set_windows) before drawing; widgets never touch
* /proc or the window manager themselves. */
static uint8_t g_system[64]; /* canonical-ABI bytes of system.snapshot */
static uint8_t *g_windows; /* count u32, then per window: id u64, focused u32, tlen u32, title u16[], alen u32, app u16[] */
static size_t g_windows_len;
static int64_t g_focus_req = -1; /* window id a widget asked to raise, until the compositor takes it */
static void mem_write(Inst *in, int32_t off, const void *src, size_t n) {
if (!in->memory || off < 0) return;
byte_t *base = wasm_memory_data(in->memory);
size_t size = wasm_memory_data_size(in->memory);
if ((size_t)off + n > size) return;
memcpy(base + off, src, n);
}
static int mem_read(Inst *in, int32_t off, void *dst, size_t n) {
if (!in->memory || off < 0) return 0;
size_t size = wasm_memory_data_size(in->memory);
if ((size_t)off + n > size) return 0;
memcpy(dst, wasm_memory_data(in->memory) + off, n);
return 1;
}
static void w32(Inst *in, int32_t off, int32_t v) { mem_write(in, off, &v, 4); }
/* Allocate in the guest through its cabi_realloc; -1 on failure. */
static int32_t guest_alloc(Inst *in, int32_t size, int32_t align) {
if (!in->ex[EX_REALLOC]) return -1;
if (size < 4) size = 4; /* the guest frees every lowered buffer, even empty ones */
wasm_val_t av[4] = { WASM_I32_VAL(0), WASM_I32_VAL(0), WASM_I32_VAL(align), WASM_I32_VAL(size) };
wasm_val_t rv[1] = { WASM_INIT_VAL };
wasm_val_vec_t a = { 4, av };
wasm_val_vec_t r = { 1, rv };
wasm_trap_t *tr = wasm_func_call(in->ex[EX_REALLOC], &a, &r);
if (tr) { wasm_trap_delete(tr); return -1; }
return rv[0].of.i32;
}
/* UTF-8 -> UTF-16LE string in guest memory; writes ptr/len (code units) at `at` and `at+4`. */
static void put_str(Inst *in, int32_t at, const uint8_t *u8, size_t n) {
size_t units = 0;
for (size_t i = 0; i < n;) {
uint8_t c = u8[i];
int len = c < 0x80 ? 1 : c < 0xE0 ? 2 : c < 0xF0 ? 3 : 4;
units += len == 4 ? 2 : 1;
i += len;
}
int32_t ptr = guest_alloc(in, (int32_t)(units * 2), 2);
if (ptr < 0) { w32(in, at, 0); w32(in, at + 4, 0); return; }
uint16_t *buf = (uint16_t *)malloc(units * 2 + 2);
size_t k = 0;
for (size_t i = 0; i < n && k < units;) {
uint8_t c = u8[i];
uint32_t cp;
int len;
if (c < 0x80) { cp = c; len = 1; }
else if (c < 0xE0) { cp = c & 0x1F; len = 2; }
else if (c < 0xF0) { cp = c & 0x0F; len = 3; }
else { cp = c & 0x07; len = 4; }
for (int j = 1; j < len && i + j < n; j++) cp = (cp << 6) | (u8[i + j] & 0x3F);
i += len;
if (cp >= 0x10000) {
cp -= 0x10000;
buf[k++] = (uint16_t)(0xD800 + (cp >> 10));
if (k < units) buf[k++] = (uint16_t)(0xDC00 + (cp & 0x3FF));
} else {
buf[k++] = (uint16_t)cp;
}
}
mem_write(in, ptr, buf, units * 2);
free(buf);
w32(in, at, ptr);
w32(in, at + 4, (int32_t)units);
}
/* A guest UTF-16 string -> malloc'd UTF-8 (NUL-terminated). */
static char *guest_str(Inst *in, int32_t ptr, int32_t units) {
if (units < 0 || units > 4096) units = 0;
uint16_t *u = (uint16_t *)malloc((size_t)units * 2 + 2);
if (units > 0 && !mem_read(in, ptr, u, (size_t)units * 2)) units = 0;
char *out = (char *)malloc((size_t)units * 3 + 1);
size_t o = 0;
for (int i = 0; i < units; i++) {
uint32_t cp = u[i];
if (cp >= 0xD800 && cp < 0xDC00 && i + 1 < units) { cp = 0x10000 + ((cp - 0xD800) << 10) + (u[i + 1] - 0xDC00); i++; }
if (cp < 0x80) out[o++] = (char)cp;
else if (cp < 0x800) { out[o++] = (char)(0xC0 | (cp >> 6)); out[o++] = (char)(0x80 | (cp & 0x3F)); }
else if (cp < 0x10000) { out[o++] = (char)(0xE0 | (cp >> 12)); out[o++] = (char)(0x80 | ((cp >> 6) & 0x3F)); out[o++] = (char)(0x80 | (cp & 0x3F)); }
else { out[o++] = (char)(0xF0 | (cp >> 18)); out[o++] = (char)(0x80 | ((cp >> 12) & 0x3F)); out[o++] = (char)(0x80 | ((cp >> 6) & 0x3F)); out[o++] = (char)(0x80 | (cp & 0x3F)); }
}
out[o] = 0;
free(u);
return out;
}
static uint32_t rd_u32(const uint8_t *p) { uint32_t v; memcpy(&v, p, 4); return v; }
/* Lower table `t` (row layout `spec`: 'i' or 's' per field) as a list<record> and write (ptr,len) at `retptr`. */
static void build_list(Inst *in, int t, const char *spec, int32_t retptr) {
Blob *b = &tables[t];
uint32_t n = b->len >= 4 ? rd_u32(b->data) : 0;
size_t esz = 0;
for (const char *c = spec; *c; c++) esz += *c == 's' ? 8 : 4;
int32_t base = guest_alloc(in, (int32_t)(esz * (n ? n : 1)), 4);
if (base < 0) { w32(in, retptr, 0); w32(in, retptr + 4, 0); return; }
size_t pos = 4;
for (uint32_t r = 0; r < n; r++) {
int32_t off = base + (int32_t)(r * esz);
for (const char *c = spec; *c; c++) {
if (*c == 'i') {
if (pos + 4 > b->len) return;
w32(in, off, (int32_t)rd_u32(b->data + pos));
pos += 4;
off += 4;
} else {
if (pos + 4 > b->len) return;
uint32_t sl = rd_u32(b->data + pos);
pos += 4;
if (pos + sl > b->len) return;
put_str(in, off, b->data + pos, sl);
pos += sl;
off += 8;
}
}
}
w32(in, retptr, base);
w32(in, retptr + 4, (int32_t)n);
}
/* Does table `t` (first field a string) contain a row whose first string equals `id`? */
static int table_has_id(int t, const char *spec, const char *id) {
Blob *b = &tables[t];
uint32_t n = b->len >= 4 ? rd_u32(b->data) : 0;
size_t pos = 4;
size_t idl = strlen(id);
for (uint32_t r = 0; r < n; r++) {
for (const char *c = spec; *c; c++) {
if (pos + 4 > b->len) return 0;
if (*c == 'i') { pos += 4; continue; }
uint32_t sl = rd_u32(b->data + pos);
pos += 4;
if (pos + sl > b->len) return 0;
if (c == spec && sl == idl && memcmp(b->data + pos, id, sl) == 0) return 1;
pos += sl;
}
}
return 0;
}
static wasm_trap_t *host_import(void *env, const wasm_val_vec_t *args, wasm_val_vec_t *results) {
Env *e = (Env *)env;
Inst *in = e->inst;
int32_t a0 = args->size >= 1 ? args->data[0].of.i32 : 0;
int32_t a1 = args->size >= 2 ? args->data[1].of.i32 : 0;
int32_t a2 = args->size >= 3 ? args->data[2].of.i32 : 0;
switch (e->kind) {
case K_TOKENS:
if (args->size >= 1) {
uint8_t buf[64];
memcpy(buf, in->tokens, 64);
/* name: the guest lifts it as one of its own allocations, so give it a real (empty) one */
memset(buf, 0, 8);
int32_t p = guest_alloc(in, 0, 2);
if (p >= 0) memcpy(buf, &p, 4);
mem_write(in, a0, buf, 64);
}
break;
case K_CLOCK:
if (args->size >= 1) {
time_t t = time(NULL);
struct tm tmv;
localtime_r(&t, &tmv);
uint8_t buf[12];
memset(buf, 0, sizeof(buf));
int32_t year = tmv.tm_year + 1900;
memcpy(buf, &year, 4);
buf[4] = (uint8_t)(tmv.tm_mon + 1);
buf[5] = (uint8_t)tmv.tm_mday;
buf[6] = (uint8_t)tmv.tm_hour;
buf[7] = (uint8_t)tmv.tm_min;
buf[8] = (uint8_t)tmv.tm_sec;
buf[9] = (uint8_t)tmv.tm_wday;
mem_write(in, a0, buf, 12);
}
break;
case K_APPS: build_list(in, T_APPS, "sssss", a0); break; /* id name comment category glyph */
case K_WINDOWS: build_list(in, T_WINDOWS, "isii", a0); break;
case K_LAYOUTS: build_list(in, T_LAYOUTS, "s", a0); break;
case K_MOD_AVAILABLE: build_list(in, T_MODULES, "sssi", a0); break;
case K_MOD_LOADED: build_list(in, T_INSTANCES, "sss", a0); break;
case K_LAYOUT_CUR:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[0]);
break;
case K_INSPECT_IS_ON:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[1]);
break;
case K_SET_LAYOUT: push_req(3, a0, NULL); break;
case K_FOCUS: push_req(2, a0, NULL); break;
case K_INSPECT_SET: push_req(4, a0, NULL); break;
case K_MOD_BROWSE: push_req(7, 0, NULL); break;
case K_MOD_LOAD: { char *s = guest_str(in, a0, a1); push_req(5, 0, s); free(s); break; }
case K_MOD_UNLOAD: { char *s = guest_str(in, a0, a1); push_req(6, 0, s); free(s); break; }
case K_LAUNCH: {
/* launch(id) -> result<_, string>; (ptr, len, retptr). Known catalog ids succeed; the shell spawns after the call. */
char *id = guest_str(in, a0, a1);
if (table_has_id(T_APPS, "sssss", id)) {
push_req(1, 0, id);
w32(in, a2, 0);
} else {
w32(in, a2, 1);
const char *msg = "unknown application";
put_str(in, a2 + 4, (const uint8_t *)msg, strlen(msg));
}
free(id);
break;
}
case K_SYSTEM_READ:
if (args->size >= 1) mem_write(in, a0, g_system, 64);
break;
case K_WIN_ALL: {
int32_t ret = a0;
uint32_t count = 0;
if (g_windows && g_windows_len >= 4) memcpy(&count, g_windows, 4);
if (count > 64) count = 64;
/* always a real allocation, even for an empty list: the guest frees it after lifting */
int32_t arr = guest_alloc(in, (int32_t)((count ? count : 1) * 32), 8);
size_t pos = 4;
uint32_t written = 0;
for (uint32_t i = 0; arr >= 0 && i < count; i++) {
uint64_t id; uint32_t focused, tlen, alen;
if (pos + 16 > g_windows_len) break;
memcpy(&id, g_windows + pos, 8); memcpy(&focused, g_windows + pos + 8, 4); memcpy(&tlen, g_windows + pos + 12, 4);
pos += 16;
if (tlen > 512 || pos + tlen * 2 + 4 > g_windows_len) break;
const uint8_t *title = g_windows + pos;
pos += tlen * 2;
memcpy(&alen, g_windows + pos, 4);
pos += 4;
if (alen > 512 || pos + alen * 2 > g_windows_len) break;
const uint8_t *app = g_windows + pos;
pos += alen * 2;
int32_t tp = tlen ? guest_alloc(in, (int32_t)(tlen * 2), 2) : 0;
int32_t ap = alen ? guest_alloc(in, (int32_t)(alen * 2), 2) : 0;
if (tlen && tp > 0) mem_write(in, tp, title, tlen * 2);
if (alen && ap > 0) mem_write(in, ap, app, alen * 2);
uint8_t rec[32];
memset(rec, 0, sizeof(rec));
int32_t tl = tp > 0 ? (int32_t)tlen : 0, al = ap > 0 ? (int32_t)alen : 0;
if (tp < 0) tp = 0;
if (ap < 0) ap = 0;
memcpy(rec, &id, 8); memcpy(rec + 8, &tp, 4); memcpy(rec + 12, &tl, 4);
memcpy(rec + 16, &ap, 4); memcpy(rec + 20, &al, 4); rec[24] = focused ? 1 : 0;
mem_write(in, arr + (int32_t)(i * 32), rec, 32);
written++;
}
int32_t out[2] = { arr >= 0 ? arr : 0, arr >= 0 ? (int32_t)written : 0 };
mem_write(in, ret, out, 8);
break;
}
case K_WIN_FOCUS_ID:
if (args->size >= 1) g_focus_req = args->data[0].of.i64;
break;
default: break;
}
return NULL;
}
static int leb(const uint8_t *p, size_t n, size_t *pos, uint32_t *out) {
uint32_t v = 0; int shift = 0;
while (*pos < n) {
uint8_t b = p[(*pos)++];
v |= (uint32_t)(b & 0x7f) << shift;
if (!(b & 0x80)) { *out = v; return 1; }
shift += 7;
if (shift > 28) return 0;
}
return 0;
}
static int try_instantiate(Inst *in, const uint8_t *bytes, size_t len);
/* Components wrap their core modules in type-1 sections; try each until one yields a plasmoid. */
static int load_bytes(Inst *in, const uint8_t *d, size_t n) {
if (n < 8 || memcmp(d, "\0asm", 4) != 0) return -1;
if (d[4] == 1) return try_instantiate(in, d, n) ? 0 : -3;
size_t pos = 8;
while (pos < n) {
uint8_t id = d[pos++];
uint32_t size;
if (!leb(d, n, &pos, &size) || pos + size > n) return -1;
if (id == 1 && size >= 8 && memcmp(d + pos, "\0asm", 4) == 0) {
if (try_instantiate(in, d + pos, size)) return 0;
}
pos += size;
}
return -4;
}
/* "moonplasma:desktop/<iface>@<ver>" -> <iface> (copied, NUL-terminated); "" for anything else. */
static void iface_of(const wasm_name_t *m, char *out, size_t cap) {
const char *pre = "moonplasma:desktop/";
size_t pl = strlen(pre);
out[0] = 0;
if (m->size <= pl || memcmp(m->data, pre, pl) != 0) return;
size_t n = 0;
while (pl + n < m->size && m->data[pl + n] != '@' && n + 1 < cap) { out[n] = m->data[pl + n]; n++; }
out[n] = 0;
}
static int classify_import(const wasm_name_t *m, const wasm_name_t *f) {
char iface[64], fn[64];
iface_of(m, iface, sizeof(iface));
size_t fl = f->size < sizeof(fn) - 1 ? f->size : sizeof(fn) - 1;
memcpy(fn, f->data, fl);
fn[fl] = 0;
if (!strcmp(iface, "theme") && !strcmp(fn, "get-tokens")) return K_TOKENS;
if (!strcmp(iface, "clock") && !strcmp(fn, "now")) return K_CLOCK;
if (!strcmp(iface, "app-catalog") && !strcmp(fn, "list-apps")) return K_APPS;
if (!strcmp(iface, "app-launch") && !strcmp(fn, "launch")) return K_LAUNCH;
if (!strcmp(iface, "windows") && !strcmp(fn, "list-windows")) return K_WINDOWS;
if (!strcmp(iface, "windows") && !strcmp(fn, "focus-window")) return K_FOCUS;
if (!strcmp(iface, "windows") && !strcmp(fn, "all")) return K_WIN_ALL;
if (!strcmp(iface, "windows") && !strcmp(fn, "focus")) return K_WIN_FOCUS_ID;
if (!strcmp(iface, "system") && !strcmp(fn, "read")) return K_SYSTEM_READ;
if (!strcmp(iface, "layout-control") && !strcmp(fn, "layout-modes")) return K_LAYOUTS;
if (!strcmp(iface, "layout-control") && !strcmp(fn, "current-layout")) return K_LAYOUT_CUR;
if (!strcmp(iface, "layout-control") && !strcmp(fn, "set-layout")) return K_SET_LAYOUT;
if (!strcmp(iface, "inspector") && !strcmp(fn, "is-on")) return K_INSPECT_IS_ON;
if (!strcmp(iface, "inspector") && !strcmp(fn, "set-on")) return K_INSPECT_SET;
if (!strcmp(iface, "modules") && !strcmp(fn, "available")) return K_MOD_AVAILABLE;
if (!strcmp(iface, "modules") && !strcmp(fn, "loaded")) return K_MOD_LOADED;
if (!strcmp(iface, "modules") && !strcmp(fn, "load-module")) return K_MOD_LOAD;
if (!strcmp(iface, "modules") && !strcmp(fn, "unload-instance")) return K_MOD_UNLOAD;
if (!strcmp(iface, "modules") && !strcmp(fn, "browse")) return K_MOD_BROWSE;
return K_OTHER;
}
/* Remember which host interfaces a module imports (its capabilities). */
static void note_import(Inst *in, const wasm_name_t *m) {
char iface[64];
iface_of(m, iface, sizeof(iface));
if (!iface[0] || !strcmp(iface, "types")) return;
size_t have = strlen(in->imports);
/* already listed? */
for (const char *p = in->imports; *p;) {
const char *nl = strchr(p, '\n');
size_t l = nl ? (size_t)(nl - p) : strlen(p);
if (l == strlen(iface) && !memcmp(p, iface, l)) return;
p += l + (nl ? 1 : 0);
}
if (have + strlen(iface) + 2 < sizeof(in->imports)) {
memcpy(in->imports + have, iface, strlen(iface));
in->imports[have + strlen(iface)] = '\n';
in->imports[have + strlen(iface) + 1] = 0;
}
}
static int try_instantiate(Inst *in, const uint8_t *bytes, size_t len) {
wasm_byte_vec_t bin;
wasm_byte_vec_new(&bin, len, (const wasm_byte_t *)bytes);
wasm_module_t *mod = wasm_module_new(store, &bin);
wasm_byte_vec_delete(&bin);
if (!mod) return 0;
wasm_exporttype_vec_t ets;
wasm_module_exports(mod, &ets);
int has_render = 0;
for (size_t i = 0; i < ets.size; i++) {
const wasm_name_t *nm = wasm_exporttype_name(ets.data[i]);
if (nm->size == strlen(ex_names[EX_RENDER]) && memcmp(nm->data, ex_names[EX_RENDER], nm->size) == 0) has_render = 1;
}
if (!has_render) { wasm_exporttype_vec_delete(&ets); wasm_module_delete(mod); return 0; }
wasm_importtype_vec_t its;
wasm_module_imports(mod, &its);
wasm_extern_vec_t imports;
wasm_extern_vec_new_uninitialized(&imports, its.size);
for (size_t i = 0; i < its.size; i++) {
const wasm_name_t *m = wasm_importtype_module(its.data[i]);
const wasm_name_t *f = wasm_importtype_name(its.data[i]);
const wasm_externtype_t *et = wasm_importtype_type(its.data[i]);
Env *env = (Env *)calloc(1, sizeof(Env));
env->inst = in;
env->kind = classify_import(m, f);
note_import(in, m);
if (wasm_externtype_kind(et) == WASM_EXTERN_FUNC) {
wasm_func_t *fn = wasm_func_new_with_env(store, wasm_externtype_as_functype_const(et), host_import, env, NULL);
imports.data[i] = wasm_func_as_extern(fn);
} else {
/* tables/memories/globals are not expected from plasmoids */
wasm_extern_vec_delete(&imports);
wasm_importtype_vec_delete(&its);
wasm_exporttype_vec_delete(&ets);
wasm_module_delete(mod);
return 0;
}
}
wasm_trap_t *trap = NULL;
wasm_instance_t *inst = wasm_instance_new(store, mod, &imports, &trap);
wasm_extern_vec_delete(&imports);
wasm_importtype_vec_delete(&its);
if (!inst) {
if (trap) wasm_trap_delete(trap);
wasm_exporttype_vec_delete(&ets);
wasm_module_delete(mod);
return 0;
}
wasm_extern_vec_t exps;
wasm_instance_exports(inst, &exps);
for (size_t i = 0; i < ets.size && i < exps.size; i++) {
const wasm_name_t *nm = wasm_exporttype_name(ets.data[i]);
wasm_extern_t *x = exps.data[i];
if (wasm_extern_kind(x) == WASM_EXTERN_MEMORY && nm->size == 6 && memcmp(nm->data, "memory", 6) == 0) {
in->memory = wasm_extern_as_memory(x);
} else if (wasm_extern_kind(x) == WASM_EXTERN_FUNC) {
for (int k = 0; k < EX_N; k++) {
if (nm->size == strlen(ex_names[k]) && memcmp(nm->data, ex_names[k], nm->size) == 0) in->ex[k] = wasm_extern_as_func(x);
}
}
}
wasm_exporttype_vec_delete(&ets);
in->module = mod;
in->instance = inst;
return in->memory && in->ex[EX_INFO] && in->ex[EX_RENDER];
}
/* Load a plasmoid from `path`; returns a handle >= 0 or a negative error. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_load(moonbit_bytes_t path_bytes, moonbit_bytes_t tokens) {
char path[1024];
int32_t plen = Moonbit_array_length(path_bytes);
size_t pn = (size_t)plen < sizeof(path) - 1 ? (size_t)plen : sizeof(path) - 1;
memcpy(path, path_bytes, pn);
path[pn] = '\0';
if (!engine) {
engine = wasm_engine_new();
store = wasm_store_new(engine);
if (!store) return -10;
}
int h = -1;
for (int i = 0; i < MAX_INST; i++) if (!insts[i].used) { h = i; break; }
if (h < 0) return -11;
FILE *f = fopen(path, "rb");
if (!f) return -2;
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
if (sz <= 8) { fclose(f); return -1; }
uint8_t *buf = (uint8_t *)malloc((size_t)sz);
if (!buf || fread(buf, 1, (size_t)sz, f) != (size_t)sz) { fclose(f); free(buf); return -2; }
fclose(f);
Inst *in = &insts[h];
memset(in, 0, sizeof(*in));
int32_t tn = Moonbit_array_length(tokens);
memcpy(in->tokens, tokens, tn < 64 ? (size_t)tn : 64);
int rc = load_bytes(in, buf, (size_t)sz);
free(buf);
if (rc != 0) { memset(in, 0, sizeof(*in)); return rc; }
in->used = 1;
return h;
}
MOONBIT_FFI_EXPORT
void mp_wasm_set_tokens(int32_t h, moonbit_bytes_t tokens) {
if (h < 0 || h >= MAX_INST || !insts[h].used) return;
int32_t tn = Moonbit_array_length(tokens);
memcpy(insts[h].tokens, tokens, tn < 64 ? (size_t)tn : 64);
}
MOONBIT_FFI_EXPORT
void mp_wasm_unload(int32_t h) {
if (h < 0 || h >= MAX_INST || !insts[h].used) return;
if (insts[h].instance) wasm_instance_delete(insts[h].instance);
if (insts[h].module) wasm_module_delete(insts[h].module);
memset(&insts[h], 0, sizeof(Inst));
}
/* Call export `which` (EX_*) with up to 4 i32 args; returns the i32 result (0 for none), -1 on trap/missing. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_call(int32_t h, int32_t which, int32_t a0, int32_t a1, int32_t a2, int32_t a3) {
if (h < 0 || h >= MAX_INST || !insts[h].used || which < 0 || which >= EX_N) return -1;
wasm_func_t *fn = insts[h].ex[which];
if (!fn) return -1;
size_t np = wasm_func_param_arity(fn);
size_t nr = wasm_func_result_arity(fn);
wasm_val_t av[4] = { WASM_I32_VAL(a0), WASM_I32_VAL(a1), WASM_I32_VAL(a2), WASM_I32_VAL(a3) };
wasm_val_t rv[1] = { WASM_INIT_VAL };
wasm_val_vec_t args = { np > 4 ? 4 : np, av };
wasm_val_vec_t res = { nr > 1 ? 1 : nr, rv };
wasm_trap_t *trap = wasm_func_call(fn, &args, &res);
if (trap) {
if (getenv("MP_WASM_DEBUG")) { wasm_message_t m; wasm_trap_message(trap, &m); fprintf(stderr, "wasm trap: %.*s\n", (int)m.size, m.data); wasm_byte_vec_delete(&m); }
wasm_trap_delete(trap);
return -1;
}
return nr > 0 ? rv[0].of.i32 : 0;
}
/* Copy `len` bytes of guest memory at `off` into `out`. Returns 0 on success. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_read(int32_t h, int32_t off, int32_t len, moonbit_bytes_t out) {
if (h < 0 || h >= MAX_INST || !insts[h].used || off < 0 || len < 0) return -1;
size_t size = wasm_memory_data_size(insts[h].memory);
if ((size_t)off + (size_t)len > size || len > Moonbit_array_length(out)) return -1;
memcpy(out, wasm_memory_data(insts[h].memory) + off, (size_t)len);
return 0;
}
/* ---- native file picker: zenity on the host session, output read through a pipe ---- */
MOONBIT_FFI_EXPORT
int32_t mp_pick_start(void) {
int fds[2];
if (pipe(fds) != 0) return -1;
signal(SIGCHLD, SIG_IGN);
pid_t pid = fork();
if (pid < 0) { close(fds[0]); close(fds[1]); return -1; }
if (pid == 0) {
setsid();
dup2(fds[1], 1);
close(fds[0]);
close(fds[1]);
int dn = open("/dev/null", O_WRONLY);
if (dn >= 0) dup2(dn, 2);
execlp("zenity", "zenity", "--file-selection", "--title=Load widget (.wasm)",
"--file-filter=WebAssembly widgets | *.wasm", "--file-filter=All files | *", (char *)NULL);
_exit(127);
}
close(fds[1]);
fcntl(fds[0], F_SETFL, fcntl(fds[0], F_GETFL, 0) | O_NONBLOCK);
return fds[0];
}
/* Read from a pipe: bytes read, 0 at EOF, -1 when nothing is available yet. */
MOONBIT_FFI_EXPORT
int32_t mp_fd_read(int32_t fd, moonbit_bytes_t out) {
ssize_t n = read(fd, out, (size_t)Moonbit_array_length(out));
if (n < 0) return -1;
return (int32_t)n;
}
MOONBIT_FFI_EXPORT
void mp_fd_close(int32_t fd) { close(fd); }
/* ---- host state a widget can read, and the one action it can ask for ---- */
/* Replace the 64-byte system.snapshot the guest's system.read returns. */
MOONBIT_FFI_EXPORT
void mp_wasm_set_system(moonbit_bytes_t b) {
int32_t n = Moonbit_array_length(b);
memset(g_system, 0, sizeof(g_system));
memcpy(g_system, b, n < 64 ? (size_t)n : 64);
}
/* Replace the window list blob (see g_windows) served by windows.all. */
MOONBIT_FFI_EXPORT
void mp_wasm_set_windows(moonbit_bytes_t b) {
int32_t n = Moonbit_array_length(b);
free(g_windows);
g_windows = (uint8_t *)malloc(n > 0 ? (size_t)n : 1);
g_windows_len = g_windows ? (size_t)n : 0;
if (g_windows) memcpy(g_windows, b, (size_t)n);
}
/* Window id a widget asked to focus since the last call, or -1. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_take_focus(void) {
int64_t id = g_focus_req;
g_focus_req = -1;
return id < 0 || id > 0x7fffffff ? -1 : (int32_t)id;
}
/* ---- host data + requests (see the tables/Req definitions above) ---- */
MOONBIT_FFI_EXPORT
void mp_host_set_table(int32_t which, moonbit_bytes_t data) {
if (which < 0 || which >= T_N) return;
int32_t n = Moonbit_array_length(data);
free(tables[which].data);
tables[which].data = (uint8_t *)malloc((size_t)n + 1);
memcpy(tables[which].data, data, (size_t)n);
tables[which].len = (size_t)n;
}
MOONBIT_FFI_EXPORT
void mp_host_set_int(int32_t which, int32_t v) {
if (which >= 0 && which < 4) host_ints[which] = v;
}
/* Pop the next guest request: returns its kind (0 = none). Fetch its arguments with req_int / req_str. */
MOONBIT_FFI_EXPORT
int32_t mp_host_req_pop(void) {
free(cur_req.s);
memset(&cur_req, 0, sizeof(cur_req));
if (req_head >= req_tail) return 0;
cur_req = reqs[req_head % MAX_REQ];
req_head++;
return cur_req.kind;
}
MOONBIT_FFI_EXPORT
int32_t mp_host_req_int(void) { return cur_req.n; }
MOONBIT_FFI_EXPORT
int32_t mp_host_req_str(moonbit_bytes_t out) {
if (!cur_req.s) return 0;
int32_t cap = Moonbit_array_length(out);
int32_t n = (int32_t)strlen(cur_req.s);
if (n > cap) n = cap;
memcpy(out, cur_req.s, (size_t)n);
return n;
}
/* Write `len` bytes into guest memory at `off`. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_write(int32_t h, int32_t off, moonbit_bytes_t src, int32_t len) {
if (h < 0 || h >= MAX_INST || !insts[h].used || off < 0 || len < 0 || len > Moonbit_array_length(src)) return -1;
size_t size = wasm_memory_data_size(insts[h].memory);
if ((size_t)off + (size_t)len > size) return -1;
memcpy(wasm_memory_data(insts[h].memory) + off, src, (size_t)len);
return 0;
}
/* Newline-separated host interfaces the module imports; returns the byte count copied into `out`. */
MOONBIT_FFI_EXPORT
int32_t mp_wasm_imports(int32_t h, moonbit_bytes_t out) {
if (h < 0 || h >= MAX_INST || !insts[h].used) return 0;
int32_t n = (int32_t)strlen(insts[h].imports);
int32_t cap = Moonbit_array_length(out);
if (n > cap) n = cap;
memcpy(out, insts[h].imports, (size_t)n);
return n;
}
/* Names of "*.wasm" files in `dir`, newline-separated, sorted. */
static int cmp_str(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
MOONBIT_FFI_EXPORT
moonbit_bytes_t mp_list_wasm(moonbit_bytes_t dir_bytes) {
char dir[1024];
int32_t dl = Moonbit_array_length(dir_bytes);
size_t dn = (size_t)dl < sizeof(dir) - 1 ? (size_t)dl : sizeof(dir) - 1;
memcpy(dir, dir_bytes, dn);
dir[dn] = 0;
DIR *d = opendir(dir);
if (!d) return moonbit_make_bytes_raw(0);
char **names = NULL;
size_t count = 0, cap = 0;
struct dirent *e;
while ((e = readdir(d)) != NULL) {
size_t n = strlen(e->d_name);
if (n < 6 || strcmp(e->d_name + n - 5, ".wasm") != 0) continue;
if (count == cap) { cap = cap ? cap * 2 : 16; names = (char **)realloc(names, cap * sizeof(char *)); }
names[count++] = strdup(e->d_name);
}
closedir(d);
if (count > 1) qsort(names, count, sizeof(char *), cmp_str);
size_t len = 0;
for (size_t i = 0; i < count; i++) len += strlen(names[i]) + 1;
moonbit_bytes_t out = moonbit_make_bytes_raw((int32_t)len);
size_t o = 0;
for (size_t i = 0; i < count; i++) {
size_t n = strlen(names[i]);
memcpy((char *)out + o, names[i], n);
o += n;
((char *)out)[o++] = '\n';
free(names[i]);
}
free(names);
return out;
}
+227
View File
@@ -0,0 +1,227 @@
///|
fn test_tokens() -> @theme.Tokens {
let c = fn(r : Int, g : Int, b : Int) -> @types.Color { { r: r.to_byte(), g: g.to_byte(), b: b.to_byte(), a: b'\xff' } }
{
name: "t",
palette: {
desktop_top: c(1, 2, 3),
desktop_bottom: c(4, 5, 6),
surface: c(30, 30, 40),
surface_hover: c(50, 50, 60),
surface_popup: c(20, 20, 30),
foreground: c(250, 250, 250),
foreground_muted: c(150, 150, 150),
accent: c(80, 120, 255),
accent_foreground: c(255, 255, 255),
border: c(90, 90, 90),
},
font_size: 14U,
radius: 6U,
spacing: 6U,
panel_height: 40U,
}
}
///|
fn load_fixture(name : String) -> Result[Plasmoid, String] {
match load("compositor/wasm/testdata/" + name, test_tokens()) {
Ok(p) => Ok(p)
Err(_) => load("testdata/" + name, test_tokens())
}
}
///|
test "a plasmoid component loads and renders through wasmer" {
let p = load_fixture("clock-digital.component.wasm").unwrap()
assert_eq(p.id, "org.moonplasma.clock.digital")
assert_true(p.pref_w > 0 && p.pref_h > 0)
let ops = p.render(p.pref_w, p.pref_h, test_tokens())
assert_true(ops.length() > 0)
// The digital clock draws its time as text, in the theme's foreground colour.
let mut texts = 0
for op in ops {
match op {
Text(t) => {
texts = texts + 1
assert_true(t.text.length() >= 4)
assert_true(t.style.color.r == b'\xfa' || t.style.color.r == b'\x96') // theme foreground / muted
}
_ => ()
}
}
assert_true(texts >= 1)
p.unload()
}
///|
test "a bare core module loads too, and junk is rejected" {
let p = load_fixture("clock-digital.core.wasm").unwrap()
assert_eq(p.id, "org.moonplasma.clock.digital")
p.unload()
assert_true(load("/nonexistent.wasm", test_tokens()) is Err(_))
}
///| Load a panel module built by scripts/build-modules.sh.
fn load_module(name : String) -> Plasmoid {
match load("build/components/" + name + ".wasm", test_tokens()) {
Ok(p) => p
Err(_) => load("../../build/components/" + name + ".wasm", test_tokens()).unwrap()
}
}
///|
fn texts_of(ops : Array[@types.DrawOp]) -> Array[String] {
let out : Array[String] = []
for op in ops {
match op {
Text(t) => out.push(t.text)
_ => ()
}
}
out
}
///|
fn drain() -> Array[HostRequest] {
let out : Array[HostRequest] = []
while true {
match next_request() {
Some(r) => out.push(r)
None => break
}
}
out
}
///|
test "task list module draws the host's windows and asks to focus one" {
let p = load_module("tasks")
assert_true(p.stretch)
assert_true(p.imports().contains("windows") && p.imports().contains("theme"))
let t = Table::new()
t.int(7)
t.str("Kate — notes")
t.int(1)
t.int(0)
t.end_row()
t.int(9)
t.str("foot")
t.int(0)
t.int(1)
t.end_row()
publish(Windows, t)
let ops = p.render(400, 36, test_tokens())
assert_eq(texts_of(ops), ["Kate — notes", "foot"])
assert_true(p.on_event(false, PointerDown(146 + 10, 10)) || true)
assert_eq(drain(), [FocusWindow(9)])
p.unload()
}
///|
test "layout module shows the current mode, opens a popup and sets the layout" {
let p = load_module("layout")
let t = Table::new()
for name in ["Tiling (BSP)", "Monocle", "Floating"] {
t.str(name)
t.end_row()
}
publish(Layouts, t)
publish_state(1, false)
assert_true(texts_of(p.render(130, 36, test_tokens())).contains("Monocle"))
assert_true(p.popup() is None)
assert_true(p.on_event(false, PointerDown(5, 5)))
match p.popup() {
None => fail("popup should be open")
Some(ps) => {
assert_true(ps.w > 100 && ps.h > 80)
assert_true(texts_of(ps.ops).contains(" Floating"))
}
}
assert_true(p.on_event(true, PointerDown(20, 4 + 28 * 2 + 3)))
assert_eq(drain(), [SetLayout(2)])
assert_true(p.popup() is None)
p.unload()
}
///|
test "launcher module reads the host catalog, filters on typed keys and launches" {
let p = load_module("launcher")
let t = Table::new()
for a in [("a.term", "Terminal"), ("b.files", "Files")] {
t.str(a.0)
t.str(a.1)
t.str("comment")
t.str("System")
t.str("T")
t.end_row()
}
publish(Apps, t)
assert_true(p.on_event(false, PointerDown(1, 1)))
assert_true(p.popup() is Some(_))
for k in ["f", "i", "l", "e", "s"] {
ignore(p.on_event(true, KeyDown(k)))
}
match p.popup() {
Some(ps) => assert_true(texts_of(ps.ops).contains("Files"))
None => fail("popup closed early")
}
assert_true(p.on_event(true, KeyDown("Enter")))
assert_eq(drain(), [Launch("b.files")])
assert_true(p.popup() is None)
p.unload()
}
///|
test "module manager lists host modules and asks to load, unload and browse" {
let p = load_module("module-manager")
assert_true(p.imports().contains("modules"))
let av = Table::new()
av.str("moon-disc")
av.str("Moon Phase (disc)")
av.str("/m/moon-disc.wasm")
av.int(0)
av.end_row()
publish(Modules, av)
let li = Table::new()
li.str("w1")
li.str("clock-digital")
li.str("Digital Clock")
li.end_row()
publish(Instances, li)
assert_true(p.on_event(false, PointerDown(1, 1)))
match p.popup() {
None => fail("popup should be open")
Some(ps) => {
let ts = texts_of(ps.ops)
assert_true(ts.contains("Digital Clock"))
assert_true(ts.contains("Moon Phase (disc)"))
}
}
// rows: header(24) loaded(28) header(24) available(28) browse(28)
ignore(p.on_event(true, PointerDown(20, 4 + 24 + 3)))
ignore(p.on_event(true, PointerDown(20, 4 + 24 + 28 + 24 + 3)))
ignore(p.on_event(true, PointerDown(20, 4 + 24 + 28 + 24 + 28 + 3)))
assert_eq(drain(), [UnloadInstance("w1"), LoadModule("/m/moon-disc.wasm"), Browse])
p.unload()
}
///|
test "interface explorer module toggles through the inspector capability" {
let p = load_module("inspector")
assert_true(p.imports().contains("inspector"))
publish_state(0, false)
assert_true(p.on_event(false, PointerDown(3, 3)))
assert_eq(drain(), [SetInspector(true)])
p.unload()
}
///|
test "moon and 12-hour clock modules render from the clock capability" {
let m = load_module("moon-disc")
assert_true(m.render(36, 36, test_tokens()).length() > 3)
m.unload()
let c = load_module("clock-digital12")
let ts = texts_of(c.render(120, 36, test_tokens()))
assert_true(ts[0].has_suffix("AM") || ts[0].has_suffix("PM"))
c.unload()
}
+29 -9
View File
@@ -26,6 +26,10 @@ tcc-build:
make -j"$(nproc)" >/dev/null make -j"$(nproc)" >/dev/null
make install >/dev/null make install >/dev/null
# Build the panel's wasm modules (application menu, task list, clock, ...) into build/components.
modules:
scripts/build-modules.sh
# Debug build of the native compositor, compiled and linked with the vendored tcc. # Debug build of the native compositor, compiled and linked with the vendored tcc.
build: tcc-build build: tcc-build
MOON_CC={{tcc}} MOON_STUB_CC={{tcc}} moon build --target native --warn-list -a compositor/bin MOON_CC={{tcc}} MOON_STUB_CC={{tcc}} moon build --target native --warn-list -a compositor/bin
@@ -35,22 +39,38 @@ build-release:
moon build --target native --release --warn-list -a compositor/bin moon build --target native --release --warn-list -a compositor/bin
# Run the compositor in a window on your current Wayland session (close the window or Ctrl-C to stop). Connect clients via `just client`. # Run the compositor in a window on your current Wayland session (close the window or Ctrl-C to stop). Connect clients via `just client`.
run: build run: build modules
rm -f {{socket}} rm -f {{socket}}
{{exe}} --window --socket {{socket}} --theme {{theme}} {{exe}} --window --socket {{socket}} --theme {{theme}}
# Rebuild the Desktop Pulse plasmoid (wasm component) into compositor/wasm/testdata.
build-pulse:
moon build --target wasm --release
wasm-tools component embed wit _build/wasm/release/build/components/pulse/gen/gen.wasm --world pulse-widget --encoding utf16 -o _build/pulse.embed.wasm
wasm-tools component new _build/pulse.embed.wasm -o compositor/wasm/testdata/pulse.component.wasm
wasm-tools component targets --world pulse-widget wit compositor/wasm/testdata/pulse.component.wasm
# Run the compositor in a window with the Desktop Pulse widget loaded (live system + window integration).
run-pulse: build
rm -f {{socket}}
{{exe}} --window --socket {{socket}} --theme {{theme}} --widget compositor/wasm/testdata/pulse.component.wasm
# One frame of the desktop with Desktop Pulse loaded, to _build/pulse.png.
view-pulse: build
{{exe}} --socket {{socket}}-snap --theme {{theme}} --widget compositor/wasm/testdata/pulse.component.wasm --gfx-out _build/pulse.png
# Run the compositor with no window (clients only; no output). # Run the compositor with no window (clients only; no output).
run-headless: build run-headless: build modules
rm -f {{socket}} rm -f {{socket}}
{{exe}} --socket {{socket}} --theme {{theme}} {{exe}} --socket {{socket}} --theme {{theme}}
# Run the compositor on the real display (DRM/KMS + libinput). Run from a login VT (Ctrl+Alt+F3), not inside another session. Ctrl+Alt+Backspace quits, Ctrl+Alt+F<n> switches VT. # Run the compositor on the real display (DRM/KMS + libinput). Run from a login VT (Ctrl+Alt+F3), not inside another session. Ctrl+Alt+Backspace quits, Ctrl+Alt+F<n> switches VT.
run-drm: build-release run-drm: build-release modules
rm -f {{socket}} rm -f {{socket}}
{{release_exe}} --drm --socket {{socket}} --theme {{theme}} {{release_exe}} --drm --socket {{socket}} --theme {{theme}}
# Install the Moon Plasma login session (display-manager entry); asks for root once. # Install the Moon Plasma login session (display-manager entry); asks for root once.
install-session: build-release install-session: build-release modules
run0 python3 session/install.py run0 python3 session/install.py
# Remove the login session again. # Remove the login session again.
@@ -62,12 +82,12 @@ client *cmd="foot":
WAYLAND_DISPLAY={{socket}} {{cmd}} WAYLAND_DISPLAY={{socket}} {{cmd}}
# Compositor + wasm component + lib tests. # Compositor + wasm component + lib tests.
test: test: modules
moon test --target native --warn-list -a compositor/renderer compositor/host XDG_CONFIG_HOME="$(mktemp -d)" MOON_PLASMA_TEST_CONFIG=1 moon test --target native --warn-list -a compositor/renderer compositor/wasm compositor/host
moon test --target wasm --warn-list -a lib/shell lib/panel lib/clock lib/launcher lib/wm moon test --target wasm --warn-list -a lib/shell lib/panel lib/clock lib/launcher lib/wm lib/taskbar lib/layoutpick lib/modmgr
# Render one composed frame to _build/e2e_frame.png (via the e2e test). # Render one composed frame to _build/e2e_frame.png (via the e2e test).
frame: frame: modules
moon test --target native --warn-list -a compositor/host moon test --target native --warn-list -a compositor/host
@echo "wrote _build/e2e_frame.png" @echo "wrote _build/e2e_frame.png"
@@ -76,6 +96,6 @@ ci:
scripts/test.sh scripts/test.sh
# Render one frame of the desktop to _build/desktop.png and open it. # Render one frame of the desktop to _build/desktop.png and open it.
view: build view: build modules
{{exe}} --socket {{socket}}-snap --theme {{theme}} --gfx-out _build/desktop.png {{exe}} --socket {{socket}}-snap --theme {{theme}} --gfx-out _build/desktop.png
xdg-open _build/desktop.png xdg-open _build/desktop.png
+15 -7
View File
@@ -56,21 +56,29 @@ pub fn render_binary(
] ]
let ops = [] let ops = []
let cols = digits.length() let cols = digits.length()
let step_x = w / cols // Columns are grouped HH MM SS with a wider gap between groups.
let group_gap = 8
let step_x = (w - 2 * group_gap) / cols
let step_y = h / 4 let step_y = h / 4
let r = (if step_x < step_y { step_x } else { step_y }) / 2 - 1 let r = (if step_x < step_y { step_x } else { step_y }) / 2 - 1
let lit = t.palette.accent
let off = @ui.with_alpha(t.palette.foreground_muted, 70)
for c = 0; c < cols; c = c + 1 { for c = 0; c < cols; c = c + 1 {
let (d, nbits) = digits[c] let (d, nbits) = digits[c]
let bits = @timefmt.bcd_bits(d, nbits) let bits = @timefmt.bcd_bits(d, nbits)
let secs = c >= 4
for i = 0; i < nbits; i = i + 1 { for i = 0; i < nbits; i = i + 1 {
// Row 3 is the least significant bit. // Row 3 is the least significant bit.
let row = 4 - nbits + i let row = 4 - nbits + i
let cx = c * step_x + step_x / 2 let cx = c * step_x + step_x / 2 + (c / 2) * group_gap
let cy = row * step_y + step_y / 2 let cy = row * step_y + step_y / 2
if bits[i] { if bits[i] {
ops.push(@ui.circle(cx, cy, r, t.palette.accent)) // Soft halo + solid dot; seconds are quieter so hours/minutes read first.
let col = if secs { @ui.with_alpha(lit, 150) } else { lit }
ops.push(@ui.circle(cx, cy, r + 2, @ui.with_alpha(lit, if secs { 28 } else { 55 })))
ops.push(@ui.circle(cx, cy, r, col))
} else { } else {
ops.push(@ui.circle(cx, cy, r, t.palette.border, filled=false)) ops.push(@ui.circle(cx, cy, r - 1, off))
} }
} }
} }
@@ -140,12 +148,12 @@ test "digital clock shows HH:MM and the date" {
///| ///|
test "binary clock draws one dot per displayed bit" { test "binary clock draws one dot per displayed bit" {
let ops = render_binary(@ui.size(96, 36), test_tokens(), test_time()) let ops = render_binary(@ui.size(96, 36), test_tokens(), test_time())
// 2+4+3+4+3+4 bits // 2+4+3+4+3+4 bits; lit bits draw a halo and a dot
assert_eq(ops.length(), 20) assert_eq(ops.length(), 20 + 10)
let mut lit = 0 let mut lit = 0
for op in ops { for op in ops {
match op { match op {
Circle(c) => if c.filled { lit += 1 } Circle(c) => if c.filled && c.color.a >= 150 { lit += 1 }
_ => () _ => ()
} }
} }
+1 -1
View File
@@ -13,7 +13,7 @@ pub fn digital_info() -> (String, String, Int32, Int32, Int32)
pub fn render_binary(@types.Size, @theme.Tokens, @types.Datetime) -> Array[@types.DrawOp] pub fn render_binary(@types.Size, @theme.Tokens, @types.Datetime) -> Array[@types.DrawOp]
pub fn render_digital(@types.Size, @theme.Tokens, @types.Datetime) -> Array[@types.DrawOp] pub fn render_digital(@types.Size, @theme.Tokens, @types.Datetime, hour12? : Bool) -> Array[@types.DrawOp]
// Errors // Errors
+18 -4
View File
@@ -53,13 +53,17 @@ fn contains_ci(hay : String, needle : String) -> Bool {
ascii_lower(hay).contains(ascii_lower(needle)) ascii_lower(hay).contains(ascii_lower(needle))
} }
///| KRunner-ish filter: case-insensitive substring over name, comment and category. ///| KRunner-ish filter: case-insensitive substring over name, id, comment and
/// category. Name matches come first, then the rest; each group keeps its order.
pub fn filter(apps : Array[@types.AppEntry], query : String) -> Array[@types.AppEntry] { pub fn filter(apps : Array[@types.AppEntry], query : String) -> Array[@types.AppEntry] {
apps.filter(a => { let by_name = apps.filter(a => contains_ci(a.name, query))
contains_ci(a.name, query) || let others = apps.filter(a => {
!contains_ci(a.name, query) &&
(contains_ci(a.id, query) ||
contains_ci(a.comment, query) || contains_ci(a.comment, query) ||
contains_ci(a.category, query) contains_ci(a.category, query))
}) })
by_name + others
} }
///| ///|
@@ -318,3 +322,13 @@ test "focus loss closes and hover tracks the pointer" {
assert_true(handle_event(apps, st, Widget, FocusLost, _ => Ok(()))) assert_true(handle_event(apps, st, Widget, FocusLost, _ => Ok(())))
assert_false(st.open) assert_false(st.open)
} }
///|
test "search matches the app id and ranks name matches first" {
let apps : Array[@types.AppEntry] = [
{ id: "org.kde.kate", name: "Text Editor", comment: "", category: "Utility", glyph: "T" },
{ id: "x.pad", name: "Kate Pad", comment: "", category: "Utility", glyph: "K" },
]
let r = filter(apps, "kate")
assert_eq(r.map(a => a.id), ["x.pad", "org.kde.kate"])
}
+119
View File
@@ -0,0 +1,119 @@
///| Moon-phase "toy" widget: a pure example plasmoid (tokens + date in, ops out)
/// with two interchangeable renderings, so the shell can offer them as
/// alternatives of one another.
///| Julian day number of a Gregorian calendar date (noon).
pub fn julian_day(year : Int, month : Int, day : Int) -> Int {
let a = (14 - month) / 12
let y = year + 4800 - a
let m = month + 12 * a - 3
day + (153 * m + 2) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 32045
}
///| Phase in [0, 1): 0 = new moon, 0.25 = first quarter, 0.5 = full, 0.75 = last quarter.
/// Mean synodic month from the new moon of 2000-01-06; good to about a day.
pub fn phase(year : Int, month : Int, day : Int) -> Double {
let days = (julian_day(year, month, day) - 2451550).to_double() - 0.1
let p = days / 29.530588853
let f = p - p.floor()
if f < 0.0 { f + 1.0 } else { f }
}
///| Percent of the disc that is lit, 0..100.
pub fn illumination(p : Double) -> Int {
((1.0 - @math.cos(2.0 * @math.pi * p)) / 2.0 * 100.0).round().to_int()
}
///|
pub fn phase_name(p : Double) -> String {
let i = ((p * 8.0) + 0.5).floor().to_int() % 8
["New Moon", "Waxing Crescent", "First Quarter", "Waxing Gibbous", "Full Moon", "Waning Gibbous", "Last Quarter", "Waning Crescent"][i]
}
///|
pub fn disc_info() -> (String, String, Int, Int, Int) {
// id, name, preferred w, preferred h, min w
("org.moonplasma.moon.disc", "Moon Phase (disc)", 36, 36, 36)
}
///|
pub fn text_info() -> (String, String, Int, Int, Int) {
("org.moonplasma.moon.text", "Moon Phase (text)", 110, 36, 90)
}
///| The moon drawn as a disc with its lit part shaded row by row.
pub fn render_disc(
size : @types.Size,
t : @theme.Tokens,
p : Double,
) -> Array[@types.DrawOp] {
let w = size.w.reinterpret_as_int()
let h = size.h.reinterpret_as_int()
let r = (if w < h { w } else { h }) / 2 - 4
let cx = w / 2
let cy = h / 2
let lit = @ui.color(244, 236, 206, 255)
let shade = @ui.lerp_color(t.palette.surface_hover, @ui.color(10, 14, 28, 255), 1, 2)
// Glow grows with illumination, then the dark side (faint earthshine).
let glow = 10 + illumination(p) / 4
let ops = [
@ui.circle(cx, cy, r + 3, @ui.with_alpha(lit, glow / 2)),
@ui.circle(cx, cy, r + 2, @ui.with_alpha(lit, glow)),
@ui.circle(cx, cy, r, shade),
]
let k = @math.cos(2.0 * @math.pi * p)
let waxing = p < 0.5
// Lit area as 1px rows with fractional end pixels, so both the limb and the terminator are smooth.
for dy = -r; dy <= r; dy = dy + 1 {
let hw = (r * r - dy * dy).to_double().sqrt()
let term = hw * k
let (x0, x1) = if waxing { (term, hw) } else { (-hw, -term) }
if x1 - x0 > 0.05 {
let xl = x0.floor().to_int()
let xr = x1.ceil().to_int()
for x = xl; x < xr; x = x + 1 {
let a = (if x1 < (x + 1).to_double() { x1 } else { (x + 1).to_double() }) -
(if x0 > x.to_double() { x0 } else { x.to_double() })
if a > 0.04 {
// Slight shading toward the limb gives the disc some roundness.
let edge = (x.to_double() + 0.5).abs() / (r.to_double() + 0.001)
let tone = @ui.lerp_color(lit, @ui.color(214, 204, 172, 255), (edge * 100.0).to_int(), 220)
ops.push(@ui.fill_rect(@ui.rect(cx + x, cy + dy, 1, 1), @ui.with_alpha(tone, (a * 255.0).to_int())))
}
}
}
}
ops.push(@ui.circle(cx, cy, r, @ui.with_alpha(t.palette.border, 160), filled=false))
ops
}
///| Phase name over illumination percent.
pub fn render_text(
size : @types.Size,
t : @theme.Tokens,
p : Double,
) -> Array[@types.DrawOp] {
let w = size.w.reinterpret_as_int()
let h = size.h.reinterpret_as_int()
let fs = t.font_size.reinterpret_as_int()
[
@ui.text(w / 2, h / 2 - fs / 2 + 1, phase_name(p), fs - 2, t.palette.foreground, align=CENTER, bold=true),
@ui.text(w / 2, h / 2 + fs / 2 + 4, illumination(p).to_string() + "% lit", fs - 3, t.palette.foreground_muted, align=CENTER),
]
}
///|
test "known dates" {
// New moon 2000-01-06, full moon 2000-01-21, new moon 2024-01-11.
assert_true(phase(2000, 1, 6) < 0.05 || phase(2000, 1, 6) > 0.95)
assert_eq(phase_name(phase(2000, 1, 21)), "Full Moon")
assert_eq(illumination(phase(2024, 1, 11)) < 5, true)
assert_eq(julian_day(2000, 1, 1), 2451545)
}
///|
test "illumination extremes" {
assert_eq(illumination(0.0), 0)
assert_eq(illumination(0.5), 100)
assert_eq(illumination(0.25), 50)
}
+6
View File
@@ -0,0 +1,6 @@
import {
"moonbitlang/core/math" @math,
"moonplasma/desktop/interface/moonplasma/desktop/types" @types,
"moonplasma/desktop/interface/moonplasma/desktop/theme" @theme,
"moonplasma/desktop/lib/ui" @ui,
}
+32
View File
@@ -0,0 +1,32 @@
// Generated using `moon info`, DON'T EDIT IT
package "moonplasma/desktop/lib/moon"
import {
"moonplasma/desktop/interface/moonplasma/desktop/theme",
"moonplasma/desktop/interface/moonplasma/desktop/types",
}
// Values
pub fn disc_info() -> (String, String, Int32, Int32, Int32)
pub fn illumination(Double) -> Int32
pub fn julian_day(Int32, Int32, Int32) -> Int32
pub fn phase(Int32, Int32, Int32) -> Double
pub fn phase_name(Double) -> String
pub fn render_disc(@types.Size, @theme.Tokens, Double) -> Array[@types.DrawOp]
pub fn render_text(@types.Size, @theme.Tokens, Double) -> Array[@types.DrawOp]
pub fn text_info() -> (String, String, Int32, Int32, Int32)
// Errors
// Types and methods
// Type aliases
// Traits
+2
View File
@@ -8,6 +8,8 @@ pub fn date_line(Int32, Int32, Int32) -> String
pub fn hhmm(Int32, Int32) -> String pub fn hhmm(Int32, Int32) -> String
pub fn hhmm12(Int32, Int32) -> String
pub fn hhmmss(Int32, Int32, Int32) -> String pub fn hhmmss(Int32, Int32, Int32) -> String
pub fn month_short(Int32) -> String pub fn month_short(Int32) -> String
+12 -1
View File
@@ -8,7 +8,9 @@ import {
// Values // Values
pub fn clamp_int(Int32, Int32, Int32) -> Int32 pub fn clamp_int(Int32, Int32, Int32) -> Int32
pub fn compute_bsp_rects(BspNode, Rect, Int32) -> Array[(UInt64, Rect)] pub fn compute_bsp_rects(BspNode, Rect, Int32, vgap? : Int32) -> Array[(UInt64, Rect)]
pub fn compute_split_handles(BspNode, Rect, Int32, Int32) -> Array[SplitHandle]
pub fn compute_work_area(Rect, excl_top? : Int32, excl_right? : Int32, excl_bottom? : Int32, excl_left? : Int32) -> Rect pub fn compute_work_area(Rect, excl_top? : Int32, excl_right? : Int32, excl_bottom? : Int32, excl_left? : Int32) -> Rect
@@ -76,6 +78,13 @@ pub(all) struct Size {
h : Int32 h : Int32
} }
pub(all) struct SplitHandle {
path : Array[Bool]
horizontal : Bool
rect : Rect
area : Rect
}
pub(all) struct WindowRecord { pub(all) struct WindowRecord {
id : UInt64 id : UInt64
app_id : String app_id : String
@@ -131,6 +140,7 @@ pub(all) struct WmState {
mut drag : DragSession? mut drag : DragSession?
} }
pub fn WmState::close_window(Self, UInt64, Rect) -> Array[WmAction] pub fn WmState::close_window(Self, UInt64, Rect) -> Array[WmAction]
pub fn WmState::drag_split(Self, SplitHandle, Int32, Int32, Rect) -> Array[WmAction]
pub fn WmState::end_drag(Self) -> Unit pub fn WmState::end_drag(Self) -> Unit
pub fn WmState::handle_request(Self, UInt64, WindowRequest, Rect) -> Array[WmAction] pub fn WmState::handle_request(Self, UInt64, WindowRequest, Rect) -> Array[WmAction]
pub fn WmState::hit_test(Self, Int32, Int32, Rect?) -> InputHit pub fn WmState::hit_test(Self, Int32, Int32, Rect?) -> InputHit
@@ -138,6 +148,7 @@ pub fn WmState::new(inner_gap? : Int32, outer_gap? : Int32, titlebar_h? : Int32,
pub fn WmState::open_window(Self, WindowRecord, Rect) -> Array[WmAction] pub fn WmState::open_window(Self, WindowRecord, Rect) -> Array[WmAction]
pub fn WmState::relayout(Self, UInt32, Rect) -> Array[WmAction] pub fn WmState::relayout(Self, UInt32, Rect) -> Array[WmAction]
pub fn WmState::set_layout_mode(Self, LayoutMode, Rect) -> Array[WmAction] pub fn WmState::set_layout_mode(Self, LayoutMode, Rect) -> Array[WmAction]
pub fn WmState::split_handles(Self, Rect) -> Array[SplitHandle]
pub fn WmState::stacking_order(Self) -> Array[UInt64] pub fn WmState::stacking_order(Self) -> Array[UInt64]
pub fn WmState::start_drag(Self, UInt64, DragMode, Int32, Int32) -> Bool pub fn WmState::start_drag(Self, UInt64, DragMode, Int32, Int32) -> Bool
pub fn WmState::sync_windows(Self, Rect, Array[WindowRecord]) -> Array[WmAction] pub fn WmState::sync_windows(Self, Rect, Array[WindowRecord]) -> Array[WmAction]
+16 -2
View File
@@ -457,8 +457,10 @@ pub fn WmState::relayout(
w: if rect.w < min_w { min_w } else { rect.w }, w: if rect.w < min_w { min_w } else { rect.w },
h: if rect.h < min_h { min_h } else { rect.h }, h: if rect.h < min_h { min_h } else { rect.h },
} }
win.geometry = clamped // A maximized tiled window covers the whole padded work area.
actions.push(SetGeometry(id, clamped)) let g = if win.maximized { padded } else { clamped }
win.geometry = g
actions.push(SetGeometry(id, g))
} }
None => () None => ()
} }
@@ -801,6 +803,18 @@ pub fn WmState::stacking_order(self : WmState) -> Array[UInt64] {
} }
collect_tree(ws.tree, order, ws.fullscreen, self.windows) collect_tree(ws.tree, order, ws.fullscreen, self.windows)
// Maximized tiled windows are drawn above their neighbours.
let below : Array[UInt64] = []
let above : Array[UInt64] = []
for id in order {
match self.windows.get(id) {
Some(w) => if w.maximized { above.push(id) } else { below.push(id) }
None => below.push(id)
}
}
order.clear()
order.append(below)
order.append(above)
for id in ws.floating { for id in ws.floating {
if ws.fullscreen != Some(id) { if ws.fullscreen != Some(id) {
match self.windows.get(id) { match self.windows.get(id) {
+75
View File
@@ -0,0 +1,75 @@
version: 7
platforms:
- name: linux-64
virtual-packages:
- __unix=0=0
- __linux=4.18
- __glibc=2.28
- __archspec=0=x86_64
environments:
default:
channels:
- url: https://prefix.dev/scns/
- url: https://conda.anaconda.org/conda-forge/
packages:
linux-64:
- conda: https://conda.anaconda.org/conda-forge/linux-64/just-0.10.4-habb4d0f_0.tar.bz2
- conda: https://prefix.dev/scns/linux-64/_libgcc_mutex-0.1-scns_forge.tar.bz2
- conda: https://prefix.dev/scns/linux-64/_openmp_mutex-4.5-2_gnu.tar.bz2
- conda: https://prefix.dev/scns/linux-64/libgcc-ng-11.2.0-h5593d30_1000.tar.bz2
- conda: https://prefix.dev/scns/linux-64/libgomp-11.2.0-h5593d30_1000.tar.bz2
- conda: https://prefix.dev/scns/linux-64/tinycc-0.9.27-pl5321h57f0786_0.conda
packages:
- conda: https://conda.anaconda.org/conda-forge/linux-64/just-0.10.4-habb4d0f_0.tar.bz2
sha256: 2da7d79edbe5aac86b731c8b5bea9760bd334a87a2d8117959de7a7a46b5d1fc
md5: b3f069cfa06ea8ffa874d49621ad5b6d
depends:
- libgcc-ng >=9.4.0
license: CC0-1.0
run_exports: {}
size: 1078485
timestamp: 1638124980753
- conda: https://prefix.dev/scns/linux-64/_libgcc_mutex-0.1-scns_forge.tar.bz2
sha256: 15caf304cf0d222cdc9c6f8145e3cb5e00106363d041805ff0777c1811baf28a
license: None
size: 4427
timestamp: 1676009793381
- conda: https://prefix.dev/scns/linux-64/_openmp_mutex-4.5-2_gnu.tar.bz2
build_number: 1000
sha256: cd1bc9bdac74d348a5ae562e0a1a260084530fcf50cfbde11f0e366876c01496
depends:
- __glibc >=2.17,<3.0.a0
- _libgcc_mutex 0.1 scns_forge
- libgomp >=7.5.0
constrains:
- openmp_impl 9999
license: BSD-3-Clause
size: 6060792
timestamp: 1710847729439
- conda: https://prefix.dev/scns/linux-64/libgcc-ng-11.2.0-h5593d30_1000.tar.bz2
sha256: 73093301e58054319b0416c947fd31541ae9c3c474d3b0561c9b843a4eccbcb0
depends:
- _libgcc_mutex 0.1 scns_forge
- _openmp_mutex >=4.5
constrains:
- libgomp 11.2.0 h5593d30_1000
license: GPL-3.0-only WITH GCC-exception-3.1
size: 6957156
timestamp: 1710847747666
- conda: https://prefix.dev/scns/linux-64/libgomp-11.2.0-h5593d30_1000.tar.bz2
sha256: 7d874391201845c730d4f37cc8bf5c478c302d9beec73cfacc4896f919593acc
depends:
- _libgcc_mutex 0.1 scns_forge
license: GPL-3.0-only WITH GCC-exception-3.1
size: 6488970
timestamp: 1710847698293
- conda: https://prefix.dev/scns/linux-64/tinycc-0.9.27-pl5321h57f0786_0.conda
sha256: 41ed2a42c53e369870e24691b4515a0067ab4f9986928327b1cd17a71af38774
md5: c5c9a3716649df5e1b52a6cb438b2d84
depends:
- __glibc >=2.17,<3.0.a0
- libgcc-ng >=11
license: LGPL-2.1-or-later
run_exports: {}
size: 2932996
timestamp: 1785949887223
+8
View File
@@ -0,0 +1,8 @@
[workspace]
name = "moon-plasma"
channels = ["https://prefix.dev/scns", "conda-forge"]
platforms = ["linux-64"]
[dependencies]
just = "*"
tinycc = "*"
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# Build the panel's wasm modules (every *-widget component in scripts/components.txt)
# into build/components/<name>.wasm, the directory the compositor loads its panel from.
# Same steps as scripts/build.sh minus the jco/JS-host transpile, so it needs only
# moon and wasm-tools.
# scripts/build-modules.sh [name ...]
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT"
export PATH="$ROOT/.tools/bin:$HOME/.moon/bin:$PATH"
for t in moon wasm-tools; do
command -v "$t" >/dev/null || { echo "error: $t not found" >&2; exit 1; }
done
want=("$@")
mkdir -p build/components
moon build --target wasm --release 2>&1 | grep -E '^Error' -A8 || true
[ "${PIPESTATUS[0]}" -eq 0 ] || { echo "error: moon build failed" >&2; exit 1; }
n=0
while read -r name world; do
case "$name" in ''|'#'*) continue;; esac
case "$world" in *-widget) ;; *) continue;; esac
if [ ${#want[@]} -gt 0 ] && [[ ! " ${want[*]} " =~ " $name " ]]; then continue; fi
core="_build/wasm/release/build/components/$name/gen/gen.wasm"
[ -f "$core" ] || { echo "error: $core missing" >&2; exit 1; }
out="build/components/$name.wasm"
wasm-tools component embed wit "$core" --world "$world" --encoding utf16 -o "build/components/$name.embed.wasm"
wasm-tools component new "build/components/$name.embed.wasm" -o "$out"
rm -f "build/components/$name.embed.wasm"
wasm-tools validate --features component-model "$out"
wasm-tools component targets --world "$world" wit "$out" >/dev/null
imports="$(wasm-tools component wit "$out" | sed -n 's/^ import moonplasma:desktop\/\([a-z-]*\)@.*;/\1/p' | grep -v '^types$' | sort | paste -sd, - || true)"
exports="$(wasm-tools component wit "$out" | sed -n 's/^ export moonplasma:desktop\/\([a-z-]*\)@.*;/\1/p' | sort | paste -sd, -)"
printf '{"name":"%s","world":"%s","imports":[%s],"exports":[%s]}\n' "$name" "$world" \
"$(echo "$imports" | sed 's/\([a-z-]\+\)/"\1"/g')" "$(echo "$exports" | sed 's/\([a-z-]\+\)/"\1"/g')" \
> "build/components/$name.meta.json"
printf ' %-16s %-22s %7s bytes imports=[%s]\n' "$name" "$world" "$(stat -c %s "$out")" "$imports"
n=$((n + 1))
done < scripts/components.txt
echo "built $n module(s) into build/components/"
+8
View File
@@ -3,3 +3,11 @@ clock-digital clock-widget
clock-binary clock-widget clock-binary clock-widget
launcher launcher-widget launcher launcher-widget
shell shell shell shell
pulse pulse-widget
clock-digital12 clock-widget
moon-disc clock-widget
moon-text clock-widget
tasks taskbar-widget
layout layout-widget
inspector inspector-widget
module-manager module-manager-widget
+6
View File
@@ -11,4 +11,10 @@ args=()
for a in "$@"; do for a in "$@"; do
[ "$a" = "-DMOONBIT_NATIVE_NO_SYS_HEADER" ] || args+=("$a") [ "$a" = "-DMOONBIT_NATIVE_NO_SYS_HEADER" ] || args+=("$a")
done done
# tcc does not link libm by default; the font rasteriser needs it. Add it on link steps only.
link=1
for a in "${args[@]}"; do
case "$a" in -c|-ar) link=0 ;; esac
done
if [ "$link" = 1 ]; then args+=(-lm); fi
exec "$tcc" "${args[@]}" exec "$tcc" "${args[@]}"
+2 -1
View File
@@ -36,5 +36,6 @@ step "host integration tests (jco + Node)"
(cd host && npm test) (cd host && npm test)
step "pure-MoonBit native Wayland compositor + wasi-gfx + e2e tests (compositor/)" step "pure-MoonBit native Wayland compositor + wasi-gfx + e2e tests (compositor/)"
moon test --target native --warn-list -a compositor/renderer compositor/gfx compositor/host XDG_CONFIG_HOME="$(mktemp -d)" MOON_PLASMA_TEST_CONFIG=1 \
moon test --target native --warn-list -a compositor/renderer compositor/gfx compositor/wasm compositor/host
moon build --target native --warn-list -a compositor/bin moon build --target native --warn-list -a compositor/bin
+14
View File
@@ -8,6 +8,7 @@ Installs:
/usr/local/bin/moon-plasma release compositor binary /usr/local/bin/moon-plasma release compositor binary
/usr/local/bin/moon-plasma-session session launcher /usr/local/bin/moon-plasma-session session launcher
/usr/local/share/moon-plasma/{config,wit}/ files the compositor reads at runtime /usr/local/share/moon-plasma/{config,wit}/ files the compositor reads at runtime
/usr/local/share/moon-plasma/modules/*.wasm the panel's wasm modules (build them first: just modules)
/usr/share/wayland-sessions/moon-plasma.desktop display-manager entry /usr/share/wayland-sessions/moon-plasma.desktop display-manager entry
""" """
import os, shutil, sys import os, shutil, sys
@@ -53,4 +54,17 @@ for d in ("config", "wit"):
os.makedirs(share, exist_ok=True) os.makedirs(share, exist_ok=True)
shutil.copytree(os.path.join(root, d), dst) shutil.copytree(os.path.join(root, d), dst)
print("installed", dst) print("installed", dst)
mods = os.path.join(root, "build/components")
dst = os.path.join(share, "modules")
if os.path.isdir(dst):
shutil.rmtree(dst)
os.makedirs(dst, exist_ok=True)
n = 0
for f in sorted(os.listdir(mods)) if os.path.isdir(mods) else []:
if f.endswith(".wasm"):
shutil.copyfile(os.path.join(mods, f), os.path.join(dst, f))
n += 1
if n == 0:
sys.exit("no modules in build/components - run `just modules` first")
print("installed", n, "modules in", dst)
print("done: pick 'Moon Plasma' in the session menu of your login screen") print("done: pick 'Moon Plasma' in the session menu of your login screen")
+91
View File
@@ -19,3 +19,94 @@ interface app-launch {
/// Ask the host to start an application by catalog id. /// Ask the host to start an application by catalog id.
launch: func(id: string) -> result<_, string>; launch: func(id: string) -> result<_, string>;
} }
/// Live machine state, sampled by the host about once a second. The widget never
/// opens /proc or /sys itself: it can only see what this interface hands it, and
/// the host can serve it from anything (Linux /proc, a mock, a remote machine).
interface system {
record snapshot {
/// Busy CPU time since the previous sample, 0..1000.
cpu-permille: u32,
mem-used-kib: u64,
mem-total-kib: u64,
/// 0..100, or -1 when the machine has no battery.
battery-percent: s32,
charging: bool,
uptime-secs: u64,
net-rx-bytes-per-sec: u64,
net-tx-bytes-per-sec: u64,
/// 1-minute load average x 100.
load-centi: u32,
}
read: func() -> snapshot;
}
/// The window list, as shown by a task bar. `id` is an opaque host handle.
interface windows {
record window-info {
id: u32,
title: string,
/// 1 when the window has keyboard focus.
focused: u32,
/// 1 when the window is minimized (it stays listed so it can be restored).
minimized: u32,
}
list-windows: func() -> list<window-info>;
/// Focus, raise (and un-minimize) a window.
focus-window: func(id: u32);
/// Richer, id-stable view for widgets that show more than a task bar (the Pulse widget).
record window-detail {
id: u64,
title: string,
app-id: string,
focused: bool,
}
all: func() -> list<window-detail>;
/// Raise and focus a window (restoring it if minimized).
focus: func(id: u64);
}
/// The window manager's layout mode (tiling / monocle / floating).
interface layout-control {
/// Display names, indexed by mode.
layout-modes: func() -> list<string>;
current-layout: func() -> u32;
set-layout: func(mode: u32);
}
/// The Interface Explorer: hover any system component to see its WIT.
interface inspector {
is-on: func() -> bool;
set-on: func(on: bool);
}
/// Hot-swap of the system's own wasm modules. A module with this capability
/// is a module manager: it decides what is loaded into the panel.
interface modules {
/// A loadable module found on the module search path.
record module-info {
/// File stem, e.g. "clock-digital".
id: string,
name: string,
path: string,
/// How many instances are loaded in the panel right now.
loaded: u32,
}
/// A module instance currently loaded in the panel, in panel order.
record instance-info {
slot: string,
module: string,
name: string,
}
available: func() -> list<module-info>;
loaded: func() -> list<instance-info>;
/// Load the module file at `path` into the panel (any number of instances).
load-module: func(path: string);
/// Unload one loaded instance, freeing its panel space.
unload-instance: func(slot: string);
/// Ask the host to show its native file chooser for a .wasm elsewhere on disk.
browse: func();
}
+31
View File
@@ -28,3 +28,34 @@ world shell {
export desktop-surface; export desktop-surface;
export panel-layout; export panel-layout;
} }
/// Desktop Pulse: reads machine state and the window list, and can raise a window.
world pulse-widget {
include widget;
import system;
import windows;
}
/// Panel task list: needs the window list.
world taskbar-widget {
include widget;
import windows;
}
/// Layout switcher.
world layout-widget {
include widget;
import layout-control;
}
/// Interface Explorer toggle.
world inspector-widget {
include widget;
import inspector;
}
/// Loads and unloads the system's wasm modules; the wasm picker opens this app.
world module-manager-widget {
include widget;
import modules;
}