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
13 changes: 12 additions & 1 deletion packages/base/src/surface-api/instance.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { JsonObject, JsonValue } from '../common/json-value.js'
import type { CardGenerator } from './cards.js'
import type { SurfaceFirmwareUpdateCache, SurfaceFirmwareUpdateInfo } from './firmware.js'
import type { SurfaceDrawProps, SurfaceId } from './types.js'
import type { ControlId, SurfaceControlEvent, SurfaceDrawProps, SurfaceId } from './types.js'

export interface SurfaceInstance {
/**
Expand Down Expand Up @@ -37,6 +37,17 @@ export interface SurfaceInstance {
*/
ready(): Promise<void>

/**
* Show that Companion acted on physical input to a control, for example with a haptic click or a flash of the key.
* Only called for events listed in the `controlEvents` the surface registered.
*
* How to show it is up to the surface, and a surface that can only signal for the whole device may ignore the controlId.
* This is best-effort: the host does not wait for or retry it, and resolving does not confirm the user noticed.
* @param controlId The control the input came from
* @param event What happened. Ignore any event that isn't recognised, as more may be added later
*/
controlEvent?(controlId: ControlId, event: SurfaceControlEvent): Promise<void>

// updateCapabilities(capabilities: ClientCapabilities): void

/**
Expand Down
16 changes: 16 additions & 0 deletions packages/base/src/surface-api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@ export interface HIDDevice {
export type SurfaceId = string
export type ControlId = string

/**
* Something Companion did in response to physical input on a control, which a surface may choose to show.
* - `press`: a press of the control ran an action group, either on press or on release
* - `hold`: an action group set to run while the control is held has fired, while it is still held
*
* More events may be added in future, so surfaces should ignore any they don't recognise.
*/
export type SurfaceControlEvent = 'press' | 'hold'

/**
* Definition of a varaible produced by a surface
*/
Expand Down Expand Up @@ -55,6 +64,13 @@ export interface SurfaceRegisterProps {
* Whether the surface supports setting brightness
*/
brightness: boolean
/**
* The control events this opened surface can show, such as a press running actions.
* Only events in this list are sent to the surface.
*
* Omitted or empty means none. When non-empty, the SurfaceInstance must also implement controlEvent.
*/
controlEvents?: SurfaceControlEvent[]
/**
* The definition of the controls on the surface and the properties needed for drawing
*/
Expand Down
177 changes: 177 additions & 0 deletions packages/host/src/__tests__/plugin.controlEvent.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import { describe, expect, it, vi } from 'vitest'
import { mock } from 'vitest-mock-extended'
import { PluginWrapper } from '../plugin.js'
import type { SurfaceHostContext } from '../context.js'
import type {
HIDDevice,
SurfaceControlEvent,
SurfaceInstance,
SurfacePlugin,
SurfaceRegisterProps,
SurfaceSchemaLayoutDefinition,
} from '@companion-surface/base'

type ControlEventFn = (controlId: string, event: SurfaceControlEvent) => Promise<void>

function validLayout(): SurfaceSchemaLayoutDefinition {
return {
stylePresets: { default: { bitmap: { w: 72, h: 72 } } },
controls: {
'0/0': { row: 0, column: 0 },
'0/1': { row: 0, column: 1 },
},
}
}

function makeSurface(controlEvent?: ControlEventFn): SurfaceInstance {
const surface = mock<SurfaceInstance>()
surface.init.mockResolvedValue(undefined)
surface.close.mockResolvedValue(undefined)
surface.ready.mockResolvedValue(undefined)
surface.controlEvent = controlEvent
return surface
}

function registerProps(controlEvents?: SurfaceControlEvent[]): SurfaceRegisterProps {
return {
brightness: false,
...(controlEvents === undefined ? {} : { controlEvents }),
surfaceLayout: validLayout(),
pincodeMap: { type: 'custom' },
location: null,
configFields: null,
}
}

function makePlugin(...opens: Array<{ surface: SurfaceInstance; props: SurfaceRegisterProps }>) {
const plugin = mock<SurfacePlugin<unknown>>()
plugin.detection = undefined
plugin.checkSupportsHidDevice.mockReturnValue({
surfaceId: 'test-surface',
description: 'Test Surface',
pluginInfo: {},
})
for (const { surface, props } of opens) {
plugin.openSurface.mockResolvedValueOnce({ surface, registerProps: props })
}
return new PluginWrapper(mock<SurfaceHostContext>(), plugin)
}

async function open(wrapper: PluginWrapper<unknown>) {
const result = await wrapper.openHidDevice(mock<HIDDevice>(), 'test-surface')
expect(result).not.toBeNull()
return result!
}

async function openReady(controlEvent: ControlEventFn) {
const wrapper = makePlugin({ surface: makeSurface(controlEvent), props: registerProps(['press', 'hold']) })
const result = await open(wrapper)
await wrapper.readySurface('test-surface', {})
return { wrapper, connectionId: result.controlEvents!.connectionId }
}

describe('PluginWrapper control events', () => {
it('keeps legacy and capability-method-mismatched surfaces unsupported', async () => {
const legacyResult = await open(makePlugin({ surface: makeSurface(), props: registerProps() }))
expect(legacyResult.controlEvents).toBeUndefined()

const methodOnly = vi.fn<ControlEventFn>().mockResolvedValue(undefined)
const methodOnlyResult = await open(makePlugin({ surface: makeSurface(methodOnly), props: registerProps() }))
expect(methodOnlyResult.controlEvents).toBeUndefined()

const capabilityOnlyResult = await open(
makePlugin({ surface: makeSurface(), props: registerProps(['press', 'hold']) }),
)
expect(capabilityOnlyResult.controlEvents).toBeUndefined()

const emptyListResult = await open(makePlugin({ surface: makeSurface(methodOnly), props: registerProps([]) }))
expect(emptyListResult.controlEvents).toBeUndefined()
})

it('passes the control and event to a ready surface, and drops them before ready', async () => {
const controlEvent = vi.fn<ControlEventFn>().mockResolvedValue(undefined)
const wrapper = makePlugin({ surface: makeSurface(controlEvent), props: registerProps(['press', 'hold']) })
const result = await open(wrapper)
const connectionId = result.controlEvents?.connectionId
expect(connectionId).toEqual(expect.any(String))

await wrapper.controlEvent('test-surface', connectionId!, '0/1', 'press')
expect(controlEvent).not.toHaveBeenCalled()

await wrapper.readySurface('test-surface', {})
await wrapper.controlEvent('test-surface', connectionId!, '0/1', 'press')
await wrapper.controlEvent('test-surface', connectionId!, '0/0', 'hold')
expect(controlEvent.mock.calls).toEqual([
['0/1', 'press'],
['0/0', 'hold'],
])
})

it('only passes events the surface listed', async () => {
const controlEvent = vi.fn<ControlEventFn>().mockResolvedValue(undefined)
const wrapper = makePlugin({ surface: makeSurface(controlEvent), props: registerProps(['press']) })
const result = await open(wrapper)
await wrapper.readySurface('test-surface', {})

await wrapper.controlEvent('test-surface', result.controlEvents!.connectionId, '0/0', 'hold')
await wrapper.controlEvent('test-surface', result.controlEvents!.connectionId, '0/0', 'press')
expect(controlEvent.mock.calls).toEqual([['0/0', 'press']])
})

it('drops events for controls the surface does not have', async () => {
const controlEvent = vi.fn<ControlEventFn>().mockResolvedValue(undefined)
const { wrapper, connectionId } = await openReady(controlEvent)

await wrapper.controlEvent('test-surface', connectionId, '9/9', 'press')
await wrapper.controlEvent('test-surface', connectionId, '__proto__', 'press')
expect(controlEvent).not.toHaveBeenCalled()
})

it('drops events while the surface is locked', async () => {
const controlEvent = vi.fn<ControlEventFn>().mockResolvedValue(undefined)
const { wrapper, connectionId } = await openReady(controlEvent)

await wrapper.showLockedStatus('test-surface', true, 0, 0)
await wrapper.controlEvent('test-surface', connectionId, '0/0', 'press')
expect(controlEvent).not.toHaveBeenCalled()

await wrapper.showLockedStatus('test-surface', false, 0, 0)
await wrapper.controlEvent('test-surface', connectionId, '0/0', 'press')
expect(controlEvent).toHaveBeenCalledTimes(1)
})

it('contains a rejecting surface and drops events after close', async () => {
const controlEvent = vi.fn<ControlEventFn>().mockRejectedValue(new Error('device unavailable'))
const { wrapper, connectionId } = await openReady(controlEvent)

await expect(wrapper.controlEvent('test-surface', connectionId, '0/0', 'press')).resolves.toBeUndefined()
expect(controlEvent).toHaveBeenCalledTimes(1)

await wrapper.closeDevice('test-surface')
await wrapper.controlEvent('test-surface', connectionId, '0/0', 'press')
expect(controlEvent).toHaveBeenCalledTimes(1)
})

it('drops an old connection id after reopening the same surface id', async () => {
const oldEvent = vi.fn<ControlEventFn>().mockResolvedValue(undefined)
const newEvent = vi.fn<ControlEventFn>().mockResolvedValue(undefined)
const wrapper = makePlugin(
{ surface: makeSurface(oldEvent), props: registerProps(['press', 'hold']) },
{ surface: makeSurface(newEvent), props: registerProps(['press', 'hold']) },
)

const oldResult = await open(wrapper)
await wrapper.readySurface('test-surface', {})
await wrapper.closeDevice('test-surface')
const newResult = await open(wrapper)
await wrapper.readySurface('test-surface', {})

expect(newResult.controlEvents!.connectionId).not.toBe(oldResult.controlEvents!.connectionId)
await wrapper.controlEvent('test-surface', oldResult.controlEvents!.connectionId, '0/0', 'press')
expect(oldEvent).not.toHaveBeenCalled()
expect(newEvent).not.toHaveBeenCalled()

await wrapper.controlEvent('test-surface', newResult.controlEvents!.connectionId, '0/0', 'press')
expect(newEvent).toHaveBeenCalledTimes(1)
})
})
2 changes: 1 addition & 1 deletion packages/host/src/__tests__/surfaceProxy.leds.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ function makeProxy() {
configFields: null,
}

const proxy = new SurfaceProxy(host, context, surface, registerProps)
const proxy = new SurfaceProxy(host, context, surface, registerProps, undefined)
return { proxy, surface }
}

Expand Down
2 changes: 1 addition & 1 deletion packages/host/src/__tests__/surfaceProxy.rotate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ function makeContext() {

const context = new SurfaceProxyContext(host, 'surf1', vi.fn())
// The SurfaceProxy constructor registers itself with the context via storeSurface
new SurfaceProxy(host, context, surface, registerProps)
new SurfaceProxy(host, context, surface, registerProps, undefined)

return { context, inputRotate }
}
Expand Down
1 change: 1 addition & 0 deletions packages/host/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export {
SurfaceFirmwareUpdateInfo,
HIDDevice,
SurfaceDrawProps,
SurfaceControlEvent,
HostCapabilities,
GridSize,
SurfaceInputVariable,
Expand Down
40 changes: 38 additions & 2 deletions packages/host/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { SurfaceProxy, SurfaceProxyContext } from './surfaceProxy.js'
import { randomUUID } from 'node:crypto'
import {
createModuleLogger,
type RemoteSurfaceConnectionInfo,
type HIDDevice,
type OpenSurfaceResult,
type ControlId,
type SurfaceControlEvent,
type SurfaceDrawProps,
type SurfacePlugin,
DetectionSurfaceInfo,
Expand Down Expand Up @@ -353,8 +356,22 @@ export class PluginWrapper<TInfo = unknown> {
modelId = null
}

// Wrap the surface
const wrapped = new SurfaceProxy(this.#host, surfaceContext, surface.surface, surface.registerProps)
const wantsControlEvents = (surface.registerProps.controlEvents?.length ?? 0) > 0
const controlEventsSupported = wantsControlEvents && typeof surface.surface.controlEvent === 'function'
if (wantsControlEvents && !controlEventsSupported) {
this.#logger.warn(`Surface ${resolvedSurfaceId} registered control events without implementing controlEvent`)
}

// The connection id is deliberately per open, so a delayed event
// cannot reach a later instance with the same surface id.
const controlEventsConnectionId = controlEventsSupported ? randomUUID() : undefined
const wrapped = new SurfaceProxy(
this.#host,
surfaceContext,
surface.surface,
surface.registerProps,
controlEventsConnectionId,
)
this.#openSurfaces.set(resolvedSurfaceId, wrapped)

// Trigger a firmware update check
Expand All @@ -365,6 +382,7 @@ export class PluginWrapper<TInfo = unknown> {
surfaceId: resolvedSurfaceId,
description: description,
supportsBrightness: surface.registerProps.brightness,
controlEvents: controlEventsConnectionId ? { connectionId: controlEventsConnectionId } : undefined,
surfaceLayout: surface.registerProps.surfaceLayout,
surfaceAppearance,
modelId,
Expand Down Expand Up @@ -452,6 +470,24 @@ export class PluginWrapper<TInfo = unknown> {
this.#cleanupSurfaceById(surfaceId)
}

/**
* Tell a ready surface about an event on one of its controls.
*
* A stale, closed, unsupported or not-ready connection, or an unknown control, is a no-op.
* Resolving does not mean the surface showed anything.
*/
async controlEvent(
surfaceId: string,
connectionId: string,
controlId: ControlId,
event: SurfaceControlEvent,
): Promise<void> {
const surface = this.#openSurfaces.get(surfaceId)
if (!surface || surface.controlEventsConnectionId !== connectionId) return

await surface.controlEvent(connectionId, controlId, event)
}

async setBrightness(surfaceId: string, brightness: number): Promise<void> {
const surface = this.#openSurfaces.get(surfaceId)
if (!surface) throw new Error(`Surface with id ${surfaceId} is not opened`)
Expand Down
Loading
Loading