Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 16 additions & 8 deletions host/host.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@

import { SPEC, TOPICS, validMessage, parseMessage, manifestErrors } from '../shared/protocol.js';
import { Policy, reconnectDelay } from './policy.js';
import { dockSize, surfaceRects, clipPath, planLayout } from './layout.js';
import { dockSize, surfaceRects, clipPath, planLayout, dragPosition } from './layout.js';
import { permittedState, permits } from './access.js';
import { StorageBroker } from './storage.js';
import { enableDragGesture } from '../shared/drag.js';
import { validPrefs, validPosition } from '../shared/positions.js';
import { layoutDelta } from '../shared/coordinates.js';
import { resetPositions, pruneSurfaces, rememberSurfaces, restoreSurfaces, surfaceKey } from './preferences.js';
import { resetPositions, loadPreferences, pruneSurfaces, rememberSurfaces, restoreSurfaces, surfaceKey } from './preferences.js';
import { DataStore, topicAllowed } from './data.js';
import { strings } from './strings.js';
const policy = new Policy(), frames = new Map(), manifests = new Map(), broker = new StorageBroker(), pins = new Set(), actionStates = new Map();
Expand Down Expand Up @@ -94,14 +93,24 @@ function scheduleLayout(final=false) {
layoutTimer=setTimeout(()=>{layoutTimer=undefined;lastLayout=now();sync();},Math.max(0,34-(now()-lastLayout)));
}
function enableDockDrag(element) {
let origin, local;
element.addEventListener('pointerdown',e=>{
if(e.button===0 && e.isPrimary!==false && !origin)origin={id:e.pointerId,x:e.clientX,y:e.clientY};
});
element.addEventListener('pointermove',e=>{
if(origin?.id===e.pointerId)local={dx:e.clientX-origin.x,dy:e.clientY-origin.y};
});
enableDragGesture(element,move=>{
if (move.phase==='start') { sendReceiver('wake'); dockGesture={...dockPosition()}; dock.className='lifted'; }
if (!dockGesture) return;
const delta=layoutDelta(move,geometry.screenScale);
geometry.dockPosition={x:dockGesture.x+delta.dx,y:dockGesture.y+delta.dy};
// The dock's document stays fixed; client deltas already account for its actual frame scale.
const localMove=local && Number.isFinite(local.dx) && Number.isFinite(local.dy);
geometry.dockPosition=dragPosition(dockGesture,localMove?local:move,localMove?undefined:geometry.screenScale);
scheduleLayout(move.phase==='end');
if (move.phase==='end') { dockGesture=false; dock.className=''; }
});
const clear=()=>{origin=local=undefined;};
for(const type of ['pointerup','pointercancel','lostpointercapture'])element.addEventListener(type,clear);
}
function renderDock() {
// Retain the launcher element during a captured gesture and geometry updates.
Expand Down Expand Up @@ -388,7 +397,7 @@ window.addEventListener('message',event => {
// Preferences bootstrap this host once. Geometry messages may echo stale storage
// while a save/reset is in flight; they must never undo live host state.
if (!prefsLoaded) {
hostPrefs=validPrefs(m.hostPrefs)?m.hostPrefs:{};
hostPrefs=loadPreferences(m.hostPrefs);
pendingRestore=new Set(Object.keys(hostPrefs.surfaces ?? {})); prefsLoaded=true;
lastPrefs=JSON.stringify(hostPrefs);
}
Expand Down Expand Up @@ -421,8 +430,7 @@ window.addEventListener('message',event => {
const move=m.move;
if(move.phase==='start') { frame.drag={x:frame.rect.x,y:frame.rect.y}; frame.element.className='lifted'; }
if(frame.drag) {
const delta=layoutDelta(move,geometry.screenScale);
frame.surface.position={x:frame.drag.x+delta.dx,y:frame.drag.y+delta.dy};
frame.surface.position=dragPosition(frame.drag,move,geometry.screenScale);
scheduleLayout(move.phase==='end');
if(move.phase==='end') { frame.drag=undefined;frame.element.className=''; }
}
Expand Down
6 changes: 6 additions & 0 deletions host/layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@
// Created by riko chen on 2026-10-16

import { placeFree, validPosition } from '../shared/positions.js';
import { layoutDelta } from '../shared/coordinates.js';

export function dragPosition(start, move, scale) {
const {dx,dy}=layoutDelta(move,scale);
return {x:start.x+dx,y:start.y+dy};
}

export function clamp(rect, viewport) {
const x = Math.max(0, Math.min(viewport.w, rect.x)), y = Math.max(0, Math.min(viewport.h, rect.y));
Expand Down
16 changes: 13 additions & 3 deletions host/preferences.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,28 @@
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Created by riko chen on 2026-10-16

import { validPosition } from '../shared/positions.js';
import { validPosition, validPrefs } from '../shared/positions.js';
const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
const persistent = s => ['companion','ambient'].includes(s.kind);
export const surfaceKey = s => `${s.plugin}/${s.id}`;
const anchors = new Set(['top-left','top-right','bottom-left','bottom-right','left','right','top','bottom']);
export function placement(value = {}) {
if (!record(value)) return {};
return {...(validPosition(value) ? {x:value.x,y:value.y} : {}),...(anchors.has(value.anchor) ? {anchor:value.anchor} : {})};
}
export function loadPreferences(value) {
if (!validPrefs(value)) return {};
const companions=Object.fromEntries(Object.entries(record(value.companions)?value.companions:{}).filter(([,p])=>validPosition(p)).map(([id,p])=>[id,placement(p)]));
// Older hosts saved active companions only as free positions.
const selected=value.surfaces===undefined?companions:record(value.surfaces)?value.surfaces:{};
const surfaces=Object.fromEntries(Object.entries(selected).filter(([,p])=>record(p)).map(([id,p])=>[id,placement(p)]));
return {...value,companions,surfaces};
}
// Desired surfaces survive temporary policy gates, but never disabled or removed plugins.
export function pruneSurfaces(saved, manifests, disabled) {
return Object.fromEntries(Object.entries(saved ?? {}).filter(([id]) => {
return Object.fromEntries(Object.entries(record(saved)?saved:{}).filter(([id,value]) => {
const [plugin,surface] = id.split('/');
return !disabled.has(plugin) && manifests.get(plugin)?.surfaces.some(s=>s.id===surface && persistent(s));
return id===`${plugin}/${surface}` && record(value) && !disabled.has(plugin) && manifests.get(plugin)?.surfaces.some(s=>s.id===surface && persistent(s));
}).map(([id,value])=>[id,placement(value ?? {})]));
}
export function rememberSurfaces(saved, loaded) {
Expand Down
6 changes: 5 additions & 1 deletion plugins/visuals/ambient.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,11 @@ function frame(wall) {
ctx.clearRect(0,0,w,h);
ctx.globalAlpha=value.brightness;
if(value.enabled&&w>=4&&h>=4){
if(value.effect==='progress')drawProgress(ctx,w,h,frozenProgress,color());
if(value.effect==='progress') {
const rect=host.surface.video;
const video=rect?{x:rect.x*w/host.surface.w,y:rect.y*h/host.surface.h,w:rect.w*w/host.surface.w,h:rect.h*h/host.surface.h}:undefined;
drawProgress(ctx,w,h,frozenProgress,color(),video);
}
if(value.effect==='album')drawGlow(ctx,w,h,host.reducedMotion?to:color());
if(value.effect==='sky')drawSky(ctx,w,h,frozenHour);
}
Expand Down
23 changes: 20 additions & 3 deletions plugins/visuals/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,27 @@ export function drawGlow(ctx,w,h,color) {
gradient.addColorStop(1,`rgba(${color.join(',')},0.8)`);
ctx.fillStyle=gradient; ctx.fillRect(0,0,w,h);
}
// Host v0 supplies no video rectangle. A perimeter sweep fills the clipped margins;
// the outer hairline is a fallback until picture geometry is exposed to plugins.
export function drawProgress(ctx,w,h,amount,color) {
export function progressPath(rect,amount) {
const {x,y,w,h}=rect, points=[[x,y]], corners=[[x+w,y],[x+w,y+h],[x,y+h],[x,y]];
let left=clamp(amount)*2*(w+h), current=points[0];
for(const next of corners) {
if(left<=0)break;
const length=Math.hypot(next[0]-current[0],next[1]-current[1]), fraction=Math.min(1,left/length);
points.push([current[0]+(next[0]-current[0])*fraction,current[1]+(next[1]-current[1])*fraction]);
left-=length;current=next;
}
return points;
}
export function drawProgress(ctx,w,h,amount,color,video) {
if (amount === null || amount <= 0) return;
if(video && ['x','y','w','h'].every(k=>Number.isFinite(video[k])) && video.w>0 && video.h>0) {
const [start,...points]=progressPath(video,amount);
ctx.save();ctx.beginPath();ctx.moveTo(...start);
for(const point of points)ctx.lineTo(...point);
ctx.strokeStyle=rgb(color);ctx.lineWidth=2;ctx.lineJoin='miter';ctx.stroke();ctx.restore();
return;
}
// Older hosts use a perimeter sweep through the clipped page margins.
const points=[[w/2,0],[w,0],[w,h],[0,h],[0,0],[w/2,0]];
let left=clamp(amount)*2*(w+h), x=w/2, y=0;
ctx.beginPath(); ctx.moveTo(w/2,h/2); ctx.lineTo(x,y);
Expand Down
19 changes: 19 additions & 0 deletions plugins/visuals/tests/render.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,22 @@ it('draws bounded scenes at tiny and target sizes without non-finite coordinates
it('does not draw progress when no duration is known or progress is zero',()=>{
const ctx=context();drawProgress(ctx,438,259,null,[1,2,3]);drawProgress(ctx,438,259,0,[1,2,3]);expect(ctx.calls).toEqual([]);
});
it('traces the video border clockwise from its top-left by perimeter distance',()=>{
const rect={x:20,y:30,w:200,h:100};
for(const [amount,end] of [[1/6,[120,30]],[1/3,[220,30]],[.5,[220,130]],[2/3,[120,130]],[5/6,[20,130]],[1,[20,30]]]){
const ctx=context();drawProgress(ctx,400,240,amount,[1,2,3],rect);
expect(ctx.calls.find(c=>c[0]==='moveTo')).toEqual(['moveTo',20,30]);
expect(ctx.calls.filter(c=>c[0]==='lineTo').at(-1)).toEqual(['lineTo',...end]);
expect(ctx.calls.some(c=>c[0]==='stroke')).toBe(true);
expect(ctx.calls.some(c=>c[0]==='clip'||c[0]==='fillRect'||c[0]==='strokeRect')).toBe(false);
}
});
it('preserves the v0 page-margin sweep when the video rect is missing or unusable',()=>{
const fallback=context();drawProgress(fallback,400,240,.5,[1,2,3]);
expect(fallback.calls.find(c=>c[0]==='moveTo')).toEqual(['moveTo',200,120]);
expect(fallback.calls).toContainEqual(['strokeRect',2,2,396,236]);
expect(fallback.calls).toContainEqual(['clip']);
for(const rect of [null,{x:20,y:30,w:0,h:100},{x:NaN,y:30,w:200,h:100}]){
const ctx=context();drawProgress(ctx,400,240,.5,[1,2,3],rect);expect(ctx.calls).toEqual(fallback.calls);
}
});
17 changes: 17 additions & 0 deletions plugins/visuals/tests/surfaces.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,20 @@ it('starts fireplace audio off and closes when parked confirmation is lost',asyn
expect(e.host.surface.close).not.toHaveBeenCalled();
e.host.parked='unknown';e.callbacks.surface();expect(e.host.surface.close).toHaveBeenCalledOnce();
});
it('redraws the progress border with current video coordinates after resize and orientation updates',async()=>{
const e=environment();e.host.state.nowPlaying={title:'Track',artist:'Artist',album:'Album',durationMs:1000,elapsedMs:500,playing:false,rate:1};
const calls=[],gradient={addColorStop:vi.fn()};
const ctx=new Proxy({moveTo:(...p)=>calls.push(['moveTo',...p]),lineTo:(...p)=>calls.push(['lineTo',...p]),createRadialGradient:()=>gradient},{get:(t,k)=>t[k]??vi.fn()});
e.elements.canvas.getContext=()=>ctx;
e.host.surface.video={x:20,y:30,w:800,h:450};
await import('../ambient.js');
e.frames.shift()(1000);
expect(calls).toContainEqual(['moveTo',10,15]);expect(calls).toContainEqual(['lineTo',410,240]);
for(const [w,h,video] of [[1001,601,{x:40,y:60,w:900,h:500}],[601,1001,{x:10,y:20,w:580,h:950}]]){
calls.length=0;Object.assign(e.host.surface,{w,h,video});e.callbacks.surface();
await vi.advanceTimersByTimeAsync(250);e.frames.shift()(2000+h);
const sx=Math.round(w/2)/w,sy=Math.round(h/2)/h;
const start=calls.find(c=>c[0]==='moveTo');expect(start[1]).toBeCloseTo(video.x*sx);expect(start[2]).toBeCloseTo(video.y*sy);
const end=calls.filter(c=>c[0]==='lineTo').at(-1);expect(end[1]).toBeCloseTo((video.x+video.w)*sx);expect(end[2]).toBeCloseTo((video.y+video.h)*sy);
}
});
7 changes: 7 additions & 0 deletions tests/coordinates.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,10 @@ it('handles per-axis transforms and defaults invalid or absent geometry to scale
for(const scale of [undefined,{x:0,y:NaN},{x:-1,y:Infinity}])expect(layoutDelta({dx:40,dy:30},scale)).toEqual({dx:40,dy:30});
expect(frameScale({width:0,height:NaN},0,0)).toEqual({x:1,y:1});
});
it('recomputes deltas from cumulative pointer movement without compounding the scale',async()=>{
const {dragPosition}=await import('../host/layout.js');
const scale=frameScale({width:438,height:259},876,518),start={x:500,y:300};
expect(dragPosition(start,{dx:-30,dy:-20},scale)).toEqual({x:440,y:260});
expect(dragPosition(start,{dx:-60,dy:-40},scale)).toEqual({x:380,y:220});
expect(dragPosition(start,{dx:0,dy:0},scale)).toEqual(start);
});
8 changes: 8 additions & 0 deletions tests/drag.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,11 @@ it('measures the tolerance in local CSS pixels when the receiver is scaled',()=>
g.fire('pointermove',{screenX:104,clientX:28,clientY:30});expect(g.report).not.toHaveBeenCalled();
g.fire('pointermove',{screenX:104.5,clientX:29,clientY:30});expect(g.report).toHaveBeenLastCalledWith({phase:'move',dx:4.5,dy:0});g.off();
});
it('reports cumulative screen deltas when a scaled companion follows the pointer',()=>{
const g=gesture();g.fire('pointerdown',{clientX:20,clientY:30});
g.fire('pointermove',{screenX:120,screenY:210,clientX:60,clientY:50});
expect(g.report).toHaveBeenLastCalledWith({phase:'move',dx:20,dy:10});
g.fire('pointermove',{screenX:140,screenY:220,clientX:60,clientY:50});
expect(g.report).toHaveBeenLastCalledWith({phase:'move',dx:40,dy:20});
g.fire('pointerup');expect(g.report).toHaveBeenLastCalledWith({phase:'end',dx:40,dy:20});g.off();
});
28 changes: 27 additions & 1 deletion tests/host.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ it('moves only an active companion, throttles layout, persists and resets its fr
});
it('restores free positions without losing them to the pet startup anchor',async()=>{
const e=await environment({dock:{x:300,y:200,dragged:true},companions:{[`${manifest.id}/widget`]:{x:450,y:100,anchor:'bottom-left'}}});
e.launch();e.click('Show Pet');const frame=e.frames()[0];e.hello(frame);expect(frame.style.left).toBe('450px');
const frame=e.frames()[0];e.hello(frame);expect(frame.style.left).toBe('450px');
e.receive({oxp:'plugin/0',type:'surface-request',anchor:'bottom-left'},frame.contentWindow);expect(frame.style.left).toBe('450px');
e.receive({oxp:'plugin/0',type:'surface-request',anchor:'bottom-left'},frame.contentWindow);expect(frame.style.left).toBe('24px');
});
Expand Down Expand Up @@ -424,3 +424,29 @@ it.each([{w:880,h:518},{w:360,h:640}])('publishes the open launcher exemption at
e.click('关闭');
expect(e.messages.filter(m=>m.type==='layout').at(-1).launcher).toBeUndefined();
});

it('roundtrips active companions and their placements across a fresh host reload',async()=>{
const first=await environment();first.launch();first.click('Show Pet');const frame=first.frames()[0];first.hello(frame);
for(const [phase,dx,dy] of [['start',0,0],['end',320,100]])first.receive({oxp:'plugin/0',type:'surface-request',move:{phase,dx,dy}},frame.contentWindow);
const saved=first.messages.filter(m=>m.type==='host-prefs').at(-1).value;
vi.clearAllTimers();
const second=await environment(saved);
expect(second.frames()).toHaveLength(1);expect(second.frames()[0].style.left).toBe('344px');expect(second.frames()[0].style.top).toBe('124px');
expect(second.frames()[0].attributes.sandbox).toBe('allow-scripts');
});
it.each([
{surfaces:{'org.openxplay.fixture/widget':null}},
{surfaces:[]}, {surfaces:42}, {surfaces:'broken',companions:null},
{companions:{'org.openxplay.fixture/widget':null}},
{surfaces:{'org.gone/widget':{x:300,y:100}}}
])('ignores corrupt or uninstalled selections on startup: %j',async prefs=>{
const e=await environment(prefs);expect(e.frames()).toHaveLength(0);expect(e.elements.dock.children).toHaveLength(1);
});
it.each([.5,.75,1,1.5])('uses actual dock pointer coordinates at frame scale %s even with stale receiver geometry',async scale=>{
const e=await environment(undefined,{x:1,y:1}),button=e.elements.dock.children[0];
const event={pointerId:1,button:0,screenX:500,screenY:300,clientX:500/scale,clientY:300/scale,preventDefault:()=>{}};
button.listeners.pointerdown(event);
button.listeners.pointermove({...event,screenX:500-60*scale,screenY:300-40*scale,clientX:event.clientX-60,clientY:event.clientY-40});
button.listeners.pointerup(event);
expect(e.messages.filter(m=>m.type==='host-prefs').at(-1).value.dock).toEqual({x:672,y:398,dragged:true});
});
15 changes: 14 additions & 1 deletion tests/preferences.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import {it,expect} from 'vitest';
import {Policy} from '../host/policy.js';
import {pruneSurfaces,rememberSurfaces,restoreSurfaces} from '../host/preferences.js';
import {loadPreferences,pruneSurfaces,rememberSurfaces,restoreSurfaces} from '../host/preferences.js';
const surfaces=[{id:'cat',kind:'companion',usage:'driving',anchor:'top-left'},{id:'sky',kind:'ambient',usage:'driving'},{id:'panel',kind:'panel',usage:'driving'},{id:'parked',kind:'companion',usage:'parked'}];
const manifests=new Map([['org.pet',{surfaces}]]);
it('roundtrips anchored, free and ambient selections, excluding transient covers',()=>{
Expand All @@ -30,3 +30,16 @@ it('drops disabled, uninstalled, removed and nonpersistent surfaces and sanitize
expect(pruneSurfaces(saved,manifests,new Set(['org.pet']))).toEqual({});
const pending=new Set(Object.keys(saved));restoreSurfaces({},pending,manifests,new Policy(),0);expect(pending.size).toBe(0);
});
it('never restores a disabled plugin from pending selections',()=>{
const policy=new Policy();policy.disabled.add('org.pet');
const saved=pruneSurfaces({'org.pet/cat':{x:300,y:100}},manifests,policy.disabled),pending=new Set(['org.pet/cat']);
restoreSurfaces(saved,pending,manifests,policy,0);expect(policy.loaded).toEqual([]);expect(pending.size).toBe(0);
});
it('migrates legacy companions but honours an explicit selection map and ignores corrupt preferences',()=>{
const companions={'org.pet/cat':{x:300,y:100,anchor:'top-left'}};
expect(loadPreferences({companions}).surfaces).toEqual(companions);
expect(loadPreferences({companions,surfaces:{}}).surfaces).toEqual({});
for(const prefs of [undefined,null,[],42,'broken'])expect(loadPreferences(prefs)).toEqual({});
expect(loadPreferences({companions:null,surfaces:{'org.pet/cat':null}})).toEqual({companions:{},surfaces:{}});
expect(pruneSurfaces({'org.pet/cat/extra':{}},manifests,new Set())).toEqual({});
});
Loading