// chandra host core (platform-agnostic: runs in Node and the browser). // // Responsibilities (the *only* things that are not components): // * instantiate components and broker capabilities (deny-by-default grants) // * drive the frame loop: shell layout -> widget render -> render-list // * route input to the component that owns the surface under the pointer // * hot-swap a widget's implementation at runtime // All policy (layout, look, behaviour) lives in components. import { CAPABILITIES } from './platform.mjs'; import { place, translate } from './scene.mjs'; const PKG = 'chandra:desktop'; const PLASMOID = `${PKG}/plasmoid`; const PANEL = `${PKG}/panel-layout`; const DESKTOP = `${PKG}/desktop-surface`; export class PermissionError extends Error { constructor(msg) { super(msg); this.name = 'PermissionError'; } } export class ComponentFault extends Error { constructor(component, fn, cause) { super(`component "${component}" faulted in ${fn}: ${cause?.message ?? cause}`); this.name = 'ComponentFault'; this.component = component; this.fn = fn; this.cause = cause; } } /** * @typedef {{meta: {name:string, world:string, imports:string[], exports:string[]}, * instantiate: (imports: object) => Promise}} LoadedComponent * @param {{config: any, loader: (name: string) => Promise, platform: any}} opts */ export class Desktop { constructor({ config, loader, platform }) { this.config = config; this.loader = loader; this.platform = platform; this.screen = { w: config.screen.w, h: config.screen.h }; this.shell = null; this.widgets = []; // {id, align, componentName, grants, meta, plasmoid} this.faults = []; // visible, never swallowed: also rendered as error tiles this.hit = { widgets: [], popup: null }; this.hovered = null; } async start() { this.shell = await this.#instantiate(this.config.shell.component, this.config.shell.grants, 'shell'); for (const w of this.config.panel) { const inst = await this.#instantiate(w.component, w.grants, 'widget'); this.widgets.push({ id: w.id, align: w.align ?? 'start', grants: w.grants, ...inst }); } return this; } /** Replace the implementation behind panel widget `id` without touching others. */ async swap(id, componentName) { const i = this.widgets.findIndex((w) => w.id === id); if (i < 0) throw new Error(`swap: no widget with id "${id}"`); const old = this.widgets[i]; const inst = await this.#instantiate(componentName, old.grants, 'widget'); this.widgets[i] = { id, align: old.align, grants: old.grants, ...inst }; this.hovered = null; } async #instantiate(componentName, grants, role) { for (const g of grants) { if (!CAPABILITIES.includes(g)) throw new PermissionError(`config grants unknown capability "${g}" to ${componentName}`); } const c = await this.loader(componentName); const need = c.meta.imports; const denied = need.filter((n) => !grants.includes(n)); if (denied.length) { throw new PermissionError( `component "${componentName}" imports [${denied.join(', ')}] which the desktop config does not grant ` + `(granted: [${grants.join(', ')}])`); } const exp = c.meta.exports; const wantExports = role === 'shell' ? ['panel-layout', 'desktop-surface'] : ['plasmoid']; for (const e of wantExports) { if (!exp.includes(e)) throw new Error(`component "${componentName}" does not export ${e}; cannot act as ${role}`); } // Only granted AND imported interfaces are wired; jco fails instantiation // loudly if anything else is missing. const imports = {}; for (const n of need) imports[`${PKG}/${n}`] = this.platform.interfaces[n](); const instance = await c.instantiate(imports); const get = (iface) => instance[`${iface}@0.1.0`] ?? instance[iface]; return role === 'shell' ? { componentName, meta: c.meta, panel: get(PANEL), desktop: get(DESKTOP) } : { componentName, meta: c.meta, plasmoid: get(PLASMOID) }; } #call(owner, fn, thunk) { try { return thunk(); } catch (e) { const f = new ComponentFault(owner.componentName, fn, e); this.faults.push(f); console.error(`[host] ${f.message}`); throw f; } } /** Compose one frame. Returns {ops, layout, screen}. */ frame() { const screen = this.screen; const ops = []; ops.push(...this.#call(this.shell, 'desktop-surface.render-background', () => this.shell.desktop.renderBackground(screen))); const slots = this.widgets.map((w) => { const info = this.#call(w, 'plasmoid.info', () => w.plasmoid.info()); w.info = info; return { id: w.id, preferred: info.preferred, minWidth: info.minWidth, stretch: info.stretch, align: w.align }; }); const layout = this.#call(this.shell, 'panel-layout.compute-layout', () => this.shell.panel.computeLayout(screen, slots)); ops.push(...this.#call(this.shell, 'panel-layout.render-panel', () => this.shell.panel.renderPanel(screen, layout.panel))); this.hit = { widgets: [], popup: null }; const rects = new Map(); for (const p of layout.placements) rects.set(p.id, p.rect); for (const w of this.widgets) { const rect = rects.get(w.id); if (!rect) throw new Error(`shell returned no placement for widget "${w.id}"`); this.hit.widgets.push({ widget: w, rect }); let wops; try { wops = this.#call(w, 'plasmoid.render', () => w.plasmoid.render({ w: rect.w, h: rect.h })); } catch { wops = faultTile(rect, w.componentName); } ops.push(...place(wops, rect)); } // Popup layer (at most one popup open at a time). for (const entry of this.hit.widgets) { let pop; try { pop = this.#call(entry.widget, 'plasmoid.popup', () => entry.widget.plasmoid.popup()); } catch { continue; } if (!pop) continue; const prect = this.#call(this.shell, 'panel-layout.popup-position', () => this.shell.panel.popupPosition(screen, layout.panel, entry.rect, pop.size)); this.hit.popup = { widget: entry.widget, anchor: entry.rect, rect: prect }; ops.push(...place(pop.ops, prect)); break; } return { ops, layout, screen }; } #send(widget, target, event) { return this.#call(widget, 'plasmoid.on-event', () => widget.plasmoid.onEvent(target, event)); } /** @param {'move'|'down'|'up'} kind Returns true when a redraw is needed. */ pointer(kind, x, y) { const pt = { x, y }; const inside = (r) => x >= r.x && y >= r.y && x < r.x + r.w && y < r.y + r.h; const tag = { move: 'pointer-move', down: 'pointer-down', up: 'pointer-up' }[kind]; if (!tag) throw new Error(`unknown pointer kind ${kind}`); let dirty = false; const popup = this.hit.popup; if (popup && inside(popup.rect)) { return this.#send(popup.widget, 'popup', { tag, val: { x: x - popup.rect.x, y: y - popup.rect.y } }); } if (popup && kind === 'down' && !inside(popup.anchor)) { // Click outside the popup: tell its owner it lost focus, then let the // click fall through to whatever is underneath. dirty = this.#send(popup.widget, 'widget', { tag: 'focus-lost', val: undefined }) || dirty; } const target = this.hit.widgets.find((e) => inside(e.rect)); if (this.hovered && this.hovered !== target?.widget) { dirty = this.#send(this.hovered, 'widget', { tag: 'pointer-leave', val: undefined }) || dirty; } this.hovered = target?.widget ?? null; if (target) { dirty = this.#send(target.widget, 'widget', { tag, val: { x: x - target.rect.x, y: y - target.rect.y } }) || dirty; } void pt; return dirty; } key(k) { const popup = this.hit.popup; if (!popup) return false; return this.#send(popup.widget, 'popup', { tag: 'key-down', val: k }); } } function faultTile(rect, name) { const red = { r: 200, g: 40, b: 40, a: 255 }; return [ { tag: 'fill-rect', val: { rect: { x: 0, y: 0, w: rect.w, h: rect.h }, color: red, radius: 4 } }, { tag: 'text', val: { origin: { x: 6, y: Math.floor(rect.h / 2) }, text: `${name} crashed`, style: { size: 12, color: { r: 255, g: 255, b: 255, a: 255 }, align: 'left', bold: true } } }, ]; } export { translate };