Compare commits

..
Author SHA1 Message Date
James Babcock e09f8eae96 Simplify glanceboard-trigger angle setting; fix incorrectly-rotated accelerometer readings on G1
The glanceboard head-tilt option was more complicated than necessary,
because it wanted the user to take two angle measurements, a baseline
angle and a tilt angle. That was a workaround to not knowing the
accelerometer's orientation/calibration, but actually, we do know those.

(Except, as it turns out, on the G1, the accelerometer orientation is
different than it is on the G2, and there was a bug where EvenHub apps
got their accelerometer readings in the wrong orientation. So for
example the EvenHub Level app didn't work correctly.)
2026-11-15 23:29:02 -08:00
James Babcock 37d81d0308 Merge branch 'main' into glanceboard-tilt-angle-and-glance-down 2026-11-15 22:38:39 -08:00
James Babcock 344e140e92 Configurable custom keybindings for bluetooth keyboards paired with the glasses 2026-11-15 22:21:12 -08:00
James Babcock fd3c26333f Add bluetooth keyboard support
G2 only: You can pair the glasses with a bluetooth keyboard. It will
relay key events, and you can use it to type in some apps and to
navigate the UI.
2026-11-15 01:54:54 -08:00
James Babcock 9372b2742c Multi-mic support and replay mode for Transcribe app 2026-11-12 21:54:57 -08:00
BrendenandClaude Opus 5.5 58626ce146 Glanceboard: Head tilt timeout setting
How long a head-tilt showing may last when no head-down arrives: 60 s
(the default, as before), 30, 15, 10 s, or never (it then stays until the
head comes down or a double-tap). Where the head-down is unlikely, the tap
duration still applies when it is shorter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 12:47:46 -08:00
BrendenandClaude Opus 5.5 b1ca8b8ca1 Glanceboard: address review of head-tilt angle and glance down
- A verification read that still disagrees no longer requeues the writes at
  once (which looped while the firmware refused the value); the next regular
  poll retries.
- "Glasses default" now writes back the glasses' own switch and angle, saved
  before Faceclaw first changed them (persisted across app restarts), and
  drops writes still queued. Disabling the Glanceboard does the same.
- "Set to current head angle" takes two readings, head level then tilted up,
  and uses the angle between them, so it no longer depends on the sensor's
  axes or folds past 45°. A head that did not move is reported, not stored
  as 5°. The math is in head-tilt-math.ts, with tests.
- A head-tilt that woke a suspended session, or a trigger under 25° (where a
  level gaze stays above the head-down threshold), hides after the tap
  duration instead of the 60 s cap. The setting's description explains it.
- The angle rows are hidden on iOS, which cannot change the setting.
- The capture row repaints while measuring, ignores repeat selects, and its
  status clears when the menu reopens or the angle changes; the angle is
  sent once, by the controller's settings listener.
- Comments describing a head-tilt as a timed press are updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 12:20:19 -08:00
BrendenandClaude Opus 5.5 cf74f34767 Glanceboard: configurable head-tilt angle, glance down to hide
- Head tilt angle setting (Glanceboard): sets the glasses' own head-up
  trigger through the stock settings message (g2_setting.proto
  DeviceReceiveInfoFromAPP.deviceReceiveHeadUpSetting), so detection stays
  on the glasses and nothing streams while the screen is off. The stored
  calibration is read back and compensated for, and the value is
  re-applied on every connect. "glasses" (the default) leaves the
  glasses' setting untouched.
- "Set to current head angle" measures the tilt from a ~1.2 s IMU burst
  and rounds it to the nearest 5 degrees.
- Glance down to hide: a head-tilt showing now stays up until the head comes back down
  (HEAD_DOWN, forwarded by Faceclaw/38) instead of a fixed timeout, with
  a 60 s safety cap. HEAD_DOWN goes only to the Glanceboard on Android
  and iOS, so it never counts as shell activity.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 08:58:33 -08:00
114 changed files with 9844 additions and 379 deletions

No files matched your search

+6
View File
@@ -23,6 +23,12 @@ and Mentra Labs, Inc. (MIT License): https://github.com/tetramo-labs/glassly and
https://github.com/tetramo-labs/glassly-rayneo-cfw. The iO wire codecs in
native/kotlin/shared/.../rayneo/RayNeoIoProtocol.kt follow their protocol work.
Bluetooth keyboard support on the G2 uses the keyboard bridge Tetramo, Inc. wrote
for their Glassly custom firmware (https://github.com/tetramo-labs/g2flash).
Faceclaw's client for it, in app/g2/keyboard/ and app/apps/terminal/terminal-keys.ts,
follows the reference client in that repository and the keyboard handling in the
Glassly app (MIT License): https://github.com/tetramo-labs/glassly.
iPhone notification icons are Pebble's notification and timeline icons, from
https://github.com/pebble-dev/iconography: the original Pebble Technology icons
and Rebble community additions. They are licensed under the Apache License 2.0;
@@ -290,6 +290,13 @@ class FaceclawBleCommunicator(context: Context, rightAddress: String?, leftAddre
/** See [GlassesSessionCore.getRingStatus]. */
fun getRingStatus(): String = core.getRingStatus()
/** See [GlassesSessionCore.setHeadUpTrigger]. */
fun setHeadUpTrigger(degrees: Int, originalSwitch: Int, originalAngle: Int) =
core.setHeadUpTrigger(degrees, originalSwitch, originalAngle)
/** See [GlassesSessionCore.getHeadUpStatus]. */
fun getHeadUpStatus(): String = core.getHeadUpStatus()
/** See [GlassesSessionCore.setGlassesRingLink]. */
fun setGlassesRingLink(action: String, fallbackAddress: String?, fallbackName: String?): Boolean =
core.setGlassesRingLink(action, fallbackAddress, fallbackName)
@@ -322,6 +329,13 @@ class FaceclawBleCommunicator(context: Context, rightAddress: String?, leftAddre
fun sendFaceclawMicControl(record: ByteArray?, label: String, rightTemple: Boolean, leftTemple: Boolean): Boolean =
core.sendFaceclawMicControl(record, label, rightTemple, leftTemple)
fun addKeyboardEventListener(listener: FaceclawKeyboardEventListener?) = core.addKeyboardEventListener(listener)
fun removeKeyboardEventListener(listener: FaceclawKeyboardEventListener?) = core.removeKeyboardEventListener(listener)
fun sendFaceclawKeyboardControl(record: ByteArray?, label: String): Boolean =
core.sendFaceclawKeyboardControl(record, label)
fun startG2AudioForwarding(listener: FaceclawAudioPacketListener?): Boolean = core.startG2AudioForwarding(listener)
fun stopG2AudioForwarding() = core.stopG2AudioForwarding()
@@ -114,6 +114,21 @@ class FaceclawVoiceController(context: Context) {
}
}
override fun micArrayLink(): MicArrayLink? {
val currentCommunicator = communicator ?: return null
return object : MicArrayLink {
override fun startForwarding(listener: FaceclawAudioPacketListener): Boolean =
currentCommunicator.startG2AudioForwarding(listener)
override fun stopForwarding() = currentCommunicator.stopG2AudioForwarding()
override fun isForwarding(): Boolean = currentCommunicator.isAudioCaptureActive()
override fun sendControl(record: ByteArray, label: String, rightTemple: Boolean, leftTemple: Boolean): Boolean =
currentCommunicator.sendFaceclawMicControl(record, label, rightTemple, leftTemple)
}
}
override fun createPacketDecoder(): AudioPacketDecoder =
if (communicator?.isRayNeoIo() == true) AndroidSpeechEngines.OpusDecoderAdapter()
else AndroidSpeechEngines.Lc3DecoderAdapter()
@@ -140,6 +155,11 @@ class FaceclawVoiceController(context: Context) {
private val session = VoiceCaptureSession(host)
// The recording of this controller's live captures (see startRecording). It outlives any one
// capture, and is only handed to the session while recording is enabled.
private var recording: MicRecordingWriter? = null
private var recordingEnabled = true
fun setListener(listener: FaceclawVoiceControllerListener?) {
session.setListener(listener)
}
@@ -201,6 +221,88 @@ class FaceclawVoiceController(context: Context) {
session.setBeamFilter(enabled, centerDeg, halfWidthDeg)
}
/**
* Capture glasses sessions from the temples' own microphones (the custom firmware's
* mic_control stream) instead of the stock mixed stream. [configureRecord] is the CONFIGURE
* record to arm both temples with; null goes back to the mixed stream. Must be set before
* {@link #start}.
*/
fun setMicArray(configureRecord: ByteArray?) {
session.setMicArray(configureRecord)
}
/**
* Have the next {@link #start} play the recording at [path] (a .mka file) from [startMs] in
* place of any microphone; null goes back to the microphones. Progress arrives through the
* listener's onReplay.
*/
fun setReplay(path: String?, startMs: Long) {
session.setReplay(path, startMs)
}
/** Continue the running replay from [positionMs] into its recording. */
fun seekReplay(positionMs: Long) {
session.seekReplay(positionMs)
}
fun setReplayPaused(paused: Boolean) {
session.setReplayPaused(paused)
}
/**
* Record live captures to a new Matroska audio file at [path], from now until
* {@link #stopRecording}, across however many captures run in between: every source's audio
* as it arrives, before any processing. [configJson] describes the capture and is stored in
* the file. Returns false when the file cannot be created.
*/
@Synchronized
fun startRecording(path: String, configJson: String?): Boolean {
stopRecording()
return try {
val parent = File(path).parentFile
if (parent != null && !parent.exists()) parent.mkdirs()
recording = MicRecordingWriter(openFileOutput(path), configJson, System.currentTimeMillis())
session.setRecorder(if (recordingEnabled) recording else null)
true
} catch (t: Throwable) {
Log.w(TAG, "could not create recording $path", t)
recording = null
false
}
}
/**
* Whether captures are written to the recording right now: off while the capture running
* isn't one that is to be recorded.
*/
@Synchronized
fun setRecordingEnabled(enabled: Boolean) {
recordingEnabled = enabled
session.setRecorder(if (enabled) recording else null)
}
/** Whether a recording is open and still being written (false once writing to it failed). */
@Synchronized
fun isRecording(): Boolean = recording?.failed == false
/**
* Note a change in what is being captured (a JSON object) at the recording's current
* position; the audio after it is placed afresh on the recording's timeline.
*/
@Synchronized
fun noteRecordingEvent(json: String) {
recording?.event(json)
}
/** Complete the recording's file. Returns its length in ms, or -1 when none was open. */
@Synchronized
fun stopRecording(): Long {
val current = recording ?: return -1
recording = null
session.setRecorder(null)
return current.finish()
}
fun start(requestedMode: String?) {
session.start(requestedMode, 0)
}
+6 -1
View File
@@ -55,8 +55,10 @@ export type GlanceboardProvider = {
isEnabled: () => boolean;
/** Whether a single tap shows the board (for tapTimeoutMs). */
showOnTap: () => boolean;
/** How long a tap or head-tilt keeps the board up. */
/** How long a tap keeps the board up (and a head-tilt, when its head-down is unlikely to come). */
tapTimeoutMs: () => number;
/** How long a head-tilt showing may last without a head-down (null = no limit). */
tiltTimeoutMs: () => number | null;
/** Whether a long-press holds the board up until released. */
showOnLongPress: () => boolean;
/** Whether the head-tilt wake goes to the board rather than the regular UI. */
@@ -187,6 +189,8 @@ export async function launchWorkerAppWindow(
matchExistingBy?: "appId" | "windowId";
/** Deliver watch swipes raw instead of the fallback (see WorkerWindowSpec). */
acceptsDirectional?: boolean;
/** Deliver hardware-keyboard keys as keys (see WorkerWindowSpec). */
acceptsKeys?: boolean;
},
): Promise<void> {
const existing = shell
@@ -207,6 +211,7 @@ export async function launchWorkerAppWindow(
icon: options.icon,
focus: true,
acceptsDirectional: options.acceptsDirectional,
acceptsKeys: options.acceptsKeys,
});
ctx.appendLog(`launched ${options.windowId}`);
}
+1
View File
@@ -312,6 +312,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
}
case "navigation-sensors":
case "text-input":
case "key":
case "tool-call":
break;
}
+5 -3
View File
@@ -1,7 +1,7 @@
import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/ui-fonts";
import { GrayImage } from "../../graphics/image";
import { clamp } from "../../util/numeric-util";
import { addImuListener, imuSourceLabel, setImuReportEnabled, type ImuReading } from "../../native/imu";
import { addImuListener, imuPitchDegrees, imuSourceLabel, setImuReportEnabled, type ImuReading } from "../../native/imu";
import { type InputEvent } from "../../ui/gestures";
import { Layer, type LayerContext } from "../../ui/layers";
import { shell } from "../../ui/shell/shell";
@@ -23,7 +23,8 @@ const BAR_RIGHT_INSET = 4;
/**
* Accelerometer demo: turns the IMU stream on while this page is visible (the
* Developer window is foregrounded and the screen is on), off otherwise, and
* shows the latest x/y/z reading with a simple per-axis bar.
* shows the latest x/y/z reading (Faceclaw's frame, imu-types.ts) with a
* simple per-axis bar, and the head's pitch.
*
* The IMU stream is experimental — the firmware may never populate it — so the
* page also reports how many samples have arrived.
@@ -92,7 +93,8 @@ export class AccelerometerDemoLayer implements Layer {
const bodyX = padding.left + BODY_INDENT;
image.drawText(small, padding.left, top, "Accelerometer", 220);
const status = this.enabled ? "IMU on" : "IMU off";
const pitch = this.reading ? `pitch ${Math.round(imuPitchDegrees(this.reading))}° ` : "";
const status = pitch + (this.enabled ? "IMU on" : "IMU off");
image.drawText(small, right - small.measureText(status), top, status, 150);
if (this.reading) {
+15 -1
View File
@@ -2,6 +2,7 @@ import { readTextFile, type DirectoryEntry } from "../../native/file-access";
import { isFontFile } from "../../native/font-files";
import { installFontFile, isFontInstalled } from "../../graphics/installed-fonts";
import { isDecodableImageFile } from "../../native/image-files";
import { isMicRecordingFile } from "../../native/mic-recording";
import { isPlayableVideoFile } from "../../native/video-player";
import { readEvenHubPackageManifest } from "../evenhub/installed-apps";
import { EvenHubPermissionDialogLayer } from "../evenhub/permission-dialog";
@@ -38,6 +39,8 @@ export type FilesAppOptions = InProcessAppOptions & {
openFontWindow: (title: string, path: string) => void;
/** Open a video file's player (settings panel first) as its own shell window. */
openVideoWindow: (title: string, path: string) => void;
/** Replay a recording (.mka) through Transcribe, in a window of its own. */
openRecordingInTranscribe: (title: string, path: string) => void;
};
/**
@@ -50,7 +53,7 @@ export function createFilesAppWindow(options: FilesAppOptions): InProcessWindow
const browser = new FileBrowserLayer({
isSupportedFile: (name) =>
TEXT_FILE.test(name) || isFontFile(name) || EHPK_FILE.test(name) ||
(!global.isIOS && (isDecodableImageFile(name) || isPlayableVideoFile(name))),
(!global.isIOS && (isDecodableImageFile(name) || isPlayableVideoFile(name) || isMicRecordingFile(name))),
// The browser handles double-click itself (up a level), so it is not
// wrapped in YieldAtRootLayer; it yields explicitly from the top level.
onLeave: () => shell.yieldFocusToSidebar(),
@@ -235,6 +238,17 @@ function fileOpenActions(entry: DirectoryEntry, options: FilesAppOptions): FileI
},
];
}
if (isMicRecordingFile(entry.name)) {
return [
{
label: "Open in Transcribe",
onSelect: (ctx) => {
ctx.stack.pop();
options.openRecordingInTranscribe(entry.name, entry.path);
},
},
];
}
if (isPlayableVideoFile(entry.name)) {
return [
{
+4
View File
@@ -14,6 +14,7 @@ import {
FILES_WINDOW_ID,
} from "./files-app";
import { createVideoPlayerWindow } from "./video-window";
import { openRecordingInTranscribe } from "../transcribe";
// Document windows are closeable and non-singleton; the serial keeps their
// windowIds unique.
@@ -91,6 +92,9 @@ const filesApp: AppDefinition = {
},
openFontWindow: (title, path) => openFontDocumentWindow(ctx, title, path),
openVideoWindow: (title, path) => openVideoWindow(ctx, title, path),
openRecordingInTranscribe: (title, path) => {
openRecordingInTranscribe(ctx, path, title);
},
}),
),
// A document arriving via Android's Share intent opens as its own window.
+1
View File
@@ -305,6 +305,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
break;
case "navigation-sensors":
case "text-input":
case "key":
case "tool-call":
break;
}
+1
View File
@@ -236,6 +236,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
case "navigation-sensors":
case "screen":
case "text-input":
case "key":
case "tool-call":
break;
}
+13
View File
@@ -6,6 +6,8 @@ import { uiFontOverridePickerMenuItem } from "../../ui/font-picker";
import { type InputEvent } from "../../ui/gestures";
import { type Layer, type LayerContext } from "../../ui/layers";
import { drawSelectionHighlight, isMenuItemDisabled, MenuLayer, openModalMenu, submenuItem, type MenuItem } from "../../ui/menu";
import { liveHeadPitchFooter } from "../../g2/head-angle";
import { headUpControlsAvailable } from "../../native/glasses-controls";
import { Menu } from "../../ui/menu-core";
import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "../../ui/metrics";
import { createInProcessWindow, type InProcessAppOptions, type InProcessWindow } from "../../ui/shell/in-process-window";
@@ -20,7 +22,9 @@ import {
glanceLayout,
glanceLayoutSetting,
glanceShowLinesSetting,
glanceAngleSetting,
glanceShowOnHeadTiltSetting,
glanceTiltTimeoutSetting,
glanceShowOnLongPressSetting,
glanceSlotChoiceLabel,
glanceSlotSettings,
@@ -329,6 +333,15 @@ function openGlanceSettings(ctx: LayerContext): void {
enumSettingMenuItem(glanceTapDurationSetting),
toggleSettingMenuItem(glanceShowOnLongPressSetting),
toggleSettingMenuItem(glanceShowOnHeadTiltSetting),
enumSettingMenuItem(glanceTiltTimeoutSetting),
// Only Android can change the glasses' head-up setting (glasses-controls.ts).
// The controller's settings listener sends a new angle to the glasses; the
// picker shows the head's current angle to choose by.
...(headUpControlsAvailable()
? [enumSettingMenuItem(glanceAngleSetting, {
pickerFooter: liveHeadPitchFooter(() => shell.isWindowVisible(GLANCEBOARD_WINDOW_ID)),
})]
: []),
toggleSettingMenuItem(glanceShowLinesSetting),
uiFontOverridePickerMenuItem(glanceFont, {
title: "Glanceboard font",
+66 -8
View File
@@ -49,8 +49,9 @@ export function glanceLayout(): GlanceLayout {
/**
* Whether sleep-time gestures show the board at all. Off restores the plain
* behaviour: a tap, hold or head-tilt while asleep does nothing (a head-tilt
* wakes the regular UI), double-tap wakes.
* behaviour: a tap or hold while asleep does nothing, a head-tilt wakes the
* regular UI, double-tap wakes; and the head-up angle goes back to the glasses'
* own.
*/
export const glanceboardEnabledSetting = new ConfigSettingBoolean({
id: "glanceboard-enabled",
@@ -85,9 +86,10 @@ function formatTapDuration(value: GlanceTapDuration): string {
}
/**
* How long a tap (or head-tilt) keeps the board up; each further tap restarts
* it. "off" means a single tap does not show the board at all; a head-tilt
* then uses the default duration.
* How long a tap keeps the board up; each further tap restarts it. "off"
* means a single tap does not show the board at all. A head-tilt showing
* lasts until the head comes back down, falling back to this duration (the
* default one when "off") where the head-down is unlikely to arrive.
*/
export const glanceTapDurationSetting = new ConfigSettingEnum<GlanceTapDuration>({
id: "glanceboard-tap-duration",
@@ -97,7 +99,7 @@ export const glanceTapDurationSetting = new ConfigSettingEnum<GlanceTapDuration>
values: TAP_DURATION_VALUES,
formatValue: formatTapDuration,
description:
"How long a single tap (or a head-tilt) keeps the Glanceboard on screen. Disabled: a single tap does not show the Glanceboard.",
"How long a single tap keeps the Glanceboard on screen. Disabled: a single tap does not show the Glanceboard.",
});
/** Whether a single tap while asleep shows the board. */
@@ -119,15 +121,71 @@ export const glanceShowOnLongPressSetting = new ConfigSettingBoolean({
description: "A long-press or short-then-long-press while asleep shows the Glanceboard until the press is released.",
});
/** The head-tilt wake shows the board (for the tap duration) instead of the regular UI. */
/** The head-tilt wake shows the board (until the head comes back down) instead of the regular UI. */
export const glanceShowOnHeadTiltSetting = new ConfigSettingBoolean({
id: "glanceboard-show-on-head-tilt",
label: "Show on head tilt",
storageKey: "glanceboard.showOnHeadTilt",
defaultValue: true,
description: "Tilting your head up while asleep shows the Glanceboard instead of waking the regular UI.",
description: "Tilting your head up while asleep shows the Glanceboard instead of waking the regular UI. It stays up until you look back down.",
});
export type GlanceTiltTimeout = "60s" | "30s" | "15s" | "10s" | "never";
/**
* How long a head-tilt showing may last if the head-down never comes (the
* board normally hides when the head comes back down). "never" removes the
* limit; a double-tap still dismisses the board.
*/
export const glanceTiltTimeoutSetting = new ConfigSettingEnum<GlanceTiltTimeout>({
id: "glanceboard-head-tilt-timeout",
label: "Head tilt timeout",
storageKey: "glanceboard.headTiltTimeout",
defaultValue: "60s",
values: ["60s", "30s", "15s", "10s", "never"],
formatValue: (value) => (value === "never" ? "Never" : value.replace("s", " s")),
description:
"The longest a head-tilt keeps the Glanceboard up when looking back down is not detected. Never: it stays until you look down or double-tap. " +
"When looking down is unlikely to register (a low Head tilt angle, or the display was suspended), the tap duration applies if shorter.",
});
/** The Head tilt timeout in ms, or null for none. */
export function glanceTiltTimeoutMs(): number | null {
const value = glanceTiltTimeoutSetting.get();
return value === "never" ? null : Number.parseInt(value, 10) * 1000;
}
const GLANCE_ANGLE_VALUES = ["glasses", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60"] as const;
export type GlanceAngle = (typeof GLANCE_ANGLE_VALUES)[number];
/**
* How far the head must tilt up for a head-tilt wake, as the glasses' own
* pitch reading (degrees). "glasses" keeps the glasses' own setting (from the
* Even app), writing back their original values if Faceclaw changed them. A
* number is written to the glasses' head-up setting on every connection while
* the Glanceboard is enabled (head-angle.ts). Android only.
*/
export const glanceAngleSetting = new ConfigSettingEnum<GlanceAngle>({
id: "glanceboard-head-tilt-angle",
label: "Head tilt angle",
storageKey: "glanceboard.headTiltAngle",
defaultValue: "glasses",
values: GLANCE_ANGLE_VALUES,
formatValue: (value) => (value === "glasses" ? "Glasses default" : `${value}°`),
description:
"How far you tilt your head up to wake the display; the list shows your head's angle now. Glasses default uses the glasses' own setting from the Even app. " +
"The board hides when your head drops 20° below this angle; under 25°, looking straight ahead may not count, so it hides after the tap duration instead.",
});
/**
* The trigger Faceclaw should maintain, in degrees: the Head tilt angle while
* the Glanceboard is enabled, else 0 (the glasses' own setting).
*/
export function glanceAngleTriggerDegrees(): number {
const value = glanceAngleSetting.get();
return value === "glasses" || !glanceboardEnabledSetting.get() ? 0 : Number(value);
}
const DEPTH_VALUES = ["-64", "-48", "-32", "-16", "0", "16", "32", "48", "64"] as const;
export type GlanceDepth = (typeof DEPTH_VALUES)[number];
+2
View File
@@ -9,6 +9,7 @@ import {
glanceShowOnLongPressSetting,
glanceShowOnTap,
glanceTapTimeoutMs,
glanceTiltTimeoutMs,
} from "./glanceboard-settings";
const glanceboardApp: AppDefinition = {
@@ -24,6 +25,7 @@ const glanceboardApp: AppDefinition = {
isEnabled: () => glanceboardEnabledSetting.get(),
showOnTap: glanceShowOnTap,
tapTimeoutMs: glanceTapTimeoutMs,
tiltTimeoutMs: glanceTiltTimeoutMs,
showOnLongPress: () => glanceShowOnLongPressSetting.get(),
showOnHeadTilt: () => glanceShowOnHeadTiltSetting.get(),
depth: glanceDepth,
+21
View File
@@ -56,6 +56,27 @@ export function saveMicConfig(config: MicConfig): void {
setStringSetting(CONFIG_SETTING_KEY, JSON.stringify(config));
}
/**
* The configuration a capture of the temples' own microphones arms them
* with: `mics` of 2 is one microphone per temple (the front one), 4 is both
* of each. The front end and direction detection follow Microphone setup
* (the Microphones app), except that both of a temple's microphones only
* come through the codec front end. Always raw PCM16 at 16 kHz, which is
* what the firmware streams and transcription takes.
*/
export function micArrayCaptureConfig(mics: 2 | 4): MicConfig {
const base = loadMicConfig();
return {
...base,
source: mics === 4 ? "codec" : base.source,
channelMask: mics === 4 ? 0b11 : 0b01,
codec: "raw",
format: "pcm16",
sampleRateHz: 16_000,
armHardware: true,
};
}
class MicArrayController {
private readonly statusListeners = new Set<(statuses: MicArrayStatuses) => void>();
private statuses: MicArrayStatuses = { left: null, right: null };
@@ -272,6 +272,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
}
case "navigation-sensors":
case "text-input":
case "key":
case "tool-call":
break;
}
+3
View File
@@ -370,6 +370,9 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
frameTimings.logFrame(message.frameId, `input received in ${message.windowId} worker`);
handleInput(window, message.event as InputEvent, message.frameId);
break;
case "key":
// Only windows opened with acceptsKeys are sent keys.
break;
case "text-input":
if (editing) {
// Voice input as an alternative to the phone keyboard.
+1
View File
@@ -433,6 +433,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
}
case "navigation-sensors":
case "text-input":
case "key":
case "tool-call":
break;
}
+3
View File
@@ -227,6 +227,9 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
frameTimings.logFrame(message.frameId, `input received in ${message.windowId} worker`);
handleInput(window, message.event as InputEvent, message.frameId);
break;
case "key":
// Only windows opened with acceptsKeys are sent keys.
break;
case "text-input":
if (editingSetting) {
// Voice input as an alternative to the phone keyboard.
+3
View File
@@ -424,6 +424,9 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
frameTimings.logFrame(message.frameId, `input received in ${message.windowId} worker`);
handleInput(window, message.event as InputEvent, message.frameId);
break;
case "key":
// Only windows opened with acceptsKeys are sent keys.
break;
case "text-input":
if (window && window.windowId === message.windowId) handleTextInput(message.text.trim());
break;
+2
View File
@@ -14,6 +14,8 @@ const terminalApp: AppDefinition = {
// Session windows stay independent: launching reopens the hub even
// while terminal sessions are open.
matchExistingBy: "windowId",
// The hub window can show a session too, so it takes keys like one.
acceptsKeys: true,
}),
};
+39
View File
@@ -55,6 +55,8 @@ import {
import * as frameTimings from "../../native/frame-timings";
import { getActiveDisplay } from "../../native/active-display";
import { GESTURE_DOUBLE_CLICK, type InputEvent } from "../../ui/gestures";
import type { KeyEvent } from "../../g2/keyboard/keys";
import { encodeTerminalKey, terminalScrollbackKey } from "./terminal-keys";
import { G2MirrorClient, type G2MirrorClientOptions, type G2MirrorSession, type G2MirrorState } from "../../native/g2mirror-client";
import { onSettingsStoreChanged } from "../../native/settings-store";
import { clamp } from "../../util/numeric-util";
@@ -435,6 +437,13 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
}
break;
}
case "key": {
const window = windows.get(message.windowId);
if (!window) break;
window.focused = message.focused;
handleKey(window, message.event as KeyEvent);
break;
}
case "render": {
const window = windows.get(message.windowId);
if (!window) break;
@@ -1260,6 +1269,35 @@ function handleInput(window: TerminalWindow, event: InputEvent, frameId: number)
frameTimings.finishFrame(frameId, "discarded: terminal view ignored input");
}
/**
* A key from a hardware keyboard (the glasses' keyboard bridge) that no
* keybinding claimed. A session with nothing over it gets the key as its
* terminal would: Escape and the arrows belong to the program, and the way
* out is Escape with Shift, Ctrl or Alt, which never arrives here (it is a
* built-in keybinding for "back"). Anywhere else (the hub's lists, an open
* menu) the key is handed back, to act as navigation.
*/
function handleKey(window: TerminalWindow, event: KeyEvent): void {
if (window.kind === "view" && !window.menu?.isOpen()) {
activeViewId = window.windowId;
const page = terminalScrollbackKey(event);
if (page !== null) {
handleViewScroll(window, page, 0);
return;
}
const bytes = encodeTerminalKey(event, window.emulator.applicationCursorKeys());
if (bytes === null) return;
// Typing follows the live screen, as in any terminal emulator.
if (window.scrollTop !== null) {
window.scrollTop = null;
scheduleRender(window);
}
window.client.sendInput(bytes);
return;
}
post({ type: "key-unhandled", windowId: window.windowId, event });
}
/** Top visible absolute line index when following the live bottom. */
function followTop(window: ViewWindow): number {
return window.historyNext + window.emulator.bufferLength() - window.gridRows;
@@ -1800,6 +1838,7 @@ function openViewWindow(control: ControlConnection, socket: string, label: strin
focus: true,
// Default to tall sessions; the app display setting can override this.
heightMode: "max",
acceptsKeys: true,
});
}
+5
View File
@@ -82,4 +82,9 @@ export class TerminalEmulator {
cursorCol(): number {
return this.term.buffer.active.cursorX;
}
/** DECCKM: the session asked for application cursor keys (ESC O A rather than ESC [ A). */
applicationCursorKeys(): boolean {
return this.term.modes.applicationCursorKeysMode;
}
}
+118
View File
@@ -0,0 +1,118 @@
/**
* What a terminal emulator sends for a key from a hardware keyboard, by the
* classic xterm conventions: Ctrl chords become control characters, Alt
* prefixes ESC, and modified cursor and function keys carry the xterm
* modifier parameter (1 + shift + 2*alt + 4*ctrl). Follows the Glassly
* Terminal miniapp's encoder (terminal/keys.ts, MIT).
* No platform imports: this runs under node in the tests.
*/
import type { KeyEvent } from "../../g2/keyboard/keys";
const ESC = "\x1b";
/** Keys xterm encodes as `ESC [ <n> ~`, with a modifier as `;m`. */
const TILDE_KEYS: Record<string, number> = {
Insert: 2,
Delete: 3,
PageUp: 5,
PageDown: 6,
F5: 15,
F6: 17,
F7: 18,
F8: 19,
F9: 20,
F10: 21,
F11: 23,
F12: 24,
};
/** Keys with a single-letter final byte: SS3 in application cursor mode, CSI otherwise. */
const LETTER_KEYS: Record<string, string> = {
ArrowUp: "A",
ArrowDown: "B",
ArrowRight: "C",
ArrowLeft: "D",
Home: "H",
End: "F",
};
/** F1-F4 are always SS3 (`ESC O P`), or CSI with a modifier. */
const SS3_KEYS: Record<string, string> = { F1: "P", F2: "Q", F3: "R", F4: "S" };
/** Ctrl with a punctuation or digit key, per xterm (^[ ^\ ^] ^^ ^_ ^? ^@). */
const CONTROL_PUNCTUATION: Record<string, string> = {
"[": "\x1b",
"\\": "\x1c",
"]": "\x1d",
"^": "\x1e",
"6": "\x1e",
"_": "\x1f",
"-": "\x1f",
"?": "\x7f",
"/": "\x7f",
"8": "\x7f",
"@": "\x00",
"2": "\x00",
};
/**
* The text to write to the terminal for one key event, or null when the key
* sends nothing: releases, bare modifiers, Meta chords, and keys a terminal
* has no bytes for (volume, media). `appCursor` is DECCKM, which the emulator
* tracks from the session's output.
*/
export function encodeTerminalKey(event: KeyEvent, appCursor: boolean): string | null {
if (event.phase !== "down") return null;
const { key, modifiers } = event;
if (modifiers.meta) return null;
const modifierParam = 1 + (modifiers.shift ? 1 : 0) + (modifiers.alt ? 2 : 0) + (modifiers.ctrl ? 4 : 0);
const modified = (prefix: string, final: string): string | null =>
modifierParam > 1 ? `${ESC}[${prefix};${modifierParam}${final}` : null;
switch (key) {
case "Enter":
return modifiers.alt ? `${ESC}\r` : "\r";
case "Escape":
return ESC;
case "Tab":
return modifiers.shift ? `${ESC}[Z` : "\t";
case "Backspace":
if (modifiers.alt) return `${ESC}\x7f`;
return modifiers.ctrl ? "\x08" : "\x7f";
case " ":
return modifiers.ctrl ? "\x00" : modifiers.alt ? `${ESC} ` : " ";
}
const letter = LETTER_KEYS[key];
if (letter) return modified("1", letter) ?? (appCursor ? `${ESC}O${letter}` : `${ESC}[${letter}`);
const tilde = TILDE_KEYS[key];
if (tilde) return modified(String(tilde), "~") ?? `${ESC}[${tilde}~`;
const ss3 = SS3_KEYS[key];
if (ss3) return modified("1", ss3) ?? `${ESC}O${ss3}`;
if (modifiers.ctrl) {
// From the unshifted key: ^A..^Z, then the punctuation set.
const base = key.length === 1 ? key.toLowerCase() : "";
let char: string | undefined;
if (base >= "a" && base <= "z") char = String.fromCharCode(base.charCodeAt(0) - 96);
else char = CONTROL_PUNCTUATION[key];
if (char === undefined) return null;
return modifiers.alt ? `${ESC}${char}` : char;
}
// With Alt held the translator leaves `text` out (it is a chord, not
// typing); a terminal still wants ESC and the character.
const text = event.text ?? (modifiers.alt && key.length === 1 ? key : undefined);
if (text === undefined) return null;
return modifiers.alt ? `${ESC}${text}` : text;
}
/** Shift+PageUp / Shift+PageDown page the emulator's own scrollback, as in xterm. */
export function terminalScrollbackKey(event: KeyEvent): -1 | 1 | null {
if (event.phase !== "down") return null;
const { shift, ctrl, alt, meta } = event.modifiers;
if (!shift || ctrl || alt || meta) return null;
if (event.key === "PageUp") return -1;
if (event.key === "PageDown") return 1;
return null;
}
+29 -2
View File
@@ -1,5 +1,32 @@
import { type AppDefinition } from "../app-definition";
import { createTranscribeAppWindow, TRANSCRIBE_SURFACE_ID, TRANSCRIBE_WINDOW_ID } from "./transcribe-app";
import { type AppContext, type AppDefinition } from "../app-definition";
import {
createTranscribeAppWindow,
createTranscribeReplayWindow,
TRANSCRIBE_SURFACE_ID,
TRANSCRIBE_WINDOW_ID,
} from "./transcribe-app";
// Replay windows are closeable and non-singleton; the serial keeps their windowIds unique.
let nextReplaySerial = 1;
/**
* Open a recording (.mka) in Transcribe's replay mode, as a window of its
* own. Returns false where recordings can't be replayed.
*/
export function openRecordingInTranscribe(ctx: AppContext, path: string, name: string): boolean {
if (!ctx.actions.openVoiceReplay) return false;
const windowId = `transcribe:replay:${nextReplaySerial++}`;
void ctx
.launchInProcessApp(windowId, `window:${windowId}`, (options) => {
const window = createTranscribeReplayWindow(windowId, path, name, options);
if (!window) throw new Error("recordings can't be replayed here");
return window;
})
.catch((error) => {
ctx.appendLog(`transcribe replay window failed: ${error}`);
});
return true;
}
const transcribeApp: AppDefinition = {
appId: "transcribe",
+23
View File
@@ -0,0 +1,23 @@
/** A position in a recording as m:ss, or h:mm:ss from an hour on (or when `withHours`). */
export function formatReplayTime(ms: number, withHours = false): string {
const total = Math.max(0, Math.floor(ms / 1000));
const hours = Math.floor(total / 3600);
const minutes = Math.floor((total % 3600) / 60);
const seconds = String(total % 60).padStart(2, "0");
if (hours === 0 && !withHours) return `${minutes}:${seconds}`;
return `${hours}:${String(minutes).padStart(2, "0")}:${seconds}`;
}
/** The time picker's fields, in display and click order. */
export const TIME_FIELDS = ["hours", "minutes", "seconds"] as const;
export type TimeField = (typeof TIME_FIELDS)[number];
const FIELD_SECONDS: Record<TimeField, number> = { hours: 3600, minutes: 60, seconds: 1 };
/**
* Step a position (whole seconds) by `delta` of a field's unit, carrying
* into the neighboring fields, within [0, maxSeconds].
*/
export function stepReplaySeconds(seconds: number, field: TimeField, delta: number, maxSeconds: number): number {
return Math.max(0, Math.min(maxSeconds, seconds + delta * FIELD_SECONDS[field]));
}
+147
View File
@@ -0,0 +1,147 @@
import { GrayImage } from "../../graphics/image";
import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/ui-fonts";
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL, gestureHints, type InputEvent } from "../../ui/gestures";
import type { Layer, LayerContext, PaintBelow } from "../../ui/layers";
import { CONTEXT_MENU_DIM } from "../../ui/menu";
import { centeredTextY } from "../../ui/metrics";
import { formatReplayTime, stepReplaySeconds, TIME_FIELDS, type TimeField } from "./replay-time";
const PADDING = 12;
const FIELD_GAP = 6;
const FIELD_PAD_X = 6;
/** Fill and outline of the active field (the Timers and date pickers' field style). */
const ACTIVE_FILL = 35;
const ACTIVE_STROKE = 130;
export type TimePickerOptions = {
title: string;
/** Where the picker starts, and the furthest it goes, in ms. */
initialMs: number;
maxMs: number;
onPick: (positionMs: number) => void;
};
/**
* A modal position picker for a recording: hours (when the recording has
* any), minutes and seconds, over the dimmed content beneath. Input follows
* the date picker's: scroll adjusts the active field (up is later, carrying
* into the fields beside it), click moves to the next field and on the last
* one picks, double-click steps back a field and on the first one cancels.
* A watch's swipes move between fields and adjust.
*/
export class TimePickerLayer implements Layer {
readonly acceptsDirectional = true;
readonly dimUnderneath = CONTEXT_MENU_DIM;
private readonly fields: readonly TimeField[];
private readonly maxSeconds: number;
private seconds: number;
private field = 0;
constructor(private readonly options: TimePickerOptions) {
this.maxSeconds = Math.max(0, Math.floor(options.maxMs / 1000));
this.seconds = Math.max(0, Math.min(this.maxSeconds, Math.floor(options.initialMs / 1000)));
this.fields = this.maxSeconds >= 3600 ? TIME_FIELDS : TIME_FIELDS.slice(1);
}
handleInput(event: InputEvent, ctx: LayerContext): void {
switch (event.type) {
case "scroll-up":
case "swipe-up":
this.adjust(1);
return;
case "scroll-down":
case "swipe-down":
this.adjust(-1);
return;
case "swipe-right":
this.field = Math.min(this.fields.length - 1, this.field + 1);
return;
case "swipe-left":
this.field = Math.max(0, this.field - 1);
return;
case "click":
if (this.field < this.fields.length - 1) {
this.field++;
} else {
ctx.stack.pop();
this.options.onPick(this.seconds * 1000);
}
return;
case "double-click":
if (this.field > 0) this.field--;
else ctx.stack.pop();
return;
default:
return;
}
}
private adjust(delta: number): void {
this.seconds = stepReplaySeconds(this.seconds, this.fields[this.field]!, delta, this.maxSeconds);
}
private hints(field: number): string {
return gestureHints([
[GESTURE_SCROLL, "adjust"],
[GESTURE_CLICK, field < this.fields.length - 1 ? "next" : "jump"],
[GESTURE_DOUBLE_CLICK, field > 0 ? "back" : "cancel"],
]);
}
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
const image = paintBelow();
const small = getDefaultSmallFont();
const medium = getDefaultMediumFont();
const focused = ctx.stack.isFocused();
const base = ctx.stack.getBaseSize();
const values = [
String(Math.floor(this.seconds / 3600)),
String(Math.floor((this.seconds % 3600) / 60)).padStart(this.fields.length === 3 ? 2 : 1, "0"),
String(this.seconds % 60).padStart(2, "0"),
].slice(TIME_FIELDS.length - this.fields.length);
// Sized for the widest value a field can show, so the dialog holds still while the time changes.
const fieldWidths = this.fields.map(
(field) => Math.max(medium.measureText("000"), small.measureText(field)) + 2 * FIELD_PAD_X,
);
const fieldsWidth = fieldWidths.reduce((sum, width) => sum + width, 0) + FIELD_GAP * (fieldWidths.length - 1);
const boxHeight = medium.lineHeight + 6;
const length = `of ${formatReplayTime(this.maxSeconds * 1000)}`;
const hintsWidth = Math.max(...this.fields.map((_, index) => small.measureText(this.hints(index))));
const width = Math.min(
base.width,
Math.max(fieldsWidth, hintsWidth, small.measureText(this.options.title), small.measureText(length)) + 2 * PADDING,
);
const titleHeight = small.lineHeight + 12;
const bodyHeight = boxHeight + 2 + small.lineHeight + 10 + small.lineHeight;
const height = Math.min(base.height, 8 + titleHeight + bodyHeight + 12 + small.lineHeight + 10);
const x = Math.max(0, Math.floor((base.width - width) / 2));
const y = Math.max(0, Math.floor((base.height - height) / 2));
// Fill 1, not 0: 0 is the transparent color key on the shell surface.
image.fillRoundedRect(x, y, width, height, 1);
image.drawRoundedRect(x, y, width, height, 72);
image.drawText(small, x + PADDING, y + 8, this.options.title, 220);
const top = y + 8 + titleHeight;
let fieldX = x + PADDING;
for (let index = 0; index < this.fields.length; index++) {
const fieldWidth = fieldWidths[index]!;
const active = index === this.field;
if (active) {
if (focused) image.fillRoundedRect(fieldX, top, fieldWidth, boxHeight, ACTIVE_FILL, 6);
image.drawRoundedRect(fieldX, top, fieldWidth, boxHeight, ACTIVE_STROKE, 6);
}
const value = values[index]!;
image.drawText(medium, fieldX + Math.floor((fieldWidth - medium.measureText(value)) / 2),
centeredTextY(medium, top, boxHeight), value, active ? 250 : 170);
const caption = this.fields[index]!;
image.drawText(small, fieldX + Math.floor((fieldWidth - small.measureText(caption)) / 2),
top + boxHeight + 2, caption, active ? 190 : 110);
fieldX += fieldWidth + FIELD_GAP;
}
image.drawText(small, x + PADDING, top + bodyHeight - small.lineHeight, length, 190);
image.drawText(small, x + PADDING, y + height - 10 - small.lineHeight, this.hints(this.field), 110);
return image;
}
}
+101 -4
View File
@@ -1,8 +1,11 @@
import { imageFromAsciiArt, type GrayImage } from "../../graphics/image";
import { voiceControlBridge } from "../../native/voice-control";
import { saveRecordingSetting, toggleSettingMenuItem } from "../../ui/dashboard-settings";
import { enumSettingMenuItem, saveRecordingSetting, toggleSettingMenuItem } from "../../ui/dashboard-settings";
import { type ContinuousCaptureOptions } from "../../ui/layers";
import { withRecordingIcon } from "../../ui/listening-header";
import { TimePickerLayer } from "./time-picker";
import { TranscribeLayer, transcriptTimestamp } from "./transcribe";
import { transcribeMicCount, transcribeMicsSetting } from "./transcribe-settings";
import {
createInProcessWindow,
YieldAtRootLayer,
@@ -45,8 +48,8 @@ export function micTrayIcon(recording: boolean): GrayImage {
}
export type TranscribeAppOptions = InProcessAppOptions & {
/** Begin continuous mic capture (kept on while the window is open). */
startContinuousVoiceCapture: (options?: { recordAs?: string }) => void;
/** Begin (or retarget) continuous mic capture, kept on while the window is open. */
startContinuousVoiceCapture: (options?: ContinuousCaptureOptions) => void;
stopContinuousVoiceCapture: () => void;
};
@@ -59,6 +62,10 @@ export function createTranscribeAppWindow(options: TranscribeAppOptions): InProc
// One timestamp per session names both the audio recording and a saved transcript.
const stamp = transcriptTimestamp();
const layer = new TranscribeLayer(stamp);
// At launch, and again when the Microphones setting changes: a running
// capture moves over to the microphones now asked for.
const startCapture = () =>
options.startContinuousVoiceCapture({ recordAs: `transcribe-${stamp}`, mics: transcribeMicCount() });
const app = createInProcessWindow({
appId: "transcribe",
windowId: TRANSCRIBE_WINDOW_ID,
@@ -78,6 +85,7 @@ export function createTranscribeAppWindow(options: TranscribeAppOptions): InProc
},
// The controller starts and stops the recording as the setting changes.
toggleSettingMenuItem(saveRecordingSetting),
enumSettingMenuItem(transcribeMicsSetting, { onChange: startCapture }),
],
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
@@ -97,7 +105,96 @@ export function createTranscribeAppWindow(options: TranscribeAppOptions): InProc
shell.setTrayIcon(TRAY_ICON_ID, micTrayIcon(voiceControlBridge.recording));
app.requestRender();
});
options.startContinuousVoiceCapture({ recordAs: `transcribe-${stamp}` });
startCapture();
shell.setTrayIcon(TRAY_ICON_ID, micTrayIcon(voiceControlBridge.recording));
return app;
}
/**
* Transcribe in replay mode: a window of its own that transcribes a
* recording (a .mka file from Save Recording) in place of the microphones,
* in real time and through the same pipeline. It neither uses the mic nor
* shows the mic tray icon, so it runs beside a live Transcribe window. The
* header shows the position in the recording; a tap pauses and resumes; the
* menu jumps to a time.
*/
export function createTranscribeReplayWindow(
windowId: string,
path: string,
name: string,
options: InProcessAppOptions,
): InProcessWindow | null {
const replay = options.actions.openVoiceReplay?.(path) ?? null;
if (!replay) return null;
// Names a saved transcript after the recording it came from.
const layer = new TranscribeLayer(name.replace(/\.[^.]+$/, ""), replay, name);
const app = createInProcessWindow({
appId: "transcribe",
windowId,
title: name,
iconLetter: "Tr",
icon: "mic",
closeable: true,
// Relaunching Transcribe after a restart would open the microphone, not this recording.
restoresApp: false,
// Like a playing video: something to watch, not to touch.
keepsScreenOn: () => replay.state === "playing",
actions: options.actions,
baseLayer: new YieldAtRootLayer(layer),
menuItems: () => [
{
label: "Jump to time",
// The length isn't known until the recording has been opened.
disabled: () => replay.durationMs <= 0,
onSelect: (ctx) => {
ctx.stack.pop();
ctx.stack.push(
new TimePickerLayer({
title: "Jump to time",
initialMs: replay.positionMs,
maxMs: replay.durationMs,
onPick: (positionMs) => {
replay.jumpTo(positionMs);
app.requestRender();
},
}),
);
},
},
{
label: replay.state === "paused" ? "Resume" : "Pause",
disabled: () => replay.state !== "playing" && replay.state !== "paused",
onSelect: (ctx) => {
ctx.stack.pop();
replay.setPaused(replay.state === "playing");
},
},
{
label: "Restart from 0:00",
onSelect: (ctx) => {
ctx.stack.pop();
replay.jumpTo(0);
},
},
{
label: "Save",
onSelect: (ctx) => {
ctx.stack.pop();
layer.saveTranscript();
},
},
],
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: () => {
layer.onRemoved();
replay.close();
options.onClosed();
},
});
// Started first, so the layer picks its opening status up as it subscribes.
replay.start();
layer.start(app.requestRender, () => shell.isWindowVisible(windowId));
return app;
}
@@ -0,0 +1,40 @@
import { ConfigSettingEnum, glassesTypeSetting } from "../../ui/dashboard-settings";
import { type MicCount } from "../../ui/layers";
import { micControlSupported } from "../microphones/mic-control";
export type TranscribeMics = "1" | "2" | "4";
const MICS_LABELS: Record<TranscribeMics, string> = {
"1": "1 (mixed)",
"2": "2 (one per temple)",
"4": "4 (two per temple)",
};
/** Whether the paired glasses can stream their microphones separately (G2, with the microphone channel in use). */
export function separateMicsSupported(): boolean {
return glassesTypeSetting.get() === "g2" && micControlSupported();
}
/**
* How many of the glasses' microphones Transcribe captures. With more than
* one, the temples stream their own microphones (each temple on its own
* clock) instead of the glasses' mixed stream; a recording keeps every one,
* and what is transcribed is a mix made on the phone.
*/
export const transcribeMicsSetting = new ConfigSettingEnum<TranscribeMics>({
id: "transcribe-mics",
label: "Microphones",
storageKey: "transcribe.mics",
defaultValue: "1",
values: ["1", "2", "4"],
formatValue: (value) => MICS_LABELS[value],
isDisabled: (value) => value !== "1" && !separateMicsSupported(),
description:
"Which of the glasses' microphones to capture. 1 is the glasses' own mixed stream. 2 and 4 stream each temple's microphones separately (custom firmware), so a saved recording has every microphone on its own channel; the transcript then comes from a mix made on the phone.",
});
/** The setting as a capture option; 1 where the glasses can't stream their microphones separately. */
export function transcribeMicCount(): MicCount {
if (!separateMicsSupported()) return 1;
return Number(transcribeMicsSetting.get()) as MicCount;
}
+72 -13
View File
@@ -3,15 +3,20 @@ import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import { lineStep } from "../../ui/metrics";
import { MicLevelMeter, paintListeningHeader, RECORDING_FAILED_NOTICE } from "../../ui/listening-header";
import { writeTextToDownloads } from "../../native/file-access";
import { voiceControlBridge } from "../../native/voice-control";
import { voiceControlBridge, type VoiceEventSource, type VoiceReplay } from "../../native/voice-control";
import { Layer, type LayerContext } from "../../ui/layers";
import { type InputEvent } from "../../ui/gestures";
import { formatReplayTime } from "./replay-time";
import { TranscriptModel, TranscriptScroll, transcriptLayout, wrapTranscribeText } from "./transcript-model";
/**
* Live transcription view. Continuous mic capture is owned by the app wrapper
* (createTranscribeAppWindow); this layer accumulates the transcript, shows
* it, and saves it to Downloads from the app menu.
*
* Given a replay, it transcribes that recording instead of the microphone:
* the header shows the position in the recording, a tap pauses and resumes,
* and each jump leaves its time as a line in the transcript.
*/
export class TranscribeLayer implements Layer {
private status = "Starting microphone...";
@@ -24,25 +29,67 @@ export class TranscribeLayer implements Layer {
private unsubscribeTranscript: (() => void) | null = null;
private unsubscribePause: (() => void) | null = null;
private unsubscribeStatus: (() => void) | null = null;
private unsubscribeReplay: (() => void) | null = null;
private readonly source: VoiceEventSource;
/** `stamp` names the saved transcript, matching the session's audio recording. */
constructor(private readonly stamp: string = transcriptTimestamp()) {}
/**
* `stamp` names the saved transcript, matching the session's audio
* recording. `replay` is the recording to transcribe in place of the
* microphone; `replayName` is what to call it.
*/
constructor(
private readonly stamp: string = transcriptTimestamp(),
private readonly replay: VoiceReplay | null = null,
private readonly replayName = "",
) {
this.source = replay ? replay.events : voiceControlBridge;
if (replay) this.status = "Opening the recording...";
}
/** `isVisible` says whether the window is on screen (the level meter repaints only then). */
/** `isVisible` says whether the window is on screen (the level meter and replay clock repaint only then). */
start(requestRender: () => void, isVisible: () => boolean): void {
this.meter.start(requestRender, isVisible);
this.unsubscribeTranscript = voiceControlBridge.onTranscript((event) => {
this.meter.start(requestRender, isVisible, this.source);
this.unsubscribeTranscript = this.source.onTranscript((event) => {
this.transcript.accept(event);
requestRender();
});
this.unsubscribePause = voiceControlBridge.onSpeechPause(() => this.transcript.pause());
this.unsubscribeStatus = voiceControlBridge.onStatus((state) => {
this.unsubscribePause = this.source.onSpeechPause(() => this.transcript.pause());
// The current status arrives while subscribing, before the window has a
// surface to render to; the window paints it when it is first shown.
let subscribing = true;
this.unsubscribeStatus = this.source.onStatus((state) => {
this.status = state.status;
this.listening = state.listening;
this.detail = state.detail;
this.saveNotice = "";
requestRender();
if (!subscribing) requestRender();
});
subscribing = false;
const replay = this.replay;
if (replay) {
let shownSecond = -1;
let shownState = replay.state;
this.unsubscribeReplay = replay.onChange((jumpedToMs) => {
if (jumpedToMs !== undefined) this.transcript.mark(`[${formatReplayTime(jumpedToMs)}]`);
// The clock ticks in whole seconds; repaint when what it shows changed.
const second = Math.floor(replay.positionMs / 1000);
if (jumpedToMs === undefined && second === shownSecond && replay.state === shownState) return;
shownSecond = second;
shownState = replay.state;
if (isVisible()) requestRender();
});
}
}
/** The header's status for a replay: where it is in the recording, and anything worth saying beside that. */
private replayStatus(replay: VoiceReplay): string {
if (replay.state === "failed" || (replay.state === "opening" && replay.durationMs === 0)) return this.status;
const withHours = replay.durationMs >= 3_600_000;
const clock = `${formatReplayTime(replay.positionMs, withHours)} / ${formatReplayTime(replay.durationMs, withHours)}`;
if (replay.state === "paused") return `${clock} · Paused`;
if (replay.state === "ended") return `${clock} · Finished`;
// Anything but plain listening is worth showing: the model loading, a provider reconnecting.
return this.listening ? clock : `${clock} · ${this.status}`;
}
paint(ctx: LayerContext): GrayImage {
@@ -50,14 +97,19 @@ export class TranscribeLayer implements Layer {
const viewport = ctx.stack.getBaseSize();
const image = new GrayImage(viewport.width, viewport.height, 0);
const status = voiceControlBridge.recordingFailed ? RECORDING_FAILED_NOTICE : this.status;
const replay = this.replay;
const status = replay
? this.replayStatus(replay)
: this.source.recordingFailed ? RECORDING_FAILED_NOTICE : this.status;
const playing = !replay || replay.state === "playing";
const bodyTop = paintListeningHeader(
image, font, "Transcribe", this.saveNotice || status, this.listening ? this.meter : null, viewport.padding,
voiceControlBridge.recording,
image, font, "Transcribe", this.saveNotice || status, this.listening && playing ? this.meter : null, viewport.padding,
this.source.recording,
);
const step = lineStep(font) + 2;
const layout = transcriptLayout(viewport, bodyTop, font.lineHeight, step);
const text = this.transcript.text || (this.listening ? "Listening..." : this.detail);
const placeholder = replay ? `Replaying ${this.replayName}` : "Listening...";
const text = this.transcript.text || (this.listening ? placeholder : this.detail);
const wrapped = wrapTranscribeText((line) => font.measureText(line), text, layout.textWidth);
const firstLine = this.scroll.layout(wrapped.length, layout.pageLines);
@@ -82,6 +134,11 @@ export class TranscribeLayer implements Layer {
ctx.actions.requestRender();
return;
}
if (event.type === "click" && this.replay) {
this.replay.setPaused(this.replay.state === "playing");
ctx.actions.requestRender();
return;
}
if (event.type === "double-click") {
ctx.stack.pop();
}
@@ -89,6 +146,8 @@ export class TranscribeLayer implements Layer {
onRemoved(): void {
this.meter.stop();
this.unsubscribeReplay?.();
this.unsubscribeReplay = null;
this.unsubscribePause?.();
this.unsubscribePause = null;
this.unsubscribeTranscript?.();
+12
View File
@@ -36,6 +36,18 @@ export class TranscriptModel {
if (this.live) this.breakAfterLive = true;
else if (this.finalized) this.separator = "\n";
}
/**
* A line of its own (where a replay jumped to), ending whatever was in
* progress: what follows it starts a new paragraph.
*/
mark(label: string): void {
const before = this.text;
this.finalized = before ? `${before}\n${label}` : label;
this.live = "";
this.separator = "\n";
this.breakAfterLive = false;
}
}
/** An absolute history position, with an explicit follow-tail mode. */
+133 -7
View File
@@ -19,9 +19,14 @@ import { ALL_NOTIFICATIONS, onAndroidNotificationPosted, onAndroidNotificationRe
import { watchNotificationListenerBinding } from "../native/notification-access";
import { openEvenAppSettings, readEvenAppNotificationState } from "../native/even-app-conflict";
import { defaultRingName, setGlassesRingLink } from "../native/ring-status";
import { applyGlanceAngle, glassesHeadUpTrigger, syncGlanceAngleOriginal } from "./head-angle";
import { glanceAngleTriggerDegrees, glanceTapTimeoutMs } from "../apps/glanceboard/glanceboard-settings";
import { GLANCE_TILT_MAX_MS, glanceTiltMaxMs } from "./glance-state";
import { getBooleanSetting, setBooleanSetting } from "../native/settings-store";
import { grayImageToPreviewSource } from "../native/gray-image-preview";
import { firmwareIncompatibilityMessage, hasCompatibleFirmware } from "./firmware-compat";
import { keyboardService } from "./keyboard/service";
import type { KeyEvent } from "./keyboard/keys";
import { hasExtractedEvenHubFonts } from "./firmware-builder";
import { isHaltedSessionPhase, resumeAutoReconnect, suppressAutoReconnect } from "./reconnect-policy";
import { WearRemote, type WearRemoteInputKind } from "./wear-remote";
@@ -53,7 +58,7 @@ import { type GlanceEvent } from "./glance-state";
import { isPreviewOnlyMode } from "../phone-ui/onboarding-state";
import { claimGlassesOnboardingAutoLaunch, ONBOARDING_APP_ID } from "../apps/onboarding/onboarding-progress";
import { beginRenderPass, endRenderPass } from "../util/render-freshness";
import { voiceControlBridge } from "../native/voice-control";
import { VoiceReplay, voiceControlBridge } from "../native/voice-control";
import { voiceActivity } from "../ui/shell/voice-activity";
import { GrayImage } from "../graphics/image";
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../graphics/plane";
@@ -76,7 +81,7 @@ import { type InProcessAppOptions, type InProcessWindow } from "../ui/shell/in-p
import { loadPersistedOpenApps, savePersistedOpenApps } from "../ui/shell/open-apps-persistence";
import { appViewportRect, isOnSwitcherEdge, screenHeight, screenWidth, sidebarStripVisible, windowEdges, type ScreenRect, type WindowHeightMode } from "../ui/shell/geometry";
import { sameEdges } from "../ui/viewport";
import { type ContinuousCaptureOptions, type LayerActions, type TextSettingsEditToggle, type TranscriptionChoice } from "../ui/layers";
import { type ContinuousCaptureOptions, type LayerActions, type MicCount, type TextSettingsEditToggle, type TranscriptionChoice } from "../ui/layers";
import { type KeyboardInputSession } from "../ui/shell/keyboard-input";
import { appSwitcherPositionSetting, glassesModelName, glassesTypeSetting, statusBarPositionSetting, statusBarVisibilitySetting, windowBorderSetting, assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, getBrightnessPreferences, displayLayoutSetting, navigateDisplayLayoutSetting, terminalDisplayLayoutSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, whisperServerApiKeySetting, whisperServerLanguageSetting, whisperServerModelSetting, whisperServerUrlSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, effectiveRingConnectionMode, type RingConnectionMode, saveRecordingSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, shouldPopUpNewNotification, suspendEvenHubWhenScreenOffSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
import { isIgnoringBatteryOptimizations, requestIgnoreBatteryOptimizations } from "../native/battery-optimization";
@@ -98,6 +103,8 @@ import { createNotificationsAppWindow, NOTIFICATIONS_SURFACE_ID, NOTIFICATIONS_W
import { isInstalledPackagePresent } from "../apps/evenhub/updates";
import { wearerVerificationOptions } from "../apps/microphones/speakers";
import { micSession } from "../apps/microphones/mic-session";
import { micArrayCaptureConfig, micControlSupported } from "../apps/microphones/mic-control";
import { encodeMicControl } from "../apps/microphones/mic-protocol";
import {
chargingPreviewMessage,
glassesDisplayAsleep,
@@ -333,6 +340,7 @@ class DashboardController {
private evenHubResumePromise: Promise<boolean> | null = null;
/** Faceclaw's firmware at the required revision reported in; its extensions can be used. */
private customFirmwareConfirmed = false;
private lastGlanceAngleDegrees = glanceAngleTriggerDegrees();
private faceclawWakeLeaseState: boolean | null = null;
/** Ring connection mode the current session was started with (it applies per connection). */
private ringModeAtConnect: RingConnectionMode = "glasses";
@@ -410,6 +418,7 @@ class DashboardController {
startContinuousVoiceCapture: (client: string, options?: ContinuousCaptureOptions) =>
this.startContinuousVoiceCapture(client, options),
stopContinuousVoiceCapture: (client: string) => this.stopContinuousVoiceCapture(client),
openVoiceReplay: (path: string) => this.openVoiceReplay(path),
playBuzzerSequence: (payload: Uint8Array) => this.playBuzzerSequence(payload),
};
this.sharedActions = sharedActions;
@@ -457,6 +466,7 @@ class DashboardController {
if (on) this.glance.dismiss();
this.handleScreenStateChanged(on);
if (on) this.requestShellRender();
if (on) keyboardService.retryNow();
this.emit();
},
});
@@ -488,6 +498,7 @@ class DashboardController {
if (!resized && !appsResized) this.applyWindowEdgesIfChanged();
this.syncAssistantBridgeIfChanged();
this.syncLockScreenSettingIfChanged();
this.applyGlanceAngleIfChanged();
this.syncContinuousRecording();
// A Preview color or scaling change should show on the mirror at once,
// not at the next composited frame (cheap: floor-limited, dedup'd on
@@ -509,6 +520,29 @@ class DashboardController {
assistantAvailable: () => shell.isAssistantAvailable(),
assistant: text => shell.sendToAssistant(text),
});
// A keyboard paired through the glasses (CFW keyboard bridge). The
// service decides what each key means (app/g2/keyboard/key-router.ts);
// this is how it reaches the display and the input pipeline.
keyboardService.setHost({
ready: () => this.phase === "connected",
locked: () => this.glassesLocked,
wake: () => {
void this.handleInputEvent({
kind: "display-wake",
containerName: "",
eventType: OsEventTypeList.DOUBLE_CLICK_EVENT,
eventSource: EventSourceType.TOUCH_EVENT_FORM_DUMMY_NULL,
systemExitReasonCode: 0,
frameId: 0,
}).catch((error) => this.appendLog(`keyboard wake failed: ${this.formatError(error)}`));
},
gesture: (gesture, origin) => this.injectSyntheticRingInput(gesture, origin),
log: (line) => this.appendLog(line),
// A keyboard that is switched off would otherwise keep the glasses'
// radio looking for it around the clock. One still connected when the
// display sleeps stays connected, and its next key wakes the display.
shouldReconnect: () => this.phase === "connected" && shell.isScreenOn(),
});
this.wearRemote = new WearRemote({
apps: launchableApps,
injectInput: (kind) => this.injectSyntheticRingInput(kind, "watch"),
@@ -1655,6 +1689,8 @@ class DashboardController {
if (mappedPhase === "connected") {
this.syncEvenHubScreenOffSetting();
this.ensureWearStateTracking();
// The session reapplies it on reconnects; restate it for a new session.
applyGlanceAngle();
this.maybeWakeAfterChargingReconnect();
} else if (mappedPhase !== "charging") {
this.cancelEvenHubSuspendTimer();
@@ -1763,6 +1799,7 @@ class DashboardController {
this.appendLog(`wake takeover lease sync failed: ${this.formatError(error)}`);
});
this.ensureWearStateTracking();
this.syncKeyboardLink();
}
// The shared session halts on incompatible firmware by itself
// ("incompatible-firmware" phase); this only explains why.
@@ -1816,6 +1853,7 @@ class DashboardController {
this.requestShellRender();
this.updateCompositePreview();
this.updateConnectedForegroundNotification();
syncGlanceAngleOriginal();
}, SHELL_REFRESH_INTERVAL_MS);
this.previewTimer = setInterval(() => this.updateCompositePreview(), PREVIEW_INTERVAL_MS);
this.screenTimeoutTimer = setInterval(() => {
@@ -2253,6 +2291,30 @@ class DashboardController {
return undefined;
}
/**
* How many of the glasses' microphones the continuous-capture windows call
* for (the most any asks for), where the glasses can stream them
* separately: G2 with the microphone channel in use. Otherwise 1, the
* mixed stream.
*/
private continuousMics(): MicCount {
if (glassesTypeSetting.get() !== "g2" || !micControlSupported()) return 1;
let mics: MicCount = 1;
for (const options of this.continuousClients.values()) {
if ((options.mics ?? 1) > mics) mics = options.mics!;
}
return mics;
}
/**
* A recording as a capture of its own (see VoiceReplay), transcribed with
* the provider and processing settings a microphone capture would get.
* "My voice only" is left out: a recording is of whoever spoke.
*/
private openVoiceReplay(path: string): VoiceReplay {
return new VoiceReplay(path, () => ({ ...this.voiceCaptureOptions(null), speakerVerification: undefined }));
}
/**
* Continuous capture's claim on the mic (the Microphones app and EvenHub
* mic apps stand down while it is held) follows whether the capture really
@@ -2278,9 +2340,26 @@ class DashboardController {
// Otherwise only Whisper server is told a language (its own setting).
const choice = this.transcriptionChoice();
const provider = choice?.provider ?? voiceProviderSetting.get();
// Separate microphones only come from connected glasses.
const mics = communicator ? this.continuousMics() : 1;
const micConfig = mics === 1 ? null : micArrayCaptureConfig(mics);
return {
communicator: communicator?.getNativeCommunicator() ?? null,
usePhoneMic: communicator === null,
micArray: micConfig ? { configure: encodeMicControl("configure", micConfig) } : null,
// Stored in a recording of the capture (see Save Recording).
captureInfo: {
glasses: communicator ? glassesModelName() : null,
mics,
micConfig: micConfig && {
source: micConfig.source,
channelMask: micConfig.channelMask,
codec: micConfig.codec,
format: micConfig.format,
sampleRateHz: micConfig.sampleRateHz,
directionDetection: micConfig.beamform,
},
},
provider,
language: choice ? choice.language : provider === "whisper-server" ? whisperServerLanguageSetting.get() : "",
elevenLabsApiKey: elevenLabsApiKeySetting.get(),
@@ -2463,6 +2542,16 @@ class DashboardController {
frameTimings.logFrame(frameId, `TS input handler start: ${event.kind} ${eventLabel(event.kind, event.eventType)}`);
let frameOwned = false;
try {
if (event.kind === "sys-event" && event.eventType === OsEventTypeList.HEAD_DOWN_EVENT) {
// Only the Glanceboard cares (it ends a head-tilt showing); never
// shell input, so it can't count as activity or wake anything.
const glanceEvent = this.glance.eventForGesture("head-down");
if (glanceEvent) {
await this.glance.handleEvent(glanceEvent, frameId);
frameOwned = true;
}
return;
}
const inputEvent = rawInputEventToInputEvent(event);
if (!acceptInput(inputEvent)) return;
// The gesture, plus which app is on screen and whether input goes to it,
@@ -2581,15 +2670,49 @@ class DashboardController {
}
}
/** Re-send the head-tilt angle when it changed (the setting, from either settings UI, or the Glanceboard toggle). */
private applyGlanceAngleIfChanged(): void {
const degrees = glanceAngleTriggerDegrees();
if (degrees === this.lastGlanceAngleDegrees) return;
this.lastGlanceAngleDegrees = degrees;
applyGlanceAngle();
}
/**
* Tell the keyboard bridge whether the session can host a keyboard: a G2
* on firmware with the bridge, connected and in use. While the glasses
* charge in their case the link stays up but nobody is typing, so the
* firmware is told to let the keyboard go.
*/
private syncKeyboardLink(): void {
const up =
this.phase === "connected" &&
this.customFirmwareConfirmed &&
glassesTypeSetting.get() === "g2";
// Charging, or a disconnect the user asked for: the link is still up, so
// the DISABLE gets out ahead of everything the teardown sends.
if (up) keyboardService.linkReady();
else keyboardService.linkLost(this.phase === "charging" || this.phase === "disconnecting");
}
/**
* The Glanceboard event a sleep-time input means, or null when the shell
* should see the input as usual. A display-wake carries the head-tilt
* gesture (HEAD_UP_EVENT) as a press; the double-tap display-wake stays the
* regular UI's wake.
* gesture (HEAD_UP_EVENT) as a tilt, which lasts until the head-down; the
* double-tap display-wake stays the regular UI's wake.
*/
private glanceEventFor(inputEvent: InputEvent, event: RawInputEvent): GlanceEvent | null {
if (inputEvent.type === "display-wake") {
return event.eventType === OsEventTypeList.HEAD_UP_EVENT ? this.glance.eventForGesture("head-tilt") : null;
if (event.eventType !== OsEventTypeList.HEAD_UP_EVENT) return null;
const glanceEvent = this.glance.eventForGesture("head-tilt");
if (glanceEvent?.type !== "tilt") return glanceEvent;
const maxMs = glanceTiltMaxMs({
capMs: glanceEvent.maxMs === undefined ? GLANCE_TILT_MAX_MS : glanceEvent.maxMs,
resumedSession: this.evenHubSessionSuspended || this.evenHubResumePromise !== null,
triggerDegrees: glassesHeadUpTrigger() ?? (glanceAngleTriggerDegrees() || null),
tapTimeoutMs: glanceTapTimeoutMs(),
});
return { type: "tilt", maxMs };
}
return this.glance.eventForGesture(inputEvent.type);
}
@@ -2688,6 +2811,7 @@ class DashboardController {
}
},
endTextSettingEdit: () => this.endTextSettingEdit(),
unhandledKey: (event) => keyboardService.handleUnhandledKey(event as KeyEvent),
});
this.appHosts.set(appId, host);
return host;
@@ -2721,10 +2845,11 @@ class DashboardController {
if (!this.openAppsRestored || this.suppressOpenAppsPersist) return;
const open: string[] = [];
for (const window of shell.getWindows()) {
if (window.appId === "launcher") continue;
if (window.appId === "launcher" || window.restoresApp === false) continue;
if (!open.includes(window.appId)) open.push(window.appId);
}
savePersistedOpenApps({ open, foreground: shell.foregroundWindow()?.appId ?? null });
const foreground = shell.foregroundWindow();
savePersistedOpenApps({ open, foreground: foreground && foreground.restoresApp !== false ? foreground.appId : null });
}
/**
@@ -3052,6 +3177,7 @@ class DashboardController {
private setPhase(phase: ConnectionPhase): void {
if (this.phase === phase) return;
this.phase = phase;
this.syncKeyboardLink();
if (phase !== "connected" && phase !== "charging") {
shell.setBatteryLevels({ ring: null, ringCharging: null });
}
+7
View File
@@ -79,6 +79,12 @@ export const OsEventTypeList = {
HEAD_UP_EVENT: 12,
/** Faceclaw/18: R1 touch-down, before click/hold/slide recognition. */
RING_PRESS_EVENT: 14,
/**
* Faceclaw/38: the IMU head-down (the head back below the head-up
* threshold minus 20 degrees), forwarded while a page is up. Ends a
* head-tilt Glanceboard; nothing else uses it.
*/
HEAD_DOWN_EVENT: 15,
} as const;
export const OsEventTypeName: Record<number, string> = {
@@ -96,4 +102,5 @@ export const OsEventTypeName: Record<number, string> = {
11: "SHORT_THEN_LONG_PRESS_EVENT",
12: "HEAD_UP_EVENT",
14: "RING_PRESS_EVENT",
15: "HEAD_DOWN_EVENT",
};
+1 -1
View File
@@ -26,7 +26,7 @@ export type FirmwareInfo = {
};
/** The Faceclaw firmware revision this build of the app needs. */
export const REQUIRED_FACECLAW_FIRMWARE_VERSION = 38;
export const REQUIRED_FACECLAW_FIRMWARE_VERSION = 39;
const FACECLAW_PREFIX = "Faceclaw/";
const LEGACY_PREFIX = "EVENCFW";
+65 -35
View File
@@ -19,12 +19,42 @@ export type FirmwarePatchSet = {
export const CFW_PATCH_SET: FirmwarePatchSet = {
"base": "g2_2.3.0.24.bin",
"baseSha256": "187ccf2bcc5c17a212106e8a376745511e8289c4232b634a7ea94b9bf25a0979",
"outputSha256": "4aac023f49ec6965186d9106e328a516f20a2915ab400d561f662f984023a432",
"outputSha256": "e43be9d04031d261574f96d45cb1e0edd67bfb39f0213f323ff82d8560ae454d",
"patches": [
{
"offset": 1379947,
"old": "0ef009fa",
"new": "0af3b8fb",
"desc": "DM callback allocation: retain keyboard lifecycle on queue exhaustion"
},
{
"offset": 1380027,
"old": "0ef0e1f9",
"new": "0af316fb",
"desc": "ATT callback allocation: expose lost keyboard events as relay gaps"
},
{
"offset": 2649417,
"old": "0a681279",
"new": "d4f167fb",
"desc": "SMP Pairing I/O capability: KeyboardDisplay only for owned keyboard"
},
{
"offset": 2651811,
"old": "0a681279",
"new": "d3f1bafe",
"desc": "SMP Pairing I/O capability: KeyboardDisplay only for owned keyboard"
},
{
"offset": 1385975,
"old": "38b584b0",
"new": "08f3d4be",
"desc": "BLE app dispatcher: isolate explicitly enabled keyboard connection"
},
{
"offset": 1045797,
"old": "38b584b0",
"new": "5cf371bb",
"new": "5df31bb9",
"desc": "ring receiver entry: timestamped unfiltered reports under framebuffer lease"
},
{
@@ -36,49 +66,49 @@ export const CFW_PATCH_SET: FirmwarePatchSet = {
{
"offset": 1437923,
"old": "fef788ff",
"new": "fdf2a2f8",
"new": "fdf24cfe",
"desc": "cfw_ancs_event"
},
{
"offset": 1437951,
"old": "fef7e8fb",
"new": "fcf2d0fd",
"new": "fdf27afb",
"desc": "cfw_ancs_open"
},
{
"offset": 1437969,
"old": "fef7e7fb",
"new": "fcf2ebfd",
"new": "fdf295fb",
"desc": "cfw_ancs_close"
},
{
"offset": 1388387,
"old": "39694d00",
"new": "25597d00",
"new": "79647d00",
"desc": "connection-bound ANCS EUS write callback"
},
{
"offset": 971497,
"old": "fff717f8",
"new": "6ef3a1fc",
"new": "6ff34bfa",
"desc": "bl faceclaw_input_bridge_received (ring relay and ordered private transport before worker pool)"
},
{
"offset": 971845,
"old": "fef769ff",
"new": "6ef3f3fb",
"new": "6ff39df9",
"desc": "bl faceclaw_input_bridge_received (ring relay and ordered private transport before worker pool)"
},
{
"offset": 979579,
"old": "fdf74ef8",
"new": "6cf3d8fc",
"new": "6df382fa",
"desc": "bl faceclaw_input_bridge_received (ring relay and ordered private transport before worker pool)"
},
{
"offset": 1428895,
"old": "f8f76cfd",
"new": "fbf250fe",
"new": "fbf2acfa",
"desc": "bl cfw_receive_packet (private SID-f0 probe before TPL reassembly)"
},
{
@@ -102,7 +132,7 @@ export const CFW_PATCH_SET: FirmwarePatchSet = {
{
"offset": 1058287,
"old": "fff754fb",
"new": "59f342fb",
"new": "5af3ecf8",
"desc": "bl ble_classify_link (only a <= 11.25 ms / latency-0 link is 'already fast')"
},
{
@@ -114,145 +144,145 @@ export const CFW_PATCH_SET: FirmwarePatchSet = {
{
"offset": 1248487,
"old": "d4f712fb",
"new": "29f344fd",
"new": "29f396f8",
"desc": "bl settings_send_wrapper (append caps field 100)"
},
{
"offset": 1246183,
"old": "f5f7e2f8",
"new": "29f3e8fe",
"new": "29f394fa",
"desc": "bl settings_decode_wrapper (Faceclaw lease field 101)"
},
{
"offset": 975219,
"old": "02f083fc",
"new": "6bf34aff",
"new": "6bf3f6fa",
"desc": "bl faceclaw_display_start @ 0x467d68 (fail-open wake takeover)"
},
{
"offset": 975411,
"old": "02f023fc",
"new": "6bf3b8ff",
"new": "6bf364fb",
"desc": "bl faceclaw_display_start_headup @ 0x467e28 (fail-open wake takeover)"
},
{
"offset": 975103,
"old": "07f085fb",
"new": "6df3a6fc",
"new": "6ef350fa",
"desc": "bl headup_gate (idle input gate: tap/long/release -> field-102 events, stock result kept)"
},
{
"offset": 830549,
"old": "19f03efb",
"new": "90f37bfe",
"new": "91f325fc",
"desc": "bl gesture_ring_press_mode (ring touch-down 14, head up 12 / down 15; stock dispatch preserved)"
},
{
"offset": 830795,
"old": "1ff071ff",
"new": "90f334fe",
"new": "91f3defb",
"desc": "bl gesture_press (owned event 9 before stock menu gate)"
},
{
"offset": 830887,
"old": "1ff043ff",
"new": "90f32efe",
"new": "91f3d8fb",
"desc": "bl gesture_short_long (Faceclaw lease gates event 11 vs stock Menu path)"
},
{
"offset": 831763,
"old": "1ff08dfd",
"new": "90f364fc",
"new": "91f30efa",
"desc": "bl gesture_release (owned event 10 before stock menu gate)"
},
{
"offset": 1570209,
"old": "7fb50600",
"new": "dbf2d5b8",
"new": "daf227bc",
"desc": "even_ai_display_ctrl entry -> conditional Faceclaw lease trampoline"
},
{
"offset": 1051545,
"old": "f6f787f9",
"new": "55f3c9f8",
"new": "54f31dfe",
"desc": "bl display_copy_hook @ 0x47a78e (640x480 direct framebuffer)"
},
{
"offset": 1051861,
"old": "f6f7e9f8",
"new": "55f32bf8",
"new": "54f37ffd",
"desc": "bl display_copy_hook @ 0x47a8ca (640x480 direct framebuffer)"
},
{
"offset": 1262237,
"old": "d9f7d0fd",
"new": "25f3bffd",
"new": "25f3c3f9",
"desc": "bl faceclaw_send_wear_event @ 0x4ade92 (outside onboarding)"
},
{
"offset": 1262337,
"old": "d9f79efd",
"new": "25f38dfd",
"new": "25f391f9",
"desc": "bl faceclaw_send_wear_event @ 0x4adef6 (outside onboarding)"
},
{
"offset": 1309405,
"old": "67f02dff",
"new": "19f35bfe",
"new": "19f35ffa",
"desc": "bl compass_decode_capture (sample-matched GAF diagnostics)"
},
{
"offset": 1307865,
"old": "fff7c9fb",
"new": "1af3ddf9",
"new": "19f3e1fd",
"desc": "bl compass_report_event (stock UI + heading with diagnostics over BLE)"
},
{
"offset": 1300937,
"old": "00210170",
"new": "1bf3bbfe",
"new": "1bf3bffa",
"desc": "bl compass_preserve_accuracy (retain magnetic calibration under Faceclaw framebuffer lease)"
},
{
"offset": 4537963,
"old": "",
"new": "b0b581ea00039b0701d0034637e0c2b110f0030315d000f1010ca2f1010e0023cc5c9e45c45403f1010404d0634413f003032346f4d121440319121b102a14d302e00346102a10d3d1f800c0d1f804e0cc688d68103adc609d60c3f804e043f810cb0f2a01f11001eed8042a07d300bf51f8045b043a032a43f8045bf8d8002a08bfb0bd0139013b11f8015f013a03f8015ff9d1b0bd00bf884218bf002a00d1704710b50b1a38bf431a934207d288420ad281ea00039b0726d0034669e0fff79fffbde81040704781ea000300eb020c9b0701eb020e42d15fea8c732bd0a0f1010c00bf8b1813f801ec8418531e04f801ec04d0624412f003021a46f2d101eb030e00eb030c17e0830736d0a2f1010c00f1010e002300bfcc5c9c45c45403f1010404d0734413f003032346f4d1121b2144031922e01346042b0ed3aef10402acf1040152f80449043b032b41f80449f8d802f1040e01f1040c1a4653b1aef10101acf1010300bf11f80149013a03f80149f9d1bde8104070470346042a06d351f8044b043a032a43f8044bf8d8002af0d00139013b00bf11f8014f013a03f8014ff9d1e6e700bf80b5002a18bf10f0030301d186460ce000f1010c864600bf013a0ef8011b04d01cf003030cf1010cf6d1102a11d35ffa81fc4ff001330cfb03fc00bf103acef80cc0cef808c0cef804c04ef810cb0f2af4d8042a0bd35ffa81fc4ff001330cfb03fc00bf043a032a4ef804cbfad8002a08bf80bdaef10103013a03f8011ffbd180bd00bf2de9f04fc7b04ff29c5bc2f2290b4ff6ff754ff47d7400274ff0010847f67f7a7f261191cde90f3007e000bf48f2a351c0f24501bff32f8f8847dbf80090bff35f8fdbf800000321cff680710140b1f1005fbff35f8f0bd101684ef66c62ccf2ff02914204d14068b0f57d7f00f096804ff47d7006f004fd002800f0cb814ff60c41cff6ff7100bf42182e3182f8f47382f8f57382f8f67382f8f77382f8f87382f8f97382f8fa7382f8fb7382f8fc7382f8fd7382f8fe7382f8ff7382f8007482f8017482f8027482f8037482f8047482f8057482f8067482f8077482f8087482f8097482f80a7482f80b7482f80c7482f80d7482f80e7482f80f7482f8107482f8117482f8127482f8137482f8147482f8157482f8167482f8177482f8187482f8197482f81a7482f81b7482f81c7482f81d7482f81e7482f81f7482f8207482f82174a0d14ef66c61ccf2ff010160446080f80e80a0f8c4a180f8c361058445848584c584058545858585c585058645868586c586058745878587c5875be8001f49457ff452afbff35f8f4be8000121b15be8001f4945f8d047e74ff47d7800274ff0010a47f67f797f2607e000bf48f2a351c0f24501bff32f8f8847dbf80040bff35f8fdbf800000321cff680710140b1f1005fbff35f8f0bd101684ef66c62ccf2ff02914204d14168b1f57d7f00f098804ff47d7006f042fc002800f009814ff60c41cff6ff7100bf42182e3182f8f47382f8f57382f8f67382f8f77382f8f87382f8f97382f8fa7382f8fb7382f8fc7382f8fd7382f8fe7382f8ff7382f8007482f8017482f8027482f8037482f8047482f8057482f8067482f8077482f8087482f8097482f80a7482f80b7482f80c7482f80d7482f80e7482f80f7482f8107482f8117482f8127482f8137482f8147482f8157482f8167482f8177482f8187482f8197482f81a7482f81b7482f81c7482f81d7482f81e7482f81f7482f8207482f82174a0d14ef66c61ccf2ff010160c0f8048080f80ea0a0f8c49180f8c361058445848584c584058545858585c585058645868586c586058745878587c5875be8001fa1427ff451afbff35f8f00bf4be8000121b15be8001fa142f8d045e7d0f8948242f6f76ac0f2440ab8f1000fbff35f8f4ad00af19a0240464ff0ff314ff0ff379047002840f090811198002861d010980778a7f1170002285bd811980c2840f07d81109c6078a178084300f07781e0780138022800f27281a279e379667a42ea0322237a207942ea034242ea0663a27ae67a6179192f42ea062200f0de81172f40f0f481002a40f05981fe2800f0b086812800f0a386002840f0b68651ea030040f04c8100f000bf04460020d047e8b104f5257151e8008fb8f1000f0cd1bff35f8f00bf41e80002002a00f0e58051e8008fb8f1000ff5d00021bff32f8f0029bff35f8f00f0d480804692e74ff0ff372ae147f6df40c0f24f00cdf83880804700274ff47d784ff0010947f67f744ff07f0a1397adf8507007e000bf48f2a351c0f24501bff32f8f8847dbf80060bff35f8fdbf800000321cff680710140b1f1005fbff35f8f0bd101684ef66c62ccf2ff02914204d14168b1f57d7f00f09f804ff47d7006f0f8fa002800f097804ff60c41cff6ff7100bf42182e3182f8f47382f8f57382f8f67382f8f77382f8f87382f8f97382f8fa7382f8fb7382f8fc7382f8fd7382f8fe7382f8ff7382f8007482f8017482f8027482f8037482f8047482f8057482f8067482f8077482f8087482f8097482f80a7482f80b7482f80c7482f80d7482f80e7482f80f7482f8107482f8117482f8127482f8137482f8147482f8157482f8167482f8177482f8187482f8197482f81a7482f81b7482f81c7482f81d7482f81e7482f81f7482f8207482f82174a0d14ef66c61ccf2ff010160c0f8048080f80e90a0f8c44180f8c3a1058445848584c584058545858585c585058645868586c586058745878587c5875be8001fb1427ff451afbff35f8f00bf4be8000159b15be8001fb142f8d045e70af5a9718847bce6012120e70020109f42f6f76addf83880c0f2440a9fb1119989b1397801f07f02b2f10b0418bf0124b2f11c0618bf01268a2924dc0b2926d01c2924d03ce00f9012a803f045ff4ff0ff3701249df85100002812a818bf4ff0ff3704f05ff8054644b99df8500028b94af21f30c0f247004c3080470f98002818bf056114e09c2901d08b2918d168b14af21f31c0f247010746884797f8681121b997f824133846109f49b14ff0ff370af5807140468847384647b0bde8f08f0f9012a8344003f007ff387800f07f061e2e05d11199384607f094fe0746b9e71d2e00f07e0018bf1a2819d1dbf800100322cff680720a40b2f1005fbff35f8f12d10a684ef66c63ccf2ff039a420bd14a68b2f57d7f04bf002281f8a12303e0a6f115010129e1d90f2e2cdd142e40f31082152e00f05d83162e00f069831f2e40f02c841198012840f0fc8438781f2840f0f88445f64d55c0f24605a847012841f0828140f24c71c0f2010105f5e2777944e02029220023b8470746002818bf4ff0ff3766e7092e00f3fe80052e00f03e82072e40f0028400274ff0010947f67f764ff07f080d943ae000294ff0ff3708bf002b7ff47caf1328bff479af102a4ff0000138bf01211228b2fa82f218bf510901297ff46caf0Line truncated
"new": "b0b581ea00039b0701d0034637e0c2b110f0030315d000f1010ca2f1010e0023cc5c9e45c45403f1010404d0634413f003032346f4d121440319121b102a14d302e00346102a10d3d1f800c0d1f804e0cc688d68103adc609d60c3f804e043f810cb0f2a01f11001eed8042a07d300bf51f8045b043a032a43f8045bf8d8002a08bfb0bd0139013b11f8015f013a03f8015ff9d1b0bd00bf884218bf002a00d1704710b50b1a38bf431a934207d288420ad281ea00039b0726d0034669e0fff79fffbde81040704781ea000300eb020c9b0701eb020e42d15fea8c732bd0a0f1010c00bf8b1813f801ec8418531e04f801ec04d0624412f003021a46f2d101eb030e00eb030c17e0830736d0a2f1010c00f1010e002300bfcc5c9c45c45403f1010404d0734413f003032346f4d1121b2144031922e01346042b0ed3aef10402acf1040152f80449043b032b41f80449f8d802f1040e01f1040c1a4653b1aef10101acf1010300bf11f80149013a03f80149f9d1bde8104070470346042a06d351f8044b043a032a43f8044bf8d8002af0d00139013b00bf11f8014f013a03f8014ff9d1e6e700bf80b5002a18bf10f0030301d186460ce000f1010c864600bf013a0ef8011b04d01cf003030cf1010cf6d1102a11d35ffa81fc4ff001330cfb03fc00bf103acef80cc0cef808c0cef804c04ef810cb0f2af4d8042a0bd35ffa81fc4ff001330cfb03fc00bf043a032a4ef804cbfad8002a08bf80bdaef10103013a03f8011ffbd180bd00bf2de9f04fc7b04ff29c5bc2f2290b4ff6ff754ff47e740027012647f67f784ff07f0a1191cde90f3007e000bf48f2a351c0f24501bff32f8f8847dbf80090bff35f8fdbf800000321cff680710140b1f1005fbff35f8f0ad101684ef66c62ccf2ff02914203d14068b0f57e7f3ed04ff47e7006f017fa002800f01b816ff0070142180831b1f57c7f177257729772d772177357739773d773f2d14ef66c61ccf2ff01016044608673a0f8c48180f8c3a1058445848584c584058545858585c585058645868586c586058745878587c5875be8001f4945a9d1bff35f8f4be8000121b15be8001f4945f8d09fe74ff47e7800264ff0010a47f67f797f2707e000bf48f2a351c0f24501bff32f8f8847dbf80040bff35f8fdbf800000321cff680710140b1f1005fbff35f8f0ad101684ef66c62ccf2ff02914203d14168b1f57e7f40d04ff47e7006f0adf9002800f0b1806ff0070142180831b1f57c7f167256729672d672167356739673d673f2d14ef66c61ccf2ff010160c0f8048080f80ea0a0f8c49180f8c371058445848584c584058545858585c585058645868586c586058745878587c5875be8001fa142a7d1bff35f8f4be8000121b15be8001fa142f8d09de7d0f8948242f6f76ac0f2440ab8f1000fbff35f8f4ad00af19a0240464ff0ff314ff0ff379047002840f036811198002860d010980778a7f1170002285ad811980c2840f02381109c6078a178084300f01d81e0780138022800f21881a279e379667a42ea0322237a207942ea034242ea0663a27ae67a6179192f42ea062200f08481172f40f09a81002a40f0ff80fe2800f0b285812800f0a585002840f0b88551ea030040f0f28000f002be04460020d047e0b104f5257151e8008fb8f1000f0cd1bff35f8f00bf41e80002002a00f08b8051e8008fb8f1000ff5d00021bff32f8f0029bff35f8f7ad0804693e74ff0ff37d1e047f6df40c0f24f00cdf83880804700274ff47e784ff0010947f67f764ff07f0a1397adf8507006e048f2a351c0f24501bff32f8f8847dbf80040bff35f8fdbf800000321cff680710140b1f1005fbff35f8f0ad101684ef66c62ccf2ff02914203d14168b1f57e7f47d04ff47e7006f0bdf8002840d06ff0070100bf42180831b1f57c7f177257729772d772177357739773d773f2d14ef66c61ccf2ff010160c0f8048080f80e90a0f8c46180f8c3a1058445848584c584058545858585c585058645868586c586058745878587c5875be8001fa142a7d1bff35f8f4be8000159b15be8001fa142f8d09de70af5a971884716e701217ae70020109f42f6f76addf83880c0f2440a9fb1119989b1397801f07f02b2f10b0418bf0124b2f11c0618bf01268a2924dc0b2926d01c2924d03ce00f9012a803f055fd4ff0ff3701269df85100002812a818bf4ff0ff3703f019fe054646b99df8500028b94af21f30c0f247004c3080470f98002818bf056114e09c2901d08b2918d168b14af21f31c0f247010746884797f8681121b997f824133846109f49b14ff0ff370af5807140468847384647b0bde8f08f0f9012a8264003f017fd387800f07f041e2c05d11199384608f048fd0746b9e71d2c00f07e0018bf1a2819d1dbf800100322cff680720a40b2f1005fbff35f8f12d10a684ef66c63ccf2ff039a420bd14a68b2f57e7f04bf002281f8a12303e0a4f115010129e1d90f2c2cdd142c40f3bb81152c00f0ba82162c00f0c4821f2c40f088831198012840f0588438781f2840f0548445f64d54c0f24604a047012841f0388041f21051c0f2010104f5e2777944e02029220023b8470746002818bf4ff0ff3766e7092c00f3a980052c00f0f081072c40f05e830d9600264ff0010947f67f744ff07f083ae000294ff0ff3708bf002b7ff47caf1328bff479af102a4ff0000138bf01211228b2fa82f218bf510901297ff46caf00f07abc182f4ff0ff3708bf00297ff463af002b7ff460af352800f36483002800f05284012800f05e84312840f05084082abff451af00f05fbc48f2a351c0f24501bff32f8f8847dbf80070bff35f8fdbf800000321cff680710140b1f1005fbff35f8f0bd101684ef66c62ccf2ff02914204d14168b1f57e7f00f060854ff47e7005f051ff002800f058856ff0070142180831b1f57c7f167256729672d672167356739673d673f2d14ef66c61ccf2ff0101604ff47e71416080f80e90a0f8c44180f8c381058445848584c584058545858585c585058645868586c586058745878587c5875be8001fb942a5d1bff35f8f4be80001002900f021855be8001fb942f6d099e70a2c00f0bc810b2c40f0b582dbf800500320cff680702840b0f1005fbff35f8f40f0698728684ef66c61ccf2ff01884240f0618768680027b0f57e7f7ff49baed5f8900342f68d49c0f244090028a5f8a07318bfc8470021a5f8d013c5f8cc13c5f86c1185f86a1185f86811d5f87001c5f8641185f86911c5f87011c5f82013a5f88c1320b148f2a351c0f245018847d5f89802002818bf03f099fd0024c5f89842d5f8880320b148f2a351c0f245018847c5f88843a5f88c43686ca5f8484040b1c847686c09f166018847002804bf002068644bf63940c0f251008047dbf800400320cff680702040b0f1005fbff35f8f48d120684ef66c61ccf2ff01884241d16068b0f57e7f3dd194f87b014Line truncated
"desc": "append injected blobs to main-app payload"
},
{
"offset": 779123,
"old": "805a3900",
"new": "68703a00",
"new": "187c3a00",
"desc": "main-app subheader payload size (ps)"
},
{
"offset": 152,
"old": "005b3900",
"new": "e8703a00",
"new": "987c3a00",
"desc": "main-app TOC entry size (ps + 128)"
},
{
"offset": 779243,
"old": "805a3904",
"new": "68703a04",
"new": "187c3a04",
"desc": "main-app preamble length (low 24 bits)"
},
{
"offset": 779247,
"old": "effdbcea",
"new": "0b0c48b0",
"new": "ed6f6deb",
"desc": "[5] ota/s200_firmware_ota.bin preamble crc32"
},
{
"offset": 156,
"old": "c0c6322a",
"new": "52937d21",
"new": "7141aa39",
"desc": "[5] ota/s200_firmware_ota.bin component crc32c (TOC)"
},
{
"offset": 779127,
"old": "c0c6322a",
"new": "52937d21",
"new": "7141aa39",
"desc": "[5] ota/s200_firmware_ota.bin component crc32c (subheader)"
}
]
+3 -2
View File
@@ -82,7 +82,7 @@ export class GlanceHost {
* The glance event a sleep-time gesture means under the board's settings,
* or null when the shell should see the input as usual: nothing while the
* board is disabled, no press from a tap when "Show on tap" is disabled,
* no hold when "Show on long press" is off, no press from a head-tilt when
* no hold when "Show on long press" is off, no tilt from a head-tilt when
* "Show on head tilt" is off (it then wakes the regular UI). A release
* always passes so a hold in progress can end.
*/
@@ -92,7 +92,8 @@ export class GlanceHost {
if (gesture === "click" && !provider.showOnTap()) return null;
if ((gesture === "long-press" || gesture === "short-then-long-press") && !provider.showOnLongPress()) return null;
if (gesture === "head-tilt" && !provider.showOnHeadTilt()) return null;
return glanceEventForGesture(gesture, this.isVisible());
const event = glanceEventForGesture(gesture, this.isVisible());
return event?.type === "tilt" ? { type: "tilt", maxMs: provider.tiltTimeoutMs() } : event;
}
/**
+82 -12
View File
@@ -1,9 +1,10 @@
/**
* The Glanceboard's visibility rules, as a pure reducer so they can be tested
* without the display plumbing. The board is an alternate sleep-time display:
* while the shell is asleep a press (single tap, or a head-tilt wake) shows it
* for a short while, a hold (long-press or short-then-long-press) shows it until release,
* and a double-tap dismisses it in favour of the regular UI. GlanceHost feeds
* while the shell is asleep a press (single tap) shows it for a short while, a
* head-tilt wake shows it until the head comes back down, a hold (long-press or
* short-then-long-press) shows it until release, and a double-tap dismisses it
* in favour of the regular UI. GlanceHost feeds
* these events in and applies the resulting visibility to the compositor.
*
* No NativeScript imports: this module is compiled and run under plain node
@@ -13,17 +14,67 @@
/** Fallback press timeout when the host supplies none; each further press restarts it. */
export const GLANCE_TIMEOUT_MS = 3000;
/**
* Default cap for a head-tilt showing: the board normally stays up until the
* head comes back down (as the stock dashboard does), but a lost head-down
* event should not leave it on indefinitely. The user's Head tilt timeout
* setting replaces it (and may remove it).
*/
export const GLANCE_TILT_MAX_MS = 60_000;
/**
* The firmware reports head-down once the pitch falls 20° below the head-up
* trigger (a fixed hysteresis in DRV_IMUCheckHeadUpEvent). Under this trigger,
* looking level again does not get below that, so the head-down may never come.
*/
export const GLANCE_LOW_TILT_TRIGGER_DEGREES = 25;
/**
* How long a head-tilt showing may last without a head-down: capMs (the Head
* tilt timeout; null = no limit), except when the head-down is unlikely to
* arrive, where the tap duration is used if shorter: a tilt that woke a
* suspended EvenHub session (the head-down is only forwarded once the page is
* back, so a quick glance can end before that), or a trigger too low for a
* level gaze to count as looking down. triggerDegrees is the glasses'
* trigger, or null when not known.
*/
export function glanceTiltMaxMs(options: {
capMs: number | null;
resumedSession: boolean;
triggerDegrees: number | null;
tapTimeoutMs: number;
}): number | null {
const lowTrigger =
options.triggerDegrees !== null && options.triggerDegrees > 0 && options.triggerDegrees < GLANCE_LOW_TILT_TRIGGER_DEGREES;
if (!options.resumedSession && !lowTrigger) return options.capMs;
return options.capMs === null ? options.tapTimeoutMs : Math.min(options.capMs, options.tapTimeoutMs);
}
export type GlanceState = {
visible: boolean;
/** A long-press is holding the board up; the timer does not run meanwhile. */
holding: boolean;
/**
* A head-tilt is holding the board up: it stays until the firmware reports
* the head back down (or tiltMaxMs passes).
*/
tilted: boolean;
/** The current head-tilt's cap (0 when not tilted, null for none); a hold ending mid-tilt re-arms it. */
tiltMaxMs: number | null;
/** When the board hides on its own (epoch ms), or null while held / hidden. */
hideAtMs: number | null;
};
export type GlanceEvent =
/** Single tap or head-tilt wake: show, and (re)start the auto-hide timer. */
/** Single tap: show, and (re)start the auto-hide timer. */
| { type: "press" }
/**
* Head-tilt (IMU head-up): show until the head comes back down, or until
* maxMs passes (default GLANCE_TILT_MAX_MS; null = no limit).
*/
| { type: "tilt"; maxMs?: number | null }
/** The IMU reported the head back down: ends a head-tilt showing. */
| { type: "head-down" }
/** Long-press: show and keep showing until the release. */
| { type: "hold" }
/** The long-press ended. */
@@ -33,7 +84,7 @@ export type GlanceEvent =
/** Double-tap (or any other wake of the regular UI): hide now. */
| { type: "dismiss" };
export const GLANCE_HIDDEN: GlanceState = Object.freeze({ visible: false, holding: false, hideAtMs: null });
export const GLANCE_HIDDEN: GlanceState = Object.freeze({ visible: false, holding: false, tilted: false, tiltMaxMs: 0, hideAtMs: null });
export function reduceGlance(
state: GlanceState,
@@ -43,14 +94,26 @@ export function reduceGlance(
): GlanceState {
switch (event.type) {
case "press":
// A tap during a hold changes nothing: the hold decides when it ends.
if (state.holding) return state;
return { visible: true, holding: false, hideAtMs: nowMs + timeoutMs };
// A tap during a hold or a head-tilt changes nothing: those decide when it ends.
if (state.holding || state.tilted) return state;
return { visible: true, holding: false, tilted: false, tiltMaxMs: 0, hideAtMs: nowMs + timeoutMs };
case "tilt": {
const maxMs = event.maxMs === undefined ? GLANCE_TILT_MAX_MS : event.maxMs;
return { visible: true, holding: state.holding, tilted: true, tiltMaxMs: maxMs, hideAtMs: state.holding ? null : tiltHideAt(nowMs, maxMs) };
}
case "head-down":
// Only a head-tilt showing ends with the head; a tap's timer or a hold keeps running.
if (!state.tilted) return state;
return state.holding ? { ...state, tilted: false, tiltMaxMs: 0 } : GLANCE_HIDDEN;
case "hold":
return { visible: true, holding: true, hideAtMs: null };
return { visible: true, holding: true, tilted: state.tilted, tiltMaxMs: state.tiltMaxMs, hideAtMs: null };
case "release":
// Releases delivered late or after a disabled hold gesture mean nothing here.
return state.holding ? GLANCE_HIDDEN : state;
if (!state.holding) return state;
// Head still up: the board stays, as if the tilt had just shown it.
return state.tilted
? { visible: true, holding: false, tilted: true, tiltMaxMs: state.tiltMaxMs, hideAtMs: tiltHideAt(nowMs, state.tiltMaxMs) }
: GLANCE_HIDDEN;
case "timeout":
if (!state.visible || state.holding || state.hideAtMs === null || nowMs < state.hideAtMs) return state;
return GLANCE_HIDDEN;
@@ -59,6 +122,10 @@ export function reduceGlance(
}
}
function tiltHideAt(nowMs: number, maxMs: number | null): number | null {
return maxMs === null ? null : nowMs + maxMs;
}
/**
* Which glance event, if any, a shell input gesture means while the screen is
* off. A double-tap only concerns the board while it is showing (it then
@@ -66,13 +133,16 @@ export function reduceGlance(
* already handles or ignores while asleep.
*/
export function glanceEventForGesture(
gesture: "click" | "double-click" | "long-press" | "short-then-long-press" | "long-press-release" | "head-tilt" | (string & {}),
gesture: "click" | "double-click" | "long-press" | "short-then-long-press" | "long-press-release" | "head-tilt" | "head-down" | (string & {}),
boardVisible: boolean,
): GlanceEvent | null {
switch (gesture) {
case "click":
case "head-tilt":
return { type: "press" };
case "head-tilt":
return { type: "tilt" };
case "head-down":
return boardVisible ? { type: "head-down" } : null;
case "long-press":
case "short-then-long-press":
return { type: "hold" };
+151
View File
@@ -0,0 +1,151 @@
import { addImuListener, imuPitchDegrees, setImuReportEnabled, type ImuReading } from "../native/imu";
import { getHeadUpStatus, setHeadUpTrigger, type HeadUpStatus } from "../native/glasses-controls";
import { getStringSetting, setStringSetting } from "../native/settings-store";
import { glanceAngleTriggerDegrees } from "../apps/glanceboard/glanceboard-settings";
// Same ImuReportPace code the accelerometer demo uses (not literal Hz).
const IMU_REPORT_PACE = 200;
/** How often the live reading checks visibility and repaints a changed value. */
const LIVE_TICK_MS = 250;
/** Weight of each new sample in the smoothed pitch. */
const LIVE_SMOOTHING = 0.3;
/** A reading older than this (or none this long after the stream started) is shown as missing. */
const LIVE_STALE_MS = 3_000;
/**
* The head's pitch, live, for the Head tilt angle picker. The IMU report
* stream runs while `visible()` holds (checked every tick, so it stops while
* the screen is off or the window is in the background) and until stop().
* text() is the footer line; a changed value repaints at most once a tick.
*/
class LiveHeadPitch {
private pitch: number | null = null;
private lastSampleAt = 0;
private streaming = false;
private streamingSince = 0;
private shown = "";
private readonly unsubscribe: () => void;
private readonly timer: ReturnType<typeof setInterval>;
constructor(
private readonly visible: () => boolean,
private readonly repaint: () => void,
) {
this.unsubscribe = addImuListener((reading) => this.onReading(reading));
this.timer = setInterval(() => this.tick(), LIVE_TICK_MS);
this.tick();
}
text(): string {
return this.shown;
}
stop(): void {
clearInterval(this.timer);
this.unsubscribe();
if (this.streaming) setImuReportEnabled(false, IMU_REPORT_PACE);
this.streaming = false;
}
private onReading(reading: ImuReading): void {
// Glasses temples only (1 right, 3 left, 0 unspecified); the ring is 2.
if (!this.streaming || reading.source === 2) return;
if (!(Math.hypot(reading.x, reading.y, reading.z) > 1e-6)) return;
const pitch = imuPitchDegrees(reading);
this.pitch = this.pitch === null ? pitch : this.pitch + LIVE_SMOOTHING * (pitch - this.pitch);
this.lastSampleAt = Date.now();
}
private tick(): void {
const now = Date.now();
const visible = this.visible();
if (visible !== this.streaming) {
setImuReportEnabled(visible, IMU_REPORT_PACE);
this.streaming = visible;
this.streamingSince = now;
this.pitch = null;
}
const text = this.format(now);
if (text !== this.shown) {
this.shown = text;
this.repaint();
}
}
private format(now: number): string {
if (this.pitch !== null && now - this.lastSampleAt < LIVE_STALE_MS) return `Head now: ${Math.round(this.pitch)}°`;
return now - Math.max(this.streamingSince, this.lastSampleAt) < LIVE_STALE_MS ? "Head now: …" : "Head now: no data";
}
}
/**
* The Head tilt angle picker's footer: the head's current pitch, read while
* the picker is open and `visible()` holds (enumSettingMenuItem pickerFooter).
*/
export function liveHeadPitchFooter(visible: () => boolean): { text: () => string; open: (repaint: () => void) => () => void } {
let reader: LiveHeadPitch | null = null;
return {
text: () => reader?.text() ?? "",
open: (repaint) => {
const opened = new LiveHeadPitch(visible, repaint);
reader = opened;
return () => {
opened.stop();
if (reader === opened) reader = null;
};
},
};
}
// The glasses' own head-up switch and angle from before Faceclaw first changed
// them, as "switch,angle", or "" when none is held. Kept here (not only in the
// session) so "Glasses default" can still restore them after an app restart.
const ORIGINAL_KEY = "glanceboard.headTiltOriginal";
function savedOriginal(): { switch: number; angle: number } | null {
const [sw, angle] = getStringSetting(ORIGINAL_KEY, "").split(",").map(Number);
return (sw === 0 || sw === 1) && Number.isInteger(angle) ? { switch: sw, angle } : null;
}
/**
* Push the wanted trigger to the session (on change and on each connect):
* the Head tilt angle while the Glanceboard is enabled, else none, which
* writes back the glasses' own values if Faceclaw changed them.
*/
export function applyGlanceAngle(): boolean {
const sent = setHeadUpTrigger(glanceAngleTriggerDegrees(), savedOriginal());
syncGlanceAngleOriginal();
return sent;
}
/**
* Keep the persisted original in step with the session: save the values the
* session captured before its first write, and drop them once a read shows
* them restored. Called on apply, from the controller's periodic refresh, and
* when the settings row draws.
*/
export function syncGlanceAngleOriginal(status: HeadUpStatus | null = getHeadUpStatus()): void {
if (!status) return;
const saved = savedOriginal();
if (!saved) {
if (status.originalSwitch === 0 || status.originalSwitch === 1) {
setStringSetting(ORIGINAL_KEY, `${status.originalSwitch},${status.originalAngle}`);
}
return;
}
if (
glanceAngleTriggerDegrees() === 0 &&
status.desired < 0 &&
!status.restorePending &&
status.switch === saved.switch &&
status.angle === saved.angle
) {
setStringSetting(ORIGINAL_KEY, "");
}
}
/** The glasses' current head-up trigger (angle + calibration), 0 when off, or null when not read yet. */
export function glassesHeadUpTrigger(status: HeadUpStatus | null = getHeadUpStatus()): number | null {
if (!status || status.switch < 0) return null;
return status.switch === 1 ? status.angle + status.calibration : 0;
}
+48 -2
View File
@@ -29,6 +29,8 @@ import { OsEventTypeList } from './events'
import { loadDeviceAddresses } from './device-addresses'
import { updateGlassesPresence } from './glasses-presence'
import { firmwareIncompatibilityMessage, hasCompatibleFirmware } from './firmware-compat'
import { keyboardService } from './keyboard/service'
import type { KeyEvent } from './keyboard/keys'
import { isHaltedSessionPhase, resumeAutoReconnect, suppressAutoReconnect } from './reconnect-policy'
import { WearRemote, type WearRemoteInputKind } from './wear-remote'
import { deviceAddressError } from './ios-peripheral-identity'
@@ -232,6 +234,7 @@ export class IosPreviewController {
if (!on) void this.display?.setScreenBlanked(true).catch(error => this.fail(error))
this.requestShellRender()
this.wearRemote?.schedulePublish()
if (on) keyboardService.retryNow()
},
})
const launcher = createLauncherWindow({
@@ -270,6 +273,28 @@ export class IosPreviewController {
assistantAvailable: () => shell.isAssistantAvailable(),
assistant: text => shell.sendToAssistant(text),
})
// A keyboard paired through the glasses (the CFW keyboard bridge). The service decides what
// each key means (app/g2/keyboard/key-router.ts); its gestures share the controller queue
// with physical input, like the watch's.
const queueKeyboardInput = (run: () => Promise<void>): Promise<void> => {
const task = this.inputQueue.then(() => { this.onActivity(); return run() })
this.inputQueue = task.catch(error => this.fail(error))
return task
}
keyboardService.setHost({
ready: () => this.state.phase === 'connected',
locked: () => this.glassesLocked,
wake: () => { void queueKeyboardInput(() => this.receiveInput(makeInputEvent({ type: 'display-wake' }))).catch(() => {}) },
gesture: (gesture, origin) => queueKeyboardInput(async () => {
await this.receiveInput(makeInputEvent({ type: gesture, source: origin } as InputEventPayload))
// A discrete hold includes its release.
if (gesture === 'long-press') await this.receiveInput(makeInputEvent({ type: 'long-press-release', source: origin }))
}),
log: line => this.logBluetooth(line),
// Only while the display is on: a keyboard that is switched off would otherwise keep the
// glasses' radio looking for it around the clock.
shouldReconnect: () => this.state.phase === 'connected' && shell.isScreenOn(),
})
// The header's EvenHub phone-UI button hides while that UI is showing.
onPhoneShownChanged(() => this.syncEvenHubPhoneUi())
registerSystemTools()
@@ -809,6 +834,7 @@ export class IosPreviewController {
},
setSurfaceVisible: (id, visible) => this.setWindowSurfaceVisible(id, visible),
removeSurface: id => this.removeWindowSurface(id),
unhandledKey: event => keyboardService.handleUnhandledKey(event as KeyEvent),
submitPixels: (id, pixels, width, height, draws) => {
void this.submitWorkerPixels(id, pixels, width, height, draws).catch(error => this.fail(error))
},
@@ -830,6 +856,18 @@ export class IosPreviewController {
this.state = { ...this.state, phase, status }
this.logBluetooth(status)
this.emitState()
this.syncKeyboardLink()
}
/**
* Tell the keyboard bridge whether the session can host a keyboard: a G2 on firmware with
* the bridge, connected. On a disconnect the user asked for, the link is still up when the
* phase turns, so the firmware is told to let the keyboard go first.
*/
private syncKeyboardLink(): void {
const up = !!this.communicator && this.state.phase === 'connected' && this.firmwareCompatible
&& glassesTypeSetting.get() === 'g2'
if (up) keyboardService.linkReady()
else keyboardService.linkLost(this.state.phase === 'disconnecting')
}
/** Mirror the session into glasses-presence (read by EvenHub's device status and Timers). */
private syncPresence(): void {
@@ -949,6 +987,7 @@ export class IosPreviewController {
const firmwareWarning = firmwareIncompatibilityMessage(info) ?? ''
if (firmwareWarning && firmwareWarning !== this.state.firmwareWarning) this.logBluetooth(`Firmware compatibility warning: ${firmwareWarning}`)
this.firmwareCompatible = !firmwareWarning && hasCompatibleFirmware(info)
this.syncKeyboardLink()
this.state = { ...this.state, leftVersion: info.leftVersion || this.state.leftVersion,
rightVersion: info.rightVersion || this.state.rightVersion, capabilities: info.extension || this.state.capabilities,
firmwareWarning }
@@ -1013,6 +1052,13 @@ export class IosPreviewController {
private handleRingEvent(input: RawInputEvent): void {
this.inputQueue = this.inputQueue.then(async () => {
if (this.state.phase !== 'connected') return
if (input.kind === 'sys-event' && input.eventType === OsEventTypeList.HEAD_DOWN_EVENT) {
// As on Android: only the Glanceboard uses it (it ends a head-tilt
// showing); it never reaches the shell or counts as activity.
const glanceEvent = this.glance.eventForGesture('head-down')
if (glanceEvent) await this.glance.handleEvent(glanceEvent, 0)
return
}
this.onActivity()
if (input.ringInput) this.state = { ...this.state, ring: true }
await this.receiveInput(rawInputEventToInputEvent(input),
@@ -1111,8 +1157,8 @@ export class IosPreviewController {
/**
* Continuous capture on behalf of `client` (one id per window: Transcribe,
* Translate, Teleprompter, Calculator); it runs while any client wants it, as
* on Android. `recordAs` names a WAV of the audio in Downloads when Save
* Recording is on.
* on Android. `recordAs` names a recording (.mka) of the audio in Downloads
* when Save Recording is on.
*/
private startContinuousVoiceCapture(client: string, options: ContinuousCaptureOptions = {}): void {
this.continuousClients.set(client, options)
+266
View File
@@ -0,0 +1,266 @@
/**
* What keys from a hardware keyboard do, apart from typing: the built-in
* defaults, the user's custom keybindings, and how the two combine.
*
* A key becomes one of the gestures the ring and the watch already have, so
* nothing downstream knows about keyboards. Three layers, first match wins:
*
* 1. Custom keybindings (Settings > Keyboard > Keybindings). These apply
* everywhere, including where the focused window takes keys for itself
* (a terminal session), since that is the point of binding a remote's
* few buttons.
* 2. Built-in bindings that also apply there: Escape with Shift, Ctrl or
* Alt goes back, which is the way out of a terminal session.
* 3. Built-in navigation, only for keys no window took: the arrows are the
* watch's four swipes, Enter selects, Escape goes back.
*
* No platform imports: this runs under node in the tests.
*/
import type { KeyEvent } from "./keys";
/** A gesture a key can stand for, named as the input pipeline names it. */
export type KeyGesture =
| "swipe-up"
| "swipe-down"
| "swipe-left"
| "swipe-right"
| "scroll-up"
| "scroll-down"
| "click"
| "double-click"
| "long-press"
| "short-then-long-press";
/**
* What a custom keybinding does. "none" turns off the key's built-in
* navigation meaning; it does not stop the key being typed into a window
* that takes keys.
*/
export type KeyAction = KeyGesture | "none";
/** The actions, in the order the picker lists them. */
export const KEY_ACTIONS: readonly { action: KeyAction; label: string }[] = [
{ action: "click", label: "Select" },
{ action: "double-click", label: "Back" },
{ action: "swipe-up", label: "Swipe up" },
{ action: "swipe-down", label: "Swipe down" },
{ action: "swipe-left", label: "Swipe left" },
{ action: "swipe-right", label: "Swipe right" },
{ action: "scroll-up", label: "Scroll up" },
{ action: "scroll-down", label: "Scroll down" },
{ action: "long-press", label: "System menu" },
{ action: "short-then-long-press", label: "App menu" },
{ action: "none", label: "Nothing" },
];
export function keyActionLabel(action: KeyAction): string {
return KEY_ACTIONS.find((entry) => entry.action === action)?.label ?? action;
}
function isKeyAction(value: unknown): value is KeyAction {
return KEY_ACTIONS.some((entry) => entry.action === value);
}
/** A physical key with the modifiers held: what a keybinding is keyed on. */
export type KeyChord = { code: string; shift: boolean; ctrl: boolean; alt: boolean; meta: boolean };
export type KeyBinding = { chord: KeyChord; action: KeyAction };
const MODIFIER_CODES = new Set([
"ControlLeft", "ControlRight", "ShiftLeft", "ShiftRight", "AltLeft", "AltRight", "MetaLeft", "MetaRight",
]);
/** Shift, Ctrl, Alt and Meta themselves: they qualify a chord rather than being one. */
export function isModifierCode(code: string): boolean {
return MODIFIER_CODES.has(code);
}
export function chordOf(event: KeyEvent): KeyChord {
const { shift, ctrl, alt, meta } = event.modifiers;
return { code: event.code, shift, ctrl, alt, meta };
}
/** Canonical text of a chord ("Ctrl+Shift+Escape"): the stored form, and the lookup key. */
export function chordId(chord: KeyChord): string {
return [chord.ctrl && "Ctrl", chord.alt && "Alt", chord.shift && "Shift", chord.meta && "Meta", chord.code]
.filter(Boolean).join("+");
}
/** The inverse of chordId, or null for anything it could not have produced. */
export function parseChordId(text: string): KeyChord | null {
const parts = text.split("+");
const code = parts.pop() ?? "";
if (!/^[A-Za-z][A-Za-z0-9]{0,39}$/.test(code) || isModifierCode(code)) return null;
const chord: KeyChord = { code, shift: false, ctrl: false, alt: false, meta: false };
for (const part of parts) {
if (part === "Ctrl" && !chord.ctrl) chord.ctrl = true;
else if (part === "Alt" && !chord.alt) chord.alt = true;
else if (part === "Shift" && !chord.shift) chord.shift = true;
else if (part === "Meta" && !chord.meta) chord.meta = true;
else return null;
}
return chord;
}
const CODE_LABELS: Record<string, string> = {
ArrowUp: "Up", ArrowDown: "Down", ArrowLeft: "Left", ArrowRight: "Right",
Escape: "Esc", PageUp: "Page Up", PageDown: "Page Down", CapsLock: "Caps Lock",
PrintScreen: "Print Screen", ScrollLock: "Scroll Lock", NumLock: "Num Lock", ContextMenu: "Menu",
Minus: "-", Equal: "=", BracketLeft: "[", BracketRight: "]", Backslash: "\\", IntlBackslash: "\\",
IntlHash: "#", Semicolon: ";", Quote: "'", Backquote: "`", Comma: ",", Period: ".", Slash: "/",
AudioVolumeUp: "Volume Up", AudioVolumeDown: "Volume Down", AudioVolumeMute: "Mute",
MediaPlayPause: "Play/Pause", MediaPlay: "Play", MediaPause: "Pause", MediaStop: "Stop",
MediaTrackNext: "Next Track", MediaTrackPrevious: "Previous Track",
BrightnessUp: "Brightness Up", BrightnessDown: "Brightness Down",
BrowserSearch: "Search", BrowserHome: "Browser Home", BrowserBack: "Browser Back", BrowserForward: "Browser Forward",
LaunchMail: "Mail", LaunchApplication1: "App 1", LaunchApplication2: "App 2",
};
/** A key as a person would name it. Unknown keys keep their HID usage number, which is all there is. */
function codeLabel(code: string): string {
const known = CODE_LABELS[code];
if (known) return known;
let match = /^Key([A-Z])$/.exec(code);
if (match) return match[1]!;
match = /^Digit([0-9])$/.exec(code);
if (match) return match[1]!;
match = /^Numpad(.+)$/.exec(code);
if (match) return `Numpad ${match[1]}`;
match = /^Usage([0-9a-f]+)$/.exec(code);
if (match) return `Key 0x${match[1]}`;
match = /^Consumer([0-9a-f]+)$/.exec(code);
if (match) return `Media key 0x${match[1]}`;
return code;
}
/** A chord for display: "Shift+Esc", "Left", "Volume Up". */
export function describeChord(chord: KeyChord): string {
return [chord.ctrl && "Ctrl", chord.alt && "Alt", chord.shift && "Shift", chord.meta && "Meta", codeLabel(chord.code)]
.filter(Boolean).join("+");
}
/** The most custom keybindings kept; far more than a keyboard has uses for. */
export const MAX_KEY_BINDINGS = 64;
/**
* Custom keybindings from their stored JSON. Lenient: whatever doesn't make
* sense is dropped, and a later entry for a chord replaces an earlier one.
*/
export function parseKeyBindings(raw: string): KeyBinding[] {
let parsed: unknown;
try {
parsed = raw ? JSON.parse(raw) : [];
} catch {
return [];
}
if (!Array.isArray(parsed)) return [];
const bindings = new Map<string, KeyBinding>();
for (const entry of parsed) {
if (!entry || typeof entry !== "object") continue;
const { key, action } = entry as { key?: unknown; action?: unknown };
const chord = typeof key === "string" ? parseChordId(key) : null;
if (!chord || !isKeyAction(action)) continue;
bindings.set(chordId(chord), { chord, action });
if (bindings.size >= MAX_KEY_BINDINGS) break;
}
return [...bindings.values()];
}
export function serializeKeyBindings(bindings: readonly KeyBinding[]): string {
return JSON.stringify(bindings.map((binding) => ({ key: chordId(binding.chord), action: binding.action })));
}
/** Custom keybindings as the lookup resolveKey takes. */
export function keyBindingMap(bindings: readonly KeyBinding[]): Map<string, KeyAction> {
return new Map(bindings.map((binding) => [chordId(binding.chord), binding.action]));
}
/**
* The built-in meaning of a key press, or null when it has none.
* `overridesTyping`: it holds even where the focused window takes keys.
* Built-ins go by the logical key, so both Enter keys select.
*/
export function defaultKeyAction(event: KeyEvent): { action: KeyGesture; overridesTyping: boolean } | null {
const { shift, ctrl, alt, meta } = event.modifiers;
if (meta) return null;
if (event.key === "Escape") {
// Plain Escape belongs to whatever takes keys (it is a keystroke in a
// terminal); with a modifier it always means "back out of here".
return { action: "double-click", overridesTyping: shift || ctrl || alt };
}
if (ctrl || alt) return null;
switch (event.key) {
case "ArrowUp":
return { action: "swipe-up", overridesTyping: false };
case "ArrowDown":
return { action: "swipe-down", overridesTyping: false };
case "ArrowLeft":
return { action: "swipe-left", overridesTyping: false };
case "ArrowRight":
return { action: "swipe-right", overridesTyping: false };
case "Enter":
return { action: "click", overridesTyping: false };
default:
return null;
}
}
/** The built-ins, for showing to the user. Keep in step with defaultKeyAction. */
export const DEFAULT_KEYS_HELP =
"Arrow keys: swipe up, down, left and right, as on the watch. Enter: select. Esc: back.\n\n" +
"In a terminal session those keys are typed instead, and Shift+Esc (or Ctrl+Esc, Alt+Esc) goes back.\n\n" +
"A custom keybinding replaces these for its key and works everywhere, terminals included. " +
"\"Nothing\" turns a key's meaning here off without stopping it being typed.";
/**
* Whether holding the key repeats the gesture. Moving up and down a list
* does. Sideways swipes don't: depending on the layout they enter and leave
* things, and a held key would flap between the two. Selecting, backing out
* and menus act once per press.
*/
export function gestureRepeats(gesture: KeyGesture): boolean {
return gesture === "scroll-up" || gesture === "scroll-down" || gesture === "swipe-up" || gesture === "swipe-down";
}
export type KeyResolution = {
/** The key is spoken for: don't offer it to the focused window. */
consume: boolean;
/**
* The gesture to perform: at once when `consume`, otherwise only if no
* window takes the key. Null for none (including a held key's repeats of
* a gesture that doesn't repeat).
*/
gesture: KeyGesture | null;
};
/** What one key press (or auto-repeat) means, given the custom keybindings. */
export function resolveKey(event: KeyEvent, custom: ReadonlyMap<string, KeyAction>): KeyResolution {
const repeatable = (gesture: KeyGesture): KeyGesture | null =>
event.repeat && !gestureRepeats(gesture) ? null : gesture;
const bound = custom.get(chordId(chordOf(event)));
if (bound !== undefined && bound !== "none") return { consume: true, gesture: repeatable(bound) };
// "none" takes the built-in meaning away and leaves the key to be typed.
if (bound === "none") return { consume: false, gesture: null };
const builtIn = defaultKeyAction(event);
if (!builtIn) return { consume: false, gesture: null };
return { consume: builtIn.overridesTyping, gesture: repeatable(builtIn.action) };
}
export type GestureOrigin = "ring" | "watch";
/**
* Which device a keyboard's gesture is presented as. Swipes are the watch's
* and scrolls the ring's; the two schemes differ in places (an icon grid
* moves by cell for the watch, by row and then cell for the ring). A tap, a
* double tap or a hold exists in both, so it goes with whichever the
* keyboard last moved with: arrow keys make the keyboard a watch, a remote
* bound to scroll makes it a ring. Before any movement, the watch.
*/
export class GestureScheme {
private scheme: GestureOrigin = "watch";
originFor(gesture: KeyGesture): GestureOrigin {
if (gesture.startsWith("swipe-")) this.scheme = "watch";
else if (gesture.startsWith("scroll-")) this.scheme = "ring";
return this.scheme;
}
}
+559
View File
@@ -0,0 +1,559 @@
/**
* The phone side of the CFW keyboard bridge for one glasses session: the
* client, the remembered keyboard, reconnecting it, and what the UI shows.
* The session hands it field-131 records and a way to send controls; the
* rest stays in here. Modelled on the Glassly app's G2KeyboardBridge (MIT).
*
* The firmware keeps nothing across a reboot (it comes back with the bridge
* off), and holds the keyboard's connection only while told to. So the
* remembered keyboard is brought back whenever the glasses link comes up and
* whenever the keyboard drops, backing off while it stays away. The
* discovered handle mapping is good for one connection and is never stored.
* No platform imports: this runs under node in the tests.
*/
import { KeyboardClient, KeyboardClientError, type KeyboardStatus } from "./client";
import type { HidKeyEvent } from "./hid";
import {
KeyboardDm,
KeyboardError,
mergeKeyboardAdverts,
parseKeyboardAddress,
type KeyboardAdvert,
} from "./protocol";
export type SavedKeyboard = { address: string; addressType: number; name: string };
export type KeyboardBridgeState =
/** No glasses link that can host a keyboard. */
| "unavailable"
| "idle"
| "scanning"
| "connecting"
| "pairing"
| "configuring"
| "connected"
| "error";
/** A pairing step waiting on the user. */
export type KeyboardPairingPrompt =
/** Type this on the keyboard, then Enter. */
| { kind: "display"; pin: number }
/** Confirm both sides show this value (answerCompare). */
| { kind: "compare"; value: number }
/** The keyboard shows a code to enter here (answerPasskey). */
| { kind: "entry" };
export type KeyboardBridgeSnapshot = {
state: KeyboardBridgeState;
saved: SavedKeyboard | null;
/** Name of the keyboard being connected or in use. */
activeName: string;
error: string;
pairing: KeyboardPairingPrompt | null;
/** Advertisers from the last scan, HID devices first, strongest first. */
scanResults: KeyboardAdvert[];
/** A user-started scan or connect is running. */
busy: boolean;
/** The remembered keyboard is away and the bridge keeps trying to bring it back. */
waiting: boolean;
};
export type KeyboardBridgeHost = {
/** Queue a control record on the live session; false when there is none. */
send(record: Uint8Array): boolean;
loadSaved(): SavedKeyboard | null;
storeSaved(saved: SavedKeyboard | null): void;
/** Key transitions from the keyboard (including forced releases). */
onKeys(events: HidKeyEvent[]): void;
/** The keyboard stopped being usable; drop held-key state without releases. */
onKeyboardGone(): void;
/** Something in snapshot() changed. */
onChanged(): void;
/**
* A line for the log. `routine` marks the ones that repeat for as long as
* a remembered keyboard stays away, which only a verbose log wants.
*/
log(line: string, routine?: boolean): void;
/** A fresh six-digit pairing passkey from a good random source. */
randomPasskey?(): number;
/**
* Whether looking for an absent keyboard is worthwhile now. Each attempt
* has the glasses' radio listening for the keyboard for up to half a
* minute, so the owner limits it to when the glasses are in use, and calls
* retryNow() when that starts. Default: always.
*/
shouldReconnect?(): boolean;
};
/** Delay before each automatic attempt after a failure; the last one repeats. */
const RECONNECT_BACKOFF_MS = [2_000, 5_000, 10_000, 20_000, 30_000];
/** After the glasses link comes up, before the first attempt. */
const RESUME_DELAY_MS = 1_000;
/** After the keyboard drops (it may just be going to sleep). */
const DROP_RETRY_DELAY_MS = 2_000;
const RELEASE_POLLS = 20;
const RELEASE_POLL_MS = 150;
export class KeyboardBridge {
private client: KeyboardClient | null = null;
private available = false;
private state: KeyboardBridgeState = "unavailable";
private saved: SavedKeyboard | null;
private activeName = "";
private error = "";
private pairing: KeyboardPairingPrompt | null = null;
private scanResults: KeyboardAdvert[] = [];
/** A user-started scan/connect holds the bridge. */
private busy = false;
/** The keyboard is connected, encrypted and subscribed. */
private ready = false;
private userDisconnected = false;
/** The keyboard was let go while the glasses were out of reach; tell the firmware when they are back. */
private releaseOnLink = false;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectAttempt = 0;
/** Bumped whenever the client is replaced; work started for an older one stops quietly. */
private generation = 0;
constructor(private readonly host: KeyboardBridgeHost) {
this.saved = host.loadSaved();
}
snapshot(): KeyboardBridgeSnapshot {
return {
state: this.state,
saved: this.saved,
activeName: this.activeName,
error: this.error,
pairing: this.pairing,
scanResults: sortAdverts(this.scanResults),
busy: this.busy,
waiting: this.available && !!this.saved && !this.ready && !this.userDisconnected && !this.busy,
};
}
/** True while key events can arrive. */
isConnected(): boolean {
return this.ready;
}
// ---------- Link lifecycle (driven by the session owner) ----------
/** The glasses link is up on firmware with the bridge: bring the remembered keyboard back. */
linkReady(): void {
if (this.available) return;
this.available = true;
this.userDisconnected = false;
this.reconnectAttempt = 0;
this.error = "";
const client = this.replaceClient();
this.setState("idle");
if (this.saved && !this.releaseOnLink) {
this.scheduleReconnect(RESUME_DELAY_MS);
} else if (this.releaseOnLink && client) {
this.userDisconnected = !!this.saved;
client.query().then((status) => {
if (status.enabled || status.conn) return client.disable();
}).catch(() => {});
}
this.releaseOnLink = false;
}
/** The glasses link is gone. Only the remembered keyboard survives. */
linkLost(): void {
if (!this.available && !this.client) return;
this.available = false;
this.cancelReconnect();
this.generation++;
this.client?.close();
this.client = null;
this.busy = false;
this.pairing = null;
this.error = "";
this.dropKeyboard();
this.setState("unavailable");
}
/**
* The app is about to close the glasses link on purpose: tell the firmware
* to let the keyboard go, so it isn't left attached to glasses nobody is
* listening to. Best effort; nothing waits for the answer.
*/
linkClosing(): void {
const client = this.client;
if (!client || !this.available || !client.status.enabled) return;
client.disable().catch(() => {});
}
/** One field-131 payload from the session. */
accept(payload: Uint8Array): void {
this.client?.accept(payload);
}
/**
* The keyboard may be reachable now, or is wanted now (the display woke):
* if it is away and the bridge is waiting out a backoff, try at once.
*/
retryNow(): void {
if (!this.available || !this.saved || this.ready || this.userDisconnected || this.busy) return;
// No timer means an attempt is already in flight.
if (this.reconnectTimer === null) return;
this.reconnectAttempt = 0;
this.scheduleReconnect(0);
}
// ---------- Commands (the settings UI) ----------
/** Scan for about five seconds; results accumulate in the snapshot as they arrive. */
async scan(): Promise<KeyboardAdvert[]> {
const client = this.beginUserOperation();
const generation = this.generation;
this.scanResults = [];
this.error = "";
this.setState("scanning");
try {
await this.releaseLink(client);
await client.enable();
await client.scan();
if (generation === this.generation) this.setState("idle");
} catch (e) {
if (generation === this.generation) this.fail(e);
throw friendly(e);
} finally {
if (generation === this.generation) this.endUserOperation();
}
return sortAdverts(this.scanResults);
}
/** Connect, pair and subscribe a keyboard, then remember it. */
async connect(keyboard: SavedKeyboard): Promise<void> {
if (!parseKeyboardAddress(keyboard.address) || keyboard.addressType < 0 || keyboard.addressType > 3) {
throw new KeyboardClientError("Invalid keyboard address");
}
const client = this.beginUserOperation();
const generation = this.generation;
this.userDisconnected = false;
try {
await this.connectWith(client, generation, keyboard, false);
} finally {
if (generation === this.generation) this.endUserOperation();
}
}
/** Try the remembered keyboard again now. */
async reconnect(): Promise<void> {
if (!this.saved) throw new KeyboardClientError("No remembered keyboard");
await this.connect(this.saved);
}
/** Drop the keyboard but keep it remembered. No automatic reconnect until the next explicit connect or glasses session. */
async disconnect(): Promise<void> {
this.userDisconnected = true;
this.cancelReconnect();
const client = this.replaceClient();
// A scan or connect this interrupts no longer owns the bridge.
this.busy = false;
this.dropKeyboard();
this.pairing = null;
this.error = "";
if (!client) {
this.releaseOnLink = true;
this.setState("unavailable");
return;
}
this.setState("idle");
try {
await client.query();
await client.disable();
} catch (e) {
this.host.log(`keyboard disconnect: ${messageOf(e)}`);
}
}
/** Forget the remembered keyboard. The glasses keep their bond with it. */
async forget(): Promise<void> {
this.saved = null;
this.host.storeSaved(null);
await this.disconnect();
this.scanResults = [];
this.activeName = "";
this.host.onChanged();
}
/** Answer a "compare" pairing prompt. */
async answerCompare(accept: boolean): Promise<void> {
if (!this.client || this.pairing?.kind !== "compare") throw new KeyboardClientError("No pairing comparison is pending");
this.pairing = null;
this.host.onChanged();
await this.client.confirm(accept);
}
/** Answer an "entry" pairing prompt with the code the keyboard shows. */
async answerPasskey(pin: number): Promise<void> {
if (!this.client || this.pairing?.kind !== "entry") throw new KeyboardClientError("No pairing code is pending");
this.pairing = null;
this.host.onChanged();
await this.client.authenticate(pin);
}
// ---------- Internals ----------
private beginUserOperation(): KeyboardClient {
if (!this.available) throw new KeyboardClientError("Connect to G2 glasses running Faceclaw firmware first");
if (this.busy) throw new KeyboardClientError("Another keyboard operation is in progress");
// An automatic attempt may be mid-flight (a sleeping keyboard holds one
// for up to 30 s): a fresh client fails it at once and takes over.
this.cancelReconnect();
const client = this.replaceClient()!;
this.dropKeyboard();
this.pairing = null;
this.busy = true;
return client;
}
private endUserOperation(): void {
this.busy = false;
this.host.onChanged();
}
/** Close the current client and, while the link is up, start a fresh one. */
private replaceClient(): KeyboardClient | null {
this.generation++;
this.client?.close();
this.client = null;
if (!this.available) return null;
const generation = this.generation;
const live = () => generation === this.generation;
const client = new KeyboardClient(
(record) => live() && this.host.send(record),
{
keys: (events) => { if (live() && this.ready) this.host.onKeys(events); },
advert: (advert) => { if (live()) this.addAdvert(advert); },
status: (status) => { if (live()) this.onStatus(status); },
dm: (event, status) => { if (live()) this.onDm(event, status); },
passkeyDisplay: (pin) => { if (live()) this.prompt({ kind: "display", pin }); },
passkeyRequest: () => { if (live()) this.prompt({ kind: "entry" }); },
compareRequest: (value) => { if (live()) this.prompt({ kind: "compare", value }); },
servicesChanged: () => { if (live()) this.onServicesChanged(); },
error: (message) => { if (live()) this.host.log(`keyboard: ${message}`); },
log: (line) => { if (live()) this.host.log(`keyboard setup: ${line}`); },
},
{ randomPasskey: this.host.randomPasskey ? () => this.host.randomPasskey!() : undefined },
);
this.client = client;
return client;
}
private async connectWith(
client: KeyboardClient,
generation: number,
keyboard: SavedKeyboard,
resume: boolean,
): Promise<void> {
const live = () => generation === this.generation;
this.error = "";
this.activeName = keyboard.name;
this.setState("connecting");
try {
const status = await client.query();
if (resume && status.enabled && status.connected && status.encrypted) {
// The glasses kept the keyboard through a phone-side drop (or an app
// restart): only the handle mapping is missing.
this.host.log("keyboard still connected to the glasses; rediscovering");
} else {
await this.releaseLink(client);
await client.enable();
await client.connect(keyboard.addressType, parseKeyboardAddress(keyboard.address)!);
}
if (!live()) return;
this.pairing = null;
this.setState("configuring");
const config = await client.configure();
if (!live()) return;
this.ready = true;
this.reconnectAttempt = 0;
// The list was for choosing; it is stale from here on.
this.scanResults = [];
if (!sameKeyboard(this.saved, keyboard)) {
this.saved = { ...keyboard };
this.host.storeSaved(this.saved);
}
this.host.log(
`keyboard ready: ${keyboard.name || keyboard.address}, ${config.watched.length} of ` +
`${config.reports.filter((r) => r.type === 1).length} input reports subscribed, epoch ${config.epoch}`);
this.setState("connected");
} catch (e) {
if (!live()) return;
this.ready = false;
this.pairing = null;
if (resume) {
// An automatic attempt: a keyboard that is asleep or out of range is
// the ordinary case, not an error to put in front of the user.
this.host.log(`keyboard reconnect: ${messageOf(friendly(e))}`, true);
this.setState("idle");
} else {
this.fail(e);
}
throw friendly(e);
}
}
/**
* The firmware refuses SCAN and CONNECT while it still owns a keyboard
* slot, and an interrupted connect keeps initiating until the close lands.
* DISABLE is epoch-checked and a fresh client hasn't seen the epoch yet,
* so QUERY first (it isn't, and its answer carries the epoch), then wait
* for the slot to clear.
*/
private async releaseLink(client: KeyboardClient): Promise<void> {
const status = await client.query();
if (!status.enabled && status.conn === 0) return;
await client.disable();
for (let i = 0; i < RELEASE_POLLS; i++) {
if ((await client.query()).conn === 0) return;
await delay(RELEASE_POLL_MS);
}
throw new KeyboardClientError("The glasses are still closing the previous keyboard link; try again in a moment");
}
private cancelReconnect(): void {
if (this.reconnectTimer !== null) clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
private scheduleReconnect(delayMs: number): void {
this.cancelReconnect();
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
void this.attemptReconnect();
}, delayMs);
}
private async attemptReconnect(): Promise<void> {
const saved = this.saved;
const client = this.client;
if (!this.available || !client || !saved || this.userDisconnected || this.ready || this.busy) return;
if (this.host.shouldReconnect && !this.host.shouldReconnect()) {
this.parkFirmware(client);
this.scheduleReconnect(RECONNECT_BACKOFF_MS[RECONNECT_BACKOFF_MS.length - 1]!);
return;
}
const generation = this.generation;
try {
await this.connectWith(client, generation, saved, true);
} catch {
if (generation !== this.generation || !this.available || this.userDisconnected) return;
// Keyboards sleep, and the ring's own scan can hold the controller
// (BUSY): keep trying, less often, while the glasses stay up.
const backoff = RECONNECT_BACKOFF_MS[Math.min(this.reconnectAttempt, RECONNECT_BACKOFF_MS.length - 1)]!;
this.reconnectAttempt++;
this.scheduleReconnect(backoff);
}
}
/**
* While it is enabled the firmware bridge runs a 20 ms timer and reports
* its status every second, keyboard or no keyboard. When nothing will be
* tried for a while, switch it off; the next attempt enables it again.
*/
private parkFirmware(client: KeyboardClient): void {
if (!client.status.enabled) return;
client.disable().catch(() => {});
}
private onStatus(status: KeyboardStatus): void {
if (this.ready && (!status.connected || !status.encrypted)) this.keyboardDropped("status");
else if (this.state === "connecting" && status.connected && !status.encrypted) this.setState("pairing");
}
private onDm(event: number, status: number): void {
if (event === KeyboardDm.connClose || event === KeyboardDm.pairFailed || event === KeyboardDm.encryptFailed) {
this.host.log(`keyboard DM event 0x${event.toString(16)} status ${status}`);
if (this.ready) this.keyboardDropped("dm");
}
}
private onServicesChanged(): void {
this.host.log("keyboard services changed; rediscovering");
this.dropKeyboard();
this.setState("idle");
if (this.saved && !this.userDisconnected && !this.busy) this.scheduleReconnect(0);
}
private keyboardDropped(reason: string): void {
this.host.log(`keyboard disconnected (${reason})`);
this.dropKeyboard();
this.setState("idle");
if (this.saved && !this.userDisconnected && !this.busy) this.scheduleReconnect(DROP_RETRY_DELAY_MS);
}
/** The keyboard is no longer usable: tell the host once. */
private dropKeyboard(): void {
if (!this.ready) return;
this.ready = false;
this.host.onKeyboardGone();
}
private addAdvert(advert: KeyboardAdvert): void {
const index = this.scanResults.findIndex(
(a) => a.address === advert.address && a.addressType === advert.addressType);
if (index < 0) {
this.scanResults.push(advert);
} else {
const merged = mergeKeyboardAdverts(this.scanResults[index]!, advert);
const old = this.scanResults[index]!;
if (merged.name === old.name && merged.hid === old.hid && merged.rssi === old.rssi) return;
this.scanResults[index] = merged;
}
this.host.onChanged();
}
private prompt(pairing: KeyboardPairingPrompt): void {
this.pairing = pairing;
this.setState("pairing");
}
private setState(next: KeyboardBridgeState): void {
this.state = next;
if (next !== "pairing" && next !== "connecting") this.pairing = null;
this.host.onChanged();
}
private fail(error: unknown): void {
this.error = messageOf(friendly(error));
this.host.log(`keyboard error: ${this.error}`);
this.setState("error");
}
}
function sameKeyboard(a: SavedKeyboard | null, b: SavedKeyboard): boolean {
return !!a && a.address === b.address && a.addressType === b.addressType && a.name === b.name;
}
function sortAdverts(adverts: readonly KeyboardAdvert[]): KeyboardAdvert[] {
return [...adverts].sort((a, b) => Number(b.hid) - Number(a.hid) || b.rssi - a.rssi);
}
/**
* Firmware BUSY nearly always means the ring's own scan or reconnect holds
* the radio; say that rather than the raw control error.
*/
function friendly(error: unknown): Error {
if (error instanceof KeyboardClientError && error.code === KeyboardError.busy) {
return new KeyboardClientError(
"The glasses' radio is busy (usually the ring reconnecting). Wait a few seconds and try again.", error.code);
}
if (error instanceof KeyboardClientError && error.code === KeyboardError.noSpace) {
return new KeyboardClientError(
"The glasses have no room for another connection or pairing.", error.code);
}
return error instanceof Error ? error : new Error(String(error));
}
function messageOf(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function delay(ms: number): Promise<void> {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
}
+709
View File
@@ -0,0 +1,709 @@
/**
* Transport-independent client for the CFW keyboard bridge: enable, scan,
* connect and pair a keyboard through the glasses, discover its HID service
* over the relayed ATT operations, subscribe its input reports, and decode
* them into key transitions. From the reference client in g2flash demos/
* (keyboard-client.ts), with the fixes its use in the Glassly app turned up.
*
* The firmware keeps almost no policy: it owns the connection and the bond,
* and forwards one ATT request at a time. Everything HID lives here. Handle
* numbers found by configure() are only good for one connection epoch.
* No platform imports: this runs under node in the tests.
*/
import { HidKeys, parseReportMap, reportHasKeys, type HidKeyEvent, type HidReport } from "./hid";
import {
KeyboardDm,
KeyboardError,
KeyboardKind,
KeyboardOp,
KeyboardRecords,
keyboardControl,
keyboardErrorName,
le16,
parseKeyboardAdvert,
u16,
u32,
type KeyboardAdvert,
type KeyboardRecord,
} from "./protocol";
/** Queue one field-130 control record; false when the glasses link can't take it now. */
export type KeyboardTransport = (record: Uint8Array) => boolean;
export type KeyboardStatus = {
enabled: boolean;
/** The firmware's connection id for the keyboard, 0 when it owns none. */
conn: number;
connected: boolean;
encrypted: boolean;
scanning: boolean;
};
export type KeyboardClientEvents = {
/** Key transitions from one input report (or the releases a gap forces). */
keys?(events: HidKeyEvent[]): void;
advert?(advert: KeyboardAdvert): void;
status?(status: KeyboardStatus): void;
/** The stream may have lost records; held keys were released. */
gap?(): void;
/** Device-manager event from the glasses' BLE host (KeyboardDm). */
dm?(event: number, status: number): void;
/** The keyboard shows a six-digit passkey; answer with authenticate(). */
passkeyRequest?(): void;
/** We chose a passkey and answered with it; the user types it on the keyboard, then Enter. */
passkeyDisplay?(pin: number): void;
/** Numeric comparison: answer with confirm() once the user has compared. */
compareRequest?(value: number): void;
/** The keyboard's GATT table changed; the mapping is void until configure() runs again. */
servicesChanged?(): void;
error?(message: string): void;
/** Setup diagnostics: the keyboard's attribute table and what was made of it. Never key contents. */
log?(line: string): void;
};
export type KeyboardReport = {
/** Handle of the HID service declaration the report belongs to. */
service: number;
handle: number;
id: number;
/** 1 input, 2 output, 3 feature. */
type: number;
ccc?: number;
/** From the characteristic's declaration; undefined when the keyboard wouldn't say (see declaredProperties). */
properties?: number;
map: Uint8Array;
};
export type KeyboardConfiguration = {
epoch: number;
/** Every report found, input or not. */
reports: KeyboardReport[];
/** Handles of the input reports subscribed for keys. */
watched: number[];
serviceChanged?: number;
};
export type KeyboardClientOptions = {
/** A fresh six-digit passkey for display pairing. Default: Math.random (pass a stronger source). */
randomPasskey?: () => number;
};
export class KeyboardClientError extends Error {
/** The firmware's control error code (KeyboardError), when that is what failed. */
readonly code: number | undefined;
/** The keyboard's ATT error code, when it refused a read or write. */
readonly attStatus: number | undefined;
constructor(message: string, code?: number, attStatus?: number) {
super(message);
this.name = "KeyboardClientError";
this.code = code;
this.attStatus = attStatus;
}
}
type Attribute = { handle: number; uuid: number | string };
type Pending = {
op: number;
resolve: (r: KeyboardRecord) => void;
reject: (e: Error) => void;
timer: ReturnType<typeof setTimeout>;
};
type Waiter = { test: () => boolean; resolve: () => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> };
type Input = { report: HidReport; id: number; service: number };
const COMMAND_TIMEOUT_MS = 32_000;
const MAX_PENDING = 8;
const MAX_ATTRIBUTES = 512;
const MAX_VALUE = 512;
const MAX_WATCHES = 16;
const UUID_PRIMARY_SERVICE = 0x2800;
const UUID_SECONDARY_SERVICE = 0x2801;
const UUID_CHARACTERISTIC = 0x2803;
const UUID_CCC = 0x2902;
const UUID_EXTERNAL_REPORT_REFERENCE = 0x2907;
const UUID_REPORT_REFERENCE = 0x2908;
const UUID_HID_SERVICE = 0x1812;
const UUID_SERVICE_CHANGED = 0x2a05;
const UUID_REPORT_MAP = 0x2a4b;
const UUID_REPORT = 0x2a4d;
const UUID_PROTOCOL_MODE = 0x2a4e;
/** ATT error codes that end a paged read rather than failing it. */
const ATT_INVALID_OFFSET = 7;
const ATT_NOT_LONG = 11;
const ATT_NOT_FOUND = 10;
/**
* ATT UUIDs are little endian. A 128-bit UUID on the Bluetooth base collapses
* to its 16-bit form; vendor UUIDs stay as hex strings.
*/
export function attributeUuid(bytes: Uint8Array): number | string {
if (bytes.length === 2) return u16(bytes);
if (bytes.length !== 16) throw new KeyboardClientError("Invalid ATT UUID length");
const base = [0xfb, 0x34, 0x9b, 0x5f, 0x80, 0, 0, 0x80, 0, 0x10, 0, 0];
if (base.every((v, i) => bytes[i] === v) && bytes[14] === 0 && bytes[15] === 0) return u16(bytes, 12);
return Array.from(bytes, (x) => x.toString(16).padStart(2, "0")).join("");
}
export class KeyboardClient {
/** The firmware's connection generation; every control but QUERY/ENABLE must carry the live one. */
epoch = 0;
status: KeyboardStatus = { enabled: false, conn: 0, connected: false, encrypted: false, scanning: false };
configuration: KeyboardConfiguration | undefined;
private serial = 0;
private closed = false;
/** The link under connect() went away (close, failed open, failed pairing). */
private linkLost = false;
private readonly pending = new Map<number, Pending>();
private readonly waiters = new Set<Waiter>();
private readonly keys = new HidKeys();
private inputs = new Map<number, Input>();
private readonly records = new KeyboardRecords(() => this.gap());
private readonly randomPasskey: () => number;
constructor(
private readonly transport: KeyboardTransport,
private readonly events: KeyboardClientEvents = {},
options: KeyboardClientOptions = {},
) {
this.randomPasskey = options.randomPasskey ?? (() => Math.floor(Math.random() * 1_000_000));
}
// ---------- Inbound ----------
/** Feed one field-131 payload, in arrival order. */
accept(data: Uint8Array): void {
if (this.closed) return;
const r = this.records.push(data);
if (!r) return;
this.epoch = r.epoch;
if (r.kind === KeyboardKind.status && r.data.length === 10) {
this.status = {
enabled: !!r.data[0], conn: r.data[1]!, connected: !!r.data[2], encrypted: !!r.data[3], scanning: !!r.data[4],
};
if (!this.status.enabled || !this.status.connected || !this.status.encrypted) this.release();
this.events.status?.(this.status);
}
const pending = this.pending.get(r.request);
if (pending && (r.kind === KeyboardKind.status || r.kind === KeyboardKind.att)) {
this.pending.delete(r.request);
clearTimeout(pending.timer);
if (r.kind === KeyboardKind.status && r.code) {
pending.reject(new KeyboardClientError(
`Keyboard command ${opName(pending.op)}: firmware ${keyboardErrorName(r.code)}`, r.code));
} else {
pending.resolve(r);
}
}
if (r.kind === KeyboardKind.dm) this.acceptDm(r);
else if (r.kind === KeyboardKind.input) this.acceptInput(r);
else if (r.kind === KeyboardKind.advert) {
const advert = parseKeyboardAdvert(r.data);
if (advert) this.events.advert?.(advert);
}
this.checkWaiters();
}
private acceptDm(r: KeyboardRecord): void {
const event = r.code & 255;
const status = r.code >>> 8;
if (event === KeyboardDm.connClose || event === KeyboardDm.pairFailed || event === KeyboardDm.encryptFailed ||
(event === KeyboardDm.connOpen && status !== 0)) {
this.linkLost = true;
this.gap();
this.inputs.clear();
this.configuration = undefined;
}
if (event === KeyboardDm.authRequest && r.data.length === 2) {
if (r.data[0]) {
this.command(KeyboardOp.disconnect).catch(() => {});
this.events.error?.("This keyboard only pairs out of band, which isn't supported.");
} else if (r.data[1]) {
// KeyboardDisplay on our side: choose the passkey, show it, and
// answer at once; the user types it on the keyboard.
const pin = Math.min(999_999, Math.max(0, Math.floor(this.randomPasskey())));
this.events.passkeyDisplay?.(pin);
this.authenticate(pin).catch((e) => this.events.error?.(messageOf(e)));
} else {
this.events.passkeyRequest?.();
}
}
if (event === KeyboardDm.compare && r.data.length === 4) this.events.compareRequest?.(u32(r.data));
this.events.dm?.(event, status);
}
private acceptInput(r: KeyboardRecord): void {
const changed = this.configuration?.serviceChanged;
if (changed !== undefined && r.handle === changed) {
this.gap();
this.inputs.clear();
this.configuration = undefined;
this.events.servicesChanged?.();
return;
}
const input = this.inputs.get(r.handle);
if (!input || this.configuration?.epoch !== r.epoch) {
this.gap();
return;
}
try {
const events = this.keys.update(r.handle, input.report, r.data);
if (events.length) this.events.keys?.(events);
} catch (e) {
this.release();
this.events.error?.(messageOf(e));
}
}
private release(): void {
const events = this.keys.reset();
if (events.length) this.events.keys?.(events);
}
private gap(): void {
this.release();
this.events.gap?.();
for (const [id, p] of this.pending) {
if (p.op < KeyboardOp.find) continue;
clearTimeout(p.timer);
this.pending.delete(id);
p.reject(new KeyboardClientError("Keyboard stream gap during ATT transaction"));
}
}
/** The phone's link to the glasses dropped: release held keys and fail everything in flight. */
lostPhoneLink(): void {
this.records.reset();
this.cancel("Glasses link lost");
}
/** Stop for good; later accept() calls are ignored. */
close(): void {
if (this.closed) return;
this.lostPhoneLink();
this.closed = true;
}
private cancel(reason: string): void {
for (const p of this.pending.values()) {
clearTimeout(p.timer);
p.reject(new KeyboardClientError(reason));
}
this.pending.clear();
for (const w of this.waiters) {
clearTimeout(w.timer);
w.reject(new KeyboardClientError(reason));
}
this.waiters.clear();
}
private checkWaiters(): void {
for (const w of [...this.waiters]) {
let done = false;
try {
done = w.test();
} catch (e) {
this.waiters.delete(w);
clearTimeout(w.timer);
w.reject(e instanceof Error ? e : new KeyboardClientError(String(e)));
continue;
}
if (!done) continue;
this.waiters.delete(w);
clearTimeout(w.timer);
w.resolve();
}
}
/** Resolve once `test` holds; it is re-evaluated after every accepted record. */
private waitFor(test: () => boolean, timeoutMs: number, what: string): Promise<void> {
if (this.closed) return Promise.reject(new KeyboardClientError("Keyboard client closed"));
if (test()) return Promise.resolve();
return new Promise<void>((resolve, reject) => {
const waiter: Waiter = {
test, resolve, reject,
timer: setTimeout(() => {
this.waiters.delete(waiter);
reject(new KeyboardClientError(`Timed out waiting for ${what}`));
}, timeoutMs),
};
this.waiters.add(waiter);
});
}
// ---------- Commands ----------
/** Send one control and await the STATUS or ATT record that answers it. */
command(op: number, body: readonly number[] = []): Promise<KeyboardRecord> {
if (this.closed) return Promise.reject(new KeyboardClientError("Keyboard client closed"));
if (this.pending.size >= MAX_PENDING) return Promise.reject(new KeyboardClientError("Too many keyboard commands"));
const request = this.serial = this.serial % 65535 + 1;
return new Promise<KeyboardRecord>((resolve, reject) => {
const timer = setTimeout(() => {
this.pending.delete(request);
reject(new KeyboardClientError(`Keyboard command ${opName(op)} timed out`));
}, COMMAND_TIMEOUT_MS);
this.pending.set(request, { op, resolve, reject, timer });
let queued = false;
try {
queued = this.transport(keyboardControl(op, request, this.epoch, body));
} catch {
queued = false;
}
if (!queued) {
clearTimeout(timer);
this.pending.delete(request);
reject(new KeyboardClientError("The glasses aren't ready for keyboard commands"));
}
});
}
async enable(): Promise<void> {
await this.command(KeyboardOp.enable);
}
/** Disconnect the keyboard and stop the bridge; the bond stays. */
async disable(): Promise<void> {
await this.command(KeyboardOp.disable);
this.release();
}
/** Ask for the firmware's state. Also the way to learn the live epoch: QUERY isn't epoch-checked. */
async query(): Promise<KeyboardStatus> {
await this.command(KeyboardOp.query);
return this.status;
}
/**
* Active scan for about five seconds; adverts arrive through events.advert.
* The firmware only clears `scanning` once the stock scanner is idle again,
* and a ring looking for its lens can hold that well past the window, so a
* lingering flag is not an error: the adverts already delivered stand.
*/
async scan(): Promise<void> {
await this.command(KeyboardOp.scan);
try {
await this.waitFor(() => !this.status.scanning, 8000, "the scan to finish");
} catch (e) {
if (this.closed) throw e;
}
}
/** Connect, then pair unless the link comes up encrypted. `address` is LSB first. */
async connect(addressType: number, address: Uint8Array): Promise<void> {
if (address.length !== 6 || !Number.isInteger(addressType) || addressType < 0 || addressType > 3) {
throw new KeyboardClientError("Invalid BLE address");
}
this.release();
this.inputs.clear();
this.configuration = undefined;
this.linkLost = false;
await this.command(KeyboardOp.connect, [addressType, ...address]);
await this.waitFor(() => this.status.connected || this.linkLost, 32_000, "the keyboard to connect");
if (!this.status.connected) throw new KeyboardClientError("The keyboard didn't answer");
if (!this.status.encrypted) {
// The keyboard's own security request may have started pairing already.
// BUSY is not success: the encrypted status below still decides.
try {
await this.command(KeyboardOp.pair);
} catch (e) {
if (!(e instanceof KeyboardClientError) || e.code !== KeyboardError.busy) throw e;
}
await this.waitFor(() => this.status.encrypted || this.linkLost, 65_000, "pairing to finish");
if (!this.status.encrypted) throw new KeyboardClientError("Pairing with the keyboard failed");
}
}
async disconnect(): Promise<void> {
await this.command(KeyboardOp.disconnect);
this.release();
}
/** Answer a pending passkey prompt. */
async authenticate(pin: number): Promise<void> {
if (!Number.isInteger(pin) || pin < 0 || pin > 999_999) throw new KeyboardClientError("Invalid pairing passkey");
await this.command(KeyboardOp.auth, [pin & 255, (pin >>> 8) & 255, pin >>> 16]);
}
/** Answer a pending numeric comparison. */
async confirm(accept: boolean): Promise<void> {
await this.command(KeyboardOp.compare, [accept ? 1 : 0]);
}
private async att(op: number, body: readonly number[]): Promise<KeyboardRecord> {
const r = await this.command(op, body);
if (r.kind !== KeyboardKind.att) throw new KeyboardClientError("Expected keyboard ATT response");
return r;
}
/** Read a whole attribute: Read, then Read Blob until a short or empty reply. Never assumes the MTU. */
async read(handle: number): Promise<Uint8Array> {
const parts: number[] = [];
for (;;) {
const r = await this.att(KeyboardOp.read, [...le16(handle), ...le16(parts.length)]);
const status = r.code >>> 8;
if (parts.length && (status === ATT_INVALID_OFFSET || status === ATT_NOT_LONG)) break;
if (status) throw new KeyboardClientError(`ATT read ${handle}: ${status}`, undefined, status);
if (!r.data.length) break;
for (const b of r.data) parts.push(b);
if (parts.length > MAX_VALUE) throw new KeyboardClientError("Attribute exceeds 512 bytes");
if (parts.length === MAX_VALUE) break;
}
return Uint8Array.from(parts);
}
/** Read a short attribute once (a Report Reference, a declaration, a service UUID). */
private async shortRead(handle: number): Promise<Uint8Array> {
const r = await this.att(KeyboardOp.read, [...le16(handle), 0, 0]);
if (r.code >>> 8) throw new KeyboardClientError(`ATT read ${handle}: ${r.code >>> 8}`, undefined, r.code >>> 8);
return r.data;
}
/** Write 1..18 bytes (an output report such as the LEDs, a CCC, the protocol mode). */
async write(handle: number, value: Uint8Array, withoutResponse = false): Promise<void> {
if (!value.length || value.length > 18) throw new KeyboardClientError("Keyboard write supports 1..18 bytes");
const r = await this.att(KeyboardOp.write, [...le16(handle), withoutResponse ? 1 : 0, value.length, ...value]);
if (r.code >>> 8) throw new KeyboardClientError(`ATT write ${handle}: ${r.code >>> 8}`, undefined, r.code >>> 8);
}
private async attributes(): Promise<Attribute[]> {
const attrs: Attribute[] = [];
let start = 1;
while (start <= 65535) {
const r = await this.att(KeyboardOp.find, [...le16(start), 255, 255]);
const status = r.code >>> 8;
if (status === ATT_NOT_FOUND) break; // the normal end of the table
if (status) throw new KeyboardClientError(`ATT Find Information: ${status}`);
const width = r.data[0] === 1 ? 4 : r.data[0] === 2 ? 18 : 0;
if (!width || r.data.length <= 1 || (r.data.length - 1) % width) {
throw new KeyboardClientError("Malformed Find Information response");
}
for (let i = 1; i < r.data.length; i += width) {
const handle = u16(r.data, i);
if (handle < start || attrs.length >= MAX_ATTRIBUTES) throw new KeyboardClientError("Invalid or excessive GATT handles");
attrs.push({ handle, uuid: attributeUuid(r.data.subarray(i + 2, i + width)) });
start = handle + 1;
}
}
return attrs;
}
/**
* The properties byte of a characteristic, from its declaration, or
* undefined when the keyboard won't say. A GATT client normally learns
* declarations through Read By Type, which the bridge doesn't relay, so
* this reads the declaration attribute itself. Most stacks answer that
* with the full declaration. Some keep only the properties byte there and
* build the rest for Read By Type alone (older Telink SDKs, common in
* small keyboards), and some refuse the read. None of that is a reason to
* turn a keyboard away: the report's handle and UUID are already known.
*/
private async declaredProperties(attrs: readonly Attribute[], a: Attribute): Promise<number | undefined> {
const decl = attrs.filter((d) => d.handle < a.handle && d.uuid === UUID_CHARACTERISTIC).pop();
if (!decl) return undefined;
let declaration: Uint8Array;
try {
declaration = await this.shortRead(decl.handle);
} catch (e) {
const status = attRefusal(e);
this.events.log?.(`declaration ${decl.handle} of ${a.handle}: read refused (ATT ${status})`);
return undefined;
}
if (declaration.length === 5 || declaration.length === 19) {
if (u16(declaration, 1) === a.handle && attributeUuid(declaration.subarray(3)) === a.uuid) return declaration[0]!;
this.events.log?.(`declaration ${decl.handle} of ${a.handle}: describes something else (${hex(declaration)})`);
return undefined;
}
if (declaration.length === 1) return declaration[0]!;
this.events.log?.(`declaration ${decl.handle} of ${a.handle}: unexpected value (${hex(declaration)})`);
return undefined;
}
/**
* Discover every HID service, its Report Map and each report's Report
* Reference; select Report Protocol and subscribe the input reports that
* can carry keys. Needs an encrypted link. No handle is assumed.
*
* Only what typing needs is required of the keyboard: a Report Map that
* parses, and at least one key-bearing input report with a Report
* Reference and a CCC. A report that can't be placed is skipped and
* logged, as is anything wrong with an external report (the battery
* level, usually).
*/
async configure(): Promise<KeyboardConfiguration> {
const epoch = this.epoch;
const log = (line: string): void => this.events.log?.(line);
// A new discovery replaces any earlier mapping, whether or not it succeeds.
this.release();
this.inputs.clear();
this.configuration = undefined;
const attrs = await this.attributes();
log(`gatt ${attrs.map((a) => `${a.handle}=${typeof a.uuid === "number" ? a.uuid.toString(16) : a.uuid}`).join(" ")}`);
const reports: KeyboardReport[] = [];
const watched: KeyboardReport[] = [];
const skipped: string[] = [];
const descriptorsFor = (handle: number): Attribute[] => {
const end = attrs.find((a) => a.handle > handle &&
(a.uuid === UUID_PRIMARY_SERVICE || a.uuid === UUID_SECONDARY_SERVICE || a.uuid === UUID_CHARACTERISTIC))?.handle ?? 65536;
return attrs.filter((a) => a.handle > handle && a.handle < end);
};
/** Why a report was left out; the link going away is not a reason to carry on. */
const skip = (a: Attribute, reason: string): void => {
skipped.push(`${a.handle}: ${reason}`);
log(`report ${a.handle} skipped: ${reason}`);
};
const addReport = async (service: number, a: Attribute, map: Uint8Array, parsed: Map<number, HidReport>) => {
if (reports.some((r) => r.handle === a.handle)) return skip(a, "already listed by another HID service");
const descriptors = descriptorsFor(a.handle);
const ref = descriptors.find((d) => d.uuid === UUID_REPORT_REFERENCE);
if (!ref) return skip(a, "no Report Reference descriptor");
let reference: Uint8Array;
try {
reference = await this.shortRead(ref.handle);
} catch (e) {
return skip(a, `Report Reference ${ref.handle} unreadable (ATT ${attRefusal(e)})`);
}
if (reference.length !== 2) return skip(a, `Report Reference ${ref.handle} is ${hex(reference) || "empty"}`);
const id = reference[0]!;
const type = reference[1]!;
if (type < 1 || type > 3) return skip(a, `Report Reference type ${type}`);
const ccc = descriptors.find((d) => d.uuid === UUID_CCC)?.handle;
const properties = await this.declaredProperties(attrs, a);
const report: KeyboardReport = { service, handle: a.handle, id, type, ccc, properties, map };
if (type === 1) {
const layout = parsed.get(id);
if (!layout) return skip(a, `input report id ${id} is not in the Report Map`);
if (ccc === undefined || (properties !== undefined && !(properties & 0x10))) return skip(a, "input report can't notify");
if (reportHasKeys(layout)) watched.push(report);
else log(`report ${a.handle} (id ${id}) carries no keys; not subscribed`);
}
reports.push(report);
log(`report ${a.handle}: id ${id} type ${type} ccc ${ccc ?? "-"} properties ${properties ?? "?"}`);
};
for (let i = 0; i < attrs.length; i++) {
const service = attrs[i]!;
if (service.uuid !== UUID_PRIMARY_SERVICE) continue;
if (attributeUuid(await this.shortRead(service.handle)) !== UUID_HID_SERVICE) continue;
const end = attrs.slice(i + 1).find((a) => a.uuid === UUID_PRIMARY_SERVICE || a.uuid === UUID_SECONDARY_SERVICE)?.handle ?? 65536;
const members = attrs.filter((a) => a.handle > service.handle && a.handle < end);
const mapAttr = members.find((a) => a.uuid === UUID_REPORT_MAP);
if (!mapAttr) throw new KeyboardClientError(`HID service ${service.handle} has no Report Map`);
const map = await this.read(mapAttr.handle);
log(`report map ${mapAttr.handle}: ${hex(map)}`);
const parsed = parseReportMap(map);
for (const mode of members.filter((a) => a.uuid === UUID_PROTOCOL_MODE)) {
try {
await this.write(mode.handle, Uint8Array.of(1), true);
} catch (e) {
// Report Protocol is the default after a connection; a keyboard
// that won't take the write is almost certainly in it already.
log(`protocol mode ${mode.handle}: write refused (ATT ${attRefusal(e)})`);
}
}
for (const a of members.filter((m) => m.uuid === UUID_REPORT)) await addReport(service.handle, a, map, parsed);
// HOGP lets a Report Map refer to reports in other services (commonly Battery).
for (const ext of descriptorsFor(mapAttr.handle).filter((a) => a.uuid === UUID_EXTERNAL_REPORT_REFERENCE)) {
let value: Uint8Array;
try {
value = await this.shortRead(ext.handle);
} catch (e) {
log(`external report reference ${ext.handle} skipped: unreadable (ATT ${attRefusal(e)})`);
continue;
}
if (value.length !== 2 && value.length !== 16) {
log(`external report reference ${ext.handle} skipped: value ${hex(value) || "empty"}`);
continue;
}
const uuid = attributeUuid(value);
for (const a of attrs.filter((m) => m.uuid === uuid && (m.handle < service.handle || m.handle >= end))) {
await addReport(service.handle, a, map, parsed);
}
}
}
if (this.closed || this.epoch !== epoch) throw new KeyboardClientError("The keyboard link changed during setup");
if (!watched.length) {
throw new KeyboardClientError(reports.length || skipped.length
? `No usable keyboard input report (${skipped.join("; ") || "none carries keys"})`
: "This device has no HID service");
}
if (watched.length > MAX_WATCHES) throw new KeyboardClientError("Keyboard has more than 16 input reports");
const changed = attrs.find((a) => a.uuid === UUID_SERVICE_CHANGED);
const changedCcc = changed && descriptorsFor(changed.handle).find((a) => a.uuid === UUID_CCC);
const watches = watched.map((r) => r.handle);
if (changed && changedCcc && watches.length < MAX_WATCHES) watches.push(changed.handle);
const serviceChanged = changed && changedCcc && watches.includes(changed.handle) ? changed.handle : undefined;
const config: KeyboardConfiguration = { epoch: this.epoch, reports, watched: watched.map((r) => r.handle), serviceChanged };
this.restore(config);
try {
await this.command(KeyboardOp.watch, [watches.length, ...watches.flatMap(le16)]);
if (serviceChanged !== undefined) {
try {
await this.write(changedCcc!.handle, Uint8Array.of(2, 0));
} catch (e) {
log(`service changed ${changedCcc!.handle}: subscription refused (ATT ${attRefusal(e)})`);
}
}
for (const r of watched) await this.write(r.ccc!, Uint8Array.of(1, 0));
} catch (e) {
this.inputs.clear();
this.configuration = undefined;
this.release();
throw e;
}
return config;
}
/**
* Install a mapping found by configure(). It is only good while the glasses
* keep the same connection (the same epoch): after a keyboard reconnect or
* a firmware boot, discover again.
*/
restore(config: KeyboardConfiguration): void {
if (!config.reports.length || config.reports.length > 64) throw new KeyboardClientError("Invalid keyboard configuration");
const inputs = new Map<number, Input>();
for (const r of config.reports) {
if (r.type !== 1 || !config.watched.includes(r.handle)) continue;
if (!Number.isInteger(r.handle) || r.handle < 1 || r.handle > 65535 || inputs.has(r.handle)) {
throw new KeyboardClientError("Invalid restored Report handle");
}
if (!r.map.length || r.map.length > MAX_VALUE) throw new KeyboardClientError("Invalid restored Report Map");
const report = parseReportMap(r.map).get(r.id);
if (!report) throw new KeyboardClientError("Restored Report ID missing");
inputs.set(r.handle, { report, id: r.id, service: r.service });
}
if (!inputs.size || inputs.size > MAX_WATCHES) throw new KeyboardClientError("Invalid restored input count");
this.release();
this.inputs = inputs;
this.configuration = config;
}
/** Output reports of the configured keyboard (the LED report is the usual one). */
outputReports(): KeyboardReport[] {
return this.configuration?.reports.filter((r) => r.type === 2) ?? [];
}
}
/**
* The ATT error code when `error` is the keyboard refusing a read or write.
* Anything else (the link dropping, a timeout, a stream gap) is rethrown:
* those end the setup, where a refusal only costs the one attribute.
*/
function attRefusal(error: unknown): number {
if (error instanceof KeyboardClientError && error.attStatus !== undefined) return error.attStatus;
throw error;
}
function hex(bytes: Uint8Array): string {
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
}
function opName(op: number): string {
for (const [name, value] of Object.entries(KeyboardOp)) if (value === op) return name;
return String(op);
}
function messageOf(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+188
View File
@@ -0,0 +1,188 @@
/**
* Bounded HID report-descriptor decoder for the keyboard bridge: turns a
* keyboard's Report Map into the layout of each input report, and input
* reports into the set of keys held. From the reference client in g2flash
* demos/ (keyboard-hid.ts).
*
* HID over GATT carries the Report ID out of band (in each characteristic's
* Report Reference descriptor), so byte zero of a report value is data: it is
* never stripped as USB HID would. Only the keyboard/keypad page (7) and the
* consumer page (12) produce keys; pointer axes and padding are ignored.
* No platform imports: this runs under node in the tests.
*/
export type HidUsage = { page: number; usage: number };
export type HidKeyEvent = HidUsage & { down: boolean };
type Global = { page: number; min: number; max: number; size: number; count: number; id: number };
type Field = {
bit: number;
size: number;
count: number;
variable: boolean;
min: number;
max: number;
usages: HidUsage[];
range?: [HidUsage, HidUsage];
};
export type HidReport = { id: number; bits: number; fields: Field[] };
const HID_PAGE_KEYBOARD = 7;
const HID_PAGE_CONSUMER = 12;
const REPORT_MAP_MAX = 512;
function fail(reason: string): never {
throw new Error(`Unsupported or malformed HID descriptor: ${reason}`);
}
const usageKey = (u: HidUsage): string => `${u.page}:${u.usage}`;
/** Input reports by Report ID (0 when the descriptor uses none). Throws on anything out of bounds. */
export function parseReportMap(bytes: Uint8Array): Map<number, HidReport> {
if (!bytes.length || bytes.length > REPORT_MAP_MAX) fail("report map must contain 1..512 bytes");
const reports = new Map<number, HidReport>();
let g: Global = { page: 0, min: 0, max: 0, size: 0, count: 0, id: 0 };
const stack: Global[] = [];
let usages: HidUsage[] = [];
let lo: HidUsage | undefined;
let hi: HidUsage | undefined;
let depth = 0;
const usage = (v: number, n: number): HidUsage =>
n === 4 ? { page: v >>> 16, usage: v & 65535 } : { page: g.page, usage: v };
for (let p = 0; p < bytes.length;) {
const prefix = bytes[p++]!;
if (prefix === 0xfe) fail("long items");
const n = [0, 1, 2, 4][prefix & 3]!;
if (p + n > bytes.length) fail("truncated item");
let v = 0;
for (let j = 0; j < n; j++) v += bytes[p++]! * 2 ** (8 * j);
const signed = n && v >= 2 ** (n * 8 - 1) ? v - 2 ** (n * 8) : v;
const type = (prefix >> 2) & 3;
const tag = prefix >> 4;
if (type === 1) {
switch (tag) {
case 0: g.page = v; break;
case 1: g.min = signed; break;
case 2: g.max = g.min < 0 ? signed : v; break;
case 7: g.size = v; break;
case 8: if (!v || v > 255) fail("Report ID"); g.id = v; break;
case 9: g.count = v; break;
case 10: if (stack.length >= 8) fail("global stack overflow"); stack.push({ ...g }); break;
case 11: if (!stack.length) fail("global stack underflow"); g = stack.pop()!; break;
case 3: case 4: case 5: case 6: break; // physical range, unit and exponent
default: fail("unknown global item");
}
} else if (type === 2) {
if (tag === 0) { if (usages.length >= 512) fail("too many usages"); usages.push(usage(v, n)); }
else if (tag === 1) lo = usage(v, n);
else if (tag === 2) hi = usage(v, n);
else if (tag === 10) fail("usage delimiters");
else if (tag > 9) fail("unknown local item");
} else if (type === 0) {
if (tag === 10) { if (++depth > 32) fail("collection depth"); }
else if (tag === 12) { if (--depth < 0) fail("collection underflow"); }
else if (tag === 8) {
if (!g.size || g.size > 32 || !g.count || g.count > 512) fail("field dimensions");
let r = reports.get(g.id);
if (!r) {
if (reports.size >= 16) fail("too many input reports");
r = { id: g.id, bits: 0, fields: [] };
reports.set(g.id, r);
}
const field: Field = {
bit: r.bits, size: g.size, count: g.count, variable: !!(v & 2), min: g.min, max: g.max, usages: [...usages],
};
if (lo || hi) {
if (!lo || !hi || lo.page !== hi.page || hi.usage < lo.usage) fail("usage range");
field.range = [lo!, hi!];
}
r.bits += g.size * g.count;
if (r.bits > 4096) fail("report exceeds 512 bytes");
// Constant padding and relative pointer axes are not keys.
if (!(v & 1) && !(v & 4)) r.fields.push(field);
} else if (tag !== 9 && tag !== 11) fail("unknown main item");
usages = [];
lo = hi = undefined;
} else fail("reserved item type");
}
if (depth || stack.length) fail("unbalanced collection/global stack");
if (reports.has(0) && reports.size > 1) fail("mixed numbered and unnumbered input reports");
if (!reports.size) fail("no input reports");
return reports;
}
function usageAt(f: Field, index: number): HidUsage | undefined {
if (index < 0) return undefined;
if (index < f.usages.length) return f.usages[index];
const rangeIndex = index - f.usages.length;
if (f.range && rangeIndex <= f.range[1].usage - f.range[0].usage) {
return { page: f.range[0].page, usage: f.range[0].usage + rangeIndex };
}
// Variable items reuse their last usage when Report Count exceeds the usages.
if (f.variable) return f.range?.[1] ?? f.usages[f.usages.length - 1];
return undefined;
}
/**
* Whether an input report can ever say a key is held. False for a pointer's
* report (a trackpad or mouse on a combined device), whose movement would
* otherwise be relayed, and thrown away, a hundred times a second.
*/
export function reportHasKeys(report: HidReport): boolean {
const isKeyPage = (u: HidUsage): boolean => u.page === HID_PAGE_KEYBOARD || u.page === HID_PAGE_CONSUMER;
return report.fields.some((f) => f.usages.some(isKeyPage) || (f.range !== undefined && isKeyPage(f.range[0])));
}
/** The keys one input report says are held. Throws on a length mismatch or a rollover report. */
export function reportKeys(report: HidReport, data: Uint8Array): HidUsage[] {
if (data.length !== Math.ceil(report.bits / 8)) throw new Error("HID input length does not match Report Map");
const keys = new Map<string, HidUsage>();
for (const f of report.fields) {
for (let i = 0; i < f.count; i++) {
let value = 0;
for (let j = 0; j < f.size; j++) {
const bit = f.bit + i * f.size + j;
if (data[bit >>> 3]! & (1 << (bit & 7))) value += 2 ** j;
}
if (f.min < 0 && value >= 2 ** (f.size - 1)) value -= 2 ** f.size;
if (value < f.min || value > f.max) continue; // null state
const u = usageAt(f, f.variable ? i : value - f.min);
if (!u || (f.variable && value === 0) || !u.usage) continue;
if (u.page === HID_PAGE_KEYBOARD && u.usage <= 3) throw new Error("HID keyboard rollover/error report");
if (u.page === HID_PAGE_KEYBOARD || u.page === HID_PAGE_CONSUMER) keys.set(usageKey(u), u);
}
}
return [...keys.values()];
}
/**
* Held keys across a keyboard's input reports. Ownership is per report
* characteristic, then unioned: releasing a key in one report cannot release
* a modifier another report still holds.
*/
export class HidKeys {
private reports = new Map<number, HidUsage[]>();
private held = new Map<string, HidUsage>();
/** Apply one report from characteristic `handle`; returns the transitions it caused. */
update(handle: number, report: HidReport, data: Uint8Array): HidKeyEvent[] {
this.reports.set(handle, reportKeys(report, data));
return this.diff();
}
/** Release everything (a stream gap, a dropped link). */
reset(): HidKeyEvent[] {
this.reports.clear();
return this.diff();
}
private diff(): HidKeyEvent[] {
const next = new Map<string, HidUsage>();
for (const values of this.reports.values()) for (const u of values) next.set(usageKey(u), u);
const events: HidKeyEvent[] = [];
for (const [k, u] of this.held) if (!next.has(k)) events.push({ ...u, down: false });
for (const [k, u] of next) if (!this.held.has(k)) events.push({ ...u, down: true });
this.held = next;
return events;
}
}
+144
View File
@@ -0,0 +1,144 @@
/**
* Where a key from the hardware keyboard goes: to a keybinding being set up,
* to a gesture it is bound to, to the window with input focus, or to the
* built-in navigation. The meanings are in bindings.ts; this is the order of
* asking, and the bookkeeping around it. Shared by the Android and iOS
* controllers through KeyRouterHost.
* No platform imports: this runs under node in the tests.
*/
import {
GestureScheme,
chordOf,
isModifierCode,
resolveKey,
type GestureOrigin,
type KeyAction,
type KeyChord,
type KeyGesture,
} from "./bindings";
import type { KeyEvent } from "./keys";
export type KeyRouterHost = {
/** Connected to glasses that are in use. */
ready(): boolean;
locked(): boolean;
screenOn(): boolean;
/** Turn a dark display on, and nothing else. */
wake(): void;
/** Offer a key to the window with input focus; true when that window takes keys. */
offerToWindow(event: KeyEvent): boolean;
/** Perform a gesture as if it came from the ring or the watch. */
gesture(gesture: KeyGesture, origin: GestureOrigin): Promise<void>;
/** The custom keybindings, by chord id. */
bindings(): ReadonlyMap<string, KeyAction>;
/** A key was used for something other than a gesture or typing (count it against the screen timeout). */
noteActivity(): void;
log(line: string): void;
now?(): number;
};
/**
* A held key repeats twenty times a second, faster than a list can repaint
* over the glasses' link. Repeats are dropped while a gesture is still being
* handled, and closer together than this.
*/
const REPEAT_MIN_INTERVAL_MS = 100;
export class KeyRouter {
private capture: ((chord: KeyChord) => void) | null = null;
/** Keys whose press was spoken for, so their release is too. */
private readonly consumed = new Set<string>();
private readonly scheme = new GestureScheme();
private gesturesInFlight = 0;
private lastGestureAtMs = 0;
constructor(private readonly host: KeyRouterHost) {}
/** One key transition from the keyboard. */
handleKey(event: KeyEvent): void {
const host = this.host;
if (!host.ready()) return;
if (host.locked() || !host.screenOn()) {
// A dark display takes no typing: the first press only wakes it, as
// the ring's double tap would, and a locked one stays locked.
if (event.phase === "down" && !event.repeat && !host.screenOn()) host.wake();
return;
}
if (this.capture) {
this.captureKey(event);
return;
}
if (event.phase === "up") {
if (!this.consumed.delete(event.code)) host.offerToWindow(event);
return;
}
const resolution = resolveKey(event, host.bindings());
if (resolution.consume) {
this.consumed.add(event.code);
if (resolution.gesture) this.perform(resolution.gesture, event.repeat);
return;
}
if (host.offerToWindow(event)) return;
if (resolution.gesture) this.perform(resolution.gesture, event.repeat);
}
/**
* A key the focused window was offered and had no use for (a terminal
* showing its session list rather than a session): it gets the built-in
* navigation meaning after all.
*/
handleUnhandledKey(event: KeyEvent): void {
const host = this.host;
if (event.phase !== "down" || this.capture || !host.ready() || host.locked() || !host.screenOn()) return;
const resolution = resolveKey(event, host.bindings());
if (!resolution.consume && resolution.gesture) this.perform(resolution.gesture, event.repeat);
}
/**
* Take the next key press instead of acting on it (setting up a
* keybinding). Modifiers held with it are part of the chord; pressed alone
* they are waited through. Returns a function that calls the capture off.
*/
captureNextKey(onChord: (chord: KeyChord) => void): () => void {
this.capture = onChord;
return () => {
if (this.capture === onChord) this.capture = null;
};
}
/** The keyboard went away: nothing is held any more. */
reset(): void {
this.consumed.clear();
}
private captureKey(event: KeyEvent): void {
this.host.noteActivity();
if (event.phase === "up") {
this.consumed.delete(event.code);
return;
}
if (event.repeat || isModifierCode(event.code)) return;
const capture = this.capture!;
this.capture = null;
this.consumed.add(event.code);
capture(chordOf(event));
}
private perform(gesture: KeyGesture, repeat: boolean): void {
const now = this.host.now ? this.host.now() : Date.now();
if (repeat && (this.gesturesInFlight > 0 || now - this.lastGestureAtMs < REPEAT_MIN_INTERVAL_MS)) return;
this.lastGestureAtMs = now;
void this.run(gesture, this.scheme.originFor(gesture));
}
private async run(gesture: KeyGesture, origin: GestureOrigin): Promise<void> {
this.gesturesInFlight++;
try {
await this.host.gesture(gesture, origin);
} catch (error) {
this.host.log(`keyboard gesture ${gesture} failed: ${error instanceof Error ? error.message : String(error)}`);
} finally {
this.gesturesInFlight--;
}
}
}
+285
View File
@@ -0,0 +1,285 @@
/**
* Key events as the rest of Faceclaw sees them, and the translation from the
* keyboard bridge's raw HID transitions: layout (US only for now), modifier
* and Caps Lock state, and typematic repeat, which a BLE keyboard never sends
* (its report just stays asserted). The translation tables follow the Glassly
* app's (GlassesKeyboardInput.ts, MIT).
* No platform imports: this runs under node in the tests, and in app workers.
*/
import type { HidKeyEvent } from "./hid";
export type KeyModifiers = { shift: boolean; ctrl: boolean; alt: boolean; meta: boolean };
/**
* One key transition, shaped like a DOM KeyboardEvent: `key` is the logical
* key with the layout applied ("a", "A", "Enter", "ArrowUp"), `code` the
* physical key ("KeyA"), `text` what a press types (absent for releases, for
* keys that type nothing, and for Ctrl/Alt/Meta chords, which are commands).
*/
export type KeyEvent = {
phase: "down" | "up";
key: string;
code: string;
text?: string;
modifiers: KeyModifiers;
/** A synthesized auto-repeat of a held key. */
repeat: boolean;
/** Date.now() when the phone saw the transition. */
timestampMs: number;
};
const HID_PAGE_KEYBOARD = 7;
const HID_PAGE_CONSUMER = 12;
const USAGE_CAPS_LOCK = 57;
/** [unshifted, shifted, code] for US-layout punctuation on the keyboard page. */
const PUNCTUATION: Record<number, [string, string, string]> = {
45: ["-", "_", "Minus"],
46: ["=", "+", "Equal"],
47: ["[", "{", "BracketLeft"],
48: ["]", "}", "BracketRight"],
49: ["\\", "|", "Backslash"],
50: ["#", "~", "IntlHash"],
51: [";", ":", "Semicolon"],
52: ["'", '"', "Quote"],
53: ["`", "~", "Backquote"],
54: [",", "<", "Comma"],
55: [".", ">", "Period"],
56: ["/", "?", "Slash"],
100: ["\\", "|", "IntlBackslash"],
};
const DIGITS = "1234567890";
const SHIFTED_DIGITS = "!@#$%^&*()";
/** [key, code] for keys that type nothing. */
const NAMED: Record<number, [string, string]> = {
40: ["Enter", "Enter"],
41: ["Escape", "Escape"],
42: ["Backspace", "Backspace"],
43: ["Tab", "Tab"],
57: ["CapsLock", "CapsLock"],
70: ["PrintScreen", "PrintScreen"],
71: ["ScrollLock", "ScrollLock"],
72: ["Pause", "Pause"],
73: ["Insert", "Insert"],
74: ["Home", "Home"],
75: ["PageUp", "PageUp"],
76: ["Delete", "Delete"],
77: ["End", "End"],
78: ["PageDown", "PageDown"],
79: ["ArrowRight", "ArrowRight"],
80: ["ArrowLeft", "ArrowLeft"],
81: ["ArrowDown", "ArrowDown"],
82: ["ArrowUp", "ArrowUp"],
83: ["NumLock", "NumLock"],
88: ["Enter", "NumpadEnter"],
101: ["ContextMenu", "ContextMenu"],
102: ["Power", "Power"],
224: ["Control", "ControlLeft"],
225: ["Shift", "ShiftLeft"],
226: ["Alt", "AltLeft"],
227: ["Meta", "MetaLeft"],
228: ["Control", "ControlRight"],
229: ["Shift", "ShiftRight"],
230: ["Alt", "AltRight"],
231: ["Meta", "MetaRight"],
};
/** [key and text, code] for the numeric keypad's operators. */
const NUMPAD: Record<number, [string, string]> = {
84: ["/", "NumpadDivide"],
85: ["*", "NumpadMultiply"],
86: ["-", "NumpadSubtract"],
87: ["+", "NumpadAdd"],
99: [".", "NumpadDecimal"],
103: ["=", "NumpadEqual"],
};
const CONSUMER: Record<number, string> = {
0xe9: "AudioVolumeUp",
0xea: "AudioVolumeDown",
0xe2: "AudioVolumeMute",
0xcd: "MediaPlayPause",
0xb0: "MediaPlay",
0xb1: "MediaPause",
0xb5: "MediaTrackNext",
0xb6: "MediaTrackPrevious",
0xb7: "MediaStop",
0x6f: "BrightnessUp",
0x70: "BrightnessDown",
0x221: "BrowserSearch",
0x223: "BrowserHome",
0x224: "BrowserBack",
0x225: "BrowserForward",
0x18a: "LaunchMail",
0x192: "LaunchApplication2",
0x194: "LaunchApplication1",
};
const MODIFIER_USAGES: Record<number, keyof KeyModifiers> = {
224: "ctrl", 228: "ctrl", 225: "shift", 229: "shift", 226: "alt", 230: "alt", 227: "meta", 231: "meta",
};
type Translated = { key: string; code: string; text?: string };
/** One HID usage under the US layout. Caps Lock only affects letters. */
export function translateUsage(page: number, usage: number, shift: boolean, capsLock: boolean): Translated {
if (page === HID_PAGE_KEYBOARD) {
if (usage >= 4 && usage <= 29) {
const lower = String.fromCharCode(97 + usage - 4);
const key = shift !== capsLock ? lower.toUpperCase() : lower;
return { key, code: `Key${lower.toUpperCase()}`, text: key };
}
if (usage >= 30 && usage <= 39) {
const index = usage - 30;
const key = shift ? SHIFTED_DIGITS[index]! : DIGITS[index]!;
return { key, code: `Digit${DIGITS[index]}`, text: key };
}
if (usage === 44) return { key: " ", code: "Space", text: " " };
const punctuation = PUNCTUATION[usage];
if (punctuation) {
const key = shift ? punctuation[1] : punctuation[0];
return { key, code: punctuation[2], text: key };
}
if (usage >= 58 && usage <= 69) return { key: `F${usage - 57}`, code: `F${usage - 57}` };
if (usage >= 104 && usage <= 115) return { key: `F${usage - 91}`, code: `F${usage - 91}` };
if (usage >= 89 && usage <= 97) {
const digit = String(usage - 88);
return { key: digit, code: `Numpad${digit}`, text: digit };
}
if (usage === 98) return { key: "0", code: "Numpad0", text: "0" };
const numpad = NUMPAD[usage];
if (numpad) return { key: numpad[0], code: numpad[1], text: numpad[0] };
const named = NAMED[usage];
if (named) return { key: named[0], code: named[1] };
return { key: "Unidentified", code: `Usage${usage.toString(16).padStart(2, "0")}` };
}
if (page === HID_PAGE_CONSUMER) {
const name = CONSUMER[usage];
return name ? { key: name, code: name } : { key: "Unidentified", code: `Consumer${usage.toString(16)}` };
}
return { key: "Unidentified", code: `Page${page.toString(16)}Usage${usage.toString(16)}` };
}
export type KeyTranslatorOptions = {
emit: (event: KeyEvent) => void;
now?: () => number;
setTimer?: (callback: () => void, delayMs: number) => unknown;
clearTimer?: (handle: unknown) => void;
/** Hold time before the first repeat, and the gap between repeats. */
repeatDelayMs?: number;
repeatIntervalMs?: number;
};
const REPEAT_DELAY_MS = 400;
const REPEAT_INTERVAL_MS = 50;
/**
* Raw HID transitions in, KeyEvents out. Modifier state comes from the same
* stream, and the bridge reports a release for every key when the stream may
* have lost something, so a missed key-up cannot leave a modifier stuck or a
* key repeating forever.
*/
export class KeyTranslator {
private readonly emitEvent: (event: KeyEvent) => void;
private readonly now: () => number;
private readonly setTimer: (callback: () => void, delayMs: number) => unknown;
private readonly clearTimer: (handle: unknown) => void;
private readonly repeatDelayMs: number;
private readonly repeatIntervalMs: number;
private readonly held = new Set<string>();
private modifiers: KeyModifiers = { shift: false, ctrl: false, alt: false, meta: false };
private capsLock = false;
private repeatTimer: unknown = null;
private repeating: { page: number; usage: number } | null = null;
constructor(options: KeyTranslatorOptions) {
this.emitEvent = options.emit;
this.now = options.now ?? (() => Date.now());
this.setTimer = options.setTimer ?? ((callback, delayMs) => setTimeout(callback, delayMs));
this.clearTimer = options.clearTimer ?? ((handle) => clearTimeout(handle as ReturnType<typeof setTimeout>));
this.repeatDelayMs = options.repeatDelayMs ?? REPEAT_DELAY_MS;
this.repeatIntervalMs = options.repeatIntervalMs ?? REPEAT_INTERVAL_MS;
}
/** Apply the transitions one input report produced, in order. */
handle(events: readonly HidKeyEvent[]): void {
for (const event of events) this.handleOne(event);
}
private handleOne(event: HidKeyEvent): void {
const id = `${event.page}:${event.usage}`;
const modifier = event.page === HID_PAGE_KEYBOARD ? MODIFIER_USAGES[event.usage] : undefined;
if (event.down) {
if (this.held.has(id)) return;
this.held.add(id);
if (modifier) this.modifiers[modifier] = true;
if (event.page === HID_PAGE_KEYBOARD && event.usage === USAGE_CAPS_LOCK) this.capsLock = !this.capsLock;
this.emit("down", event.page, event.usage, false);
// The newest non-modifier key is the one that repeats, as on a PC.
if (!modifier) this.startRepeat(event.page, event.usage);
} else {
if (!this.held.delete(id)) return;
if (modifier) this.modifiers[modifier] = this.otherHeld(event.usage, modifier);
if (this.repeating?.page === event.page && this.repeating.usage === event.usage) this.stopRepeat();
this.emit("up", event.page, event.usage, false);
}
}
/** The keyboard went away: forget everything without emitting releases. */
reset(): void {
this.stopRepeat();
this.held.clear();
this.modifiers = { shift: false, ctrl: false, alt: false, meta: false };
this.capsLock = false;
}
/** Whether the same modifier's key on the other side is still down. */
private otherHeld(released: number, modifier: keyof KeyModifiers): boolean {
for (const [usage, name] of Object.entries(MODIFIER_USAGES)) {
if (name === modifier && Number(usage) !== released && this.held.has(`${HID_PAGE_KEYBOARD}:${usage}`)) return true;
}
return false;
}
private emit(phase: "down" | "up", page: number, usage: number, repeat: boolean): void {
const translated = translateUsage(page, usage, this.modifiers.shift, this.capsLock);
const event: KeyEvent = {
phase,
key: translated.key,
code: translated.code,
modifiers: { ...this.modifiers },
repeat,
timestampMs: this.now(),
};
if (phase === "down" && translated.text !== undefined &&
!this.modifiers.ctrl && !this.modifiers.alt && !this.modifiers.meta) {
event.text = translated.text;
}
this.emitEvent(event);
}
private startRepeat(page: number, usage: number): void {
this.stopRepeat();
this.repeating = { page, usage };
this.repeatTimer = this.setTimer(() => this.repeatTick(), this.repeatDelayMs);
}
private repeatTick(): void {
const key = this.repeating;
this.repeatTimer = null;
if (!key || !this.held.has(`${key.page}:${key.usage}`)) {
this.repeating = null;
return;
}
this.emit("down", key.page, key.usage, true);
this.repeatTimer = this.setTimer(() => this.repeatTick(), this.repeatIntervalMs);
}
private stopRepeat(): void {
if (this.repeatTimer !== null) this.clearTimer(this.repeatTimer);
this.repeatTimer = null;
this.repeating = null;
}
}
+297
View File
@@ -0,0 +1,297 @@
/**
* Wire format of the CFW keyboard bridge (Faceclaw/39). The master temple acts
* as a BLE central for one HID-over-GATT keyboard; the phone drives that link
* over private settings fields and gets the keyboard's raw input reports back.
* The firmware side is g2flash patches/keyboard_core.h, documented in its
* docs/keyboard.md. This follows the reference client in g2flash demos/
* (keyboard-protocol.ts), which came with the firmware from tetramo-labs.
*
* Phone -> glasses, settings field 130 (wrapped by the native session):
* ['K','B',1,op, request LE16, epoch LE16, body...] at most 80 bytes
* Glasses -> phone, settings field 131:
* ['K','B',1,kind, sequence LE32, epoch LE16, request LE16, code LE16,
* handle LE16, total LE16, offset LE16, timestamp LE32, fragment...]
*
* All integers are little endian. No platform imports: this runs under node
* in the tests.
*/
export const KEYBOARD_PROTOCOL_VERSION = 1;
/** Fixed part of a field-131 record, before its fragment. */
export const KEYBOARD_RECORD_HEADER = 24;
/** Most body bytes one record carries; longer bodies are fragmented. */
export const KEYBOARD_RECORD_CHUNK = 96;
/** Largest reassembled body (an ATT value or a HID report). */
export const KEYBOARD_BODY_MAX = 512;
/** Largest control body after the 8-byte prefix. */
export const KEYBOARD_CONTROL_BODY_MAX = 72;
export const KeyboardOp = {
query: 0,
enable: 1,
disable: 2,
scan: 3,
connect: 4,
disconnect: 5,
pair: 6,
auth: 7,
compare: 8,
find: 9,
read: 10,
write: 11,
watch: 12,
} as const;
export type KeyboardOpCode = (typeof KeyboardOp)[keyof typeof KeyboardOp];
export const KeyboardKind = {
status: 1,
att: 2,
input: 3,
dm: 4,
advert: 5,
} as const;
/** Control error codes, carried in a STATUS record's `code`. */
export const KeyboardError = {
ok: 0,
badRequest: 1,
disabled: 2,
busy: 3,
staleEpoch: 4,
noSpace: 5,
notConnected: 6,
notEncrypted: 7,
timeout: 8,
noMemory: 9,
} as const;
export function keyboardErrorName(code: number): string {
switch (code) {
case KeyboardError.ok: return "ok";
case KeyboardError.badRequest: return "bad request";
case KeyboardError.disabled: return "keyboard bridge disabled";
case KeyboardError.busy: return "busy";
case KeyboardError.staleEpoch: return "stale epoch";
case KeyboardError.noSpace: return "no connection or bond space";
case KeyboardError.notConnected: return "not connected";
case KeyboardError.notEncrypted: return "not encrypted";
case KeyboardError.timeout: return "timeout";
case KeyboardError.noMemory: return "allocation failure";
default: return `error ${code}`;
}
}
/** Cordio device-manager events the bridge relays (a DM record's `code & 0xff`). */
export const KeyboardDm = {
connOpen: 0x27,
connClose: 0x28,
pairComplete: 0x2a,
pairFailed: 0x2b,
encrypted: 0x2c,
encryptFailed: 0x2d,
authRequest: 0x2e,
compare: 0x35,
} as const;
/** ATT client events (an ATT record's `code & 0xff`; the status is `code >> 8`). */
export const KeyboardAtt = {
notification: 13,
indication: 14,
} as const;
export type KeyboardRecord = {
kind: number;
sequence: number;
epoch: number;
request: number;
code: number;
handle: number;
/** Glasses uptime in ms when the record was queued. */
timestamp: number;
data: Uint8Array;
};
export const u16 = (p: Uint8Array, off = 0): number => p[off]! | (p[off + 1]! << 8);
export const u32 = (p: Uint8Array, off = 0): number =>
(p[off]! | (p[off + 1]! << 8) | (p[off + 2]! << 16) | (p[off + 3]! << 24)) >>> 0;
export const le16 = (v: number): number[] => [v & 255, (v >>> 8) & 255];
/** A field-130 control record. The session wraps it in the settings package. */
export function keyboardControl(op: number, request: number, epoch: number, body: readonly number[] = []): Uint8Array {
if (!Number.isInteger(op) || op < 0 || op > KeyboardOp.watch || body.length > KEYBOARD_CONTROL_BODY_MAX) {
throw new Error("Keyboard control bounds");
}
return Uint8Array.from([75, 66, KEYBOARD_PROTOCOL_VERSION, op, ...le16(request), ...le16(epoch), ...body]);
}
/**
* Bounded, ordered reassembly of field-131 records. `onGap` fires whenever
* the stream may have lost something (a skipped sequence, an epoch change, a
* malformed or orphaned fragment): the caller then releases every held key
* and fails any setup transaction in flight. The firmware's once-a-second
* status record makes a lost final release visible even when no further keys
* arrive.
*/
export class KeyboardRecords {
private epoch: number | undefined;
private last: number | undefined;
private fragment: { record: KeyboardRecord; total: number; used: number } | undefined;
constructor(private readonly onGap: () => void) {}
/** Forget the stream position (the phone link dropped); counts as a gap. */
reset(): void {
this.epoch = undefined;
this.last = undefined;
this.fragment = undefined;
this.onGap();
}
/** Feed one field-131 payload; returns a complete record, or undefined. */
push(p: Uint8Array): KeyboardRecord | undefined {
const invalid = (): undefined => {
this.fragment = undefined;
this.onGap();
return undefined;
};
if (
p.length < KEYBOARD_RECORD_HEADER || p.length > KEYBOARD_RECORD_HEADER + KEYBOARD_RECORD_CHUNK ||
p[0] !== 75 || p[1] !== 66 || p[2] !== KEYBOARD_PROTOCOL_VERSION
) {
return invalid();
}
const r: KeyboardRecord = {
kind: p[3]!,
sequence: u32(p, 4),
epoch: u16(p, 8),
request: u16(p, 10),
code: u16(p, 12),
handle: u16(p, 14),
timestamp: u32(p, 20),
data: new Uint8Array(0),
};
const total = u16(p, 16);
const offset = u16(p, 18);
const n = p.length - KEYBOARD_RECORD_HEADER;
if (r.kind < KeyboardKind.status || r.kind > KeyboardKind.advert || total > KEYBOARD_BODY_MAX ||
offset + n > total || (total > 0 && n === 0)) {
return invalid();
}
if (this.epoch !== r.epoch) {
this.onGap();
this.fragment = undefined;
this.last = undefined;
this.epoch = r.epoch;
}
if (offset === 0) {
if (this.last !== undefined) {
const distance = (r.sequence - this.last) >>> 0;
if (distance === 0 || distance >= 0x80000000) return undefined; // duplicate or old delivery
}
if (this.fragment || (this.last !== undefined && r.sequence !== ((this.last + 1) >>> 0))) this.onGap();
this.last = r.sequence;
this.fragment = { record: { ...r, data: new Uint8Array(total) }, total, used: 0 };
}
const f = this.fragment;
if (!f || f.used !== offset || f.total !== total || f.record.sequence !== r.sequence ||
f.record.kind !== r.kind || f.record.request !== r.request || f.record.code !== r.code ||
f.record.handle !== r.handle || f.record.timestamp !== r.timestamp) {
return invalid();
}
f.record.data.set(p.subarray(KEYBOARD_RECORD_HEADER), offset);
f.used += n;
if (f.used !== total) return undefined;
this.fragment = undefined;
return f.record;
}
}
/** BLE address types as the controller reports them. */
export const KEYBOARD_ADDRESS_TYPES = ["public", "random", "public-identity", "random-identity"] as const;
/** One advertiser seen during a scan (an ADVERT record's body, parsed). */
export type KeyboardAdvert = {
addressType: number;
/** "aa:bb:cc:dd:ee:ff", most significant byte first. */
address: string;
rssi: number;
name: string;
/** Advertises the HID service, or a HID appearance. */
hid: boolean;
};
/** ADVERT body: addrType, addr[6] (LSB first), RSSI, event type, AD length, AD structures. */
export function parseKeyboardAdvert(body: Uint8Array): KeyboardAdvert | null {
if (body.length < 10 || body[0]! > 3) return null;
let name = "";
let hid = false;
for (let i = 10; i < body.length;) {
const n = body[i++]!;
if (n === 0 || i + n > body.length) break;
const type = body[i]!;
if (type === 8 || type === 9) name = decodeUtf8(body.subarray(i + 1, i + n));
// 16-bit service lists (incomplete / complete): 0x1812 is HID.
if (type === 2 || type === 3) {
for (let j = i + 1; j + 1 < i + n; j += 2) if (body[j] === 0x12 && body[j + 1] === 0x18) hid = true;
}
// Appearance 0x03C0..0x03FF is the HID category (0x03C1 keyboard); some
// keyboards advertise that without the service list.
if (type === 0x19 && n >= 3 && body[i + 2] === 0x03 && body[i + 1]! >= 0xc0) hid = true;
i += n;
}
return {
addressType: body[0]!,
address: formatKeyboardAddress(body.subarray(1, 7)),
rssi: (body[7]! << 24) >> 24,
name,
hid,
};
}
/**
* Fold a later record for the same advertiser into an earlier one. An active
* scan reports the advertisement and its scan response separately and the
* name usually only rides in the latter: keep a name once seen, HID once
* seen, and the best signal.
*/
export function mergeKeyboardAdverts(a: KeyboardAdvert, b: KeyboardAdvert): KeyboardAdvert {
return { ...a, rssi: Math.max(a.rssi, b.rssi), name: a.name || b.name, hid: a.hid || b.hid };
}
/** Controller byte order (LSB first) to the usual "aa:bb:cc:dd:ee:ff". */
export function formatKeyboardAddress(lsbFirst: Uint8Array): string {
return Array.from(lsbFirst).reverse().map((b) => b.toString(16).padStart(2, "0")).join(":");
}
/** "aa:bb:cc:dd:ee:ff" to the controller's LSB-first bytes, or null if malformed. */
export function parseKeyboardAddress(text: string): Uint8Array | null {
if (!/^(?:[0-9a-f]{2}:){5}[0-9a-f]{2}$/i.test(text)) return null;
return Uint8Array.from(text.split(":").reverse().map((part) => parseInt(part, 16)));
}
/** Lenient UTF-8 decode (advertised names); no TextDecoder in every runtime this loads in. */
function decodeUtf8(bytes: Uint8Array): string {
let out = "";
for (let i = 0; i < bytes.length;) {
const b = bytes[i++]!;
let code = b;
let extra = 0;
if (b >= 0xf0 && b < 0xf8) { code = b & 0x07; extra = 3; }
else if (b >= 0xe0) { code = b & 0x0f; extra = 2; }
else if (b >= 0xc0) { code = b & 0x1f; extra = 1; }
else if (b >= 0x80) { out += "�"; continue; }
if (i + extra > bytes.length) { out += "�"; break; }
let valid = true;
for (let k = 0; k < extra; k++) {
const c = bytes[i + k]!;
if ((c & 0xc0) !== 0x80) { valid = false; break; }
code = (code << 6) | (c & 0x3f);
}
if (!valid || code > 0x10ffff) { out += "�"; continue; }
i += extra;
if (code === 0) continue;
out += String.fromCodePoint(code);
}
return out;
}
+216
View File
@@ -0,0 +1,216 @@
/**
* The keyboard bridge as the app uses it: one KeyboardBridge for the life of
* the app, fed by whichever glasses session is live, its remembered keyboard
* and the custom keybindings kept in the settings store, and its key
* transitions turned into KeyEvents and routed. The platform's controller
* reports the link coming and going and performs the gestures keys stand
* for; the Settings app drives pairing through `bridge` and edits the
* keybindings.
*/
import { addKeyboardEventListener, keyboardLinkSession, sendKeyboardControlRecord } from "../../native/keyboard-link";
import { getStringSetting, setStringSetting } from "../../native/settings-store";
import { shell } from "../../ui/shell/shell";
import {
MAX_KEY_BINDINGS,
chordId,
keyBindingMap,
parseKeyBindings,
serializeKeyBindings,
type GestureOrigin,
type KeyAction,
type KeyBinding,
type KeyChord,
type KeyGesture,
} from "./bindings";
import { KeyboardBridge, type KeyboardBridgeSnapshot, type SavedKeyboard } from "./bridge";
import { KeyRouter } from "./key-router";
import { KeyTranslator, type KeyEvent } from "./keys";
declare const java: any;
declare const arc4random_uniform: ((bound: number) => number) | undefined;
/** JSON of the remembered keyboard ({ address, addressType, name }), or "" for none. */
const SAVED_KEYBOARD_KEY = "keyboard.saved";
/** JSON list of the custom keybindings ({ key, action }); see bindings.ts. */
const KEY_BINDINGS_KEY = "keyboard.bindings";
/** What the platform's controller does for the keyboard. */
export type KeyboardServiceHost = {
/** Connected to glasses that are in use (not charging in their case). */
ready(): boolean;
locked(): boolean;
/** Turn a dark display on, and nothing else (a locked display stays locked). */
wake(): void;
/** Perform a gesture as if it came from the ring or the watch. */
gesture(gesture: KeyGesture, origin: GestureOrigin): Promise<void>;
/** Routine lines only (failed background reconnects); the rest go to the device log directly. */
log(line: string): void;
/** Whether an absent keyboard is worth looking for now (see KeyboardBridgeHost). */
shouldReconnect(): boolean;
};
function loadSavedKeyboard(): SavedKeyboard | null {
try {
const raw = getStringSetting(SAVED_KEYBOARD_KEY, "");
if (!raw) return null;
const value = JSON.parse(raw);
if (typeof value?.address !== "string" || typeof value?.addressType !== "number") return null;
return { address: value.address, addressType: value.addressType, name: typeof value.name === "string" ? value.name : "" };
} catch {
return null;
}
}
/** Passkey entry only protects the pairing if the passkey can't be guessed. */
function randomPasskey(): number {
try {
if (global.isAndroid) return new java.security.SecureRandom().nextInt(1_000_000);
if (typeof arc4random_uniform === "function") return arc4random_uniform(1_000_000);
} catch {
// Fall through to the weaker source rather than failing the pairing.
}
return Math.floor(Math.random() * 1_000_000);
}
class KeyboardService {
private host: KeyboardServiceHost | null = null;
private session: unknown = null;
private offEvents: (() => void) | null = null;
private readonly listeners = new Set<() => void>();
private bindings: KeyBinding[] = parseKeyBindings(getStringSetting(KEY_BINDINGS_KEY, ""));
private bindingMap = keyBindingMap(this.bindings);
private readonly router = new KeyRouter({
ready: () => this.host?.ready() ?? false,
locked: () => this.host?.locked() ?? false,
screenOn: () => shell.isScreenOn(),
wake: () => this.host?.wake(),
offerToWindow: (event) => shell.receiveKeyEvent(event),
gesture: (gesture, origin) => this.host?.gesture(gesture, origin) ?? Promise.resolve(),
bindings: () => this.bindingMap,
noteActivity: () => shell.noteUserActivity(),
log: (line) => console.log(`[keyboard] ${line}`),
});
private readonly translator = new KeyTranslator({ emit: (event) => this.router.handleKey(event) });
readonly bridge = new KeyboardBridge({
send: (record) => {
const session = this.session;
if (!session) return false;
try {
return sendKeyboardControlRecord(session, record, `op=${record[3]}`);
} catch {
return false;
}
},
loadSaved: loadSavedKeyboard,
storeSaved: (saved) => setStringSetting(SAVED_KEYBOARD_KEY, saved ? JSON.stringify(saved) : ""),
onKeys: (events) => this.translator.handle(events),
onKeyboardGone: () => {
this.translator.reset();
this.router.reset();
},
onChanged: () => {
for (const listener of [...this.listeners]) listener();
},
// Pairing and setup are rare and are what a failure report needs, so
// they always reach the device log. Nothing here ever includes a key.
log: (line, routine) => {
if (routine) this.host?.log(line);
else console.log(`[keyboard] ${line}`);
},
randomPasskey,
shouldReconnect: () => this.host?.shouldReconnect() ?? true,
});
setHost(host: KeyboardServiceHost): void {
this.host = host;
}
snapshot(): KeyboardBridgeSnapshot {
return this.bridge.snapshot();
}
/** Called on every bridge state change. Returns an unsubscribe function. */
subscribe(listener: () => void): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
/** The glasses came into use (the display woke): look for an absent keyboard now. */
retryNow(): void {
this.bridge.retryNow();
}
/** A G2 session on firmware with the bridge is up. Idempotent. */
linkReady(): void {
const session = keyboardLinkSession();
if (!session) return;
if (session !== this.session) {
// The native session object is rebuilt across reconnects.
this.offEvents?.();
this.session = session;
this.offEvents = addKeyboardEventListener(session, (body) => this.bridge.accept(body));
}
this.bridge.linkReady();
}
/**
* The session can't host the keyboard any more. `release` asks the firmware
* to let the keyboard go first, for when the link itself stays up (the
* glasses went into their case, or the app is disconnecting on purpose).
* Idempotent.
*/
linkLost(release = false): void {
if (release) this.bridge.linkClosing();
this.bridge.linkLost();
this.offEvents?.();
this.offEvents = null;
this.session = null;
}
/** A key a worker's window was sent and had no use for (the "key-unhandled" reply). */
handleUnhandledKey(event: KeyEvent): void {
this.router.handleUnhandledKey(event);
}
// ---------- Custom keybindings ----------
/** The custom keybindings, in the order they were added. */
keyBindings(): readonly KeyBinding[] {
return this.bindings;
}
/** Bind a chord, replacing what it was bound to. False when the list is full. */
setKeyBinding(chord: KeyChord, action: KeyAction): boolean {
const id = chordId(chord);
const index = this.bindings.findIndex((binding) => chordId(binding.chord) === id);
if (index < 0 && this.bindings.length >= MAX_KEY_BINDINGS) return false;
const next = [...this.bindings];
if (index < 0) next.push({ chord, action });
else next[index] = { chord, action };
this.storeBindings(next);
return true;
}
removeKeyBinding(chord: KeyChord): void {
const id = chordId(chord);
this.storeBindings(this.bindings.filter((binding) => chordId(binding.chord) !== id));
}
/**
* Take the next key pressed on the keyboard instead of acting on it. Returns
* a function that calls the capture off.
*/
captureNextKey(onChord: (chord: KeyChord) => void): () => void {
return this.router.captureNextKey(onChord);
}
private storeBindings(bindings: KeyBinding[]): void {
this.bindings = bindings;
this.bindingMap = keyBindingMap(bindings);
setStringSetting(KEY_BINDINGS_KEY, serializeKeyBindings(bindings));
}
}
export const keyboardService = new KeyboardService();
+21
View File
@@ -19,6 +19,7 @@ declare const FaceclawKitFaceclawCompassListener: any;
declare const FaceclawKitFaceclawImuListener: any;
declare const FaceclawKitIosAmbientLightListener: any;
declare const FaceclawKitIosMicStatusListener: any;
declare const FaceclawKitIosKeyboardEventListener: any;
export type CommunicatorPhase =
@@ -198,6 +199,13 @@ class MicStatusListener extends NSObject {
onNsDataMicStatusBodyArm(body: NSData, arm: string): void { this.handler(fromData(body), String(arm ?? "")); }
}
@NativeClass()
class KeyboardEventListener extends NSObject {
static ObjCProtocols = [FaceclawKitIosKeyboardEventListener];
handler!: (body: Uint8Array) => void;
onNsDataKeyboardEventBody(body: NSData): void { this.handler(fromData(body)); }
}
/**
* The iOS twin of the Android communicator bridge: the same public API over
* the shared Kotlin session (FaceclawKitIosGlassesSession, CoreBluetooth
@@ -803,6 +811,19 @@ export class FaceclawCommunicatorBridge {
toData(new Uint8Array(record)), label, Boolean(rightTemple), Boolean(leftTemple)));
}
/** Raw field-131 keyboard-bridge records, in arrival order, on the main queue. */
addKeyboardEventListener(listener: (body: Uint8Array) => void): () => void {
const proxy = KeyboardEventListener.new() as KeyboardEventListener;
proxy.handler = listener;
const handle = this.communicator.addKeyboardEventListenerNsDataListener(proxy);
return () => { this.communicator.removeKeyboardEventListenerListener(handle); };
}
/** Queue a CFW keyboard-bridge control for the right temple; false when nothing was queued. */
sendFaceclawKeyboardControl(record: Uint8Array, label: string): boolean {
return Boolean(this.communicator.sendFaceclawKeyboardControlRecordLabel(toData(new Uint8Array(record)), label));
}
/**
* Every audio-characteristic packet, whatever enabled the mics, on the
* main queue. Passive: sends nothing and doesn't affect capture.
+65
View File
@@ -0,0 +1,65 @@
declare const com: any;
/**
* Head-up (look-up wake) trigger on the active glasses session
* (GlassesSessionCore.setHeadUpTrigger / getHeadUpStatus). Android only for
* now (headUpControlsAvailable): on iOS, or with no session, the setter does
* nothing and the getter returns null.
*/
/** Whether this platform can change the glasses' head-up setting at all. */
export function headUpControlsAvailable(): boolean {
return Boolean(global.isAndroid);
}
/** GlassesSessionCore.getHeadUpStatus. switch -1 = not read on this connection. */
export type HeadUpStatus = {
switch: number;
angle: number;
calibration: number;
/** The trigger Faceclaw is maintaining, or -1 when it leaves the glasses' own setting. */
desired: number;
readAgeMs: number;
/** The glasses' own switch and angle from before Faceclaw changed them (switch -1 = none held). */
originalSwitch: number;
originalAngle: number;
/** Those originals are being written back. */
restorePending: boolean;
};
function activeCommunicator(): any {
if (!global.isAndroid) return null;
try {
return com.faceclaw.app.FaceclawBleCommunicator.getActive();
} catch {
return null;
}
}
/**
* Ask the session to keep the head-up trigger at `degrees` (1..90); 0 stops
* managing it and writes back `original` (or what the session saved itself)
* if Faceclaw changed the glasses' values.
*/
export function setHeadUpTrigger(degrees: number, original: { switch: number; angle: number } | null = null): boolean {
const active = activeCommunicator();
if (!active) return false;
try {
active.setHeadUpTrigger(Math.round(degrees), original ? original.switch : -1, original ? Math.round(original.angle) : 0);
return true;
} catch (error) {
console.warn(`setHeadUpTrigger failed: ${error}`);
return false;
}
}
export function getHeadUpStatus(): HeadUpStatus | null {
const active = activeCommunicator();
if (!active) return null;
try {
return JSON.parse(String(active.getHeadUpStatus())) as HeadUpStatus;
} catch (error) {
console.warn(`getHeadUpStatus failed: ${error}`);
return null;
}
}
+16
View File
@@ -1,7 +1,23 @@
/** Platform-neutral IMU types, shared by imu.ts and imu.ios.ts. */
/**
* An accelerometer sample in g, in Faceclaw's frame for every glasses model
* (the G2's own; the session rotates other models' samples into it, see
* ImuOrientation.kt): +x forward, +y to the wearer's left, +z up through the
* top of the head. At rest it is the "up" direction: head level reads
* (0, 0, 1), looking 45° up (0.71, 0, 0.71), the head tilted 45° to the right
* (0, 0.71, 0.71).
*/
export type ImuReading = { x: number; y: number; z: number; source: number };
/**
* How far the head is tilted up from level, in degrees (negative: down), from
* a reading taken at rest. Rolling the head to the side does not change it.
*/
export function imuPitchDegrees(reading: { x: number; y: number; z: number }): number {
return (Math.atan2(reading.x, Math.hypot(reading.y, reading.z)) * 180) / Math.PI;
}
/** Map an IMU sample's EventSource to a short label. */
export function imuSourceLabel(source: number): string {
switch (source) {
+24
View File
@@ -0,0 +1,24 @@
import { FaceclawCommunicatorBridge } from "./faceclaw-communicator.ios";
/** The iOS twin of keyboard-link.ts, over the running shared-Kotlin session. */
export function keyboardLinkSession(): unknown {
return FaceclawCommunicatorBridge.getActive();
}
/** Queue a control record for the right temple; false when the session wasn't ready and nothing was queued. */
export function sendKeyboardControlRecord(session: unknown, record: Uint8Array, label: string): boolean {
return (session as FaceclawCommunicatorBridge).sendFaceclawKeyboardControl(record, label);
}
/** Raw keyboard-bridge records (undecoded, possibly fragments), in arrival order. Returns an unsubscribe function. */
export function addKeyboardEventListener(session: unknown, listener: (body: Uint8Array) => void): () => void {
const unsubscribe = (session as FaceclawCommunicatorBridge).addKeyboardEventListener(listener);
return () => {
try {
unsubscribe();
} catch {
// The session may have been closed during a reconnect.
}
};
}
+40
View File
@@ -0,0 +1,40 @@
import { toJavaBytes } from "./cloud-stt";
import { toUint8Array } from "../util/array-util";
declare const com: any;
/**
* Platform plumbing for the CFW keyboard bridge (app/g2/keyboard/): the running
* session to send field-130 controls on and to hear field-131 records from.
* The session is opaque and is a different object after a reconnect.
*/
export function keyboardLinkSession(): unknown {
if (!global.isAndroid) return null;
try {
return com.faceclaw.app.FaceclawBleCommunicator.getActive();
} catch {
return null;
}
}
/** Queue a control record for the right temple; false when the session wasn't ready and nothing was queued. */
export function sendKeyboardControlRecord(session: unknown, record: Uint8Array, label: string): boolean {
return (session as any).sendFaceclawKeyboardControl(toJavaBytes(record), label) !== false;
}
/** Raw keyboard-bridge records (undecoded, possibly fragments), in arrival order. Returns an unsubscribe function. */
export function addKeyboardEventListener(session: unknown, listener: (body: Uint8Array) => void): () => void {
const communicator = session as any;
const proxy = new com.faceclaw.app.FaceclawKeyboardEventListener({
onKeyboardEvent: (body: any) => listener(toUint8Array(body)),
});
communicator.addKeyboardEventListener(proxy);
return () => {
try {
communicator.removeKeyboardEventListener(proxy);
} catch {
// The old communicator instance may be gone after a reconnect.
}
};
}
+50
View File
@@ -0,0 +1,50 @@
import { knownFolders, path as paths } from '@nativescript/core'
// Kotlin/Native facade exported by FaceclawKit (native/kotlin/shared/src/iosMain/.../IosMicRecorder.kt).
declare const FaceclawKitIosMicRecordings: any
/**
* Records 16 kHz mono PCM16 to a Matroska audio file (.mka) in
* Documents/Downloads while it is captured, through the shared Kotlin writer
* that Android's captures are recorded with. The file is written about a
* second at a time, so a crash leaves everything up to the last second.
*/
export class MicRecorder {
private constructor(private recorder: any, readonly path: string) {}
/**
* A recorder for Downloads/<name>.mka (a -2, -3... suffix if taken), or null.
* `info` describes the capture and is stored in the file.
*/
static open(name: string, info: Record<string, unknown> = {}): MicRecorder | null {
const fm = NSFileManager.defaultManager
const dir = paths.join(knownFolders.documents().path, 'Downloads')
try {
fm.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(dir, true, null)
let path = paths.join(dir, `${name}.mka`)
for (let n = 2; fm.fileExistsAtPath(path); n++) path = paths.join(dir, `${name}-${n}.mka`)
const recorder = FaceclawKitIosMicRecordings.shared.openPathConfigJson(path, JSON.stringify(info))
return recorder ? new MicRecorder(recorder, path) : null
} catch {
return null
}
}
append(pcm: Uint8Array): void {
if (!this.recorder || !pcm.length) return
// The handle is the buffer's start: a view into a larger buffer is copied out first.
const bytes = pcm.byteOffset === 0 && pcm.byteLength === pcm.buffer.byteLength ? pcm : pcm.slice()
try {
// Copied by the recorder before this returns.
this.recorder.appendPcm16le(NSData.dataWithBytesLength(interop.handleof(bytes.buffer), bytes.byteLength))
} catch {
// Stop recording rather than retry.
this.close()
}
}
close(): void {
try { this.recorder?.finish() } catch { /* already closed */ }
this.recorder = null
}
}
+29
View File
@@ -0,0 +1,29 @@
declare const android: any;
declare const java: any;
/** Extension of the recordings Save Recording writes, and Transcribe replays (Matroska audio). */
export const RECORDING_EXTENSION = ".mka";
export function isMicRecordingFile(name: string): boolean {
return name.toLowerCase().endsWith(RECORDING_EXTENSION);
}
/**
* The path for a new recording in the public Downloads directory:
* Downloads/<name>.mka, with a -2, -3... suffix if that is taken. Null when
* Downloads isn't available. The file itself is created by whoever records.
*/
export function newRecordingPath(name: string): string | null {
try {
const downloads = android.os.Environment.getExternalStoragePublicDirectory(
android.os.Environment.DIRECTORY_DOWNLOADS,
);
downloads.mkdirs();
let file = new java.io.File(downloads, `${name}${RECORDING_EXTENSION}`);
for (let n = 2; file.exists(); n++) file = new java.io.File(downloads, `${name}-${n}${RECORDING_EXTENSION}`);
return String(file.getAbsolutePath());
} catch (error) {
console.warn(`Voice: no Downloads directory for ${name}${RECORDING_EXTENSION}: ${error}`);
return null;
}
}
+8 -5
View File
@@ -3,7 +3,7 @@ import type { CloudSttTranscriptEvent } from './cloud-stt'
import type { ReconnectingSttClient } from './reconnecting-stt'
import { createCloudSttClient, usesCloudStt, type VoiceProviderSelection } from './cloud-stt-provider'
import { createSpeechAnalyzerClient, speechAnalyzerSupported } from './speech-analyzer-stt.ios'
import { WavRecorder } from './wav-recorder.ios'
import { MicRecorder } from './mic-recorder.ios'
import { pcmLevel } from '../util/audio-level'
declare const FaceclawSpeech: any
@@ -57,11 +57,11 @@ export class IosVoiceControlBridge {
private continuous = false
// Shown instead of the native "ended" status once a drain the bridge started completes.
private drainStatus: string | null = null
// Continuous captures' audio goes to Downloads/<recordingName>.wav while it is
// Continuous captures' audio goes to Downloads/<recordingName>.mka while it is
// set. The file outlives a capture, so a restarted one keeps appending to it,
// and it is created by the first audio, so a failed start leaves no file.
private recordingName = ''
private recorder: WavRecorder | null = null
private recorder: MicRecorder | null = null
// The file could not be created: one attempt per recording, not one per packet.
private recordingFailure = false
private readonly recordingListeners = new Set<() => void>()
@@ -209,7 +209,7 @@ export class IosVoiceControlBridge {
/** Where a listening continuous capture gets its audio; null when none is listening. */
get continuousSource(): 'glasses' | 'phone' | null { return this.continuous && this.capturing ? this.source : null }
/**
* Record continuous captures' audio to Downloads/<name>.wav, across restarts,
* Record continuous captures' audio to Downloads/<name>.mka, across restarts,
* until called with another name or ''. Only cloud captures supply PCM.
*/
recordTo(name: string): void {
@@ -232,7 +232,10 @@ export class IosVoiceControlBridge {
private record(pcm: Uint8Array): void {
if (!this.recording) return
if (!this.recorder) {
this.recorder = WavRecorder.open(this.recordingName)
this.recorder = MicRecorder.open(this.recordingName, {
recording: this.recordingName, startedAt: new Date().toISOString(), platform: 'ios',
source: this.source === 'phone' ? 'phone' : 'glasses', mics: 1,
})
this.log(this.recorder ? `Voice: recording audio to ${this.recorder.path}` : 'Voice: could not create the audio recording')
if (!this.recorder) { this.setRecording(this.recordingName, true); return }
}
+319 -27
View File
@@ -1,9 +1,9 @@
import { Utils } from "@nativescript/core";
import { type CloudSttTranscriptEvent, CloudSttClient } from "./cloud-stt";
import { type CloudSttTranscriptEvent, CloudSttClient, toJavaBytes } from "./cloud-stt";
import { createCloudSttClient, transcriptionKey } from "./cloud-stt-provider";
import { newRecordingPath } from "./mic-recording";
import { SpeechPauseDetector } from "./speech-pause";
import { WavRecorder } from "./wav-recorder";
import { toUint8Array } from "../util/array-util";
import { pcmLevel } from "../util/audio-level";
@@ -84,6 +84,49 @@ export type PushToTalkOptions = {
* frame). Null/absent leaves the mic omnidirectional.
*/
beamFilter?: { centerDeg: number; halfWidthDeg: number } | null;
/**
* Capture from the temples' own microphones (the custom firmware's
* mic_control stream) instead of the glasses' mixed stream. Each temple
* streams its microphones on its own link and clock; the phone mixes them
* into the mono feed that is transcribed. Null/absent keeps the mixed
* stream; ignored with usePhoneMic.
*/
micArray?: MicArrayCapture | null;
/**
* Play this recording (a .mka file from Save Recording) in real time in
* place of any microphone. The capture needs no glasses, and ends by
* itself when the recording does.
*/
replay?: { path: string; startMs: number } | null;
/** What the caller knows of the capture, for the description stored in a recording of it. */
captureInfo?: Record<string, unknown>;
};
export type MicArrayCapture = {
/** The mic_control CONFIGURE record both temples are armed with (see mic-protocol.ts). */
configure: Uint8Array;
};
/** Progress of a capture that replays a recording; positions are ms into it. */
export type VoiceReplayEvent = {
/**
* `start` once the file is open, `position` about once per second played,
* `seek` when a jump took effect, `end` when the recording ran out, and
* `error` when it could not be opened (the status says why).
*/
kind: "start" | "position" | "seek" | "end" | "error";
positionMs: number;
durationMs: number;
};
/** What a listening view (Transcribe, Translate) takes from a capture: the microphone's, or a replay's. */
export type VoiceEventSource = {
onStatus(listener: (state: VoiceControlState) => void): () => void;
onTranscript(listener: (event: VoiceTranscriptEvent) => void): () => void;
onSpeechPause(listener: () => void): () => void;
onMicLevel(listener: (level: number) => void): () => void;
readonly recording: boolean;
readonly recordingFailed: boolean;
};
/** Who currently wants the mic running. */
@@ -130,9 +173,13 @@ export class FaceclawVoiceControlBridge {
private captureEndpointing = false;
// Non-null while a cloud provider owns the transcript; Java only decodes PCM.
private cloudClient: CloudSttClient | null = null;
// What the running STT stream transcribes with (transcriptionKey); a holder
// asking for something else restarts the stream rather than sharing it.
// What the running STT stream captures from and transcribes with
// (streamKey); a holder asking for something else restarts the stream
// rather than sharing it.
private streamProvider: string | null = null;
// The options of the running stream, for the description of a recording of it.
private streamOptions: PushToTalkOptions | null = null;
private readonly replayListeners = new Set<(event: VoiceReplayEvent) => void>();
// Raw-PCM tap (EvenHub mic apps, the Microphones app): when active, the
// controller runs in the decode-only "cloud" mode and every decoded PCM
// frame is broadcast to these listeners. STT capture preempts it — a live
@@ -150,11 +197,14 @@ export class FaceclawVoiceControlBridge {
// the bridge swallow it.
private verificationActive = false;
private verificationRejected = false;
// Continuous captures' audio goes to Downloads/<recordingName>.wav while it is
// set. The file outlives a capture, so a restarted one keeps appending to it,
// and it is created by the first audio, so a failed start leaves no file.
// Continuous captures' audio goes to Downloads/<recordingName>.mka while it is
// set: every source's chunks as they arrive, before any processing, written
// by the controller. The file outlives a capture, so a restarted one keeps
// adding to it, and it is created by the first audio, so a failed start
// leaves no file.
private recordingName = "";
private recorder: WavRecorder | null = null;
// The file is open in the controller.
private recordingOpen = false;
// The file could not be created: one attempt per recording, not one per packet.
private recordingFailure = false;
private readonly recordingListeners = new Set<() => void>();
@@ -251,16 +301,55 @@ export class FaceclawVoiceControlBridge {
}
/**
* Record continuous captures' audio to Downloads/<name>.wav, across restarts,
* End the continuous capture as an utterance: stop it and have the
* transcript of its last audio come as a final. For a capture whose audio
* ran out by itself (a replay).
*/
finishContinuousCapture(): void {
this.releaseCapture("continuous", true);
}
/** Progress of a capture that replays a recording (PushToTalkOptions.replay). */
onReplay(listener: (event: VoiceReplayEvent) => void): () => void {
this.replayListeners.add(listener);
return () => this.replayListeners.delete(listener);
}
/** Continue the running replay from `positionMs` into its recording. */
seekReplay(positionMs: number): void {
this.controller?.seekReplay(Math.max(0, Math.round(positionMs)));
}
/** Hold the running replay where it is, or let it go on. */
setReplayPaused(paused: boolean): void {
this.controller?.setReplayPaused(paused);
}
/** Whether a capture is running and still has audio coming (a replay stops being so at its end). */
isCaptureLive(): boolean {
return this.micIsLive();
}
/**
* Record continuous captures' audio to Downloads/<name>.mka, across restarts,
* until called with another name or "".
*/
recordTo(name: string): void {
if (name === this.recordingName) return;
this.recorder?.close();
this.recorder = null;
this.closeRecording();
this.setRecording(name, false);
}
private closeRecording(): void {
if (!this.recordingOpen) return;
this.recordingOpen = false;
try {
this.controller?.stopRecording();
} catch (error) {
console.warn(`Voice: closing the recording failed: ${error}`);
}
}
/** Whether continuous captures' audio is being saved (see recordTo). */
get recording(): boolean {
return this.recordingName !== "" && !this.recordingFailure;
@@ -286,18 +375,48 @@ export class FaceclawVoiceControlBridge {
for (const listener of Array.from(this.recordingListeners)) listener();
}
/** `pcm` is the controller's Java byte[], handed to the recorder as it came. */
private record(pcm: any): void {
if (!this.recording) return;
if (!this.recorder) {
this.recorder = WavRecorder.open(this.recordingName);
if (!this.recorder) {
this.setRecording(this.recordingName, true);
return;
}
console.log(`Voice: recording audio to ${this.recorder.path}`);
/**
* Audio arrived for a continuous capture: open the recording asked for, if
* it isn't open yet. The controller writes it from then on, as the audio
* arrives on its own thread.
*/
private ensureRecording(): void {
if (!this.recording || this.recordingOpen) return;
const path = newRecordingPath(this.recordingName);
let opened = false;
try {
opened = path !== null && Boolean(this.controller?.startRecording(path, JSON.stringify(this.describeCapture())));
} catch (error) {
console.warn(`Voice: could not create the recording: ${error}`);
}
this.recorder.append(pcm);
if (!opened) {
this.setRecording(this.recordingName, true);
return;
}
this.recordingOpen = true;
console.log(`Voice: recording audio to ${path}`);
}
/** Only captures a continuous holder has a part in are recorded: push-to-talk on its own is not. */
private syncRecordingEnabled(): void {
this.controller?.setRecordingEnabled(this.captureHolders.has("continuous"));
}
/** The running capture, as the JSON stored in a recording of it. */
private describeCapture(): Record<string, unknown> {
const options = this.streamOptions;
return {
recording: this.recordingName,
startedAt: new Date().toISOString(),
source: options?.usePhoneMic ? "phone" : "glasses",
micArray: Boolean(options?.micArray) && !options?.usePhoneMic,
transcription: { provider: options?.provider ?? "", language: options?.language ?? "" },
processing: {
noiseSuppression: Boolean(options?.noiseSuppression),
beamFilter: options?.beamFilter ?? null,
},
...options?.captureInfo,
};
}
/** Subscribe to decoded raw mic PCM (16 kHz mono S16LE). */
@@ -364,6 +483,8 @@ export class FaceclawVoiceControlBridge {
// preview-mode capture may have left on the shared controller.
this.controller?.setUsePhoneMic(false);
this.controller?.setEndpointing(false);
this.controller?.setMicArray(null);
this.controller?.setReplay(null, 0);
// Raw means raw: the Microphones session (and EvenHub apps) get the
// unprocessed stream and run their own beam/suppression processing.
this.controller?.setNoiseSuppression(false);
@@ -399,18 +520,33 @@ export class FaceclawVoiceControlBridge {
const micLive = this.micIsLive();
this.suspendedHolders.delete(holder);
this.captureHolders.add(holder);
if (micLive && this.streamProvider === transcriptionKey(options)) {
if (micLive && this.streamProvider === streamKey(options)) {
// Mic already running; the new holder just shares the existing stream
// (transcripts are already broadcast to its listeners).
this.syncRecordingEnabled();
return;
}
// Any leftover capture is dead, or transcribes with another provider than
// Any leftover capture is dead, or captures or transcribes otherwise than
// this holder needs; drop it before starting the new one.
if (this.started) this.teardownCapture();
this.streamProvider = transcriptionKey(options);
this.streamProvider = streamKey(options);
this.streamOptions = options;
this.ensureController();
this.syncRecordingEnabled();
// A recording under way carries on into this capture: note what changed.
if (this.recordingOpen) {
try {
this.controller?.noteRecordingEvent(JSON.stringify({ event: "capture", ...this.describeCapture() }));
} catch (error) {
console.warn(`Voice: recording event failed: ${error}`);
}
}
this.controller?.setCommunicator(options.communicator);
this.controller?.setUsePhoneMic(Boolean(options.usePhoneMic));
this.controller?.setMicArray(
options.micArray && !options.usePhoneMic && !options.replay ? toJavaBytes(options.micArray.configure) : null,
);
this.controller?.setReplay(options.replay?.path ?? null, Math.max(0, Math.round(options.replay?.startMs ?? 0)));
this.controller?.setEndpointing(Boolean(options.endpointing));
this.captureEndpointing = Boolean(options.endpointing);
this.controller?.setNoiseSuppression(Boolean(options.noiseSuppression));
@@ -435,7 +571,7 @@ export class FaceclawVoiceControlBridge {
this.speechPause.reset();
// Replaces whatever the last capture left behind ("Listening...", an
// error, the permission prompt) until the controller reports progress.
this.setStatus("Starting microphone...");
this.setStatus(options.replay ? "Opening the recording..." : "Starting microphone...");
// A previous push-to-talk commit may still be awaiting its final result.
this.cloudClient?.stop();
const cloudClient = this.createCloudClient(options);
@@ -480,6 +616,7 @@ export class FaceclawVoiceControlBridge {
if (commit) this.cloudClient?.finish();
return;
}
this.syncRecordingEnabled();
if (this.captureHolders.size > 0) {
// Another holder still wants the mic; keep it running.
return;
@@ -504,6 +641,7 @@ export class FaceclawVoiceControlBridge {
this.captureHolders.clear();
this.suspendedHolders.clear();
this.suspendedRaw = false;
this.syncRecordingEnabled();
this.teardownCapture();
this.setStatus("Voice control stopped.");
}
@@ -521,6 +659,7 @@ export class FaceclawVoiceControlBridge {
this.suspendedHolders.add(holder);
}
this.captureHolders.clear();
this.syncRecordingEnabled();
this.suspendedRaw = this.rawActive;
this.teardownCapture();
if (this.suspendedHolders.size > 0) {
@@ -578,6 +717,7 @@ export class FaceclawVoiceControlBridge {
private teardownCapture(): void {
this.rawActive = false;
this.streamProvider = null;
this.streamOptions = null;
if (global.isAndroid) {
this.controller?.stop();
}
@@ -611,7 +751,7 @@ export class FaceclawVoiceControlBridge {
const bytes = toUint8Array(pcm);
this.cloudClient?.acceptPcm(bytes);
// Push-to-talk on a capture of its own is not recorded.
if (this.captureHolders.has("continuous")) this.record(pcm);
if (this.captureHolders.has("continuous")) this.ensureRecording();
if (!this.cloudClient && this.captureHolders.has("continuous") && this.speechPause.accept(bytes)) {
for (const listener of this.speechPauseListeners) listener();
}
@@ -642,6 +782,10 @@ export class FaceclawVoiceControlBridge {
);
}
},
onReplay: (kind: string, positionMs: number, durationMs: number) => {
const event = { kind: String(kind) as VoiceReplayEvent["kind"], positionMs: Number(positionMs), durationMs: Number(durationMs) };
for (const listener of Array.from(this.replayListeners)) listener(event);
},
});
this.controller.setListener(this.listenerProxy);
}
@@ -678,6 +822,21 @@ export class FaceclawVoiceControlBridge {
}
}
/**
* What a capture reads and transcribes with. A running capture is shared only
* by holders asking for the same: the provider and language, the microphones
* (the mixed stream, or the temples' own under a given configuration), or the
* recording it replays.
*/
function streamKey(options: PushToTalkOptions): string {
const source = options.replay
? `replay:${options.replay.path}`
: options.micArray && !options.usePhoneMic
? `array:${Array.from(options.micArray.configure).join(",")}`
: "mixed";
return `${transcriptionKey(options)}|${source}`;
}
function toJavaFloats(values: Float32Array): any {
const javaFloats = Array.create("float", values.length);
for (let i = 0; i < values.length; i++) {
@@ -687,3 +846,136 @@ function toJavaFloats(values: Float32Array): any {
}
export const voiceControlBridge = new FaceclawVoiceControlBridge();
export type VoiceReplayState = "opening" | "playing" | "paused" | "ended" | "failed";
/**
* A recording played back as a capture of its own: transcribed by the same
* pipeline as the microphone, with the same settings, on a bridge and native
* controller separate from the microphone's. Nothing here touches the mic,
* so voice input and a live Transcribe window carry on beside a replay.
*/
export class VoiceReplay {
private readonly bridge = new FaceclawVoiceControlBridge();
private readonly listeners = new Set<(jumpedToMs?: number) => void>();
private readonly offReplay: () => void;
private position = 0;
private duration = 0;
private current: VoiceReplayState = "opening";
private closed = false;
/**
* `options` gives the capture options (provider, keys, processing) each
* time the replay starts, so a restart picks up changed settings.
*/
constructor(readonly path: string, private readonly options: () => PushToTalkOptions) {
this.offReplay = this.bridge.onReplay((event) => this.handle(event));
}
/** The replay's status, transcript and level events. */
get events(): VoiceEventSource {
return this.bridge;
}
/** Milliseconds into the recording. */
get positionMs(): number {
return this.position;
}
/** The recording's length in ms; 0 until it has been opened. */
get durationMs(): number {
return this.duration;
}
get state(): VoiceReplayState {
return this.current;
}
/**
* The position, duration or state changed. `jumpedToMs` is given when
* playback moved there other than by playing on: a jump, or a start
* part-way in. It comes after the transcript of what played before.
*/
onChange(listener: (jumpedToMs?: number) => void): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
/** Play from `positionMs` into the recording. */
start(positionMs = 0): void {
if (this.closed) return;
this.position = Math.max(0, positionMs);
this.set("opening");
this.bridge.startContinuousCapture({
...this.options(),
communicator: null,
usePhoneMic: false,
micArray: null,
replay: { path: this.path, startMs: this.position },
});
}
/** Continue from `positionMs`: a jump while playing, a fresh start once the replay has ended. */
jumpTo(positionMs: number): void {
if (this.closed) return;
const target = Math.max(0, this.duration > 0 ? Math.min(positionMs, this.duration) : positionMs);
if ((this.current === "playing" || this.current === "paused") && this.bridge.isCaptureLive()) {
this.bridge.seekReplay(target);
this.position = target;
this.notify();
return;
}
this.start(target);
}
setPaused(paused: boolean): void {
if (this.closed || (this.current !== "playing" && this.current !== "paused")) return;
this.bridge.setReplayPaused(paused);
this.set(paused ? "paused" : "playing");
}
/** Stop for good and release the capture. */
close(): void {
if (this.closed) return;
this.closed = true;
this.offReplay();
this.listeners.clear();
this.bridge.stop();
}
private handle(event: VoiceReplayEvent): void {
this.duration = event.durationMs;
switch (event.kind) {
case "start":
this.position = event.positionMs;
this.current = "playing";
this.notify(event.positionMs > 0 ? event.positionMs : undefined);
return;
case "seek":
this.position = event.positionMs;
this.notify(event.positionMs);
return;
case "end":
this.position = event.durationMs;
// Its last audio is still to be transcribed (a cloud provider's final).
this.bridge.finishContinuousCapture();
this.set("ended");
return;
case "error":
this.set("failed");
return;
default:
this.position = event.positionMs;
this.notify();
}
}
private set(state: VoiceReplayState): void {
this.current = state;
this.notify();
}
private notify(jumpedToMs?: number): void {
for (const listener of Array.from(this.listeners)) listener(jumpedToMs);
}
}
-22
View File
@@ -1,22 +0,0 @@
/** The 44-byte header of a 16 kHz mono PCM16 WAV file holding `dataBytes` of samples. */
export function wavHeader(dataBytes: number): Uint8Array {
const header = new Uint8Array(44);
const view = new DataView(header.buffer);
const ascii = (offset: number, text: string) => {
for (let i = 0; i < text.length; i++) header[offset + i] = text.charCodeAt(i);
};
ascii(0, "RIFF");
view.setUint32(4, 36 + dataBytes, true);
ascii(8, "WAVE");
ascii(12, "fmt ");
view.setUint32(16, 16, true);
view.setUint16(20, 1, true); // PCM
view.setUint16(22, 1, true); // mono
view.setUint32(24, 16000, true);
view.setUint32(28, 32000, true); // byte rate
view.setUint16(32, 2, true); // block align
view.setUint16(34, 16, true); // bits per sample
ascii(36, "data");
view.setUint32(40, dataBytes, true);
return header;
}
-75
View File
@@ -1,75 +0,0 @@
import { knownFolders, path as paths } from '@nativescript/core'
import { wavHeader } from './wav-header'
// About a second of 16 kHz mono PCM16: written in batches, not per 50 ms packet.
const FLUSH_BYTES = 32000
/**
* Appends 16 kHz mono PCM16 to a WAV file in Documents/Downloads while it is
* captured. The header's sizes are rewritten on every flush, so a crash leaves a
* playable file of everything up to the last second.
*/
export class WavRecorder {
private pending: Uint8Array[] = []
private pendingBytes = 0
private dataBytes = 0
private constructor(private handle: NSFileHandle | null, readonly path: string) {}
/** A recorder for Downloads/<name>.wav (a -2, -3... suffix if taken), or null. */
static open(name: string): WavRecorder | null {
const fm = NSFileManager.defaultManager
const dir = paths.join(knownFolders.documents().path, 'Downloads')
try {
fm.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(dir, true, null)
let path = paths.join(dir, `${name}.wav`)
for (let n = 2; fm.fileExistsAtPath(path); n++) path = paths.join(dir, `${name}-${n}.wav`)
if (!fm.createFileAtPathContentsAttributes(path, toData(wavHeader(0)), null)) return null
const handle = NSFileHandle.fileHandleForWritingAtPath(path)
if (!handle || !handle.seekToEndReturningOffsetError(null)) return null
return new WavRecorder(handle, path)
} catch {
return null
}
}
append(pcm: Uint8Array): void {
if (!this.handle || !pcm.length) return
this.pending.push(pcm.slice())
this.pendingBytes += pcm.length
if (this.pendingBytes >= FLUSH_BYTES) this.flush()
}
close(): void {
this.flush()
try { this.handle?.closeAndReturnError() } catch { /* already closed */ }
this.handle = null
}
private flush(): void {
const handle = this.handle
if (!handle || !this.pendingBytes) return
const chunk = new Uint8Array(this.pendingBytes)
let offset = 0
for (const part of this.pending) { chunk.set(part, offset); offset += part.length }
this.pending = []
this.pendingBytes = 0
try {
// NativeScript throws a failed call's NSError (storage full, file removed).
handle.writeDataError(toData(chunk))
handle.seekToOffsetError(0)
handle.writeDataError(toData(wavHeader(this.dataBytes + chunk.length)))
handle.seekToEndReturningOffsetError(null)
this.dataBytes += chunk.length
return
} catch {
// Stop recording rather than retry.
}
try { handle.closeAndReturnError() } catch { /* ignore */ }
this.handle = null
}
}
function toData(bytes: Uint8Array): NSData {
return NSData.dataWithBytesLength(interop.handleof(bytes.buffer), bytes.byteLength)
}
-42
View File
@@ -1,42 +0,0 @@
declare const android: any;
declare const java: any;
declare const com: any;
const SAMPLE_RATE = 16000;
/**
* Appends 16 kHz mono PCM16 to a WAV file in the public Downloads directory
* while it is captured (Android; wav-recorder.ios.ts is the iOS one). The
* native recorder keeps the header's sizes current, so a crash leaves a
* playable file of everything up to the last second.
*/
export class WavRecorder {
private constructor(private recorder: any, readonly path: string) {}
/** A recorder for Downloads/<name>.wav (a -2, -3... suffix if taken), or null. */
static open(name: string): WavRecorder | null {
try {
const downloads = android.os.Environment.getExternalStoragePublicDirectory(
android.os.Environment.DIRECTORY_DOWNLOADS,
);
downloads.mkdirs();
let file = new java.io.File(downloads, `${name}.wav`);
for (let n = 2; file.exists(); n++) file = new java.io.File(downloads, `${name}-${n}.wav`);
const path = String(file.getAbsolutePath());
return new WavRecorder(new com.faceclaw.app.FaceclawWavRecorder(path, SAMPLE_RATE, 1), path);
} catch (error) {
console.warn(`WavRecorder: could not create ${name}.wav in Downloads: ${error}`);
return null;
}
}
/** `pcm` is the Java byte[] the voice controller delivered, passed back as it came. */
append(pcm: any): void {
this.recorder?.append(pcm);
}
close(): void {
this.recorder?.finish();
this.recorder = null;
}
}
+19 -4
View File
@@ -947,7 +947,7 @@ export const useMicControlSetting = new ConfigSettingBoolean({
storageKey: "developer.useMicControl",
defaultValue: true,
description:
"Use the custom firmware's per-temple mic-control channel for the Microphones app's array capture. When off, use the standard single mixed stream.",
"Use the custom firmware's per-temple mic-control channel for capturing the microphones separately (the Microphones app's array capture, and Transcribe's Microphones option). When off, use the standard single mixed stream.",
});
export const showBleBandwidthSetting = new ConfigSettingBoolean({
@@ -1054,7 +1054,9 @@ export const saveRecordingSetting = new ConfigSettingBoolean({
label: "Save Recording",
storageKey: "voice.saveRecording",
defaultValue: false,
description: "Record the audio of Transcribe and Translate sessions as WAV files in Downloads (about 2 MB per minute), named after the app and the session's start time. Recordings are kept until you delete them.",
description: global.isIOS
? "Record the audio of Transcribe and Translate sessions as Matroska audio (.mka) files in Downloads (about 2 MB per minute), named after the app and the session's start time. Recordings are kept until you delete them."
: "Record the audio of Transcribe and Translate sessions as Matroska audio (.mka) files in Downloads: about 2 MB per minute, or 10 MB with all four microphones. Named after the app and the session's start time, and kept until you delete them. Transcribe can replay one: pick it in the Files app.",
});
export const assistantSkipConfirmationSetting = new ConfigSettingBoolean({
@@ -1722,9 +1724,18 @@ type SettingsMenuOptions<T> = {
label?: string
}
type EnumSettingMenuOptions<T> = SettingsMenuOptions<T> & {
/**
* A live line under the picker's values, such as a sensor reading to pick
* by. open() runs as the picker opens, with a function that repaints it,
* and returns what to run when the picker closes.
*/
pickerFooter?: { text: () => string; open: (repaint: () => void) => () => void }
}
export function enumSettingMenuItem<TValue extends string, TId extends string = string>(
setting: ConfigSettingEnum<TValue, TId>,
opts?: SettingsMenuOptions<TValue>
opts?: EnumSettingMenuOptions<TValue>
): MenuItem {
const label = opts?.label ?? setting.label;
return {
@@ -1752,7 +1763,11 @@ export function enumSettingMenuItem<TValue extends string, TId extends string =
);
},
}));
openModalMenu(ctx, label, items, Math.max(0, setting.values.indexOf(current)));
const footer = opts?.pickerFooter;
openModalMenu(ctx, label, items, Math.max(0, setting.values.indexOf(current)), {
footer: footer?.text,
onClosed: footer?.open(() => ctx.actions.requestRender()),
});
},
render: ({ image, x, y, width }) => {
drawRightValueMenuItem(image, getDefaultSmallFont(), x, y, width, label, setting.displayValue(setting.get()));
+10
View File
@@ -103,6 +103,8 @@ import { openSettingsSubMenu, SettingsPanelLayer, type SettingsSection } from ".
import { uiFontPickerMenuItem } from "../font-picker";
import { NotificationFilterLayer } from "../notification-filter";
import { compatibleModelDiscoveryMenuItem } from "../openai-compatible-model-picker";
import { keyboardSettingsMenuItem } from "../keyboard-settings";
import { keybindingsMenuItem } from "../keybinding-settings";
import { isVeniceApiBaseUrl } from "../../native/openai-chat";
/** The Settings section the Notifications app's "Settings" menu item opens. */
@@ -242,6 +244,14 @@ function settingsSections(): SettingsSection[] {
],
renderDetail: renderWatchStatus,
},
// A Bluetooth keyboard paired with the glasses themselves (the G2's
// custom firmware hosts it; app/g2/keyboard/). Hidden rather than left
// out: the Settings window can be open across a change of glasses.
{
label: "Keyboard",
items: [keyboardSettingsMenuItem(), keybindingsMenuItem()],
hidden: () => glassesTypeSetting.get() !== "g2",
},
{
label: "Developer",
items: [
+30 -2
View File
@@ -28,6 +28,13 @@ export type SettingsSection = {
height: number;
ctx: LayerContext;
}) => number | void;
/**
* Leave the section out of the list while this returns true. Re-read on
* every paint and input, for a section that only applies with some other
* setting (the paired glasses' type): the Settings window outlives changes
* to those.
*/
hidden?: () => boolean;
};
const LEFT_W = 150;
@@ -66,7 +73,7 @@ export class SettingsPanelLayer implements Layer {
constructor(private readonly sections: SettingsSection[]) {
this.leftMenu = new Menu<SettingsSection>({
items: sections,
items: sections.filter((section) => !section.hidden?.()),
wrap: true,
rowGap: ROW_GAP,
highlight: { radius: 6 },
@@ -108,9 +115,28 @@ export class SettingsPanelLayer implements Layer {
return this.leftMenu.selectedItem ?? this.sections[0]!;
}
/**
* Bring the left column in line with which sections are hidden now. The
* highlight stays on its section; if that one just went away it moves to
* the list's start, with focus back in the left column.
*/
private syncSections(): void {
const visible = this.sections.filter((section) => !section.hidden?.());
const shown = this.leftMenu.items;
if (visible.length === shown.length && visible.every((section, index) => section === shown[index])) return;
const selected = this.leftMenu.selectedItem;
const index = selected ? visible.indexOf(selected) : -1;
this.leftMenu.setItems(visible, Math.max(0, index));
if (index < 0) {
this.focus = "left";
this.resetRight();
}
}
/** Select a left-column section by label (deep link, e.g. from an app's menu). */
focusSection(label: string): void {
const index = this.sections.findIndex((section) => section.label === label);
this.syncSections();
const index = this.leftMenu.items.findIndex((section) => section.label === label);
if (index < 0) return;
this.leftMenu.select(index);
this.focus = "left";
@@ -123,6 +149,7 @@ export class SettingsPanelLayer implements Layer {
const { width, height, padding } = viewport;
const image = new GrayImage(width, height, 0);
const appFocused = ctx.stack.isFocused();
this.syncSections();
const section = this.section();
const rightItems = section.items;
this.rightMenu.setItems(rightItems);
@@ -228,6 +255,7 @@ export class SettingsPanelLayer implements Layer {
}
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
this.syncSections();
const scroll = scrollEventFor(event);
if (this.focus === "left") {
if (scroll) {
+147
View File
@@ -0,0 +1,147 @@
import { getDefaultSmallFont } from "../graphics/ui-fonts";
import {
DEFAULT_KEYS_HELP,
KEY_ACTIONS,
chordId,
describeChord,
keyActionLabel,
type KeyChord,
} from "../g2/keyboard/bindings";
import { keyboardService } from "../g2/keyboard/service";
import { TextViewerLayer } from "../apps/files/text-viewer";
import type { LayerContext } from "./layers";
import { drawRightValueMenuItem, MenuLayer, openModalMenu, submenuItem, TextPageLayer, type MenuItem } from "./menu";
/**
* Settings > Keyboard > Keybindings: the custom keybindings (a key, with
* any modifiers held, to a gesture), which come before the built-in
* meanings in app/g2/keyboard/bindings.ts. Adding one asks for the key on
* the keyboard itself, so it works for a remote whose buttons send who
* knows what.
*/
/** Waits for the key to bind. Double tap backs out, as from any page. */
class KeyCaptureLayer extends TextPageLayer {
private cancel: (() => void) | null = null;
constructor(private readonly onChord: (chord: KeyChord, ctx: LayerContext) => void) {
super(
"Add keybinding",
"Press the key to bind, on the keyboard. Hold Shift, Ctrl or Alt with it to bind the combination.",
);
}
open(ctx: LayerContext): void {
ctx.stack.push(this);
this.cancel = keyboardService.captureNextKey((chord) => {
this.cancel = null;
ctx.stack.popThrough(this);
this.onChord(chord, ctx);
ctx.actions.requestRender();
});
}
onRemoved(): void {
this.cancel?.();
this.cancel = null;
}
}
class KeybindingsLayer extends MenuLayer {
constructor(viewport: { width: number; height: number }) {
super("Keybindings", [], {
x: "center",
y: 8,
width: Math.min(320, viewport.width - 40),
minHeight: Math.min(160, viewport.height - 40),
maxHeight: Math.min(240, viewport.height - 40),
depth: 4,
});
}
open(ctx: LayerContext): void {
this.updateRows();
ctx.stack.push(this);
}
/** Rebuild the rows, with the highlight on `selectId`'s keybinding when given. */
private updateRows(selectId?: string): void {
const bindings = keyboardService.keyBindings();
const rows: MenuItem[] = bindings.map((binding) => {
const label = describeChord(binding.chord);
return {
label,
onSelect: (ctx: LayerContext) => this.pickAction(ctx, binding.chord),
render: ({ image, x, y, width }) => {
drawRightValueMenuItem(image, getDefaultSmallFont(), x, y, width, label, keyActionLabel(binding.action));
},
};
});
rows.push(
{ label: "Add keybinding", onSelect: (ctx) => this.add(ctx) },
// Scrolls, where a page would cut the text off in a short window.
submenuItem("Default keys", (ctx) => ctx.stack.push(new TextViewerLayer(DEFAULT_KEYS_HELP, "Default keys"))),
);
const selected = selectId === undefined ? -1 : bindings.findIndex((binding) => chordId(binding.chord) === selectId);
if (selected >= 0) this.setItems(rows, selected);
else this.setItems(rows);
}
private add(ctx: LayerContext): void {
if (!keyboardService.bridge.isConnected()) {
ctx.stack.push(new TextPageLayer(
"Add keybinding",
"No keyboard is connected. Pair or reconnect one under Bluetooth keyboard, then come back: the key to bind is read from the keyboard.",
));
return;
}
new KeyCaptureLayer((chord, captureCtx) => this.pickAction(captureCtx, chord)).open(ctx);
}
/** Choose what `chord` does: for a new keybinding, or to change or remove one. */
private pickAction(ctx: LayerContext, chord: KeyChord): void {
const id = chordId(chord);
const current = keyboardService.keyBindings().find((binding) => chordId(binding.chord) === id)?.action;
const done = (inner: LayerContext): void => {
inner.stack.pop();
this.updateRows(id);
inner.actions.requestRender();
};
const rows: MenuItem[] = KEY_ACTIONS.map((entry) => ({
label: entry.action === current ? `${entry.label} *` : entry.label,
onSelect: (inner: LayerContext) => {
if (!keyboardService.setKeyBinding(chord, entry.action)) {
inner.stack.pop();
inner.stack.push(new TextPageLayer("Keybindings", "There is no room for another keybinding. Remove one first."));
return;
}
done(inner);
},
}));
if (current !== undefined) {
rows.push({
label: "Remove keybinding",
onSelect: (inner) => {
keyboardService.removeKeyBinding(chord);
done(inner);
},
});
}
const selected = Math.max(0, KEY_ACTIONS.findIndex((entry) => entry.action === current));
openModalMenu(ctx, describeChord(chord), rows, selected);
}
}
/** The Settings row that opens the keybindings menu. */
export function keybindingsMenuItem(): MenuItem {
return {
label: "Keybindings",
description:
"Choose what keys do: arrows, Enter and Esc navigate by default, and any key (or a remote's button) can be bound to select, back, a swipe, a scroll or a menu.",
onSelect: (ctx) => new KeybindingsLayer(ctx.stack.getBaseSize()).open(ctx),
render: ({ image, x, y, width }) => {
const count = keyboardService.keyBindings().length;
drawRightValueMenuItem(image, getDefaultSmallFont(), x, y, width, "Keybindings", count ? `${count} custom` : "Default");
},
};
}
+232
View File
@@ -0,0 +1,232 @@
import { getDefaultSmallFont } from "../graphics/ui-fonts";
import type { KeyboardBridgeSnapshot } from "../g2/keyboard/bridge";
import type { KeyboardAdvert } from "../g2/keyboard/protocol";
import { keyboardService } from "../g2/keyboard/service";
import { ConfigSettingString, textSettingMenuItem } from "./dashboard-settings";
import type { LayerContext } from "./layers";
import { drawRightValueMenuItem, MenuLayer, type MenuItem } from "./menu";
/**
* Settings > Keyboard: pairing a Bluetooth keyboard with the glasses (the
* CFW keyboard bridge, app/g2/keyboard/). The keyboard pairs with the
* glasses, not the phone, so all of it happens here, on the glasses: scan,
* pick, and for a keyboard that wants one, the passkey to type on it.
*/
/** The code a keyboard with a display shows, typed on the phone. Scratch, not a preference. */
const pairingCodeSetting = new ConfigSettingString({
id: "keyboardPairingCode",
storageKey: "keyboard.pairingCode",
label: "Code on keyboard",
defaultValue: "",
normalize: (value) => (value ?? "").replace(/\D/g, "").slice(0, 6),
});
const sixDigits = (value: number): string => {
const text = String(value).padStart(6, "0");
return `${text.slice(0, 3)} ${text.slice(3)}`;
};
function advertLabel(advert: KeyboardAdvert): string {
const name = advert.name.trim() || advert.address;
return name.length > 30 ? `${name.slice(0, 27)}...` : name;
}
/** One line saying where the keyboard stands, for the Settings row and the menu's first row. */
export function keyboardStatusText(snapshot: KeyboardBridgeSnapshot): string {
const name = snapshot.activeName || snapshot.saved?.name || "keyboard";
switch (snapshot.state) {
case "unavailable":
return snapshot.saved ? "Glasses not connected" : "Not set up";
case "scanning":
return "Scanning...";
case "connecting":
return `Connecting to ${name}...`;
case "pairing":
return `Pairing with ${name}...`;
case "configuring":
return `Setting up ${name}...`;
case "connected":
return `Connected: ${name}`;
case "error":
return snapshot.error || "Failed";
default:
if (snapshot.waiting) return `Waiting for ${name}`;
return snapshot.saved ? `${name} (disconnected)` : "Not set up";
}
}
/** The short form for the right edge of the Settings row. */
function keyboardStatusBrief(snapshot: KeyboardBridgeSnapshot): string {
switch (snapshot.state) {
case "connected":
return "Connected";
case "scanning":
return "Scanning";
case "connecting":
case "pairing":
case "configuring":
return "Connecting";
case "error":
return "Failed";
case "unavailable":
return snapshot.saved ? "Offline" : "Off";
default:
return snapshot.waiting ? "Waiting" : snapshot.saved ? "Disconnected" : "Off";
}
}
const info = (label: string): MenuItem => ({ label, disabled: true, onSelect: () => {} });
class KeyboardSettingsLayer extends MenuLayer {
private unsubscribe: (() => void) | null = null;
private showOthers = false;
/** What kind of rows are showing; a change moves the highlight to the first row that does something. */
private shape = "";
constructor(viewport: { width: number; height: number }) {
super("Bluetooth keyboard", [], {
x: "center",
y: 8,
width: Math.min(320, viewport.width - 40),
minHeight: Math.min(160, viewport.height - 40),
maxHeight: Math.min(240, viewport.height - 40),
depth: 4,
});
}
open(ctx: LayerContext): void {
ctx.stack.push(this);
this.updateRows();
this.unsubscribe = keyboardService.subscribe(() => {
this.updateRows();
ctx.actions.requestRender();
});
}
onRemoved(): void {
this.unsubscribe?.();
this.unsubscribe = null;
}
/** Run a bridge command; its failure shows up in the snapshot, which repaints the rows. */
private run(action: () => Promise<unknown>): void {
void action().catch(() => {});
}
private updateRows(): void {
const snapshot = keyboardService.snapshot();
const bridge = keyboardService.bridge;
const rows: MenuItem[] = [info(keyboardStatusText(snapshot))];
let shape: string = snapshot.state;
const scanRow = (label: string): MenuItem => ({
label,
disabled: snapshot.busy,
onSelect: () => {
this.showOthers = false;
this.run(() => bridge.scan());
},
});
if (snapshot.state === "unavailable") {
rows.push(info("Connect G2 glasses to pair one."));
if (snapshot.saved) rows.push({ label: `Forget ${snapshot.saved.name || "keyboard"}`, onSelect: () => this.run(() => bridge.forget()) });
} else if (snapshot.pairing) {
const pairing = snapshot.pairing;
shape = `pairing:${pairing.kind}`;
if (pairing.kind === "display") {
rows.push(info(`Type ${sixDigits(pairing.pin)} on the keyboard,`), info("then press Enter."));
} else if (pairing.kind === "compare") {
rows.push(
info(`Does the keyboard show ${sixDigits(pairing.value)}?`),
{ label: "Yes, pair", onSelect: () => this.run(() => bridge.answerCompare(true)) },
{ label: "No", onSelect: () => this.run(() => bridge.answerCompare(false)) },
);
} else {
rows.push(
info("Enter the code the keyboard shows."),
textSettingMenuItem(pairingCodeSetting),
{
label: "Pair with this code",
disabled: () => pairingCodeSetting.get().length !== 6,
onSelect: () => {
const code = pairingCodeSetting.get();
pairingCodeSetting.set("");
this.run(() => bridge.answerPasskey(parseInt(code, 10)));
},
},
);
}
rows.push({ label: "Cancel pairing", onSelect: () => this.run(() => bridge.disconnect()) });
} else if (snapshot.state === "connecting" || snapshot.state === "pairing" || snapshot.state === "configuring") {
rows.push({ label: "Cancel", onSelect: () => this.run(() => bridge.disconnect()) });
} else if (snapshot.state === "scanning" || (snapshot.scanResults.length > 0 && snapshot.state !== "connected")) {
shape = "results";
const hid = snapshot.scanResults.filter((advert) => advert.hid);
const others = snapshot.scanResults.filter((advert) => !advert.hid);
const pick = (advert: KeyboardAdvert): MenuItem => ({
label: advertLabel(advert),
disabled: snapshot.busy,
onSelect: () => {
this.run(() => bridge.connect({ address: advert.address, addressType: advert.addressType, name: advert.name.trim() || advert.address }));
},
});
rows.push(...hid.map(pick));
if (!hid.length && snapshot.state !== "scanning") rows.push(info("No keyboards found."), info("Put it in pairing mode."));
if (others.length && this.showOthers) rows.push(...others.map(pick));
else if (others.length) {
rows.push({
label: `Show ${others.length} other device${others.length === 1 ? "" : "s"}`,
onSelect: (ctx) => {
this.showOthers = true;
this.updateRows();
ctx.actions.requestRender();
},
});
}
if (snapshot.state !== "scanning") rows.push(scanRow("Scan again"));
if (snapshot.saved && snapshot.state !== "scanning") {
rows.push({ label: `Reconnect ${snapshot.saved.name || "keyboard"}`, disabled: snapshot.busy, onSelect: () => this.run(() => bridge.reconnect()) });
}
} else if (snapshot.state === "connected") {
rows.push(
{ label: "Disconnect", onSelect: () => this.run(() => bridge.disconnect()) },
{ label: "Forget this keyboard", onSelect: () => this.run(() => bridge.forget()) },
scanRow("Pair a different keyboard"),
);
} else if (snapshot.saved) {
shape = snapshot.waiting ? "waiting" : "saved";
rows.push({ label: "Reconnect now", disabled: snapshot.busy, onSelect: () => this.run(() => bridge.reconnect()) });
if (snapshot.waiting) rows.push({ label: "Stop reconnecting", onSelect: () => this.run(() => bridge.disconnect()) });
rows.push(
{ label: "Forget this keyboard", onSelect: () => this.run(() => bridge.forget()) },
scanRow("Pair a different keyboard"),
);
} else {
shape = "empty";
rows.push(info("Put the keyboard in pairing mode,"), info("then scan."), scanRow("Scan for keyboards"));
}
const firstAction = rows.findIndex((row) => row.disabled !== true);
if (shape !== this.shape) {
this.shape = shape;
this.setItems(rows, Math.max(0, firstAction));
} else {
this.setItems(rows);
}
}
}
/** The Settings row that opens the keyboard menu. */
export function keyboardSettingsMenuItem(): MenuItem {
return {
label: "Bluetooth keyboard",
description:
"Pair a Bluetooth keyboard with the glasses. It types into Terminal sessions, and its arrow keys, Enter and Escape work everywhere as scroll, select and back.",
onSelect: (ctx) => new KeyboardSettingsLayer(ctx.stack.getBaseSize()).open(ctx),
render: ({ image, x, y, width }) => {
drawRightValueMenuItem(image, getDefaultSmallFont(), x, y, width, "Bluetooth keyboard", keyboardStatusBrief(keyboardService.snapshot()));
},
};
}
+19 -1
View File
@@ -3,6 +3,7 @@ import { screenHeight, screenWidth } from "../graphics/screen-size";
import { dimPlanes, type Plane } from "../graphics/plane";
import { spanCurrent } from "../native/frame-timings";
import { type ConfigSettingBoolean, type ConfigSettingString, type VoiceProvider } from "./dashboard-settings";
import { type VoiceReplay } from "../native/voice-control";
import { directionalFallback, isDirectionalInput, type InputEvent } from "./gestures";
import { toViewport, type Viewport, type ViewportSize } from "./viewport";
@@ -13,8 +14,17 @@ export type TextSettingsEditToggle = {
/** A continuous-capture client's needs (see LayerActions.startContinuousVoiceCapture). */
export type ContinuousCaptureOptions = {
/** Names a WAV of the captured audio in Downloads, written while Save Recording is on. */
/** Names a recording (.mka) of the captured audio in Downloads, written while Save Recording is on. */
recordAs?: string;
/**
* How many of the glasses' microphones to capture: 1 is their own mixed
* stream; 2 (one per temple) and 4 (both of each temple) stream the
* microphones separately through the custom firmware, for recording and
* array processing. While any client asks for more than one, every capture
* uses the most asked for. Glasses without the microphone channel, and the
* phone's microphone, give 1 whatever is asked.
*/
mics?: MicCount;
/**
* Transcribe with this provider, expecting this spoken language (ISO 639-1,
* or "" for the provider to detect it), instead of the Transcription
@@ -26,6 +36,8 @@ export type ContinuousCaptureOptions = {
export type TranscriptionChoice = { provider: VoiceProvider; language: string };
export type MicCount = 1 | 2 | 4;
export type LayerActions = {
/** Ask for a dashboard repaint+transmit, e.g. when async data arrives. */
requestRender: () => void;
@@ -55,6 +67,12 @@ export type LayerActions = {
*/
startContinuousVoiceCapture: (client: string, options?: ContinuousCaptureOptions) => Promise<void> | void;
stopContinuousVoiceCapture: (client: string) => Promise<void> | void;
/**
* Open a recording (.mka) for playing back through transcription in place
* of the microphone; the caller starts and closes it. Absent, or null,
* where recordings can't be replayed.
*/
openVoiceReplay?: (path: string) => VoiceReplay | null;
/** Play a CFW tone-sequencer payload (see sound-effects.ts). */
playBuzzerSequence: (payload: Uint8Array) => Promise<void> | void;
};
+4 -3
View File
@@ -1,6 +1,6 @@
import { GrayImage, imageFromAsciiArt, type UiFont } from "../graphics/image";
import { truncateText } from "../graphics/textwrap";
import { voiceControlBridge } from "../native/voice-control";
import { voiceControlBridge, type VoiceEventSource } from "../native/voice-control";
import { lineStep } from "./metrics";
import type { Edges } from "./viewport";
@@ -68,8 +68,9 @@ export class MicLevelMeter {
private timer: ReturnType<typeof setInterval> | null = null;
private unsubscribe: (() => void) | null = null;
start(requestRender: () => void, isVisible: () => boolean): void {
this.unsubscribe = voiceControlBridge.onMicLevel((level) => {
/** `source` is the capture whose level to show: the microphone's unless given. */
start(requestRender: () => void, isVisible: () => boolean, source: VoiceEventSource = voiceControlBridge): void {
this.unsubscribe = source.onMicLevel((level) => {
this.peak = Math.max(this.peak, level);
});
this.timer = setInterval(() => {
+33 -6
View File
@@ -57,7 +57,7 @@ export type MenuLayout = {
* Dim hint line pinned to the bottom edge inside the box, below the items
* (gesture help such as "●— system menu"). Takes a line off the item area.
*/
footer?: string;
footer?: MenuFooter;
/** Brightness factor for everything beneath the menu (see Layer.dimUnderneath). Default: none. */
dimUnderneath?: number;
/**
@@ -83,9 +83,16 @@ export type MenuPageLayout = {
/** Width of the rows. Default (and at most): the window's, inside its side padding. */
width?: number;
/** Dim hint line pinned above the window's bottom padding, below the rows. */
footer?: string;
footer?: MenuFooter;
};
/** A menu's footer line: fixed text, or read on every paint (a live value). */
export type MenuFooter = string | (() => string);
function footerText(footer: MenuFooter): string {
return typeof footer === "function" ? footer() : footer;
}
export type MenuItemRenderArgs = {
image: GrayImage;
x: number;
@@ -360,7 +367,7 @@ export class MenuLayer implements Layer {
image.drawText(font, x + 12, y + 8, this.title, 220);
}
if (layout.footer) {
image.drawText(font, x + 22, y + height - MENU_BODY_PADDING - font.lineHeight, layout.footer, 110);
image.drawText(font, x + 22, y + height - MENU_BODY_PADDING - font.lineHeight, footerText(layout.footer), 110);
}
const bodyY = y + chromeTop;
@@ -397,7 +404,7 @@ export class MenuLayer implements Layer {
let fixedBottom = height - padding.bottom;
if (layout.footer) {
const footerY = height - padding.bottom - font.lineHeight;
image.drawText(font, x + MENU_ROW_TEXT_INSET, footerY, layout.footer, 110);
image.drawText(font, x + MENU_ROW_TEXT_INSET, footerY, footerText(layout.footer), 110);
bottom = fixedBottom = footerY - MENU_FOOTER_GAP;
}
if (bottom <= top) return image;
@@ -431,17 +438,26 @@ export class MenuLayer implements Layer {
}
}
export type ModalMenuOptions = {
/** A dim line under the items (see MenuLayout.footer). */
footer?: MenuFooter;
/** Runs when the menu leaves the stack, however it closes. */
onClosed?: () => void;
};
/** Open a centered, bordered menu over the current layer. */
export function openModalMenu(
ctx: LayerContext,
title: string,
items: MenuItem[],
initialSelectedIndex = 0,
options: ModalMenuOptions = {},
): void {
const { width, height } = ctx.stack.getBaseSize();
const font = getDefaultSmallFont();
const menuWidth = Math.min(320, width - 40);
const naturalHeight = menuTitleHeight(font) + 2 * MENU_BODY_PADDING + items.length * listRowHeight(font);
const footerHeight = options.footer ? MENU_FOOTER_GAP + lineStep(font) : 0;
const naturalHeight = menuTitleHeight(font) + 2 * MENU_BODY_PADDING + items.length * listRowHeight(font) + footerHeight;
// 20px clear above and below, or 8 in a short window (the RayNeo iO's),
// where those rows are worth more than the margin.
const marginY = height < SHORT_WINDOW_HEIGHT ? 8 : 20;
@@ -454,8 +470,19 @@ export function openModalMenu(
maxHeight: menuHeight,
// Floats nearer than the content it opens over, like the window and system menus.
depth: 4,
footer: options.footer,
};
ctx.stack.push(new MenuLayer(title, items, layout).selectItem(initialSelectedIndex));
ctx.stack.push(new ModalMenuLayer(title, items, layout, options.onClosed).selectItem(initialSelectedIndex));
}
class ModalMenuLayer extends MenuLayer {
constructor(title: string, items: MenuItem[], layout: MenuLayout, private readonly onClosed?: () => void) {
super(title, items, layout);
}
onRemoved(): void {
this.onClosed?.();
}
}
export function isMenuItemDisabled(item: MenuItem): boolean {
+3
View File
@@ -48,6 +48,8 @@ export type InProcessWindowOptions = {
setScreenOn?: ShellWindow["setScreenOn"];
/** See ShellWindow.keepsScreenOn. */
keepsScreenOn?: ShellWindow["keepsScreenOn"];
/** See ShellWindow.restoresApp. */
restoresApp?: boolean;
/** The window came to or left the foreground (after its surface visibility follows). */
onForegroundChanged?: (foreground: boolean) => void;
/** Shared actions; requestRender is rebound to this window's render. */
@@ -177,6 +179,7 @@ export function createInProcessWindow(options: InProcessWindowOptions): InProces
holdToTalk: options.holdToTalk,
isVoiceCapturing: options.isVoiceCapturing,
keepsScreenOn: options.keepsScreenOn,
restoresApp: options.restoresApp,
setScreenOn: options.setScreenOn,
heightMode,
hasAppMenu: () => appMenuItems().length > 0,
+32
View File
@@ -17,6 +17,7 @@ import {
isWatchInput,
makeInputEvent,
} from "../gestures";
import type { KeyEvent } from "../../g2/keyboard/keys";
import { Layer, LayerActions, LayerContext, LayerStack, noopLayerActions } from "../layers";
import { CONTEXT_MENU_DIM, MenuLayer, type MenuItem } from "../menu";
import { VoiceInputLayer, type VoiceSendTarget } from "./voice-input";
@@ -151,6 +152,13 @@ export type ShellWindow = {
* draws this window's top bar.
*/
heightMode: WindowHeightMode;
/**
* False for a window that must not bring its app back when Faceclaw
* restarts (the controller's open-apps restore relaunches apps, not
* windows): one that shows something a plain launch of its app would not,
* where the relaunch would do something else in its place.
*/
restoresApp?: boolean;
/** App-side cleanup when the shell closes the window (worker notification, surface removal). */
close?: () => void;
drawIcon: ShellChromeWindow["drawIcon"];
@@ -185,6 +193,15 @@ export type ShellWindow = {
* only windows that consume typed text (the terminal) implement it.
*/
receiveTextInput?: (text: string, options?: { submit?: boolean }) => void;
/**
* Take a key from a hardware keyboard (app/g2/keyboard) as a key. Optional:
* only windows that give keys a meaning of their own (the terminal)
* implement it. They get the keys no keybinding claimed while they have
* input focus, presses and releases alike; the rest of the time, and for
* every other window, the navigation keys act as gestures (see
* app/g2/keyboard/bindings.ts).
*/
handleKeyEvent?: (event: KeyEvent) => void;
/** Foreground state changed: this window's surface is (not) the visible one. */
setForeground?: (foreground: boolean) => void;
/**
@@ -1599,6 +1616,21 @@ class Shell {
this.foregroundWindow()?.receiveTextInput?.(text, options);
}
/**
* Offer a hardware-keyboard key to the window that has input focus. True
* when that window takes keys (ShellWindow.handleKeyEvent) and got this
* one; false when the key is the caller's to interpret: the screen is off,
* the sidebar or a shell overlay has focus, or the window has no use for
* keys. Typing counts as activity for the screen timeout.
*/
receiveKeyEvent(event: KeyEvent): boolean {
const window = this.inputTargetWindow();
if (!window?.handleKeyEvent) return false;
if (event.phase === "down") this.lastInputAtMs = Date.now();
window.handleKeyEvent(event);
return true;
}
/**
* Open the voice dialog aimed at the foreground window. Called when the
* user picks Voice input from the system menu (or an app asks via a
+35
View File
@@ -28,6 +28,8 @@ export type WorkerAppMessage =
| { type: "close-window"; windowId: string }
| { type: "input"; windowId: string; event: unknown; frameId: number; focused: boolean }
| { type: "text-input"; windowId: string; text: string; submit?: boolean }
/** A hardware-keyboard key (a KeyEvent), for windows opened with acceptsKeys. */
| { type: "key"; windowId: string; event: unknown; focused: boolean }
| { type: "render"; windowId: string; focused: boolean }
| { type: "foreground"; windowId: string; foreground: boolean; focused: boolean }
/**
@@ -56,6 +58,16 @@ export type WorkerAppReply =
type: "worker-ready";
}
| { type: "yield-focus"; windowId: string }
| {
/**
* A "key" message the window had no use for as a key (a terminal
* showing its session list rather than a session). The host gives it
* the keyboard's navigation meaning instead.
*/
type: "key-unhandled";
windowId: string;
event: unknown;
}
| {
/** Foreground and focus one of the app's existing windows. */
type: "focus-window";
@@ -81,6 +93,8 @@ export type WorkerAppReply =
focus?: boolean;
/** Window height: the standard 288px band ("min", default) or full screen ("max"). */
heightMode?: WindowHeightMode;
/** Send the window hardware-keyboard keys (see WorkerWindowSpec). */
acceptsKeys?: boolean;
}
| {
/**
@@ -196,6 +210,13 @@ export type WorkerWindowSpec = {
* of all four directions in every window state (see ShellWindow).
*/
acceptsDirectional?: boolean;
/**
* Deliver hardware-keyboard keys to the worker as "key" messages while the
* window has input focus (see ShellWindow.handleKeyEvent). The worker
* answers "key-unhandled" for a key it doesn't want as a key just then,
* which gets the keyboard's navigation meaning instead.
*/
acceptsKeys?: boolean;
};
export type WorkerAppHostOptions = {
@@ -223,6 +244,8 @@ export type WorkerAppHostOptions = {
startTextSettingEdit: (settingId: string) => void;
/** Close the phone text editor opened by startTextSettingEdit. */
endTextSettingEdit: () => void;
/** A key a window was sent and handed back (the "key-unhandled" reply); a KeyEvent. */
unhandledKey?: (event: unknown) => void;
};
/**
@@ -312,6 +335,10 @@ export class WorkerAppHost {
shell.yieldFocusToSidebar();
}
break;
case "key-unhandled":
// Stale once focus has moved on: the key was meant for that window.
if (shell.isWindowFocused(message.windowId)) this.options.unhandledKey?.(message.event);
break;
case "focus-window":
if (this.openWindows.has(message.windowId)) {
shell.focusWindow(message.windowId);
@@ -335,6 +362,7 @@ export class WorkerAppHost {
iconGlyph: message.iconGlyph,
focus: message.focus,
heightMode: message.heightMode,
acceptsKeys: message.acceptsKeys,
});
break;
case "set-height-mode":
@@ -522,6 +550,13 @@ export class WorkerAppHost {
receiveTextInput: (text, options) => {
this.post({ type: "text-input", windowId: spec.windowId, text, ...(options?.submit === undefined ? {} : { submit: options.submit }) });
},
...(spec.acceptsKeys
? {
handleKeyEvent: (event) => {
this.post({ type: "key", windowId: spec.windowId, event, focused: shell.isWindowFocused(spec.windowId) });
},
}
: {}),
setForeground: (foreground) => {
this.options.setSurfaceVisible(surfaceId, foreground);
if (foreground) {
+2 -1
View File
@@ -11,7 +11,8 @@ local `@faceclaw/kotlin` plugin. Generated binaries and Gradle caches are ignore
callback interfaces. Since 2026-09-22 also the platform-neutral cores behind
the Android adapters: `util/` (Json codec, FrameTimingsCore, concurrency
primitives, sha256/clock/log/file expects), `g2protocol/FirmwareImage`,
`audio/` (Lc3PacketFramer, AudioSegmentation, VoicePrint, WavPcmReader),
`audio/` (Lc3PacketFramer, AudioSegmentation, VoicePrint, WavPcmReader, the Matroska
writer/reader and the MicRecording capture format built on it, MicArrayProtocol),
`graphics/` (GrayPacket, PreviewPalette, StatusIconArt, NotificationIconArt,
ColorGlyphArt, GlyphPacket, OpenTypeNames, SvgIconSource), `net/` (HttpIdentity, SseStream,
ResumableDownload, RemoteInputSession), `evenhub/EvenHubAssetServer`,
@@ -69,3 +69,41 @@ actual fun fileLength(path: String): Long = java.io.File(path).let { if (it.exis
actual fun deleteFile(path: String): Boolean = java.io.File(path).delete()
actual fun renameFile(from: String, to: String): Boolean = java.io.File(from).renameTo(java.io.File(to))
actual fun openFileOutput(path: String): SeekableOutput = object : SeekableOutput {
private val file = java.io.RandomAccessFile(path, "rw").also { it.setLength(0) }
override var size = 0L
private set
override fun write(bytes: ByteArray, offset: Int, length: Int) {
file.write(bytes, offset, length)
size += length
}
override fun writeAt(position: Long, bytes: ByteArray) {
require(position >= 0 && position + bytes.size <= size)
file.seek(position)
file.write(bytes)
file.seek(size)
}
override fun close() = file.close()
}
actual fun openFileInput(path: String): SeekableInput = object : SeekableInput {
private val file = java.io.RandomAccessFile(path, "r")
override val length = file.length()
override fun readAt(position: Long, buffer: ByteArray, offset: Int, length: Int): Int {
file.seek(position)
var total = 0
while (total < length) {
val read = file.read(buffer, offset + total, length - total)
if (read <= 0) break
total += read
}
return total
}
override fun close() = file.close()
}
@@ -20,3 +20,33 @@ expect fun fileLength(path: String): Long
expect fun deleteFile(path: String): Boolean
expect fun renameFile(from: String, to: String): Boolean
/** A file being written front to back whose earlier bytes can still be patched (container headers). */
interface SeekableOutput {
/** Bytes appended so far. */
val size: Long
/** Appends [length] bytes of [bytes] from [offset]. */
fun write(bytes: ByteArray, offset: Int, length: Int)
/** Overwrites bytes already written, at [position]; later appends still go to the end. */
fun writeAt(position: Long, bytes: ByteArray)
fun close()
}
/** A file read at arbitrary positions without loading it whole. */
interface SeekableInput {
val length: Long
/** Reads up to [length] bytes at [position] into [buffer]; returns the count read (short only at the end). */
fun readAt(position: Long, buffer: ByteArray, offset: Int, length: Int): Int
fun close()
}
/** Creates (or truncates) [path] for writing; parent directories must exist. Throws when it cannot. */
expect fun openFileOutput(path: String): SeekableOutput
/** Opens [path] for reading. Throws when it cannot. */
expect fun openFileInput(path: String): SeekableInput
@@ -0,0 +1,764 @@
package com.faceclaw.app
import kotlin.jvm.JvmField
/**
* A small Matroska (EBML) muxer and demuxer for audio captures (.mka): PCM16 audio tracks that
* each have their own sample rate and channel count, UTF-8 text tracks for timed metadata, and
* file attachments. Every block carries its own timestamp, so tracks on independent clocks and
* gaps in a track survive in the file. See notes/mic-recording-format.md for how captures use it.
*
* The writer produces files standard players open (VLC, mpv, ffmpeg): known-size clusters of
* about a second each, cues and the segment size written when the recording finishes. A
* recording cut short by a crash is still a valid live-style stream of everything up to its last
* complete cluster, and the reader takes it as such.
*/
internal object MatroskaIds {
const val EBML = 0x1A45DFA3
const val EBML_VERSION = 0x4286
const val EBML_READ_VERSION = 0x42F7
const val EBML_MAX_ID_LENGTH = 0x42F2
const val EBML_MAX_SIZE_LENGTH = 0x42F3
const val DOC_TYPE = 0x4282
const val DOC_TYPE_VERSION = 0x4287
const val DOC_TYPE_READ_VERSION = 0x4285
const val VOID = 0xEC
const val SEGMENT = 0x18538067
const val SEEK_HEAD = 0x114D9B74
const val SEEK = 0x4DBB
const val SEEK_ID = 0x53AB
const val SEEK_POSITION = 0x53AC
const val INFO = 0x1549A966
const val TIMESTAMP_SCALE = 0x2AD7B1
const val DURATION = 0x4489
const val DATE_UTC = 0x4461
const val TITLE = 0x7BA9
const val MUXING_APP = 0x4D80
const val WRITING_APP = 0x5741
const val TRACKS = 0x1654AE6B
const val TRACK_ENTRY = 0xAE
const val TRACK_NUMBER = 0xD7
const val TRACK_UID = 0x73C5
const val TRACK_TYPE = 0x83
const val FLAG_DEFAULT = 0x88
const val FLAG_LACING = 0x9C
const val NAME = 0x536E
const val LANGUAGE = 0x22B59C
const val CODEC_ID = 0x86
const val AUDIO = 0xE1
const val SAMPLING_FREQUENCY = 0xB5
const val CHANNELS = 0x9F
const val BIT_DEPTH = 0x6264
const val ATTACHMENTS = 0x1941A469
const val ATTACHED_FILE = 0x61A7
const val FILE_NAME = 0x466E
const val FILE_MIME_TYPE = 0x4660
const val FILE_DATA = 0x465C
const val FILE_UID = 0x46AE
const val CLUSTER = 0x1F43B675
const val TIMESTAMP = 0xE7
const val SIMPLE_BLOCK = 0xA3
const val BLOCK_GROUP = 0xA0
const val BLOCK = 0xA1
const val BLOCK_DURATION = 0x9B
const val CUES = 0x1C53BB6B
const val CUE_POINT = 0xBB
const val CUE_TIME = 0xB3
const val CUE_TRACK_POSITIONS = 0xB7
const val CUE_TRACK = 0xF7
const val CUE_CLUSTER_POSITION = 0xF1
}
/** Builds EBML elements into a byte buffer. */
internal class EbmlWriter(capacity: Int = 256) {
private val sink = ByteSink(capacity)
fun size(): Int = sink.size()
fun bytes(): ByteArray = sink.toByteArray()
/** An element ID, written as given: its length marker is part of the value. */
fun id(id: Int) {
if (id > 0xFFFFFF) sink.write(id ushr 24)
if (id > 0xFFFF) sink.write(id ushr 16)
if (id > 0xFF) sink.write(id ushr 8)
sink.write(id)
}
/** A data size in [width] bytes, or in the fewest that hold it when [width] is 0. */
fun dataSize(size: Long, width: Int = 0) {
var bytes = width
if (bytes == 0) {
bytes = 1
// The all-ones value of each width means "unknown size".
while (bytes < 8 && size >= (1L shl (7 * bytes)) - 1) bytes++
}
val marked = size or (1L shl (7 * bytes))
for (index in bytes - 1 downTo 0) sink.write((marked ushr (8 * index)).toInt())
}
fun uint(id: Int, value: Long) {
var bytes = 1
while (bytes < 8 && (value ushr (8 * bytes)) != 0L) bytes++
id(id)
dataSize(bytes.toLong())
for (index in bytes - 1 downTo 0) sink.write((value ushr (8 * index)).toInt())
}
/** A fixed eight-byte integer (dates). */
fun int64(id: Int, value: Long) {
id(id)
dataSize(8)
for (index in 7 downTo 0) sink.write((value ushr (8 * index)).toInt())
}
fun float64(id: Int, value: Double) = int64(id, value.toRawBits())
fun string(id: Int, text: String) {
val bytes = text.encodeToByteArray()
binary(id, bytes, 0, bytes.size)
}
fun binary(id: Int, bytes: ByteArray, offset: Int, length: Int) {
id(id)
dataSize(length.toLong())
sink.write(bytes, offset, length)
}
fun raw(bytes: ByteArray) = sink.write(bytes)
fun raw(value: Int) = sink.write(value)
fun master(id: Int, build: EbmlWriter.() -> Unit) {
val child = EbmlWriter()
child.build()
id(id)
dataSize(child.size().toLong())
sink.write(child.bytes())
}
companion object {
/** [element] followed by a Void element filling the rest of [reserved] bytes, or null when it doesn't fit. */
fun padded(element: ByteArray, reserved: Int): ByteArray? {
val filler = reserved - element.size
// A Void element is at least two bytes.
if (filler < 0 || filler == 1) return null
val out = element.copyOf(reserved)
if (filler == 0) return out
val at = element.size
out[at] = MatroskaIds.VOID.toByte()
if (filler < 9) {
out[at + 1] = (0x80 or (filler - 2)).toByte()
} else {
val size = (filler - 9).toLong()
out[at + 1] = 0x01
for (index in 0 until 7) out[at + 2 + index] = (size ushr (8 * (6 - index))).toByte()
}
return out
}
}
}
class MkaAttachment(@JvmField val name: String, @JvmField val mimeType: String, @JvmField val data: ByteArray)
/**
* Writes one Matroska audio file. Tracks can be added at any time before the first block that
* uses them: the track list sits in a reserved region that is rewritten in place. Timestamps are
* milliseconds from the start of the file. Not thread-safe.
*/
class MkaWriter(
private val output: SeekableOutput,
title: String?,
/** When the recording began (Unix epoch ms), for the file's date. */
dateUtcMs: Long,
attachments: List<MkaAttachment>,
) {
companion object {
const val CODEC_PCM = "A_PCM/INT/LIT"
const val CODEC_TEXT = "S_TEXT/UTF8"
const val TRACK_AUDIO = 2
const val TRACK_SUBTITLE = 0x11
const val APP_NAME = "Faceclaw"
private const val SEEK_RESERVED = 128
private const val TRACKS_RESERVED = 4096
private const val CLUSTER_SPAN_MS = 1000L
private const val CLUSTER_MAX_BYTES = 1 shl 20
// Block timestamps are signed 16-bit offsets from their cluster's.
private const val CLUSTER_MAX_BACKSTEP_MS = 30_000L
private const val DURATION_PATCH_CLUSTERS = 5
// Matroska dates count nanoseconds from 2001-01-01T00:00:00 UTC.
private const val DATE_EPOCH_MS = 978_307_200_000L
}
private class Track(
val number: Int,
val type: Int,
val name: String,
val sampleRate: Int,
val channels: Int,
val preferred: Boolean,
)
private class Cue(val clusterPosition: Long, val timeMs: Long)
private val tracks = ArrayList<Track>()
private val cues = ArrayList<Cue>()
private val segmentSizePosition: Long
private val segmentStart: Long
private val seekPosition: Long
private val infoPosition: Long
private val durationPosition: Long
private val tracksPosition: Long
private val attachmentsPosition: Long
private var cluster: EbmlWriter? = null
private var clusterBaseMs = 0L
private var clustersSincePatch = 0
private var finished = false
private val hasAttachments = attachments.isNotEmpty()
/** The end of the latest audio or text written, in ms from the start of the file. */
var durationMs = 0L
private set
init {
val head = EbmlWriter()
head.master(MatroskaIds.EBML) {
uint(MatroskaIds.EBML_VERSION, 1)
uint(MatroskaIds.EBML_READ_VERSION, 1)
uint(MatroskaIds.EBML_MAX_ID_LENGTH, 4)
uint(MatroskaIds.EBML_MAX_SIZE_LENGTH, 8)
string(MatroskaIds.DOC_TYPE, "matroska")
uint(MatroskaIds.DOC_TYPE_VERSION, 4)
uint(MatroskaIds.DOC_TYPE_READ_VERSION, 2)
}
head.id(MatroskaIds.SEGMENT)
segmentSizePosition = head.size().toLong()
// Unknown size (a live stream) until finish() knows it.
head.raw(0x01)
repeat(7) { head.raw(0xFF) }
segmentStart = head.size().toLong()
append(head.bytes())
seekPosition = output.size
infoPosition = seekPosition + SEEK_RESERVED
val info = EbmlWriter()
info.master(MatroskaIds.INFO) {
uint(MatroskaIds.TIMESTAMP_SCALE, 1_000_000)
string(MatroskaIds.MUXING_APP, APP_NAME)
string(MatroskaIds.WRITING_APP, APP_NAME)
int64(MatroskaIds.DATE_UTC, (dateUtcMs - DATE_EPOCH_MS) * 1_000_000)
if (!title.isNullOrEmpty()) string(MatroskaIds.TITLE, title)
// Last, so its eight bytes are the element's final ones.
float64(MatroskaIds.DURATION, 0.0)
}
durationPosition = infoPosition + info.size() - 8
tracksPosition = infoPosition + info.size()
attachmentsPosition = tracksPosition + TRACKS_RESERVED
append(seekHead(-1))
append(info.bytes())
append(EbmlWriter.padded(ByteArray(0), TRACKS_RESERVED)!!)
if (attachments.isNotEmpty()) {
val files = EbmlWriter()
files.master(MatroskaIds.ATTACHMENTS) {
attachments.forEachIndexed { index, file ->
master(MatroskaIds.ATTACHED_FILE) {
string(MatroskaIds.FILE_NAME, file.name)
string(MatroskaIds.FILE_MIME_TYPE, file.mimeType)
binary(MatroskaIds.FILE_DATA, file.data, 0, file.data.size)
uint(MatroskaIds.FILE_UID, index + 1L)
}
}
}
append(files.bytes())
}
}
private fun append(bytes: ByteArray) = output.write(bytes, 0, bytes.size)
private fun seekHead(cuesPosition: Long): ByteArray {
val head = EbmlWriter()
head.master(MatroskaIds.SEEK_HEAD) {
fun entry(id: Int, position: Long) = master(MatroskaIds.SEEK) {
val idBytes = EbmlWriter()
idBytes.id(id)
binary(MatroskaIds.SEEK_ID, idBytes.bytes(), 0, idBytes.size())
uint(MatroskaIds.SEEK_POSITION, position - segmentStart)
}
entry(MatroskaIds.INFO, infoPosition)
entry(MatroskaIds.TRACKS, tracksPosition)
if (hasAttachments) entry(MatroskaIds.ATTACHMENTS, attachmentsPosition)
if (cuesPosition >= 0) entry(MatroskaIds.CUES, cuesPosition)
}
return EbmlWriter.padded(head.bytes(), SEEK_RESERVED) ?: error("seek head exceeds its reserved space")
}
/**
* Adds a PCM16 little-endian audio track and returns its number, or -1 when the track list
* is full. A [preferred] track is listed ahead of the others, and the first listed track is
* the one players pick by default.
*/
fun addAudioTrack(name: String, sampleRate: Int, channels: Int, preferred: Boolean): Int =
addTrack(Track(tracks.size + 1, TRACK_AUDIO, name, sampleRate, channels, preferred))
/** Adds a UTF-8 text track (one string per block) and returns its number, or -1 when the track list is full. */
fun addTextTrack(name: String): Int = addTrack(Track(tracks.size + 1, TRACK_SUBTITLE, name, 0, 0, false))
private fun addTrack(track: Track): Int {
check(!finished) { "recording already finished" }
// A block's track number is written in one byte.
if (track.number > 126) return -1
tracks.add(track)
val region = EbmlWriter.padded(tracksElement(), TRACKS_RESERVED)
if (region == null) {
tracks.remove(track)
return -1
}
output.writeAt(tracksPosition, region)
return track.number
}
private fun listedTracks(): List<Track> =
tracks.filter { it.type == TRACK_AUDIO && it.preferred } +
tracks.filter { it.type == TRACK_AUDIO && !it.preferred } +
tracks.filter { it.type != TRACK_AUDIO }
private fun tracksElement(): ByteArray {
val listed = listedTracks()
val defaultTrack = listed.firstOrNull { it.type == TRACK_AUDIO }
val out = EbmlWriter(1024)
out.master(MatroskaIds.TRACKS) {
for (track in listed) {
master(MatroskaIds.TRACK_ENTRY) {
uint(MatroskaIds.TRACK_NUMBER, track.number.toLong())
uint(MatroskaIds.TRACK_UID, track.number.toLong())
uint(MatroskaIds.TRACK_TYPE, track.type.toLong())
uint(MatroskaIds.FLAG_DEFAULT, if (track === defaultTrack) 1 else 0)
uint(MatroskaIds.FLAG_LACING, 0)
string(MatroskaIds.NAME, track.name)
string(MatroskaIds.LANGUAGE, "und")
if (track.type == TRACK_AUDIO) {
string(MatroskaIds.CODEC_ID, CODEC_PCM)
master(MatroskaIds.AUDIO) {
float64(MatroskaIds.SAMPLING_FREQUENCY, track.sampleRate.toDouble())
uint(MatroskaIds.CHANNELS, track.channels.toLong())
uint(MatroskaIds.BIT_DEPTH, 16)
}
} else {
string(MatroskaIds.CODEC_ID, CODEC_TEXT)
}
}
}
}
return out.bytes()
}
private fun track(number: Int): Track = tracks.getOrNull(number - 1) ?: error("no track $number")
/** Appends interleaved PCM16 little-endian samples to an audio track, starting at [timeMs]. */
fun writeAudio(trackNumber: Int, timeMs: Long, pcm16le: ByteArray, offset: Int, length: Int) {
val track = track(trackNumber)
require(track.type == TRACK_AUDIO) { "track $trackNumber is not audio" }
if (length <= 0) return
val block = openCluster(timeMs)
block.id(MatroskaIds.SIMPLE_BLOCK)
block.dataSize(4L + length)
blockHeader(block, trackNumber, timeMs, 0x80)
block.raw(if (offset == 0 && length == pcm16le.size) pcm16le else pcm16le.copyOfRange(offset, offset + length))
val frames = length / (2 * track.channels)
noteEnd(timeMs + frames * 1000L / track.sampleRate)
}
/** Appends one string to a text track, shown from [timeMs] for [durationMs]. */
fun writeText(trackNumber: Int, timeMs: Long, durationMs: Long, text: String) {
require(track(trackNumber).type == TRACK_SUBTITLE) { "track $trackNumber is not text" }
val bytes = text.encodeToByteArray()
val block = openCluster(timeMs)
block.master(MatroskaIds.BLOCK_GROUP) {
id(MatroskaIds.BLOCK)
dataSize(4L + bytes.size)
blockHeader(this, trackNumber, timeMs, 0)
raw(bytes)
uint(MatroskaIds.BLOCK_DURATION, maxOf(1L, durationMs))
}
noteEnd(timeMs + maxOf(1L, durationMs))
}
private fun blockHeader(block: EbmlWriter, trackNumber: Int, timeMs: Long, flags: Int) {
val relative = (maxOf(0L, timeMs) - clusterBaseMs).toInt()
block.raw(0x80 or trackNumber)
block.raw(relative shr 8)
block.raw(relative)
block.raw(flags)
}
private fun noteEnd(endMs: Long) {
if (endMs > durationMs) durationMs = endMs
}
/** The cluster a block at [timeMs] goes in: the open one, or a new one once that is full or too far away in time. */
private fun openCluster(timeMs: Long): EbmlWriter {
check(!finished) { "recording already finished" }
val time = maxOf(0L, timeMs)
val open = cluster
if (open != null) {
val relative = time - clusterBaseMs
if (relative < CLUSTER_SPAN_MS && relative > -CLUSTER_MAX_BACKSTEP_MS && open.size() < CLUSTER_MAX_BYTES) return open
flushCluster()
}
clusterBaseMs = time
return EbmlWriter(64 * 1024).also { cluster = it }
}
private fun flushCluster() {
val body = cluster ?: return
cluster = null
if (body.size() == 0) return
val timestamp = EbmlWriter(16)
timestamp.uint(MatroskaIds.TIMESTAMP, clusterBaseMs)
val header = EbmlWriter(32)
header.id(MatroskaIds.CLUSTER)
header.dataSize(timestamp.size().toLong() + body.size())
header.raw(timestamp.bytes())
cues.add(Cue(output.size - segmentStart, clusterBaseMs))
append(header.bytes())
append(body.bytes())
if (++clustersSincePatch >= DURATION_PATCH_CLUSTERS) patchDuration()
}
private fun patchDuration() {
clustersSincePatch = 0
val value = durationMs.toDouble().toRawBits()
output.writeAt(durationPosition, ByteArray(8) { (value ushr (8 * (7 - it))).toByte() })
}
/** Writes what is buffered, then the cues, duration and segment size, and closes the file. */
fun finish() {
if (finished) return
try {
flushCluster()
finished = true
val cuesPosition = output.size
val cueTrack = listedTracks().firstOrNull()?.number ?: 1
if (cues.isNotEmpty()) {
val index = EbmlWriter(cues.size * 16 + 16)
index.master(MatroskaIds.CUES) {
for (cue in cues) {
master(MatroskaIds.CUE_POINT) {
uint(MatroskaIds.CUE_TIME, cue.timeMs)
master(MatroskaIds.CUE_TRACK_POSITIONS) {
uint(MatroskaIds.CUE_TRACK, cueTrack.toLong())
uint(MatroskaIds.CUE_CLUSTER_POSITION, cue.clusterPosition)
}
}
}
}
append(index.bytes())
output.writeAt(seekPosition, seekHead(cuesPosition))
}
patchDuration()
val size = EbmlWriter(8)
size.dataSize(output.size - segmentStart, 8)
output.writeAt(segmentSizePosition, size.bytes())
} finally {
finished = true
output.close()
}
}
}
class MkaTrackInfo(
@JvmField val number: Int,
/** [MkaWriter.TRACK_AUDIO], [MkaWriter.TRACK_SUBTITLE] or another Matroska track type. */
@JvmField val type: Int,
@JvmField val codecId: String,
@JvmField val name: String,
@JvmField val sampleRate: Int,
@JvmField val channels: Int,
@JvmField val bitDepth: Int,
) {
val isPcm16: Boolean get() = type == MkaWriter.TRACK_AUDIO && codecId == MkaWriter.CODEC_PCM && bitDepth == 16
}
class MkaBlock(
@JvmField val track: Int,
@JvmField val timeMs: Long,
@JvmField val data: ByteArray,
/** From the block's group, or -1 when the file doesn't say (audio blocks). */
@JvmField val durationMs: Long,
)
/**
* Reads the blocks of a Matroska file in file order, a cluster at a time. Handles what
* [MkaWriter] and ffmpeg write for PCM audio: known-size clusters, unlaced blocks. Throws
* IllegalArgumentException for anything that is not such a file.
*/
class MkaReader(private val input: SeekableInput) {
private class ClusterRef(val position: Long, val size: Int, val rawTime: Long)
private val clusters = ArrayList<ClusterRef>()
private val trackList = ArrayList<MkaTrackInfo>()
private val attachmentList = ArrayList<MkaAttachment>()
private var timestampScale = 1_000_000L
private var infoDurationMs = 0L
private var nextCluster = 0
private var blocks: List<MkaBlock> = emptyList()
private var blockIndex = 0
private var skipBeforeMs = 0L
val tracks: List<MkaTrackInfo> get() = trackList
val attachments: List<MkaAttachment> get() = attachmentList
/** The end of the last audio or text in the file, in ms. */
val durationMs: Long
init {
scan()
var end = infoDurationMs
if (clusters.isNotEmpty()) {
for (block in readCluster(clusters.last())) end = maxOf(end, block.timeMs + blockSpanMs(block))
}
durationMs = end
}
fun track(number: Int): MkaTrackInfo? = trackList.firstOrNull { it.number == number }
/** Continue from the first block at or after [timeMs]. */
fun seekTo(timeMs: Long) {
val index = clusters.indexOfLast { toMs(it.rawTime) <= timeMs }
nextCluster = maxOf(0, index)
blocks = emptyList()
blockIndex = 0
skipBeforeMs = timeMs
}
/** The next block, or null at the end of the file. */
fun next(): MkaBlock? {
while (true) {
while (blockIndex >= blocks.size) {
if (nextCluster >= clusters.size) return null
blocks = readCluster(clusters[nextCluster++])
blockIndex = 0
}
val block = blocks[blockIndex++]
if (block.timeMs >= skipBeforeMs) return block
}
}
fun close() = input.close()
private fun toMs(raw: Long): Long = raw * timestampScale / 1_000_000L
private fun blockSpanMs(block: MkaBlock): Long {
if (block.durationMs >= 0) return block.durationMs
val track = track(block.track) ?: return 0
if (!track.isPcm16 || track.channels <= 0 || track.sampleRate <= 0) return 0
return block.data.size / (2L * track.channels) * 1000L / track.sampleRate
}
/** An element header at [at] in [bytes]: its ID, payload size (-1 unknown) and header length; null when cut off. */
private class Header(val id: Int, val size: Long, val length: Int)
private fun header(bytes: ByteArray, at: Int, end: Int): Header? {
if (at >= end) return null
val first = bytes[at].toInt() and 0xff
val idLength = first.countLeadingZeroBits() - 24 + 1
if (idLength > 4 || at + idLength >= end) return null
var id = 0
for (index in 0 until idLength) id = (id shl 8) or (bytes[at + index].toInt() and 0xff)
val sizeAt = at + idLength
val sizeFirst = bytes[sizeAt].toInt() and 0xff
val sizeLength = sizeFirst.countLeadingZeroBits() - 24 + 1
if (sizeLength > 8 || sizeAt + sizeLength > end) return null
var size = (sizeFirst and (0xff shr sizeLength)).toLong()
var allOnes = size == (0xff shr sizeLength).toLong()
for (index in 1 until sizeLength) {
val byte = bytes[sizeAt + index].toInt() and 0xff
if (byte != 0xff) allOnes = false
size = (size shl 8) or byte.toLong()
}
return Header(id, if (allOnes) -1 else size, idLength + sizeLength)
}
private fun readAt(position: Long, length: Int): ByteArray {
val buffer = ByteArray(length)
val read = input.readAt(position, buffer, 0, length)
return if (read == length) buffer else buffer.copyOf(maxOf(0, read))
}
private fun uint(bytes: ByteArray, at: Int, size: Int): Long {
var value = 0L
for (index in 0 until size) value = (value shl 8) or (bytes[at + index].toLong() and 0xff)
return value
}
private fun float(bytes: ByteArray, at: Int, size: Int): Double = when (size) {
4 -> Float.fromBits(uint(bytes, at, 4).toInt()).toDouble()
8 -> Double.fromBits(uint(bytes, at, 8))
else -> 0.0
}
/** Calls [visit] with the ID, payload offset and payload size of each complete child element. */
private inline fun children(bytes: ByteArray, start: Int, end: Int, visit: (id: Int, at: Int, size: Int) -> Unit) {
var at = start
while (true) {
val child = header(bytes, at, end) ?: return
val payload = at + child.length
if (child.size < 0 || child.size > end - payload) return
visit(child.id, payload, child.size.toInt())
at = payload + child.size.toInt()
}
}
private fun scan() {
val length = input.length
val start = readAt(0, 64)
val ebml = header(start, 0, start.size)
require(ebml != null && ebml.id == MatroskaIds.EBML && ebml.size >= 0) { "not a Matroska file" }
var position = ebml.length + ebml.size
val segment = readAt(position, 12).let { header(it, 0, it.size) }
require(segment != null && segment.id == MatroskaIds.SEGMENT) { "not a Matroska file" }
position += segment.length
val end = if (segment.size < 0) length else minOf(length, position + segment.size)
while (position < end) {
val head = readAt(position, 12)
val element = header(head, 0, head.size) ?: break
val payload = position + element.length
if (element.id == MatroskaIds.CLUSTER) {
require(element.size >= 0) { "unsupported Matroska file (clusters of unknown size)" }
// A recording cut short ends in a partial cluster; its complete blocks still count.
val available = minOf(element.size, end - payload)
require(available <= Int.MAX_VALUE) { "unsupported Matroska file (oversized cluster)" }
clusters.add(ClusterRef(payload, available.toInt(), clusterTime(payload, available.toInt())))
} else if (element.size < 0) {
break
} else if (element.size <= end - payload && element.size <= 64L * 1024 * 1024) {
when (element.id) {
MatroskaIds.INFO -> parseInfo(readAt(payload, element.size.toInt()))
MatroskaIds.TRACKS -> parseTracks(readAt(payload, element.size.toInt()))
MatroskaIds.ATTACHMENTS -> parseAttachments(readAt(payload, element.size.toInt()))
}
}
if (element.size < 0) break
position = payload + element.size
}
}
private fun clusterTime(position: Long, size: Int): Long {
val head = readAt(position, minOf(size, 16))
val first = header(head, 0, head.size)
if (first != null && first.id == MatroskaIds.TIMESTAMP && first.size in 0..8 && first.length + first.size <= head.size) {
return uint(head, first.length, first.size.toInt())
}
val whole = readAt(position, size)
var time = 0L
children(whole, 0, whole.size) { id, at, length -> if (id == MatroskaIds.TIMESTAMP) time = uint(whole, at, length) }
return time
}
private fun parseInfo(bytes: ByteArray) {
var duration = 0.0
children(bytes, 0, bytes.size) { id, at, size ->
when (id) {
MatroskaIds.TIMESTAMP_SCALE -> timestampScale = maxOf(1L, uint(bytes, at, size))
MatroskaIds.DURATION -> duration = float(bytes, at, size)
}
}
infoDurationMs = (duration * timestampScale / 1_000_000.0).toLong()
}
private fun parseTracks(bytes: ByteArray) {
trackList.clear()
children(bytes, 0, bytes.size) { id, at, size ->
if (id == MatroskaIds.TRACK_ENTRY) {
var number = 0
var type = 0
var codec = ""
var name = ""
var rate = 8000.0
var channels = 1
var depth = 0
children(bytes, at, at + size) { field, fieldAt, fieldSize ->
when (field) {
MatroskaIds.TRACK_NUMBER -> number = uint(bytes, fieldAt, fieldSize).toInt()
MatroskaIds.TRACK_TYPE -> type = uint(bytes, fieldAt, fieldSize).toInt()
MatroskaIds.CODEC_ID -> codec = bytes.decodeToString(fieldAt, fieldAt + fieldSize).trimEnd('\u0000')
MatroskaIds.NAME -> name = bytes.decodeToString(fieldAt, fieldAt + fieldSize).trimEnd('\u0000')
MatroskaIds.AUDIO -> children(bytes, fieldAt, fieldAt + fieldSize) { audio, audioAt, audioSize ->
when (audio) {
MatroskaIds.SAMPLING_FREQUENCY -> rate = float(bytes, audioAt, audioSize)
MatroskaIds.CHANNELS -> channels = uint(bytes, audioAt, audioSize).toInt()
MatroskaIds.BIT_DEPTH -> depth = uint(bytes, audioAt, audioSize).toInt()
}
}
}
}
val audio = type == MkaWriter.TRACK_AUDIO
trackList.add(
MkaTrackInfo(number, type, codec, name, if (audio) rate.toInt() else 0, if (audio) channels else 0, if (audio) depth else 0),
)
}
}
}
private fun parseAttachments(bytes: ByteArray) {
children(bytes, 0, bytes.size) { id, at, size ->
if (id == MatroskaIds.ATTACHED_FILE) {
var name = ""
var mime = ""
var data = ByteArray(0)
children(bytes, at, at + size) { field, fieldAt, fieldSize ->
when (field) {
MatroskaIds.FILE_NAME -> name = bytes.decodeToString(fieldAt, fieldAt + fieldSize)
MatroskaIds.FILE_MIME_TYPE -> mime = bytes.decodeToString(fieldAt, fieldAt + fieldSize)
MatroskaIds.FILE_DATA -> data = bytes.copyOfRange(fieldAt, fieldAt + fieldSize)
}
}
attachmentList.add(MkaAttachment(name, mime, data))
}
}
}
private fun readCluster(cluster: ClusterRef): List<MkaBlock> {
val bytes = readAt(cluster.position, cluster.size)
val out = ArrayList<MkaBlock>()
var clusterRaw = cluster.rawTime
children(bytes, 0, bytes.size) { id, at, size ->
when (id) {
MatroskaIds.TIMESTAMP -> clusterRaw = uint(bytes, at, size)
MatroskaIds.SIMPLE_BLOCK -> block(bytes, at, size, clusterRaw, -1)?.let { out.add(it) }
MatroskaIds.BLOCK_GROUP -> {
var blockAt = -1
var blockSize = 0
var duration = -1L
children(bytes, at, at + size) { field, fieldAt, fieldSize ->
when (field) {
MatroskaIds.BLOCK -> {
blockAt = fieldAt
blockSize = fieldSize
}
MatroskaIds.BLOCK_DURATION -> duration = toMs(uint(bytes, fieldAt, fieldSize))
}
}
if (blockAt >= 0) block(bytes, blockAt, blockSize, clusterRaw, duration)?.let { out.add(it) }
}
}
}
return out
}
/** A block's payload: track number, 16-bit timestamp offset, flags, then the frame. Laced blocks are skipped. */
private fun block(bytes: ByteArray, at: Int, size: Int, clusterRaw: Long, durationMs: Long): MkaBlock? {
if (size < 4) return null
val first = bytes[at].toInt() and 0xff
val trackLength = first.countLeadingZeroBits() - 24 + 1
if (trackLength > 2 || size < trackLength + 3) return null
var track = first and (0xff shr trackLength)
if (trackLength == 2) track = (track shl 8) or (bytes[at + 1].toInt() and 0xff)
val head = at + trackLength
val relative = ((bytes[head].toInt() shl 8) or (bytes[head + 1].toInt() and 0xff)).toShort().toLong()
val flags = bytes[head + 2].toInt() and 0xff
if (flags and 0x06 != 0) return null
return MkaBlock(track, toMs(clusterRaw + relative), bytes.copyOfRange(head + 3, at + size), durationMs)
}
}
@@ -0,0 +1,93 @@
package com.faceclaw.app
import kotlin.jvm.JvmField
import kotlin.jvm.JvmStatic
/**
* The parts of the CFW mic_control wire format the capture session speaks itself: the 'SM'
* multi-channel stream frame each temple sends, and the fixed STOP/RENEW control records. The
* CONFIGURE record is built by the caller (app/apps/microphones/mic-protocol.ts encodes it; the
* contract is the header of g2flash patches/mic_control.c).
*/
object MicArrayProtocol {
const val VERSION = 1
const val HEADER_BYTES = 21
const val OP_CONFIGURE = 1
const val OP_STOP = 3
const val OP_RENEW = 4
/** How long an armed temple streams without a CONFIGURE or RENEW. */
const val LEASE_MS = 90_000L
const val FLAG_TRUNCATED = 0x80
const val CODEC_RAW = 1
const val FORMAT_PCM16 = 0
/** One decoded 'SM' frame header; the samples are [payloadLength] bytes at [payloadOffset] of its packet. */
class Frame(
/** Low 16 bits of the temple's frame counter. */
@JvmField val sequence: Int,
/** The temple's own 1 ms tick when it packed the frame (unsigned 32-bit). */
@JvmField val deviceTickMs: Long,
@JvmField val channels: Int,
@JvmField val sampleRate: Int,
@JvmField val format: Int,
@JvmField val codec: Int,
/** The temple's own bearing estimate, in signed degrees (0 unless it was asked for one). */
@JvmField val angleDegrees: Int,
@JvmField val ssr: Int,
/** The firmware cut the payload short of the samples it captured. */
@JvmField val truncated: Boolean,
@JvmField val payloadOffset: Int,
@JvmField val payloadLength: Int,
)
/** A control record with no payload: ['M','C', version, op]. */
@JvmStatic
fun control(op: Int): ByteArray = byteArrayOf('M'.code.toByte(), 'C'.code.toByte(), VERSION.toByte(), op.toByte())
@JvmStatic
fun isConfigure(record: ByteArray?): Boolean =
record != null && record.size >= 13 && record[0] == 'M'.code.toByte() && record[1] == 'C'.code.toByte() &&
record[2] == VERSION.toByte() && record[3] == OP_CONFIGURE.toByte()
/** Decodes a stream frame's header, or returns null when [data] isn't one. */
@JvmStatic
fun decodeFrame(data: ByteArray): Frame? {
if (data.size < HEADER_BYTES || data[0] != 'S'.code.toByte() || data[1] != 'M'.code.toByte() || data[2] != VERSION.toByte()) {
return null
}
val length = minOf(u16(data, 19), data.size - HEADER_BYTES)
return Frame(
sequence = u16(data, 4),
deviceTickMs = u16(data, 6).toLong() or (u16(data, 8).toLong() shl 16),
channels = data[10].toInt() and 0xff,
sampleRate = u16(data, 11) * 100,
format = data[13].toInt() and 0xff,
codec = data[14].toInt() and 0xff,
angleDegrees = u16(data, 15).toShort().toInt(),
ssr = u16(data, 17).toShort().toInt(),
truncated = (data[3].toInt() and FLAG_TRUNCATED) != 0,
payloadOffset = HEADER_BYTES,
payloadLength = length,
)
}
/**
* The frame's samples as interleaved PCM16 (whole sample frames only), or null when the
* payload isn't raw 16-bit PCM or holds none.
*/
@JvmStatic
fun pcm16(data: ByteArray, frame: Frame): ShortArray? {
if (frame.codec != CODEC_RAW || frame.format != FORMAT_PCM16 || frame.channels < 1) return null
val frames = frame.payloadLength / (2 * frame.channels)
if (frames <= 0) return null
val samples = ShortArray(frames * frame.channels)
var at = frame.payloadOffset
for (index in samples.indices) {
samples[index] = AudioSegmentation.pcm16le(data[at], data[at + 1])
at += 2
}
return samples
}
private fun u16(data: ByteArray, at: Int): Int = (data[at].toInt() and 0xff) or ((data[at + 1].toInt() and 0xff) shl 8)
}
@@ -0,0 +1,484 @@
package com.faceclaw.app
import kotlin.concurrent.Volatile
import kotlin.jvm.JvmField
import kotlin.jvm.JvmStatic
import kotlin.math.abs
/** Which microphones a chunk of capture audio came from. */
object MicStream {
/** One mixed channel: the glasses' stock stream, or the phone's own microphone. */
const val MONO = 0
/** A temple's own microphones, on that temple's clock (channel 0 front, channel 1 rear). */
const val LEFT = 1
const val RIGHT = 2
/** The mono feed derived from the temples for speech recognition: recorded, never replayed. */
const val MIX = 3
const val COUNT = 4
/** The stream's name in frame metadata. */
@JvmStatic
fun key(stream: Int): String = when (stream) {
MONO -> "mic"
LEFT -> "left"
RIGHT -> "right"
else -> "mix"
}
/** The name of the stream's audio tracks in a recording. */
@JvmStatic
fun trackName(stream: Int): String = when (stream) {
MONO -> "mic"
LEFT -> "left temple"
RIGHT -> "right temple"
else -> "mix"
}
/** The stream a recording's track or metadata names, or -1. */
@JvmStatic
fun named(name: String): Int = (0 until COUNT).firstOrNull { trackName(it) == name || key(it) == name } ?: -1
}
/**
* One chunk of microphone audio as a capture source delivered it (about 50 ms), before any
* processing. Live captures, recordings and replays all trade in these.
*/
class MicChunk(
@JvmField val stream: Int,
@JvmField val channels: Int,
@JvmField val sampleRate: Int,
/** Interleaved PCM16; the first [frames] sample frames are the chunk. */
@JvmField val pcm: ShortArray,
@JvmField val frames: Int,
/** When the chunk arrived: the phone's monotonic clock for a live capture, the offset into the file for a replay. */
@JvmField val timeMs: Long,
) {
/** Whether the source reported a direction of arrival with the chunk. */
@JvmField var hasDirection = false
@JvmField var angleDegrees = 0
@JvmField var ssr = 0
/** The source's packet counter, or -1 when it has none. */
@JvmField var sequence = -1
/** The source's own clock when it captured the chunk (unsigned 32-bit ms), or -1 when it has none. */
@JvmField var deviceTickMs = -1L
/** Whose clock [deviceTickMs] is on: the stream the samples were captured by. */
@JvmField var clockStream = stream
/** The source cut the chunk short of what it captured. */
@JvmField var truncated = false
/** Sample frames known to be missing between the previous chunk of this stream and this one. */
@JvmField var lostFramesBefore = 0
val durationMs: Long get() = frames * 1000L / sampleRate
}
/**
* Derives the mono feed speech recognition hears from the temples' chunks. This is the seam for
* array processing (beamforming, noise cancellation): replays feed it the recorded chunks with
* the times they first arrived at, so an implementation that decides from the chunks alone
* behaves the same on a replay as it did live.
*/
interface MicArrayMixer {
/** The mono chunk [chunk] contributes to the feed, or null when it contributes nothing. */
fun mix(chunk: MicChunk): MicChunk?
fun reset()
}
/**
* The feed is one temple at a time, its microphones averaged (the firmware's own stock downmix).
* The temples sample on independent clocks, so their audio is never summed. The left temple
* feeds whenever it is streaming; the right one stands in while it is not.
*/
class SingleTempleMixer : MicArrayMixer {
companion object {
/** A temple that has delivered nothing for this long no longer counts as streaming. */
const val SILENT_MS = 300L
}
private var leftAtMs = Long.MIN_VALUE
override fun reset() {
leftAtMs = Long.MIN_VALUE
}
override fun mix(chunk: MicChunk): MicChunk? {
if (chunk.stream == MicStream.LEFT) {
leftAtMs = chunk.timeMs
} else if (chunk.stream != MicStream.RIGHT || (leftAtMs != Long.MIN_VALUE && chunk.timeMs - leftAtMs < SILENT_MS)) {
return null
}
val channels = chunk.channels
val mono = ShortArray(chunk.frames)
for (frame in 0 until chunk.frames) {
var sum = 0
for (channel in 0 until channels) sum += chunk.pcm[frame * channels + channel]
mono[frame] = (sum / channels).toShort()
}
val out = MicChunk(MicStream.MIX, 1, chunk.sampleRate, mono, chunk.frames, chunk.timeMs)
out.hasDirection = chunk.hasDirection
out.angleDegrees = chunk.angleDegrees
out.ssr = chunk.ssr
out.deviceTickMs = chunk.deviceTickMs
out.clockStream = chunk.stream
out.truncated = chunk.truncated
return out
}
}
/**
* Records a capture's chunks to a Matroska audio file (.mka), one PCM16 track per stream and
* layout as each first appears, plus a "frames" text track with one JSON object per chunk that
* has metadata, written just ahead of the chunk's audio. Format: notes/mic-recording-format.md.
*
* Block timestamps are capture times, not arrival times. A stream's own clock (a temple's tick,
* or the count of samples from a source without one) says how far apart its chunks were
* captured; the least-delayed recent arrival places that clock on the file's timeline. So a
* chunk held up over Bluetooth still lands where it was captured, and lost audio leaves a gap.
*
* Safe to share between the capture thread and whoever finishes the recording.
*/
class MicRecordingWriter(
output: SeekableOutput,
/** A JSON document describing the capture, stored as the file's "capture.json" attachment. */
configJson: String?,
/** When the recording began (Unix epoch ms). */
startedAtMs: Long,
platform: ProtocolPlatform = protocolPlatform(),
private val logWarn: (String) -> Unit = { PlatformLog.w("FaceclawMicRecording", it) },
) {
companion object {
const val CONFIG_ATTACHMENT = "capture.json"
const val META_TRACK = "frames"
/** How far a chunk's arrival may sit from where its stream's clock puts it before the clock is re-placed. */
const val DISCONTINUITY_MS = 5000L
private const val WINDOW_BUCKETS = 8
private const val BUCKET_MS = 1000L
}
/**
* Places one track's chunks on the file's timeline. `source` time is the stream's own clock
* since this clock was anchored; the offset from it to arrival time is taken as the least
* seen over the last few seconds, which is the least-delayed delivery.
*/
private class TrackClock(val number: Int, val sampleRate: Int) {
private var anchored = false
private var clockStream = -1
private var tickBase = -1L
private var lastTick = -1L
private var frames = 0L
private val minima = LongArray(WINDOW_BUCKETS)
private var bucket = 0
private var bucketStartMs = 0L
var endMs = Long.MIN_VALUE
private set
fun reset() {
anchored = false
}
private fun offset(): Long = minima.min()
fun stamp(chunk: MicChunk): Long {
val arrival = chunk.timeMs
val ticked = chunk.deviceTickMs >= 0
if (anchored) {
// Another clock (the feed moved to the other temple), or this one restarted.
if (chunk.clockStream != clockStream || ticked != (tickBase >= 0)) anchored = false
else if (ticked && (chunk.deviceTickMs - lastTick).toInt() < 0) anchored = false
}
var anchorNow = !anchored
var source = 0L
if (anchored) {
frames += chunk.lostFramesBefore
source = sourceTime(chunk)
if (abs(arrival - source - offset()) > DISCONTINUITY_MS) anchorNow = true
}
if (anchorNow) {
anchored = true
clockStream = chunk.clockStream
tickBase = if (ticked) chunk.deviceTickMs else -1L
frames = 0
minima.fill(Long.MAX_VALUE)
bucket = 0
bucketStartMs = arrival
source = 0
}
if (arrival - bucketStartMs >= BUCKET_MS) {
bucket = (bucket + 1) % WINDOW_BUCKETS
minima[bucket] = Long.MAX_VALUE
bucketStartMs = arrival
}
if (arrival - source < minima[bucket]) minima[bucket] = arrival - source
// Never before the end of the track's previous block.
val time = maxOf(source + offset(), endMs)
frames += chunk.frames
lastTick = chunk.deviceTickMs
endMs = time + chunk.durationMs
return time
}
private fun sourceTime(chunk: MicChunk): Long =
if (tickBase >= 0) (chunk.deviceTickMs - tickBase) and 0xffffffffL else frames * 1000L / sampleRate
}
private val lock = platform.createLock()
private val writer: MkaWriter
private val clocks = HashMap<Long, TrackClock>()
private var metaTrack = 0
private var originMs = Long.MIN_VALUE
private var lastTimeMs = 0L
private var closed = false
/** The recording stopped early: the file could not be written. */
@Volatile
var failed = false
private set
init {
val attachments = if (configJson.isNullOrEmpty()) emptyList()
else listOf(MkaAttachment(CONFIG_ATTACHMENT, "application/json", configJson.encodeToByteArray()))
writer = MkaWriter(output, null, startedAtMs, attachments)
}
/** Length of the recording so far, in ms. */
val durationMs: Long get() = lock.withLock { writer.durationMs }
/** Appends [chunk] to its stream's track, adding the track on its first chunk. */
fun write(chunk: MicChunk) {
if (chunk.frames <= 0) return
lock.withLock {
if (closed) return
try {
val clock = clockFor(chunk) ?: return
if (originMs == Long.MIN_VALUE) originMs = chunk.timeMs
val time = clock.stamp(chunk) - originMs
val meta = metadata(chunk)
if (meta != null && metaTrack > 0) writer.writeText(metaTrack, time, maxOf(1L, chunk.durationMs), meta)
val bytes = AudioSegmentation.pcm16ToLittleEndian(chunk.pcm, 0, chunk.frames * chunk.channels)
writer.writeAudio(clock.number, time, bytes, 0, bytes.size)
lastTimeMs = maxOf(lastTimeMs, time)
} catch (error: Throwable) {
fail(error)
}
}
}
/**
* Records a JSON object as an event at the recording's current position (a capture starting
* over with another configuration, say), and has every stream's clock placed afresh by its
* next chunk: what follows an event is not continuous with what came before.
*/
fun event(json: String) {
lock.withLock {
if (closed) return
try {
for (clock in clocks.values) clock.reset()
if (ensureMetaTrack()) writer.writeText(metaTrack, maxOf(lastTimeMs, writer.durationMs), 1, json)
} catch (error: Throwable) {
fail(error)
}
}
}
/** Completes the file. Returns the recording's length in ms. */
fun finish(): Long {
lock.withLock {
if (!closed) {
closed = true
try {
writer.finish()
} catch (error: Throwable) {
failed = true
logWarn("finishing the recording failed: ${error.message}")
}
}
return writer.durationMs
}
}
private fun fail(error: Throwable) {
failed = true
closed = true
logWarn("recording stopped: ${error.message}")
try {
writer.finish()
} catch (ignored: Throwable) {
// The file is whatever made it to disk.
}
}
private fun ensureMetaTrack(): Boolean {
if (metaTrack == 0) metaTrack = writer.addTextTrack(META_TRACK)
return metaTrack > 0
}
private fun clockFor(chunk: MicChunk): TrackClock? {
val key = (chunk.stream.toLong() shl 48) or (chunk.channels.toLong() shl 32) or chunk.sampleRate.toLong()
clocks[key]?.let { return it }
// The frames track goes in with the first audio track, so it is there for that track's first chunk.
ensureMetaTrack()
// The mixed streams are what a player should pick; a temple's raw pair is for analysis.
val preferred = chunk.stream == MicStream.MONO || chunk.stream == MicStream.MIX
val number = writer.addAudioTrack(MicStream.trackName(chunk.stream), chunk.sampleRate, chunk.channels, preferred)
if (number <= 0) {
logWarn("recording has no room for another track; dropping ${MicStream.trackName(chunk.stream)} audio")
return null
}
return TrackClock(number, chunk.sampleRate).also { clocks[key] = it }
}
/** The chunk's frame-metadata JSON, or null when it has nothing to say beyond its audio. */
private fun metadata(chunk: MicChunk): String? {
if (chunk.stream == MicStream.MIX) return null
if (!chunk.hasDirection && chunk.sequence < 0 && chunk.deviceTickMs < 0 && !chunk.truncated && chunk.lostFramesBefore == 0) return null
val text = StringBuilder(96)
text.append("{\"s\":\"").append(MicStream.key(chunk.stream)).append("\",\"rx\":").append(chunk.timeMs - originMs)
if (chunk.sequence >= 0) text.append(",\"seq\":").append(chunk.sequence)
if (chunk.deviceTickMs >= 0) text.append(",\"tick\":").append(chunk.deviceTickMs)
if (chunk.hasDirection) text.append(",\"angle\":").append(chunk.angleDegrees).append(",\"ssr\":").append(chunk.ssr)
if (chunk.truncated) text.append(",\"trunc\":true")
if (chunk.lostFramesBefore > 0) text.append(",\"lost\":").append(chunk.lostFramesBefore)
return text.append('}').toString()
}
}
/**
* Reads a recording back as the chunks its capture delivered: the "mic" track as [MicStream.MONO]
* chunks and the temple tracks as [MicStream.LEFT] / [MicStream.RIGHT] ones, each with the
* metadata its frame carried. The "mix" track is skipped: a replay derives the feed again. A
* Matroska file from elsewhere plays its first PCM16 track as the mono microphone.
*
* Throws IllegalArgumentException when the file has no audio a replay can use.
*/
class MicRecordingReader(input: SeekableInput) {
companion object {
const val SAMPLE_RATE = 16000
/** Blocks longer than this many frames are handed out in pieces, like a live capture's chunks. */
const val MAX_CHUNK_FRAMES = SAMPLE_RATE / 20
}
private class Meta(val timeMs: Long, val fields: Map<String, Any?>)
private val reader = MkaReader(input)
private val streams = HashMap<Int, Int>()
private var metaTrack = -1
private val pendingMeta = arrayOfNulls<Meta>(MicStream.COUNT)
private val queued = ArrayDeque<MicChunk>()
val durationMs: Long get() = reader.durationMs
/** The capture's "capture.json" attachment, or null. */
val configJson: String? =
reader.attachments.firstOrNull { it.name == MicRecordingWriter.CONFIG_ATTACHMENT }?.data?.decodeToString()
/** What the replay plays, for a status line: "left temple 2ch + right temple 2ch". */
val description: String
init {
try {
val audio = reader.tracks.filter { it.isPcm16 && it.channels in 1..8 }
for (track in audio) {
val stream = MicStream.named(track.name)
if (stream == MicStream.MONO || stream == MicStream.LEFT || stream == MicStream.RIGHT) streams[track.number] = stream
}
if (streams.isEmpty()) {
// Not one of ours: its first usable track stands in for the microphone.
val first = audio.firstOrNull { MicStream.named(it.name) != MicStream.MIX } ?: audio.firstOrNull()
require(first != null) { "no 16-bit PCM audio track" }
streams[first.number] = MicStream.MONO
}
for (number in streams.keys) {
val rate = reader.track(number)!!.sampleRate
require(rate == SAMPLE_RATE) { "unsupported sample rate ($rate Hz; replay needs ${SAMPLE_RATE / 1000} kHz)" }
}
metaTrack = reader.tracks.firstOrNull {
it.type == MkaWriter.TRACK_SUBTITLE && it.name == MicRecordingWriter.META_TRACK
}?.number ?: -1
description = streams.entries.sortedBy { it.value }.joinToString(" + ") { (number, stream) ->
val channels = reader.track(number)!!.channels
MicStream.trackName(stream) + if (channels > 1 || stream != MicStream.MONO) " ${channels}ch" else ""
}
} catch (error: Throwable) {
reader.close()
throw error
}
}
/** Continue from the first chunk at or after [timeMs]. */
fun seekTo(timeMs: Long) {
queued.clear()
pendingMeta.fill(null)
reader.seekTo(timeMs)
}
/** The next chunk in file order, or null at the end. */
fun next(): MicChunk? {
while (queued.isEmpty()) {
val block = reader.next() ?: return null
if (block.track == metaTrack) {
noteMeta(block)
continue
}
val stream = streams[block.track] ?: continue
val track = reader.track(block.track) ?: continue
queueChunks(block, stream, track)
}
return queued.removeFirst()
}
fun close() = reader.close()
private fun noteMeta(block: MkaBlock) {
try {
val fields = Json.parseObject(block.data.decodeToString())
val stream = MicStream.named(fields["s"].asString() ?: return)
if (stream >= 0) pendingMeta[stream] = Meta(block.timeMs, fields)
} catch (ignored: Throwable) {
// An event or a frame we can't read: the audio plays without it.
}
}
private fun queueChunks(block: MkaBlock, stream: Int, track: MkaTrackInfo) {
val sourceChannels = track.channels
val totalFrames = block.data.size / (2 * sourceChannels)
if (totalFrames <= 0) return
// The mixed microphone is one channel however a foreign file stored it.
val channels = if (stream == MicStream.MONO) 1 else sourceChannels
val meta = pendingMeta[stream]?.takeIf { it.timeMs == block.timeMs }
pendingMeta[stream] = null
var start = 0
while (start < totalFrames) {
val frames = minOf(MAX_CHUNK_FRAMES, totalFrames - start)
val pcm = ShortArray(frames * channels)
for (frame in 0 until frames) {
val at = (start + frame) * sourceChannels * 2
if (channels == sourceChannels) {
for (channel in 0 until channels) {
pcm[frame * channels + channel] = AudioSegmentation.pcm16le(block.data[at + channel * 2], block.data[at + channel * 2 + 1])
}
} else {
var sum = 0
for (channel in 0 until sourceChannels) sum += AudioSegmentation.pcm16le(block.data[at + channel * 2], block.data[at + channel * 2 + 1])
pcm[frame] = (sum / sourceChannels).toShort()
}
}
val chunk = MicChunk(stream, channels, track.sampleRate, pcm, frames, block.timeMs + start * 1000L / track.sampleRate)
if (meta != null && start == 0) applyMeta(chunk, meta.fields)
queued.addLast(chunk)
start += frames
}
}
private fun applyMeta(chunk: MicChunk, fields: Map<String, Any?>) {
chunk.sequence = fields["seq"].asInt() ?: -1
chunk.deviceTickMs = fields["tick"].asLong() ?: -1L
val angle = fields["angle"].asInt()
if (angle != null) {
chunk.hasDirection = true
chunk.angleDegrees = angle
chunk.ssr = fields["ssr"].asInt() ?: 0
}
chunk.truncated = fields["trunc"].asBoolean() ?: false
chunk.lostFramesBefore = fields["lost"].asInt() ?: 0
}
}
@@ -35,6 +35,12 @@ interface VoiceCaptureHost {
/** The speaker-embedding model at [modelPath] (may be shared/cached across sessions). */
fun speakerEmbedder(modelPath: String): SpeakerEmbedder
/** The glasses' per-temple microphone channel, or null when there are no glasses that have one. */
fun micArrayLink(): MicArrayLink? = null
/** Opens a recording to replay; throws when it cannot be read. */
fun openRecording(path: String): SeekableInput = openFileInput(path)
}
/**
@@ -44,6 +50,12 @@ interface VoiceCaptureHost {
* REPLACE-semantics partials, and speaker verification at session end. The session owns its
* worker thread (started through the shared [startThread]); listener callbacks go through the
* host's [CallbackDispatcher] so the adapter decides the delivery thread.
*
* Audio comes from one of four sources, chosen at start(): the glasses' stock mixed stream, the
* phone's microphone, the glasses' per-temple microphones ([setMicArray]), or a recording
* played back in real time ([setReplay]). Each delivers [MicChunk]s; a live capture's chunks go
* to the recorder ([setRecorder]) as they came, before any processing, which is what lets a
* replay of the recording run the same processing again.
*/
class VoiceCaptureSession(
private val host: VoiceCaptureHost,
@@ -95,6 +107,19 @@ class VoiceCaptureSession(
const val DEFAULT_VERIFY_THRESHOLD = 0.8f
/** Samples per G2 packet; the decode buffer the worker reuses. */
const val PACKET_SAMPLES = Lc3PacketFramer.SAMPLES_PER_PACKET
// Mic array upkeep: the temples stop streaming unless their lease is renewed, and a
// temple that goes quiet (a lost CONFIGURE, or it restarted) is configured again.
const val ARRAY_CHECK_MS = 1000L
const val ARRAY_RENEW_MS = MicArrayProtocol.LEASE_MS / 3
const val ARRAY_TEMPLE_SILENT_MS = 5000L
const val ARRAY_WAITING_MS = 2000L
const val ARRAY_WAITING_STATUS = "Waiting for the glasses microphones..."
// A replay skips stretches of the recording with no audio longer than this
// (a recording made across a disconnect) instead of sitting through them.
const val REPLAY_MAX_GAP_MS = 2000L
const val REPLAY_POSITION_INTERVAL_MS = 1000L
const val REPLAY_WAIT_SLICE_MS = 20L
const val REPLAY_FINISHED_STATUS = "Replay finished."
/** Joins transcript pieces, attaching leading punctuation to the previous text. */
@JvmStatic
@@ -120,6 +145,8 @@ class VoiceCaptureSession(
CLOUD, // decode locally, emit PCM for a cloud recognizer on the TS side
}
private enum class Source { G2, PHONE, ARRAY, REPLAY }
private class AudioPacket(val data: ByteArray, arm: String?, val arrivalMs: Long) {
val arm: String = arm ?: "?"
}
@@ -137,11 +164,33 @@ class VoiceCaptureSession(
@Volatile
private var workerThreadName: String? = null
// Capture from the phone's own microphone instead of the G2 over BLE
// (preview-only mode). Latched into activePhoneMic at start() (under `lock`)
// (preview-only mode). Latched into activeSource at start() (under `lock`)
// so a mid-session setter call can't switch pipelines underneath the worker.
@Volatile
private var usePhoneMic = false
private var activePhoneMic = false
// What the next capture reads (see start()); latched into activeSource and its
// companions under `lock`, like usePhoneMic.
@Volatile
private var micArrayConfigure: ByteArray? = null
@Volatile
private var replayPath: String? = null
@Volatile
private var replayStartMs = 0L
private var activeSource = Source.G2
private var activeConfigure: ByteArray? = null
private var activeReplayPath: String? = null
private var activeReplayStartMs = 0L
// Replay controls, picked up by the worker between chunks.
@Volatile
private var replaySeekMs = -1L
@Volatile
private var replayPaused = false
@Volatile
private var recorder: MicRecordingWriter? = null
@Volatile
private var mixer: MicArrayMixer = SingleTempleMixer()
private var lastMissingPackets = 0L
private var arrayRateWarned = false
private var mode = Mode.CLOUD
@Volatile
private var onboardModelKind = VoiceModelKind.MOONSHINE
@@ -193,6 +242,47 @@ class VoiceCaptureSession(
this.usePhoneMic = usePhoneMic
}
/**
* Capture the next glasses session from the temples' own microphones instead of the stock
* mixed stream: [configureRecord] is the mic_control CONFIGURE record sent to both temples
* (it decides how many microphones each one streams). Null goes back to the mixed stream.
*/
fun setMicArray(configureRecord: ByteArray?) {
this.micArrayConfigure = if (MicArrayProtocol.isConfigure(configureRecord)) configureRecord else null
}
/** How the temples' chunks become the mono feed that is transcribed. */
fun setMicArrayMixer(mixer: MicArrayMixer) {
this.mixer = mixer
}
/**
* Have the next capture play the recording at [path] from [startMs] in real time, in place
* of any microphone; null goes back to the microphones. A replay needs no glasses.
*/
fun setReplay(path: String?, startMs: Long) {
this.replayPath = path
this.replayStartMs = maxOf(0L, startMs)
}
/** Continue the running replay from [positionMs] into its recording. */
fun seekReplay(positionMs: Long) {
this.replaySeekMs = maxOf(0L, positionMs)
}
/** Hold the running replay where it is, or let it go on. A new capture starts unpaused. */
fun setReplayPaused(paused: Boolean) {
this.replayPaused = paused
}
/**
* Where live captures' chunks are recorded as they arrive, or null. Takes effect at once,
* also mid-capture; the caller finishes the recording. A replay is never recorded.
*/
fun setRecorder(recorder: MicRecordingWriter?) {
this.recorder = recorder
}
fun setOnboardModelKind(kind: String?) {
this.onboardModelKind = parseModelKind(kind)
}
@@ -258,13 +348,26 @@ class VoiceCaptureSession(
emitStopped(captureId)
return
}
if (!usePhoneMic && !host.isG2SessionReady()) {
val path = replayPath
val configure = micArrayConfigure
val source = when {
path != null -> Source.REPLAY
usePhoneMic -> Source.PHONE
configure != null -> Source.ARRAY
else -> Source.G2
}
if ((source == Source.G2 || source == Source.ARRAY) && !host.isG2SessionReady()) {
emitStatus("Voice control needs an active G2 connection.")
emitStopped(captureId)
return
}
mode = parseMode(requestedMode)
activePhoneMic = usePhoneMic
activeSource = source
activeConfigure = configure
activeReplayPath = path
activeReplayStartMs = replayStartMs
replaySeekMs = -1L
replayPaused = false
started = true
audioStarted = false
val finished = Latch(1, platform)
@@ -281,21 +384,22 @@ class VoiceCaptureSession(
*/
fun isCapturing(): Boolean {
var audioUp = false
var phoneMic = false
var source = Source.G2
lock.withLock {
if (!started) {
return false
}
audioUp = audioStarted
phoneMic = activePhoneMic
source = activeSource
}
if (!audioUp) {
// The worker is still bringing the mic up; report it as running so
// a concurrent request shares it instead of restarting it.
return true
}
if (phoneMic) {
// The phone mic has no session to lose the enable to; it runs until stop().
if (source == Source.PHONE || source == Source.REPLAY) {
// Neither has a glasses session to lose the enable to: the phone mic runs
// until stop(), a replay until its recording ends.
return true
}
return host.isG2AudioCaptureActive()
@@ -317,7 +421,7 @@ class VoiceCaptureSession(
finished = workerFinished
workerName = workerThreadName
}
stopG2Audio()
stopSource()
audioQueue.wake()
if (finished != null && (workerName == null || currentThreadName() != workerName)) {
finished.await(1500)
@@ -356,28 +460,62 @@ class VoiceCaptureSession(
val verifying = verifySpeakerModelPath != null && verifyWearerEmbedding != null
verifyBuffer = if (verifying) ShortArray(VERIFY_MAX_SAMPLES) else null
verifyCount = 0
if (activePhoneMic) {
val record = host.openPhoneMic()
if (record == null) {
emitStatus("Could not start the phone microphone.")
return
mixer.reset()
lastMissingPackets = 0
val listening = if (currentMode == Mode.CLOUD) "Listening (cloud)..." else "Listening..."
when (activeSource) {
Source.PHONE -> {
val record = host.openPhoneMic()
if (record == null) {
emitStatus("Could not start the phone microphone.")
return
}
lock.withLock { audioStarted = true }
emitStatus(listening)
try {
processPhoneAudio(record)
} finally {
record.close()
}
}
lock.withLock { audioStarted = true }
emitStatus(if (currentMode == Mode.CLOUD) "Listening (cloud)..." else "Listening...")
try {
processPhoneAudio(record)
} finally {
record.close()
Source.REPLAY -> {
val reader = try {
MicRecordingReader(host.openRecording(activeReplayPath!!))
} catch (error: Throwable) {
emitStatus("Could not open the recording: " + error.message)
emitReplay("error", 0, 0)
return
}
try {
lock.withLock { audioStarted = true }
logInfo("replaying " + reader.description + ", " + formatFixed(reader.durationMs / 1000.0, 1) + " s")
emitStatus(listening)
processReplay(reader)
} finally {
reader.close()
}
}
} else {
packetDecoder = host.createPacketDecoder()
if (!startG2Audio()) {
emitStatus("Could not start G2 microphone input.")
return
Source.ARRAY -> {
val link = host.micArrayLink()
val configure = activeConfigure
if (link == null || configure == null || !startArray(link, configure)) {
emitStatus("Could not start the glasses microphone array.")
return
}
lock.withLock { audioStarted = true }
emitStatus(listening)
processArray(link, configure, listening)
}
Source.G2 -> {
packetDecoder = host.createPacketDecoder()
if (!startG2Audio()) {
emitStatus("Could not start G2 microphone input.")
return
}
lock.withLock { audioStarted = true }
emitStatus(listening)
processG2Audio()
}
lock.withLock { audioStarted = true }
emitStatus(if (currentMode == Mode.CLOUD) "Listening (cloud)..." else "Listening...")
processG2Audio()
}
// Verification result must precede the final transcript so the
// TS bridge can suppress a non-wearer command before it is acted
@@ -392,7 +530,7 @@ class VoiceCaptureSession(
logError("Voice control failed", error)
emitStatus("Voice control failed: " + error.message)
} finally {
stopG2Audio()
stopSource()
releaseRecognizer()
releaseDecoder()
lock.withLock {
@@ -432,23 +570,214 @@ class VoiceCaptureSession(
continue
}
decodedSamples += count.toLong()
// The beam filter drops packets whose firmware direction-of-arrival
// falls outside the listening wedge (isolating the aimed talker for
// every consumer, recognition included); the spectral noise
// suppressor then cleans what remains before it reaches the
// recognizer, cloud PCM, endpointing, or speaker verification.
val angleDegrees = currentDecoder.lastAngleDegrees
val ssr = currentDecoder.lastSsr
if (beamFilterEnabled && ssr > 0 && !withinBeam(angleDegrees)) {
emitFrameMeta(angleDegrees, ssr)
maybeEmitAudioStats(false)
continue
}
processPcmChunk(pcm, count, angleDegrees, ssr, currentDecoder.hasFrameMeta)
val chunk = MicChunk(MicStream.MONO, 1, SAMPLE_RATE, pcm, count, packet.arrivalMs)
chunk.hasDirection = currentDecoder.hasFrameMeta
chunk.angleDegrees = currentDecoder.lastAngleDegrees
chunk.ssr = currentDecoder.lastSsr
// Packets the decoder found missing ahead of this one: a gap in a recording.
val missing = currentDecoder.missingPackets
chunk.lostFramesBefore = ((missing - lastMissingPackets) * currentDecoder.maxSamplesPerPacket).toInt()
lastMissingPackets = missing
handleMonoChunk(chunk)
maybeEmitAudioStats(false)
}
}
/**
* A mixed-microphone chunk from any source: recorded as it came, then on to processing
* unless the beam filter drops it. The filter drops chunks whose firmware
* direction-of-arrival falls outside the listening wedge (isolating the aimed talker for
* every consumer, recognition included); the spectral noise suppressor then cleans what
* remains before it reaches the recognizer, cloud PCM, endpointing, or speaker verification.
*/
private fun handleMonoChunk(chunk: MicChunk) {
recordChunk(chunk)
if (beamFilterEnabled && chunk.ssr > 0 && !withinBeam(chunk.angleDegrees)) {
emitFrameMeta(chunk.angleDegrees, chunk.ssr)
return
}
processPcmChunk(chunk.pcm, chunk.frames, chunk.angleDegrees, chunk.ssr, chunk.hasDirection)
}
/**
* A chunk of one temple's own microphones: recorded as it came, then mixed into the mono
* feed, which is recorded too (as what was transcribed) and processed like a mixed chunk.
* The beam filter does not apply: a temple's bearing is along its own pair, not the
* head-frame direction the filter is aimed in.
*/
private fun handleArrayChunk(chunk: MicChunk) {
recordChunk(chunk)
val feed = mixer.mix(chunk) ?: return
recordChunk(feed)
if (feed.sampleRate != SAMPLE_RATE || feed.channels != 1) {
if (!arrayRateWarned) logWarn("mic array feed is ${feed.channels}ch ${feed.sampleRate} Hz; recognition needs mono $SAMPLE_RATE Hz")
arrayRateWarned = true
return
}
processPcmChunk(feed.pcm, feed.frames, feed.angleDegrees, feed.ssr, feed.hasDirection)
}
private fun recordChunk(chunk: MicChunk) {
if (activeSource != Source.REPLAY) recorder?.write(chunk)
}
private fun handleChunk(chunk: MicChunk) {
if (chunk.stream == MicStream.MONO) handleMonoChunk(chunk) else handleArrayChunk(chunk)
}
private fun startArray(link: MicArrayLink, configure: ByteArray): Boolean {
resetAudioStats()
audioQueue.clear()
if (!startArrayForwarding(link)) return false
return link.sendControl(configure, "configure", true, true)
}
private fun startArrayForwarding(link: MicArrayLink): Boolean =
link.startForwarding(object : FaceclawAudioPacketListener {
override fun onAudioPacket(data: ByteArray?, arm: String?, arrivalMs: Long) {
queueAudioPacket(data, arm, arrivalMs)
}
})
/**
* Mic array capture loop: each temple's 'SM' frames become chunks of that temple's stream.
* Between frames it keeps the streams alive: renews the temples' lease, configures a temple
* again when it has gone quiet, and takes forwarding back when the glasses session dropped it.
*/
private fun processArray(link: MicArrayLink, configure: ByteArray, listening: String) {
val startedAt = platform.elapsedRealtimeMs()
var checkedAt = startedAt
var renewedAt = startedAt
// Left, right.
val armedAt = longArrayOf(startedAt, startedAt)
val frameAt = longArrayOf(startedAt, startedAt)
var waiting = false
while (started) {
val packet = takeAudioPacket()
val now = platform.elapsedRealtimeMs()
if (packet != null) {
val side = if (packet.arm == "L") 0 else if (packet.arm == "R") 1 else -1
val frame = if (side >= 0) MicArrayProtocol.decodeFrame(packet.data) else null
val pcm = if (frame != null) MicArrayProtocol.pcm16(packet.data, frame) else null
// Anything else is a stock-format packet from before arming took effect.
if (frame != null && pcm != null) {
frameAt[side] = now
val frames = pcm.size / frame.channels
decodedSamples += frames.toLong()
val stream = if (side == 0) MicStream.LEFT else MicStream.RIGHT
val chunk = MicChunk(stream, frame.channels, frame.sampleRate, pcm, frames, packet.arrivalMs)
chunk.hasDirection = frame.angleDegrees != 0 || frame.ssr != 0
chunk.angleDegrees = frame.angleDegrees
chunk.ssr = frame.ssr
chunk.sequence = frame.sequence
chunk.deviceTickMs = frame.deviceTickMs
chunk.truncated = frame.truncated
handleArrayChunk(chunk)
}
}
if (now - checkedAt >= ARRAY_CHECK_MS) {
checkedAt = now
if (!link.isForwarding()) {
if (host.isG2SessionReady() && startArrayForwarding(link) && link.sendControl(configure, "configure", true, true)) {
logInfo("mic array forwarding re-established")
armedAt.fill(now)
renewedAt = now
}
} else {
if (now - renewedAt >= ARRAY_RENEW_MS) {
link.sendControl(MicArrayProtocol.control(MicArrayProtocol.OP_RENEW), "renew", true, true)
renewedAt = now
}
for (side in 0..1) {
if (now - maxOf(frameAt[side], armedAt[side]) < ARRAY_TEMPLE_SILENT_MS) continue
logWarn("mic array: " + (if (side == 0) "left" else "right") + " temple silent; configuring it again")
link.sendControl(configure, "configure-" + (if (side == 0) "left" else "right"), side == 1, side == 0)
armedAt[side] = now
}
}
val silent = now - maxOf(frameAt[0], frameAt[1]) >= ARRAY_WAITING_MS
if (silent != waiting) {
waiting = silent
emitStatus(if (silent) ARRAY_WAITING_STATUS else listening)
}
}
maybeEmitAudioStats(false)
}
}
/**
* Replay loop: hands the recording's chunks to the pipeline at the pace they were captured,
* so recognition (its partials, a cloud provider's stream) sees what a live capture would.
* Jumps and pauses asked for from outside take effect between chunks.
*/
private fun processReplay(reader: MicRecordingReader) {
val duration = reader.durationMs
var position = minOf(activeReplayStartMs, duration)
reader.seekTo(position)
emitReplay("start", position, duration)
var reportedAt = position
// Wall-clock time at which file time `anchorFile` plays; unset after a jump, pause or gap.
var anchorWall = -1L
var anchorFile = 0L
var pending: MicChunk? = null
while (started) {
val seek = replaySeekMs
if (seek >= 0) {
replaySeekMs = -1L
// What played so far is a finished utterance; the rest starts clean.
finishReplayedUtterance()
position = minOf(seek, duration)
reader.seekTo(position)
pending = null
anchorWall = -1L
reportedAt = position
emitReplay("seek", position, duration)
}
if (replayPaused) {
anchorWall = -1L
sleepMs(REPLAY_WAIT_SLICE_MS)
continue
}
val chunk = pending ?: reader.next()
if (chunk == null) {
emitReplay("end", duration, duration)
emitStatus(REPLAY_FINISHED_STATUS)
return
}
pending = chunk
val now = platform.elapsedRealtimeMs()
if (anchorWall < 0 || chunk.timeMs - position > REPLAY_MAX_GAP_MS) {
anchorWall = now
anchorFile = chunk.timeMs
}
val wait = anchorWall + (chunk.timeMs - anchorFile) - now
if (wait > 0) {
// Short slices, so a stop, jump or pause is noticed promptly.
sleepMs(minOf(wait, REPLAY_WAIT_SLICE_MS))
continue
}
pending = null
position = chunk.timeMs
decodedSamples += chunk.frames.toLong()
handleChunk(chunk)
if (position - reportedAt >= REPLAY_POSITION_INTERVAL_MS) {
reportedAt = position
emitReplay("position", position, duration)
}
}
}
/** Ends the utterance a replay was in the middle of when it jumped, so the audio on both sides isn't joined. */
private fun finishReplayedUtterance() {
mixer.reset()
endpointDetector.reset()
suppressor?.reset()
if (mode != Mode.ONBOARD) return
decodeTranscript(true)
resetTranscriptState()
lastTranscript = ""
}
/**
* Per-chunk processing shared by the G2 and phone-mic paths, downstream of
* decode and the beam filter. hasFrameMeta is false for the phone mic,
@@ -495,7 +824,7 @@ class VoiceCaptureSession(
continue
}
decodedSamples += read.toLong()
processPcmChunk(pcm, read, 0, 0, false)
handleMonoChunk(MicChunk(MicStream.MONO, 1, SAMPLE_RATE, pcm, read, platform.elapsedRealtimeMs()))
}
}
@@ -681,6 +1010,11 @@ class VoiceCaptureSession(
host.dispatcher.post { currentListener.onFrameMeta(angleDegrees, ssr) }
}
private fun emitReplay(event: String, positionMs: Long, durationMs: Long) {
val currentListener = listener ?: return
host.dispatcher.post { currentListener.onReplay(event, positionMs, durationMs) }
}
private fun emitSpeechEnd() {
val currentListener = listener ?: return
host.dispatcher.post { currentListener.onSpeechEnd() }
@@ -691,8 +1025,21 @@ class VoiceCaptureSession(
host.dispatcher.post { currentListener.onStopped(captureId) }
}
private fun stopG2Audio() {
host.g2AudioSource()?.stop()
/**
* Release what the running capture's source holds on the glasses. Runs on stop() and again
* as the worker winds down (it may have started the source after stop() looked), so
* everything here is safe to repeat.
*/
private fun stopSource() {
val source = lock.withLock { activeSource }
when (source) {
Source.G2 -> host.g2AudioSource()?.stop()
Source.ARRAY -> host.micArrayLink()?.let { link ->
link.sendControl(MicArrayProtocol.control(MicArrayProtocol.OP_STOP), "stop", true, true)
link.stopForwarding()
}
Source.PHONE, Source.REPLAY -> {}
}
maybeEmitAudioStats(true)
}
@@ -711,7 +1058,7 @@ class VoiceCaptureSession(
if (!started || data == null) {
return
}
if ("L" != arm) {
if ("L" != arm && activeSource != Source.ARRAY) {
wrongArmPackets++
}
audioQueue.put(AudioPacket(data, arm, arrivalMs)) {
@@ -67,6 +67,24 @@ interface PacketAudioSource {
fun isActive(): Boolean
}
/**
* The custom firmware's mic_control channel on a glasses session: each temple streams its own
* microphones as 'SM' frames (see [MicArrayProtocol]) on the characteristic the stock mixed
* stream uses, while it holds a configuration that the phone keeps renewing.
*/
interface MicArrayLink {
/** Deliver the audio characteristic's packets to [listener]; false when no session is up. */
fun startForwarding(listener: FaceclawAudioPacketListener): Boolean
fun stopForwarding()
/** Whether forwarding still holds: it lives in the glasses session, which can drop it. */
fun isForwarding(): Boolean
/** Queue a control record for the chosen temples; false when nothing was queued. */
fun sendControl(record: ByteArray, label: String, rightTemple: Boolean, leftTemple: Boolean): Boolean
}
/** The phone's own microphone delivering 16 kHz mono PCM16 in blocking reads. */
interface PcmAudioSource {
/** Blocking read into [pcm]; returns samples read, 0 to retry, or a negative error. */
@@ -3,6 +3,8 @@ package com.faceclaw.app
/**
* Receives IMU (accelerometer) readings decoded from the glasses' sys-event stream. Registered on
* FaceclawBleCommunicator via addImuListener; callbacks are delivered on the Android main thread.
* x, y, z are in g, in the canonical frame of every glasses model (+x forward, +y left, +z up;
* see ImuOrientation).
*/
interface FaceclawImuListener {
fun onImuData(x: Double, y: Double, z: Double, eventSource: Int): Unit
@@ -0,0 +1,10 @@
package com.faceclaw.app
interface FaceclawKeyboardEventListener {
/**
* One CFW keyboard-bridge record (settings field 131) from the glasses: the raw
* ['K','B',ver,kind,...] bytes, possibly one fragment of a longer record. Decoded and
* reassembled on the TS side (app/g2/keyboard/protocol.ts). Delivered in arrival order.
*/
fun onKeyboardEvent(body: ByteArray?): Unit
}
@@ -41,4 +41,13 @@ interface FaceclawVoiceControllerListener {
* speaker model could not be loaded.
*/
fun onSpeakerVerified(isWearer: Boolean, similarity: Float): Unit
/**
* Progress of a capture that replays a recording (see VoiceCaptureSession.setReplay):
* "start" once the file is open, "position" about once per second of it played, "seek" after
* a jump took effect (the transcript of what played before it has been emitted as final),
* "end" when the file ran out, and "error" when it could not be opened (the status says
* why). Positions are milliseconds into the file.
*/
fun onReplay(event: String?, positionMs: Long, durationMs: Long): Unit
}
@@ -119,6 +119,19 @@ class BleProtocol {
*/
const val FACECLAW_ALS_REPORT_FIELD: Int = 105
/**
* CFW keyboard bridge (Faceclaw/39): the master temple hosts one BLE HID keyboard. The
* host writes ['K','B',ver,op,request,epoch,...] controls as settings field 130; results,
* pairing prompts and the keyboard's raw input reports come back as commandId=3 pushes
* carrying field 131 (['K','B',ver,kind,...], decoded in app/g2/keyboard/protocol.ts).
*/
const val FACECLAW_KEYBOARD_CONTROL_FIELD: Int = 130
const val FACECLAW_KEYBOARD_EVENT_FIELD: Int = 131
/** Fixed header of a field-131 record; fragments follow it. */
const val FACECLAW_KEYBOARD_EVENT_HEADER: Int = 24
const val FACECLAW_WAKE_OP_ACQUIRE: Int = 1
const val FACECLAW_WAKE_OP_RELEASE: Int = 2
@@ -497,6 +510,70 @@ class BleProtocol {
)
}
// Field numbers from g2_setting.proto (package g2.g2_setting; see g2-kit-unofficial
// ble/gen/g2_setting_pb.ts), named after the schema fields.
/** G2SettingPackage.commandId */
private const val G2_SETTING_PACKAGE_COMMAND_ID: Int = 1
/** G2SettingPackage.magicRandom */
private const val G2_SETTING_PACKAGE_MAGIC_RANDOM: Int = 2
/** G2SettingPackage.deviceReceiveInfoFromApp */
private const val G2_SETTING_PACKAGE_DEVICE_RECEIVE_INFO_FROM_APP: Int = 3
/** G2SettingPackage.deviceReceiveRequestFromApp (the settings-read reply) */
private const val G2_SETTING_PACKAGE_DEVICE_RECEIVE_REQUEST_FROM_APP: Int = 4
/** g2_settingCommandId.DeviceReceiveInfo */
private const val G2_SETTING_COMMAND_DEVICE_RECEIVE_INFO: Int = 1
/** DeviceReceiveInfoFromAPP.deviceReceiveHeadUpSetting */
private const val DEVICE_RECEIVE_INFO_HEAD_UP_SETTING: Int = 4
/** DeviceReceiveRequestFromAPP.headUpSwitchRestored */
private const val DEVICE_RECEIVE_REQUEST_HEAD_UP_SWITCH_RESTORED: Int = 7
/** DeviceReceiveRequestFromAPP.headUpAngleRestored */
private const val DEVICE_RECEIVE_REQUEST_HEAD_UP_ANGLE_RESTORED: Int = 8
/** DeviceReceiveRequestFromAPP.headUpAngleCalibrationRestored */
private const val DEVICE_RECEIVE_REQUEST_HEAD_UP_CALIBRATION_RESTORED: Int = 9
/**
* One head-up (look-up wake) setting: DeviceReceiveInfoFromAPP.deviceReceiveHeadUpSetting,
* a DeviceReceive_Head_UP_Setting carrying one of headUpSwitch, headUpAngle,
* headUpCalibrationSwitch or headUpCalibration ([field] is one of the HEAD_UP_FIELD_*).
* The firmware treats that submessage as a oneof: setting_handle_head_up_setting
* (2.3.0.24, 0x46c39a) receives a single {field, value} and applies it, so the switch and
* the angle go out as separate packages. headUpCalibration is not stored from the
* phone; it is the pitch the glasses measured on their own calibration screen. The
* effective trigger pitch is angle + calibration, clamped to -90..90 and accepted only in
* 1..90 (SVC_Settings_HeadUpConfig 0x470580, DRV_IMUHUDParameterConfig). The angle is a
* uint32 on the wire but used as a signed int, so a negative offset is sent as its
* 32-bit two's complement.
*/
@JvmStatic
fun buildSetHeadUp(magic: Int, field: Int, value: Int): ByteArray {
var headUp: ByteArray = concat(CollectionUtils.listOf(encodeKey(field, 0), encodeUint32(value)))
return concat(
CollectionUtils.listOf(
encodeVarintField(G2_SETTING_PACKAGE_COMMAND_ID, G2_SETTING_COMMAND_DEVICE_RECEIVE_INFO),
encodeVarintField(G2_SETTING_PACKAGE_MAGIC_RANDOM, magic),
encodeMessageField(
G2_SETTING_PACKAGE_DEVICE_RECEIVE_INFO_FROM_APP,
encodeMessageField(DEVICE_RECEIVE_INFO_HEAD_UP_SETTING, headUp),
),
)
)
}
/** DeviceReceive_Head_UP_Setting.headUpSwitch */
const val HEAD_UP_FIELD_SWITCH: Int = 1
/** DeviceReceive_Head_UP_Setting.headUpAngle */
const val HEAD_UP_FIELD_ANGLE: Int = 2
/** Enable the firmware's wear detector (DeviceReceiveInfoFromAPP field 5). */
@JvmStatic
fun buildSetWearDetection(magic: Int, enabled: Boolean): ByteArray {
@@ -724,6 +801,42 @@ class BleProtocol {
return body
}
/**
* Wrap an already-encoded ['K','B',ver,op,...] keyboard control as a settings write
* carrying CFW field 130. Magic zero, like the other private controls: the answer is a
* field-131 record naming the control's request id, not the settings ACK.
*/
@JvmStatic
fun buildFaceclawKeyboardControl(record: ByteArray): ByteArray {
return concat(
CollectionUtils.listOf(
encodeVarintField(1, 1),
encodeVarintField(2, 0),
encodeBytesField(FACECLAW_KEYBOARD_CONTROL_FIELD, record),
)
)
}
/**
* Extract a CFW keyboard record (field 131) from a settings frame, or null when the frame
* carries none. Only the ['K','B'] prelude and the fixed header's length are checked
* here; the TS side validates the version and decodes the rest.
*/
@JvmStatic
fun parseFaceclawKeyboardEvent(pb: ByteArray?): ByteArray? {
if (pb == null) {
return null
}
val body = readFieldBytes(stripTrailingCrc(pb), FACECLAW_KEYBOARD_EVENT_FIELD)
if (
body == null || body.size < FACECLAW_KEYBOARD_EVENT_HEADER ||
body[0].toInt() != 75 || body[1].toInt() != 66
) {
return null
}
return body
}
/**
* Return the raw CFW ambient-light report from a sid-0x09 frame, or null when this is an
* ordinary settings frame. Only the 65.toByte(),76.toByte(),version prelude is validated
@@ -905,6 +1018,26 @@ class BleProtocol {
return BatterySnapshot(battery, charging, silentMode)
}
/**
* The head-up settings in a settings READ ack: deviceReceiveRequestFromApp (field 4)
* headUpSwitchRestored=7, headUpAngleRestored=8, headUpAngleCalibrationRestored=9.
* Returns null when the ack has no request submessage. Absent fields (proto3 drops
* zeros) read as 0; angle and calibration are signed ints carried as uint32.
*/
@JvmStatic
fun parseSettingsHeadUp(pb: ByteArray): IntArray? {
var root: ByteArray = stripTrailingCrc(pb)
var request: ByteArray? = readFieldBytes(root, G2_SETTING_PACKAGE_DEVICE_RECEIVE_REQUEST_FROM_APP)
if ((request == null)) {
return null
}
return intArrayOf(
readVarintFieldValue(request, DEVICE_RECEIVE_REQUEST_HEAD_UP_SWITCH_RESTORED, 0),
readVarintFieldValue(request, DEVICE_RECEIVE_REQUEST_HEAD_UP_ANGLE_RESTORED, 0),
readVarintFieldValue(request, DEVICE_RECEIVE_REQUEST_HEAD_UP_CALIBRATION_RESTORED, 0),
)
}
/** GlassesCaseDataPackage{commandId=CASE_INFO, magicRandom, caseInfo={}}, as the Even app sends it. */
@JvmStatic
fun buildCaseInfoQuery(magic: Int): ByteArray {
@@ -1089,6 +1222,18 @@ class BleProtocol {
return out.toByteArray()
}
/** A varint of the value's 32-bit two's complement (encodeVarint stops short on negatives). */
private fun encodeUint32(value: Int): ByteArray {
var out: ByteSink = ByteSink()
var v: Long = (value.toLong() and 0xffffffffL)
while ((v >= 0x80L)) {
out.write((((v and 0x7fL).toInt()) or 0x80))
v = (v ushr 7)
}
out.write(v.toInt())
return out.toByteArray()
}
private fun crcBytesLe(data: ByteArray): ByteArray {
var crc: Int = 0xffff
for (b in data) {
@@ -188,6 +188,22 @@ class MessageBuilder {
)
}
/** One head-up setting field (see BleProtocol.buildSetHeadUp). */
fun setHeadUp(field: Int, value: Int): OutboundMessage {
var magic: Int = magicPool.allocate()
return OutboundMessage(
"head-up-control",
("head-up field " + field + "=" + value),
BleProtocol.SID_UI_SETTING,
BleProtocol.FLAG_REQUEST,
magic,
BleProtocol.buildSetHeadUp(magic, field, value),
ACK_TIMEOUT_MS,
-1,
false,
)
}
fun createLayout(): OutboundMessage {
var magic: Int = magicPool.allocate()
return OutboundMessage(
@@ -321,6 +337,24 @@ class MessageBuilder {
)
}
/**
* CFW keyboard control (settings field 130). Always the right arm: only the master temple
* acts on it, and a copy sent down each arm would run the control twice.
*/
fun faceclawKeyboardControl(record: ByteArray, label: String): OutboundMessage {
return OutboundMessage(
"keyboard-control",
"keyboard control $label",
BleProtocol.SID_UI_SETTING,
BleProtocol.FLAG_REQUEST,
0,
BleProtocol.buildFaceclawKeyboardControl(record),
ACK_TIMEOUT_MS,
-1,
false,
)
}
fun faceclawWearQuery(leftArm: Boolean): OutboundMessage {
return OutboundMessage(
"wear-query-control",
@@ -506,6 +506,9 @@ internal fun GlassesSessionCore.scheduleReconnectLocked(sessionWasReady: Boolean
internal fun GlassesSessionCore.resetSessionStateLocked() {
ringBattery = -1
ringCharging = -1
headUpSwitch = -1
headUpReadAtMs = 0L
headUpVerifyPending = false
directRingBattery = -1
directRingCharging = -1
sessionReady = false
@@ -583,6 +586,22 @@ internal fun GlassesSessionCore.emitMicStatus(body: ByteArray, address: String)
}
}
internal fun GlassesSessionCore.emitKeyboardEvent(body: ByteArray) {
if (keyboardEventListeners.isEmpty()) {
return
}
val copy = body.copyOf()
host.postToMain {
for (keyboardListener in keyboardEventListeners) {
try {
keyboardListener.onKeyboardEvent(copy)
} catch (t: Throwable) {
logWarn("keyboard event listener failed", t)
}
}
}
}
internal fun GlassesSessionCore.emitAudioMonitorPacket(data: ByteArray, arm: String, arrivalMs: Long) {
if (audioMonitorListeners.isEmpty()) {
return
@@ -634,14 +653,16 @@ internal fun GlassesSessionCore.finishFrame(frameId: Int, outcome: String) {
}
}
/** [x], [y], [z] as the hardware reports them; listeners get them in [ImuOrientation]'s frame. */
internal fun GlassesSessionCore.emitImuData(x: Double, y: Double, z: Double, eventSource: Int) {
if (imuListeners.isEmpty()) {
return
}
val (cx, cy, cz) = ImuOrientation.toCanonical(glassesType, x, y, z)
host.postToMain {
for (imuListener in imuListeners) {
try {
imuListener.onImuData(x, y, z, eventSource)
imuListener.onImuData(cx, cy, cz, eventSource)
} catch (t: Throwable) {
logWarn("listener onImuData failed", t)
}
@@ -131,6 +131,7 @@ class GlassesSessionCore(
internal val compassSubscriptions = CopyOnWriteList<CompassSubscription>(platform)
internal val ambientLightListeners = CopyOnWriteList<FaceclawAmbientLightListener>(platform)
internal val micStatusListeners = CopyOnWriteList<FaceclawMicStatusListener>(platform)
internal val keyboardEventListeners = CopyOnWriteList<FaceclawKeyboardEventListener>(platform)
internal val audioMonitorListeners = CopyOnWriteList<FaceclawAudioPacketListener>(platform)
@Volatile internal var running = false
@Volatile internal var userDisconnectRequested = false
@@ -357,6 +358,26 @@ class GlassesSessionCore(
internal var lastGlassesRingInputAtMs = 0L
internal var lastGlassesRingInputLabel = ""
internal var lastGlassesRingBatteryAtMs = 0L
// Head-up (look-up wake) state from settings reads: -1 switch = not read yet.
internal var headUpSwitch = -1
internal var headUpAngle = 0
internal var headUpCalibration = 0
internal var headUpReadAtMs = 0L
// The trigger pitch TS asked for (degrees, 1..90), or -1 to leave the glasses'
// own setting alone. Reapplied after every read that disagrees with it.
internal var desiredHeadUpTrigger = -1
// The glasses' own switch and angle from before Faceclaw first changed them
// (switch -1 = unknown): captured before the first write, or handed back by TS,
// which persists them across app restarts. Written back while
// headUpRestorePending (TS stopped managing the trigger), then forgotten once a
// read confirms them.
internal var headUpOriginalSwitch = -1
internal var headUpOriginalAngle = 0
internal var headUpRestorePending = false
// Set after queueing a correction so the next settings read comes right away to
// confirm it; cleared by that read, so a firmware that refuses the value is
// retried on the normal poll cadence, not in a loop.
internal var headUpVerifyPending = false
internal var ringConnectedChangedAtMs = 0L
internal var ringConnectCount = 0
internal var lastDirectRingError = ""
@@ -1015,6 +1036,61 @@ class GlassesSessionCore(
interruptibleSleep.interrupt()
}
/**
* Set the pitch (degrees, 1..90) at which looking up wakes the display, or 0 to stop
* managing it. Kept for the life of this object and reapplied on every connection: the
* next settings read supplies the glasses' calibration, then the switch and angle are
* written (see reconcileHeadUpLocked) and a follow-up read confirms them.
*
* [originalSwitch] (0/1, or -1 when unknown) and [originalAngle] are the glasses' own
* values from before Faceclaw changed them, as TS saved them from getHeadUpStatus; they
* take precedence over what this object captured. With degrees 0 they are written back.
*/
fun setHeadUpTrigger(degrees: Int, originalSwitch: Int, originalAngle: Int) {
monitor.withLock {
if (originalSwitch in 0..1) {
headUpOriginalSwitch = originalSwitch
headUpOriginalAngle = originalAngle
}
// A change of mind drops writes still queued for the previous value.
clearMessagesOfKindLocked("head-up-control")
headUpVerifyPending = false
desiredHeadUpTrigger = if (degrees in 1..90) degrees else -1
headUpRestorePending = desiredHeadUpTrigger < 0 && headUpOriginalSwitch >= 0
logLine(when {
desiredHeadUpTrigger > 0 -> "head-up trigger requested: ${desiredHeadUpTrigger}°"
headUpRestorePending -> "head-up trigger: restore the glasses' own " +
"(switch=$headUpOriginalSwitch angle=$headUpOriginalAngle)"
else -> "head-up trigger: left to the glasses"
})
if (!running || !sessionReady) return
if (desiredHeadUpTrigger <= 0 && !headUpRestorePending) return
if (headUpSwitch >= 0) {
applyHeadUpLocked(verifying = false)
} else {
// Calibration unknown: read the settings first; the ack applies the trigger.
lastBatteryRefreshAtMs = 0L
}
}
interruptibleSleep.interrupt()
}
/** Head-up settings as last read, as JSON (switch -1 = not read on this connection). */
fun getHeadUpStatus(): String {
monitor.withLock {
val status = linkedMapOf<String, Any?>()
status["switch"] = headUpSwitch
status["angle"] = headUpAngle
status["calibration"] = headUpCalibration
status["desired"] = desiredHeadUpTrigger
status["originalSwitch"] = headUpOriginalSwitch
status["originalAngle"] = headUpOriginalAngle
status["restorePending"] = headUpRestorePending
status["readAgeMs"] = if (headUpReadAtMs == 0L) -1L else maxOf(0L, now() - headUpReadAtMs)
return try { Json.write(status) } catch (e: Exception) { "{}" }
}
}
// ---------------------------------------------------------------------
// Bandwidth benchmark
@@ -1388,6 +1464,39 @@ class GlassesSessionCore(
return true
}
fun addKeyboardEventListener(listener: FaceclawKeyboardEventListener?) {
if (listener != null) {
keyboardEventListeners.add(listener)
}
}
fun removeKeyboardEventListener(listener: FaceclawKeyboardEventListener?) {
if (listener != null) {
keyboardEventListeners.remove(listener)
}
}
/**
* Queue a CFW keyboard-bridge control (['K','B',ver,op,request,epoch,...]) as a settings
* field-130 write to the right temple. Fire-and-forget: the firmware answers with field-131
* records, which arrive through addKeyboardEventListener. Returns false when nothing was
* queued (not a G2, no session, or a malformed record).
*/
fun sendFaceclawKeyboardControl(record: ByteArray?, label: String): Boolean {
if (!isG2 || record == null || record.size < 8) {
return false
}
monitor.withLock {
if (!running || !sessionReady) {
logLine("skip keyboard control ($label); session not ready")
return false
}
pendingMessages.addLast(messageBuilder.faceclawKeyboardControl(record, label))
}
interruptibleSleep.interrupt()
return true
}
/**
* Forward render-characteristic audio packets to the listener WITHOUT
* sending the stock EvenHub audio-control enable. Used for the CFW
@@ -1894,6 +2003,18 @@ class GlassesSessionCore(
}
logDebug("onNotification: address=" + address + " characteristicUuid=" + characteristicUuid + " data.length=" + data.size)
val frame = BleProtocol.parseFrame(data)
if (frame.ok && frame.sid == BleProtocol.SID_UI_SETTING) {
// CFW keyboard-bridge records (field 131) come from whichever temple hosts the
// keyboard. They are their own stream: neither an ACK nor glasses input, and the
// once-a-second status record among them must not count as user activity (which
// would hold off battery polling).
val keyboardEvent = BleProtocol.parseFaceclawKeyboardEvent(frame.pb)
if (keyboardEvent != null) {
monitor.withLock { lastIncomingAtMs = now() }
emitKeyboardEvent(keyboardEvent)
return
}
}
val decodedWearState = BleProtocol.parseWearState(frame)
val compassEvent = if (address.equals(rightAddress, ignoreCase = true))
BleProtocol.parseCompassEvent(frame)
@@ -2061,11 +2182,10 @@ class GlassesSessionCore(
} else if (decoded != null
&& "sys-event" == decoded.kind
&& decoded.eventType == BleProtocol.EVENT_HEAD_DOWN) {
// Faceclaw/38 also forwards the head coming back down. Nothing
// uses it yet; as an unknown input it would count as activity
// and keep the screen awake, so drop it here.
logLine("head-down forwarded by CFW (ignored)")
decoded = null
// Faceclaw/38 also forwards the head coming back down. TS uses
// it to end a head-tilt Glanceboard and otherwise drops it
// before the shell, so it never counts as activity.
logLine("head-down forwarded by CFW")
}
event = decoded
if (decoded != null) {
@@ -299,7 +299,8 @@ internal fun GlassesSessionCore.g1StopAudioCapture() {
}
/**
* There is no magnetometer on a G1, only the accelerometer and gyroscope: x, y, z in g, head frame, from the right arm.
* There is no magnetometer on a G1, only the accelerometer and gyroscope: x, y, z in g from the right arm, in the
* G1's own axes, which [emitImuData] rotates into the G2's ([ImuOrientation]).
* [enable] raises the sample rate and polls it; [g1MaxSleepMs] follows.
*/
internal fun GlassesSessionCore.g1SetImuReport(enable: Boolean) {
@@ -1078,6 +1078,85 @@ internal fun GlassesSessionCore.shouldPollBatteryLocked(now: Long): Boolean {
&& (lastBatteryRefreshAtMs == 0L || now - lastBatteryRefreshAtMs >= ConnectionOptions.BATTERY_REFRESH_INTERVAL_MS)
}
/**
* Bring the glasses' head-up trigger to [GlassesSessionCore.desiredHeadUpTrigger] after a settings
* read: switch on, then angle = trigger - calibration (the firmware adds its stored calibration).
*/
internal fun GlassesSessionCore.reconcileHeadUpLocked(ackPayload: ByteArray?) {
val verifying = headUpVerifyPending
headUpVerifyPending = false
val headUp = if (ackPayload == null) null else BleProtocol.parseSettingsHeadUp(ackPayload)
if (headUp != null) {
headUpSwitch = headUp[0]
headUpAngle = headUp[1]
headUpCalibration = headUp[2]
headUpReadAtMs = now()
}
if (headUpSwitch < 0 || !sessionReady) return
applyHeadUpLocked(verifying)
}
/**
* Compare the last read with what is wanted (the trigger, or the glasses' original values
* while a restore is pending) and queue writes when they differ. After a verifying read
* that still disagrees nothing is queued: the next regular poll retries, so a firmware
* that clamps or refuses the value costs one attempt per poll interval, not a write loop.
*/
internal fun GlassesSessionCore.applyHeadUpLocked(verifying: Boolean) {
val desired = desiredHeadUpTrigger
val wantSwitch: Int
val wantAngle: Int
if (desired > 0) {
wantSwitch = 1
wantAngle = desired - headUpCalibration
} else if (headUpRestorePending) {
wantSwitch = headUpOriginalSwitch
wantAngle = headUpOriginalAngle
} else {
return
}
if (headUpSwitch == wantSwitch && headUpAngle == wantAngle) {
if (desired > 0) {
if (verifying) logLine("head-up trigger confirmed: ${desired}° (angle $wantAngle + calibration $headUpCalibration)")
} else {
logLine("head-up setting restored (switch=$wantSwitch angle=$wantAngle)")
headUpRestorePending = false
headUpOriginalSwitch = -1
headUpOriginalAngle = 0
}
return
}
if (verifying) {
logLine("head-up setting not applied yet (switch=$headUpSwitch angle=$headUpAngle); retrying on next poll")
return
}
if (desired > 0 && headUpOriginalSwitch < 0) {
headUpOriginalSwitch = headUpSwitch
headUpOriginalAngle = headUpAngle
logLine("head-up original saved (switch=$headUpSwitch angle=$headUpAngle)")
}
queueHeadUpWritesLocked(wantSwitch, wantAngle)
}
internal fun GlassesSessionCore.queueHeadUpWritesLocked(switch: Int, angle: Int) {
clearMessagesOfKindLocked("head-up-control")
val sw = messageBuilder.setHeadUp(BleProtocol.HEAD_UP_FIELD_SWITCH, switch)
sw.onTimeout = MessageCallback { logLine("head-up switch ack timeout") }
val set = messageBuilder.setHeadUp(BleProtocol.HEAD_UP_FIELD_ANGLE, angle)
set.onTimeout = MessageCallback { logLine("head-up angle ack timeout") }
// Switch on before the angle; when switching off, the angle goes first.
if (switch == 1) {
pendingMessages.addLast(sw)
pendingMessages.addLast(set)
} else {
pendingMessages.addLast(set)
pendingMessages.addLast(sw)
}
headUpVerifyPending = true
lastBatteryRefreshAtMs = 0L
logLine("queue head-up switch $switch + angle $angle (trigger ${desiredHeadUpTrigger}°, calibration $headUpCalibration)")
}
internal fun GlassesSessionCore.createBatteryQueryMessageLocked(): OutboundMessage {
val message = messageBuilder.batteryQuery()
message.onAck = MessageCallback {
@@ -1086,6 +1165,7 @@ internal fun GlassesSessionCore.createBatteryQueryMessageLocked(): OutboundMessa
ringBattery = if (ring == null) -1 else ring.battery
ringCharging = if (ring == null) -1 else ring.charging
if (ringBattery >= 0) releaseRingFromGlassesLocked("glasses report the ring connected")
reconcileHeadUpLocked(message.ackPayload)
val snapshot = BleProtocol.parseSettingsBattery(message.ackPayload)
if (snapshot != null) {
headsetBattery = snapshot.battery
@@ -0,0 +1,29 @@
package com.faceclaw.app
/**
* Faceclaw's accelerometer frame. Every model's samples are rotated into it before they reach a
* FaceclawImuListener ([GlassesSessionCore.emitImuData]), so Faceclaw apps and EvenHub pages see
* the same frame whichever glasses are worn. It is the G2's own frame, in g, glasses worn:
*
* +x forward (the way the wearer faces), +y to the wearer's left, +z up through the top of the head.
*
* At rest a reading is the "up" direction (the reaction to gravity): head level reads (0, 0, 1),
* looking 45° up (0.71, 0, 0.71), and the head tilted 45° to the right (right ear down)
* (0, 0.71, 0.71). Pitch above level is atan2(x, hypot(y, z)).
*/
object ImuOrientation {
/**
* A sample as [type]'s hardware reports it, in the canonical frame. Axes measured on hardware
* with the Developer app's accelerometer page:
* - G2: already canonical.
* - G1 (g1v0): +x right, +y up, +z back. Level reads (0, 1, 0), 45° up (0, 0.71, -0.71),
* 45° to the right (-0.71, 0.71, 0).
* - RayNeo iO: no accelerometer stream yet, so nothing to rotate; measure its axes when one
* is added.
*/
fun toCanonical(type: GlassesType, x: Double, y: Double, z: Double): DoubleArray = when (type) {
GlassesType.G2 -> doubleArrayOf(x, y, z)
GlassesType.G1 -> doubleArrayOf(-z, -x, y)
GlassesType.RAYNEO_IO -> doubleArrayOf(x, y, z)
}
}
@@ -0,0 +1,37 @@
package com.faceclaw.app
import platform.Foundation.NSData
/**
* Records the iOS voice bridge's audio to a Matroska audio file (.mka), the format Android's
* captures are recorded in (see [MicRecordingWriter]). The bridge has one stream to record:
* 16 kHz mono PCM16, as its recognizer hands it to TypeScript.
*/
class IosMicRecorder internal constructor(private val writer: MicRecordingWriter) {
/** The recording stopped early: the file could not be written. */
val failed: Boolean get() = writer.failed
/** Appends a chunk of 16 kHz mono PCM16 (little-endian), as having arrived now. */
fun append(pcm16le: NSData) {
val bytes = pcm16le.byteArray()
val samples = ShortArray(bytes.size / 2) { AudioSegmentation.pcm16le(bytes[it * 2], bytes[it * 2 + 1]) }
writer.write(MicChunk(MicStream.MONO, 1, 16000, samples, samples.size, IosProtocolPlatform.elapsedRealtimeMs()))
}
/** Completes the file. Returns the recording's length in ms. */
fun finish(): Long = writer.finish()
}
object IosMicRecordings {
/**
* A recorder writing a new file at [path], or null when the file cannot be created.
* [configJson] describes the capture and is stored in the file.
*/
fun open(path: String, configJson: String?): IosMicRecorder? =
try {
IosMicRecorder(MicRecordingWriter(openFileOutput(path), configJson, currentTimeMillis(), IosProtocolPlatform))
} catch (error: Throwable) {
PlatformLog.w("FaceclawMicRecording", "could not create $path: ${error.message}")
null
}
}
@@ -114,3 +114,54 @@ actual fun fileLength(path: String): Long = memScoped {
actual fun deleteFile(path: String): Boolean = unlink(path) == 0
actual fun renameFile(from: String, to: String): Boolean = rename(from, to) == 0
actual fun openFileOutput(path: String): SeekableOutput {
val file = fopen(path, "wb+") ?: error("Cannot write $path")
return object : SeekableOutput {
override var size = 0L
private set
private fun put(bytes: ByteArray, offset: Int, length: Int) {
if (length == 0) return
bytes.usePinned {
check(fwrite(it.addressOf(offset), 1u, length.convert(), file) == length.convert<platform.posix.size_t>()) { "Short write to $path" }
}
}
override fun write(bytes: ByteArray, offset: Int, length: Int) {
put(bytes, offset, length)
size += length
// Each write is a complete element; hand it to the OS so a crash keeps it.
platform.posix.fflush(file)
}
override fun writeAt(position: Long, bytes: ByteArray) {
require(position >= 0 && position + bytes.size <= size)
check(platform.posix.fseek(file, position, platform.posix.SEEK_SET) == 0)
put(bytes, 0, bytes.size)
check(platform.posix.fseek(file, size, platform.posix.SEEK_SET) == 0)
platform.posix.fflush(file)
}
override fun close() {
fclose(file)
}
}
}
actual fun openFileInput(path: String): SeekableInput {
val file = fopen(path, "rb") ?: error("Cannot read $path")
val fileSize = fileLength(path)
return object : SeekableInput {
override val length = fileSize
override fun readAt(position: Long, buffer: ByteArray, offset: Int, length: Int): Int {
if (length == 0 || platform.posix.fseek(file, position, platform.posix.SEEK_SET) != 0) return 0
return buffer.usePinned { platform.posix.fread(it.addressOf(offset), 1u, length.convert(), file).toInt() }
}
override fun close() {
fclose(file)
}
}
}
@@ -34,6 +34,11 @@ interface IosMicStatusListener {
fun onNsDataMicStatus(body: NSData, arm: String)
}
/** CFW keyboard-bridge records (the raw field-131 record) as NSData. Main queue. */
interface IosKeyboardEventListener {
fun onNsDataKeyboardEvent(body: NSData)
}
/**
* ObjC-facing facade over the shared [GlassesSessionCore] for the NativeScript app: the iOS
* counterpart of Android's FaceclawBleCommunicator with the same method names. GATT goes
@@ -230,6 +235,20 @@ class IosGlassesSession internal constructor(
return adapter
}
fun addKeyboardEventListenerNsData(listener: IosKeyboardEventListener): FaceclawKeyboardEventListener {
val adapter = object : FaceclawKeyboardEventListener {
override fun onKeyboardEvent(body: ByteArray?) =
listener.onNsDataKeyboardEvent((body ?: ByteArray(0)).data())
}
core.addKeyboardEventListener(adapter)
return adapter
}
fun removeKeyboardEventListener(listener: FaceclawKeyboardEventListener?) = core.removeKeyboardEventListener(listener)
fun sendFaceclawKeyboardControl(record: NSData?, label: String): Boolean =
core.sendFaceclawKeyboardControl(record?.byteArray(), label)
/** Every audio-characteristic packet, whether or not a capture is active (passive; sends nothing). */
fun addAudioMonitorListenerNsData(listener: IosAudioPacketListener): FaceclawAudioPacketListener {
val adapter = object : FaceclawAudioPacketListener {
+23 -1
View File
@@ -2,7 +2,7 @@ const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
function settingsEnv(initialUrl = '', initialModel = 'openai-compatible') {
function settingsEnv(initialUrl = '', initialModel = 'openai-compatible', glassesType = 'g2') {
let url = initialUrl;
let model = initialModel;
let webSearch = false;
@@ -31,6 +31,7 @@ function settingsEnv(initialUrl = '', initialModel = 'openai-compatible') {
assistantHermesUrlSetting: { ...dummySetting, id: 'assistant-hermes-url', label: 'Hermes URL' },
assistantHermesKeySetting: { ...dummySetting, id: 'assistant-hermes-key', label: 'Hermes key' },
veniceWebSearchSetting: searchSetting,
glassesTypeSetting: { ...dummySetting, id: 'glasses-type', get: () => (typeof glassesType === 'function' ? glassesType() : glassesType) },
enumSettingMenuItem: row,
textSettingMenuItem: row,
toggleSettingMenuItem: row,
@@ -73,6 +74,8 @@ function settingsEnv(initialUrl = '', initialModel = 'openai-compatible') {
},
'../font-picker': { uiFontPickerMenuItem: () => ({ label: 'Font' }) },
'../notification-filter': { NotificationFilterLayer: class {} },
'../keyboard-settings': { keyboardSettingsMenuItem: () => ({ label: 'Bluetooth keyboard' }) },
'../keybinding-settings': { keybindingsMenuItem: () => ({ label: 'Keybindings' }) },
'../openai-compatible-model-picker': {
compatibleModelDiscoveryMenuItem: () => ({ label: 'Discover models' }),
},
@@ -83,6 +86,7 @@ function settingsEnv(initialUrl = '', initialModel = 'openai-compatible') {
assert.ok(section);
return {
section,
sections: panel.sections,
labels: () => section.items.map(item => item.label),
setUrl: value => { url = value; },
setModel: value => { model = value; },
@@ -148,3 +152,21 @@ test('OpenAI-compatible rows appear only while OpenAI-compatible is the selected
const labels = env.labels();
assert.equal(labels.indexOf('Compatible API URL'), labels.indexOf('Assistant model') + 1, 'compatible rows follow the model row');
});
test('the Keyboard section, with its pairing row, follows the glasses type while Settings stays open', () => {
let glassesType = 'g1';
const sections = settingsEnv('', 'openai-compatible', () => glassesType).sections;
const labels = sections.map(section => section.label);
// Always in the list, between the other input devices and the developer
// options; whether it shows is asked again on every paint.
assert.equal(labels.indexOf('Keyboard'), labels.indexOf('Watch') + 1);
const keyboard = sections.find(section => section.label === 'Keyboard');
assert.equal(keyboard.items.map(item => item.label).join(), 'Bluetooth keyboard,Keybindings');
assert.equal(keyboard.hidden(), true);
glassesType = 'rayneo-io';
assert.equal(keyboard.hidden(), true);
glassesType = 'g2';
assert.equal(keyboard.hidden(), false);
// Nothing else is conditional this way.
assert.equal(sections.filter(section => section.hidden).length, 1);
});
+66 -4
View File
@@ -4,7 +4,9 @@ const assert = require("node:assert/strict");
const {
GLANCE_HIDDEN,
GLANCE_TIMEOUT_MS,
GLANCE_TILT_MAX_MS,
glanceEventForGesture,
glanceTiltMaxMs,
reduceGlance,
} = require("../.test-build/app/g2/glance-state.js");
@@ -12,7 +14,7 @@ const T0 = 1_000_000;
test("a press shows the board and arms the auto-hide timer", () => {
const shown = reduceGlance(GLANCE_HIDDEN, { type: "press" }, T0);
assert.deepEqual(shown, { visible: true, holding: false, hideAtMs: T0 + GLANCE_TIMEOUT_MS });
assert.deepEqual(shown, { visible: true, holding: false, tilted: false, tiltMaxMs: 0, hideAtMs: T0 + GLANCE_TIMEOUT_MS });
// A timer firing early is ignored; on time it hides.
assert.equal(reduceGlance(shown, { type: "timeout" }, T0 + GLANCE_TIMEOUT_MS - 1), shown);
assert.deepEqual(reduceGlance(shown, { type: "timeout" }, T0 + GLANCE_TIMEOUT_MS), GLANCE_HIDDEN);
@@ -27,7 +29,7 @@ test("a further press renews the timer from the new press", () => {
test("a hold shows the board without a timer and the release hides it", () => {
const held = reduceGlance(GLANCE_HIDDEN, { type: "hold" }, T0);
assert.deepEqual(held, { visible: true, holding: true, hideAtMs: null });
assert.deepEqual(held, { visible: true, holding: true, tilted: false, tiltMaxMs: 0, hideAtMs: null });
assert.equal(reduceGlance(held, { type: "timeout" }, T0 + 60_000), held);
// A tap mid-hold neither hides nor starts a timer.
assert.equal(reduceGlance(held, { type: "press" }, T0 + 500), held);
@@ -47,9 +49,11 @@ test("dismiss hides from any state", () => {
assert.deepEqual(reduceGlance(shown, { type: "dismiss" }, T0), GLANCE_HIDDEN);
});
test("gesture mapping: taps and head-tilt press, both long-press gestures hold, double-tap dismisses only a visible board", () => {
test("gesture mapping: taps press, head-tilt tilts, both long-press gestures hold, double-tap dismisses only a visible board", () => {
assert.deepEqual(glanceEventForGesture("click", false), { type: "press" });
assert.deepEqual(glanceEventForGesture("head-tilt", false), { type: "press" });
assert.deepEqual(glanceEventForGesture("head-tilt", false), { type: "tilt" });
assert.deepEqual(glanceEventForGesture("head-down", true), { type: "head-down" });
assert.equal(glanceEventForGesture("head-down", false), null);
assert.deepEqual(glanceEventForGesture("long-press", false), { type: "hold" });
assert.deepEqual(glanceEventForGesture("short-then-long-press", false), { type: "hold" });
assert.deepEqual(glanceEventForGesture("short-then-long-press", true), { type: "hold" });
@@ -65,3 +69,61 @@ test("the press timeout is the host's when supplied", () => {
assert.equal(reduceGlance(shown, { type: "timeout" }, T0 + GLANCE_TIMEOUT_MS), shown);
assert.deepEqual(reduceGlance(shown, { type: "timeout" }, T0 + 10_000), GLANCE_HIDDEN);
});
test("a head-tilt shows the board until the head comes back down", () => {
const up = reduceGlance(GLANCE_HIDDEN, { type: "tilt" }, T0);
assert.deepEqual(up, { visible: true, holding: false, tilted: true, tiltMaxMs: GLANCE_TILT_MAX_MS, hideAtMs: T0 + GLANCE_TILT_MAX_MS });
// The tap duration no longer applies, and taps change nothing.
assert.equal(reduceGlance(up, { type: "timeout" }, T0 + GLANCE_TIMEOUT_MS), up);
assert.equal(reduceGlance(up, { type: "press" }, T0 + 500), up);
assert.deepEqual(reduceGlance(up, { type: "head-down" }, T0 + 9000), GLANCE_HIDDEN);
// The safety cap still hides it if the head-down never arrives.
assert.deepEqual(reduceGlance(up, { type: "timeout" }, T0 + GLANCE_TILT_MAX_MS), GLANCE_HIDDEN);
});
test("head-down leaves a tap's or a hold's showing alone", () => {
const shown = reduceGlance(GLANCE_HIDDEN, { type: "press" }, T0);
assert.equal(reduceGlance(shown, { type: "head-down" }, T0 + 100), shown);
const held = reduceGlance(GLANCE_HIDDEN, { type: "hold" }, T0);
assert.equal(reduceGlance(held, { type: "head-down" }, T0 + 100), held);
});
test("a hold and a head-tilt together: the board stays until both end", () => {
const both = reduceGlance(reduceGlance(GLANCE_HIDDEN, { type: "tilt" }, T0), { type: "hold" }, T0 + 100);
assert.deepEqual(both, { visible: true, holding: true, tilted: true, tiltMaxMs: GLANCE_TILT_MAX_MS, hideAtMs: null });
const released = reduceGlance(both, { type: "release" }, T0 + 200);
assert.deepEqual(released, { visible: true, holding: false, tilted: true, tiltMaxMs: GLANCE_TILT_MAX_MS, hideAtMs: T0 + 200 + GLANCE_TILT_MAX_MS });
const downWhileHeld = reduceGlance(both, { type: "head-down" }, T0 + 200);
assert.deepEqual(downWhileHeld, { visible: true, holding: true, tilted: false, tiltMaxMs: 0, hideAtMs: null });
assert.deepEqual(reduceGlance(downWhileHeld, { type: "release" }, T0 + 300), GLANCE_HIDDEN);
});
test("a tilt with a shorter cap keeps it, also across a hold", () => {
const up = reduceGlance(GLANCE_HIDDEN, { type: "tilt", maxMs: 5000 }, T0);
assert.equal(up.hideAtMs, T0 + 5000);
assert.deepEqual(reduceGlance(up, { type: "timeout" }, T0 + 5000), GLANCE_HIDDEN);
const held = reduceGlance(up, { type: "hold" }, T0 + 100);
assert.equal(reduceGlance(held, { type: "release" }, T0 + 1000).hideAtMs, T0 + 1000 + 5000);
});
test("the tilt cap is the Head tilt timeout, or the tap duration if shorter where the head-down is unlikely", () => {
const tapTimeoutMs = 5000;
const cap = (capMs, resumedSession, triggerDegrees) => glanceTiltMaxMs({ capMs, resumedSession, triggerDegrees, tapTimeoutMs });
assert.equal(cap(60_000, false, 30), 60_000);
assert.equal(cap(15_000, false, null), 15_000);
assert.equal(cap(null, false, 30), null);
assert.equal(cap(60_000, true, 30), tapTimeoutMs);
assert.equal(cap(60_000, false, 20), tapTimeoutMs);
assert.equal(cap(null, false, 20), tapTimeoutMs);
assert.equal(cap(3000, true, 30), 3000);
assert.equal(cap(60_000, false, 25), 60_000);
});
test("a tilt with no timeout stays until the head-down, also across a hold", () => {
const up = reduceGlance(GLANCE_HIDDEN, { type: "tilt", maxMs: null }, T0);
assert.equal(up.hideAtMs, null);
assert.equal(reduceGlance(up, { type: "timeout" }, T0 + 3_600_000), up);
const held = reduceGlance(up, { type: "hold" }, T0 + 100);
assert.equal(reduceGlance(held, { type: "release" }, T0 + 1000).hideAtMs, null);
assert.deepEqual(reduceGlance(up, { type: "head-down" }, T0 + 9000), GLANCE_HIDDEN);
});
+30
View File
@@ -0,0 +1,30 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const { imuPitchDegrees } = require("../.test-build/app/native/imu-types.js");
const rad = (deg) => (deg * Math.PI) / 180;
/**
* A reading at rest in the canonical frame (+x forward, +y left, +z up), in
* m/s^2 to show the scale does not matter: the head pitched up by pitchDeg,
* then rolled by rollDeg.
*/
function reading(pitchDeg, rollDeg = 0) {
const p = rad(pitchDeg);
const r = rad(rollDeg);
return { x: 9.8 * Math.sin(p), y: 9.8 * Math.cos(p) * Math.sin(r), z: 9.8 * Math.cos(p) * Math.cos(r) };
}
test("imuPitchDegrees reads the head's pitch from one reading, past 45° and with the head rolled", () => {
for (const pitch of [-30, 0, 5, 20, 45, 50, 60, 75]) {
for (const roll of [0, 30, -40]) {
assert.ok(Math.abs(imuPitchDegrees(reading(pitch, roll)) - pitch) < 1e-6, `pitch ${pitch} roll ${roll}`);
}
}
// The poses measured on a G2 (in g).
const s = Math.SQRT1_2;
assert.ok(Math.abs(imuPitchDegrees({ x: 0, y: 0, z: 1 })) < 1e-9);
assert.ok(Math.abs(imuPitchDegrees({ x: s, y: 0, z: s }) - 45) < 1e-9);
assert.ok(Math.abs(imuPitchDegrees({ x: 0, y: s, z: s })) < 1e-9);
});
+1 -1
View File
@@ -33,7 +33,7 @@ function harness(refused = new Set()) {
FaceclawKitIosGlassesSession: { alloc: () => ({ initWithRightAddressLeftAddressRingAddress: () => session }) },
FaceclawKitFaceclawBleCommunicatorListener: {}, FaceclawKitIosAncsListener: {}, FaceclawKitIosAudioPacketListener: {},
FaceclawKitFaceclawCompassListener: {}, FaceclawKitFaceclawImuListener: {}, FaceclawKitIosAmbientLightListener: {},
FaceclawKitIosMicStatusListener: {}, console: { log() {}, warn() {} },
FaceclawKitIosMicStatusListener: {}, FaceclawKitIosKeyboardEventListener: {}, console: { log() {}, warn() {} },
}, {
'@nativescript/core': { File: {}, knownFolders: {}, path: {} },
'../g2/firmware-compat': { REQUIRED_FACECLAW_FIRMWARE_VERSION: 37 },
+55 -1
View File
@@ -30,6 +30,9 @@ function fixture() {
let now = 1000, nextTask = 0, screenOn = true, shellOptions;
const battery = {};
const tasks = new Map(), sent = [], previews = [], received = [], errors = [];
// The keyboard bridge's service, as the controller sees it: what it was told, and the host it was given.
const keyboard = { host: null, calls: [], setHost(host) { this.host = host; }, linkReady() { this.calls.push('ready'); },
linkLost(release) { this.calls.push(release ? 'lost+release' : 'lost'); }, retryNow() { this.calls.push('retry'); }, handleUnhandledKey() {} };
const boardStats = { starts: 0, stops: 0, paints: 0 };
const registered = [], inProcessApps = [];
const settings = { lock: true, enabled: true, tap: true, hold: true, tilt: true, duration: 3000, depth: 0 };
@@ -165,6 +168,7 @@ function fixture() {
'./device-addresses': { loadDeviceAddresses: () => ({ right: 'AA', left: 'BB', ring: '' }) }, './ios-peripheral-identity': { deviceAddressError: () => null },
'./wear-remote': { WearRemote: class { schedulePublish() {} } },
'./firmware-compat': load('app/g2/firmware-compat.ts', {}), './reconnect-policy': load('app/g2/reconnect-policy.ts', {}),
'./keyboard/service': { keyboardService: keyboard },
'../apps/launcher': { launcherEntries: () => [] },
'../apps/evenhub/installed-apps': {}, '../apps/evenhub/manager': { onPhoneShownChanged: () => () => {}, phoneUiButton: () => null },
'../apps/evenhub/updates': {}, '../apps/evenhub': {},
@@ -223,7 +227,7 @@ function fixture() {
}
async function phone(type, origin = 'ring') { controller.gesture(type, origin); await render(); }
async function connect() { await controller.connect(); await render(); }
return { relay, controller, shell, battery, remoteHost, keyboardChanged: session => shellOptions.onKeyboardInputChanged(session), settings, phoneState, observers,
return { relay, controller, shell, battery, remoteHost, keyboard, keyboardChanged: session => shellOptions.onKeyboardInputChanged(session), settings, phoneState, observers,
get shellOptions() { return shellOptions; }, registered, inProcessApps,
get bridge() { return bridge; }, connect, wear: wearing => bridge.emitWear(wearing), settingsChanged: () => settingsChanged(), sent, previews, received, boardStats, hardware, phone, advance, render };
}
@@ -348,3 +352,53 @@ test('the switcher can open the Notifications window in the background, once, wi
assert.equal(f.shellOptions.openNotificationsWindow().opened, true);
assert.equal(f.inProcessApps.length, 2);
});
test('a paired keyboard: the bridge follows the G2 link, and its keys\' gestures go in with physical input', async () => {
const f = fixture();
await f.connect();
// Connected is not enough: the firmware has to be one with the bridge.
f.bridge.emitState('connected');
assert.ok(!f.keyboard.calls.includes('ready'));
f.bridge.listeners.firmware({ leftVersion: '2.3.0.24', rightVersion: '2.3.0.24', extension: 'Faceclaw/38' });
assert.ok(!f.keyboard.calls.includes('ready'));
f.bridge.listeners.firmware({ leftVersion: '2.3.0.24', rightVersion: '2.3.0.24', extension: 'Faceclaw/39' });
assert.equal(f.keyboard.calls.at(-1), 'ready');
assert.equal(f.keyboard.host.ready(), true);
// The link dropping on its own ends it without a word to the firmware; coming back restores it.
f.bridge.emitState('retrying', 'Reconnecting');
assert.equal(f.keyboard.calls.at(-1), 'lost'); assert.equal(f.keyboard.host.ready(), false);
f.bridge.emitState('connected');
assert.equal(f.keyboard.calls.at(-1), 'ready');
// A key's gesture is ordinary input from there on, tagged with the device it stands in for.
f.received.length = 0;
await f.keyboard.host.gesture('swipe-left', 'watch'); await f.keyboard.host.gesture('click', 'ring');
await f.keyboard.host.gesture('long-press', 'watch');
assert.deepEqual(f.received.map(input => `${input.type}/${input.source}`),
['swipe-left/watch', 'click/ring', 'long-press/watch', 'long-press-release/watch']);
// A dark display: the bridge stops looking for an absent keyboard, a key wakes it, and it looks again.
f.shell.sleep();
assert.equal(f.keyboard.host.shouldReconnect(), false);
f.keyboard.calls.length = 0; f.received.length = 0;
f.keyboard.host.wake(); await f.render();
assert.deepEqual(f.received.map(input => input.type), ['display-wake']);
assert.equal(f.shell.isScreenOn(), true); assert.ok(f.keyboard.calls.includes('retry'));
assert.equal(f.keyboard.host.shouldReconnect(), true);
// Disconnecting on purpose lets the keyboard go while the link is still up.
f.keyboard.calls.length = 0;
await f.controller.disconnect();
assert.equal(f.keyboard.calls[0], 'lost+release');
assert.equal(f.keyboard.host.ready(), false);
});
test('a keyboard needs a G2: other glasses never bring the bridge up', async () => {
glassesType = 'g1';
try {
const f = fixture();
await f.connect();
f.bridge.emitState('connected');
f.bridge.listeners.firmware({ leftVersion: 'g1v0 0.5.66', rightVersion: 'g1v0 0.5.66', extension: 'Faceclaw/39' });
assert.ok(!f.keyboard.calls.includes('ready'), f.keyboard.calls.join());
} finally { glassesType = 'g2'; }
});
+1 -1
View File
@@ -37,7 +37,7 @@ function harness() {
FaceclawKitIosGlassesSession: { alloc: () => ({ initWithRightAddressLeftAddressRingAddress: () => session }) },
FaceclawKitFaceclawBleCommunicatorListener: {}, FaceclawKitIosAncsListener: {}, FaceclawKitIosAudioPacketListener: {},
FaceclawKitFaceclawCompassListener: {}, FaceclawKitFaceclawImuListener: {}, FaceclawKitIosAmbientLightListener: {},
FaceclawKitIosMicStatusListener: {}, console: { log() {}, warn() {} },
FaceclawKitIosMicStatusListener: {}, FaceclawKitIosKeyboardEventListener: {}, console: { log() {}, warn() {} },
}, {
'@nativescript/core': { File: {}, knownFolders: {}, path: {} },
'../g2/firmware-compat': { REQUIRED_FACECLAW_FIRMWARE_VERSION: 37 },
+2 -2
View File
@@ -36,7 +36,7 @@ function harness() {
static open(name) {
recordingAttempts++;
if (failRecordings) return null;
const r = new FakeRecorder(); r.name = name; r.path = `/Downloads/${name}.wav`; r.pcm = []; r.closed = false; recordings.push(r); return r;
const r = new FakeRecorder(); r.name = name; r.path = `/Downloads/${name}.mka`; r.pcm = []; r.closed = false; recordings.push(r); return r;
}
append(bytes) { this.pcm.push(...bytes); }
close() { this.closed = true; }
@@ -49,7 +49,7 @@ function harness() {
setTimeout: fn => { timers.set(fn, fn); return fn; }, clearTimeout: fn => timers.delete(fn),
NSData: { dataWithBytesLength: (b, n) => Buffer.from(b, 0, n) }, interop: { handleof: b => b, bufferFromData: d => d },
require: name => name === './cloud-stt-provider' ? provider : name === './speech-analyzer-stt.ios' ? analyzer
: name === './wav-recorder.ios' ? { WavRecorder: FakeRecorder } : {} };
: name === './mic-recorder.ios' ? { MicRecorder: FakeRecorder } : {} };
vm.runInNewContext(ts.transpileModule(fs.readFileSync('app/native/voice-control.ios.ts', 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 } }).outputText, sandbox);
const bridge = new sandbox.exports.IosVoiceControlBridge();
+160
View File
@@ -0,0 +1,160 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
function load(file, modules) {
const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
const context = { exports: {}, console, require(name) { assert.ok(name in modules, name); return modules[name]; } };
vm.runInNewContext(ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
return context.exports;
}
const graphics = require('../.test-build/app/graphics/image.js');
const metrics = require('../.test-build/app/ui/metrics.js');
const menuCore = require('../.test-build/app/ui/menu-core.js');
const bindings = require('../.test-build/app/g2/keyboard/bindings.js');
const { BdfFont } = load('app/graphics/bdffont.ts', { '@nativescript/core': {} });
const font = BdfFont.parse(fs.readFileSync(path.join(__dirname, '../app/fonts/terminus/ter-u12n.bdf'), 'utf8'));
const textwrap = load('app/graphics/textwrap.ts', {});
const fonts = { getDefaultSmallFont: () => font };
const menu = load('app/ui/menu.ts', {
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), './animation-speed': require('../.test-build/app/ui/animation-speed.js'), '../native/settings-store': { getStringSetting: (_key, fallback) => fallback }, '../graphics/screen-size': { screenWidth: () => 640, screenHeight: () => 480 },
'../graphics/image': graphics, '../graphics/textwrap': textwrap, '../graphics/ui-fonts': fonts,
'../util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) }, './gestures': {},
'./metrics': metrics, './menu-core': menuCore,
});
/** The settings menu over a fake keyboard service and layer stack. */
function fixture({ connected = true, stored = [], room = true } = {}) {
const service = {
list: [...stored], capture: null, cancelled: 0,
bridge: { isConnected: () => connected },
keyBindings() { return this.list; },
setKeyBinding(chord, action) {
if (!room) return false;
const id = bindings.chordId(chord);
const index = this.list.findIndex(b => bindings.chordId(b.chord) === id);
const next = [...this.list];
if (index < 0) next.push({ chord, action }); else next[index] = { chord, action };
this.list = next;
return true;
},
removeKeyBinding(chord) { this.list = this.list.filter(b => bindings.chordId(b.chord) !== bindings.chordId(chord)); },
captureNextKey(onChord) { this.capture = onChord; return () => { if (this.capture === onChord) { this.capture = null; this.cancelled++; } }; },
};
class TextViewerLayer { constructor(text, title) { this.text = text; this.title = title; } handleInput(event, ctx) { if (event.type === 'double-click') ctx.stack.pop(); } }
const { keybindingsMenuItem } = load('app/ui/keybinding-settings.ts', {
'../graphics/ui-fonts': fonts, '../g2/keyboard/bindings': bindings, '../g2/keyboard/service': { keyboardService: service },
'../apps/files/text-viewer': { TextViewerLayer }, './menu': menu,
});
const layers = [{ base: true }];
let renders = 0;
const removed = layer => layer.onRemoved?.();
const ctx = {
actions: { requestRender: () => { renders++; } },
stack: {
getBaseSize: () => ({ width: 576, height: 260, padding: { top: 0, right: 0, bottom: 0, left: 0 } }), isFocused: () => true,
push: layer => { layers.push(layer); },
pop: () => { if (layers.length > 1) removed(layers.pop()); },
popThrough: layer => {
const index = layers.indexOf(layer);
if (index <= 0) return false;
for (const gone of layers.splice(index).reverse()) removed(gone);
return true;
},
},
};
const top = () => layers[layers.length - 1];
const input = type => top().handleInput({ type, timestampMs: 0 }, ctx);
const labels = () => top().items.map(item => item.label);
/** Move the highlight of the menu on top to the row with this label, and select it. */
async function choose(label) {
const layer = top();
for (let i = 0; i <= layer.items.length && layer.selectedItem?.label !== label; i++) await input('scroll-down');
assert.equal(layer.selectedItem?.label, label, `${label} in ${labels().join(' | ')}`);
await input('click');
}
const item = keybindingsMenuItem();
return { service, item, ctx, layers, top, input, labels, choose, renders: () => renders,
open: () => item.onSelect(ctx), chord: (code, mods = {}) => ({ code, shift: false, ctrl: false, alt: false, meta: false, ...mods }) };
}
test('adding a keybinding: the key is read from the keyboard, then an action is picked', async () => {
const f = fixture();
f.open();
assert.deepEqual(f.labels(), ['Add keybinding', 'Default keys']);
await f.choose('Add keybinding');
assert.ok(f.service.capture, 'waiting for a key');
assert.match(f.top().body ?? f.top().constructor.name, /Press the key|KeyCaptureLayer/);
f.service.capture(f.chord('AudioVolumeUp'));
// The waiting page is gone and the picker for that key is up, with every action in it.
assert.equal(f.layers.length, 3); assert.equal(f.top().title, 'Volume Up');
assert.deepEqual(f.labels(), ['Select', 'Back', 'Swipe up', 'Swipe down', 'Swipe left', 'Swipe right',
'Scroll up', 'Scroll down', 'System menu', 'App menu', 'Nothing']);
await f.choose('Scroll up');
assert.deepEqual(f.service.list, [{ chord: f.chord('AudioVolumeUp'), action: 'scroll-up' }]);
// Back on the list, on the new row.
assert.equal(f.layers.length, 2);
assert.deepEqual(f.labels(), ['Volume Up', 'Add keybinding', 'Default keys']);
assert.equal(f.top().selectedItem.label, 'Volume Up');
assert.ok(f.renders() > 0);
});
test('a keybinding can be changed or removed, and a chord is one keybinding however often it is added', async () => {
const f = fixture();
f.service.list = [{ chord: f.chord('Escape', { shift: true }), action: 'none' }, { chord: f.chord('KeyQ', { ctrl: true }), action: 'long-press' }];
f.open();
assert.deepEqual(f.labels(), ['Shift+Esc', 'Ctrl+Q', 'Add keybinding', 'Default keys']);
await f.choose('Ctrl+Q');
// The picker opens on the current action, marks it, and offers removal.
assert.equal(f.top().selectedItem.label, 'System menu *'); assert.equal(f.labels().at(-1), 'Remove keybinding');
await f.choose('App menu');
assert.equal(f.service.list[1].action, 'short-then-long-press'); assert.equal(f.service.list.length, 2);
// Adding the same chord again edits it rather than making a second one.
await f.choose('Add keybinding');
f.service.capture(f.chord('KeyQ', { ctrl: true }));
assert.equal(f.top().selectedItem.label, 'App menu *');
await f.choose('Back');
assert.deepEqual(f.service.list.map(b => b.action), ['none', 'double-click']);
await f.choose('Shift+Esc');
await f.choose('Remove keybinding');
assert.deepEqual(f.labels(), ['Ctrl+Q', 'Add keybinding', 'Default keys']);
});
test('backing out of the wait calls the capture off; with no keyboard there is nothing to wait for', async () => {
const f = fixture();
f.open();
await f.choose('Add keybinding');
await f.input('double-click');
assert.equal(f.service.capture, null); assert.equal(f.service.cancelled, 1); assert.equal(f.layers.length, 2);
// A key pressed after that is not taken for a keybinding.
assert.deepEqual(f.service.list, []);
const away = fixture({ connected: false });
away.open();
await away.choose('Add keybinding');
assert.equal(away.service.capture, null);
assert.match(away.top().body, /No keyboard is connected/);
await away.input('double-click');
assert.equal(away.layers.length, 2);
});
test('the defaults are a page of their own, and a full list says so', async () => {
const f = fixture();
f.open();
await f.choose('Default keys');
assert.equal(f.top().title, 'Default keys');
for (const phrase of ['Arrow keys', 'Enter', 'Shift+Esc', 'terminal']) assert.ok(f.top().text.includes(phrase), phrase);
const full = fixture({ room: false });
full.open();
await full.choose('Add keybinding');
full.service.capture(full.chord('F5'));
await full.choose('Select');
assert.match(full.top().body, /no room/); assert.deepEqual(full.service.list, []);
});
+245
View File
@@ -0,0 +1,245 @@
const test = require('node:test')
const assert = require('node:assert/strict')
const {
KEY_ACTIONS, MAX_KEY_BINDINGS, GestureScheme, chordId, chordOf, defaultKeyAction, describeChord, gestureRepeats,
isModifierCode, keyActionLabel, keyBindingMap, parseChordId, parseKeyBindings, resolveKey, serializeKeyBindings,
} = require('../.test-build/app/g2/keyboard/bindings.js')
const { KeyRouter } = require('../.test-build/app/g2/keyboard/key-router.js')
const key = (k, overrides = {}) => ({
phase: 'down', key: k, code: overrides.code ?? k, repeat: false, timestampMs: 0,
...overrides, modifiers: { shift: false, ctrl: false, alt: false, meta: false, ...overrides.modifiers },
})
const chord = (code, mods = {}) => ({ code, shift: false, ctrl: false, alt: false, meta: false, ...mods })
const none = new Map()
test('built-in keys: arrows are the watch\'s swipes, Enter selects, Esc backs out', () => {
const action = (k, overrides) => defaultKeyAction(key(k, overrides))
assert.deepEqual(action('ArrowLeft'), { action: 'swipe-left', overridesTyping: false })
assert.deepEqual(action('ArrowRight'), { action: 'swipe-right', overridesTyping: false })
assert.deepEqual(action('ArrowUp'), { action: 'swipe-up', overridesTyping: false })
assert.deepEqual(action('ArrowDown'), { action: 'swipe-down', overridesTyping: false })
assert.deepEqual(action('Enter'), { action: 'click', overridesTyping: false })
assert.deepEqual(action('Enter', { code: 'NumpadEnter' }), { action: 'click', overridesTyping: false })
assert.deepEqual(action('Escape'), { action: 'double-click', overridesTyping: false })
// With a modifier, Escape means "back" even where keys are being typed.
for (const modifier of ['shift', 'ctrl', 'alt']) {
assert.deepEqual(action('Escape', { modifiers: { [modifier]: true } }), { action: 'double-click', overridesTyping: true })
}
assert.equal(action('Escape', { modifiers: { meta: true } }), null)
assert.equal(action('ArrowLeft', { modifiers: { ctrl: true } }), null)
assert.equal(action('Enter', { modifiers: { alt: true } }), null)
for (const k of ['a', ' ', 'Backspace', 'Tab', 'F1', 'AudioVolumeUp']) assert.equal(action(k), null)
})
test('chords: canonical ids round-trip, and read naturally', () => {
const c = chord('Escape', { shift: true, ctrl: true })
assert.equal(chordId(c), 'Ctrl+Shift+Escape'); assert.deepEqual(parseChordId('Ctrl+Shift+Escape'), c)
assert.deepEqual(parseChordId('ArrowLeft'), chord('ArrowLeft'))
assert.deepEqual(chordOf(key('A', { code: 'KeyA', modifiers: { shift: true } })), chord('KeyA', { shift: true }))
for (const bad of ['', 'Shift+', 'Shift+Shift+KeyA', 'Hyper+KeyA', 'ShiftLeft', 'Ctrl+ControlRight', 'Key A', '+'.repeat(3)]) {
assert.equal(parseChordId(bad), null, bad)
}
assert.equal(isModifierCode('AltRight'), true); assert.equal(isModifierCode('CapsLock'), false)
const said = (code, mods) => describeChord(chord(code, mods))
assert.equal(said('Escape', { shift: true }), 'Shift+Esc'); assert.equal(said('ArrowLeft'), 'Left')
assert.equal(said('KeyA', { ctrl: true, alt: true }), 'Ctrl+Alt+A'); assert.equal(said('Digit7'), '7')
assert.equal(said('AudioVolumeUp'), 'Volume Up'); assert.equal(said('MediaPlayPause'), 'Play/Pause')
assert.equal(said('NumpadEnter'), 'Numpad Enter'); assert.equal(said('F5'), 'F5'); assert.equal(said('Slash'), '/')
// A remote's unnamed buttons keep the only name they have.
assert.equal(said('Consumer1cb'), 'Media key 0x1cb'); assert.equal(said('Usagea5'), 'Key 0xa5')
})
test('custom keybindings survive storage; junk in storage is dropped', () => {
const bindings = [
{ chord: chord('AudioVolumeUp'), action: 'scroll-up' },
{ chord: chord('KeyQ', { ctrl: true }), action: 'long-press' },
{ chord: chord('ArrowLeft'), action: 'none' },
]
assert.deepEqual(parseKeyBindings(serializeKeyBindings(bindings)), bindings)
assert.deepEqual([...keyBindingMap(bindings)], [['AudioVolumeUp', 'scroll-up'], ['Ctrl+KeyQ', 'long-press'], ['ArrowLeft', 'none']])
assert.deepEqual(parseKeyBindings(''), []); assert.deepEqual(parseKeyBindings('{'), []); assert.deepEqual(parseKeyBindings('{"a":1}'), [])
assert.deepEqual(parseKeyBindings(JSON.stringify([
null, 7, { key: 'KeyA' }, { key: 'KeyA', action: 'explode' }, { key: 'Shift+ShiftLeft', action: 'click' },
{ key: 'KeyB', action: 'click' }, { key: 'KeyB', action: 'double-click' },
])), [{ chord: chord('KeyB'), action: 'double-click' }])
const many = Array.from({ length: 200 }, (_, i) => ({ key: `F${i + 1}`, action: 'click' }))
assert.equal(parseKeyBindings(JSON.stringify(many)).length, MAX_KEY_BINDINGS)
// Every action has a label for the picker, and the list has no duplicates.
assert.equal(new Set(KEY_ACTIONS.map(a => a.action)).size, KEY_ACTIONS.length)
assert.equal(keyActionLabel('double-click'), 'Back'); assert.equal(keyActionLabel('none'), 'Nothing')
})
test('resolution: custom first and everywhere, then the built-ins; "Nothing" only removes the built-in', () => {
const custom = keyBindingMap([
{ chord: chord('AudioVolumeUp'), action: 'scroll-up' },
{ chord: chord('ArrowLeft'), action: 'double-click' },
{ chord: chord('ArrowRight'), action: 'none' },
{ chord: chord('Escape', { shift: true }), action: 'none' },
])
// Unbound keys: typed where something takes keys, otherwise the built-in.
assert.deepEqual(resolveKey(key('a', { code: 'KeyA' }), custom), { consume: false, gesture: null })
assert.deepEqual(resolveKey(key('ArrowUp'), custom), { consume: false, gesture: 'swipe-up' })
assert.deepEqual(resolveKey(key('Escape'), custom), { consume: false, gesture: 'double-click' })
assert.deepEqual(resolveKey(key('Escape', { modifiers: { ctrl: true } }), custom), { consume: true, gesture: 'double-click' })
// Custom: spoken for even in a terminal.
assert.deepEqual(resolveKey(key('AudioVolumeUp'), custom), { consume: true, gesture: 'scroll-up' })
assert.deepEqual(resolveKey(key('ArrowLeft'), custom), { consume: true, gesture: 'double-click' })
// The chord is exact: Shift+Left is not the Left keybinding.
assert.deepEqual(resolveKey(key('ArrowLeft', { modifiers: { shift: true } }), custom), { consume: false, gesture: 'swipe-left' })
// "Nothing": no navigation, still typed; and it can take a built-in override away.
assert.deepEqual(resolveKey(key('ArrowRight'), custom), { consume: false, gesture: null })
assert.deepEqual(resolveKey(key('Escape', { modifiers: { shift: true } }), custom), { consume: false, gesture: null })
// Held keys: moving repeats, the rest acts once but stays spoken for.
assert.deepEqual(resolveKey(key('AudioVolumeUp', { repeat: true }), custom), { consume: true, gesture: 'scroll-up' })
assert.deepEqual(resolveKey(key('ArrowLeft', { repeat: true }), custom), { consume: true, gesture: null })
assert.deepEqual(resolveKey(key('ArrowDown', { repeat: true }), none), { consume: false, gesture: 'swipe-down' })
assert.deepEqual(resolveKey(key('ArrowRight', { repeat: true }), none), { consume: false, gesture: null })
assert.deepEqual(resolveKey(key('Enter', { repeat: true }), none), { consume: false, gesture: null })
assert.deepEqual(['swipe-left', 'swipe-right', 'click', 'double-click', 'long-press'].filter(gestureRepeats), [])
})
test('taps go with whichever scheme the keyboard last moved by', () => {
const scheme = new GestureScheme()
assert.equal(scheme.originFor('click'), 'watch')
assert.equal(scheme.originFor('scroll-down'), 'ring'); assert.equal(scheme.originFor('click'), 'ring')
assert.equal(scheme.originFor('double-click'), 'ring'); assert.equal(scheme.originFor('long-press'), 'ring')
assert.equal(scheme.originFor('swipe-left'), 'watch'); assert.equal(scheme.originFor('click'), 'watch')
assert.equal(scheme.originFor('short-then-long-press'), 'watch')
})
function router(options = {}) {
const state = {
ready: true, locked: false, screenOn: true, windowTakesKeys: false, now: 1000,
bindings: keyBindingMap(options.bindings ?? []), gestures: [], offered: [], wakes: 0, activity: 0, pending: [],
hold: false,
}
const r = new KeyRouter({
ready: () => state.ready, locked: () => state.locked, screenOn: () => state.screenOn,
wake: () => { state.wakes++ },
offerToWindow: event => { state.offered.push(`${event.phase}:${event.key}`); return state.windowTakesKeys },
gesture: (gesture, origin) => {
state.gestures.push(`${gesture}/${origin}`)
return state.hold ? new Promise(resolve => state.pending.push(resolve)) : Promise.resolve()
},
bindings: () => state.bindings, noteActivity: () => { state.activity++ }, log: () => {}, now: () => state.now,
})
return { r, state }
}
const up = (k, overrides) => key(k, { ...overrides, phase: 'up' })
const flush = () => new Promise(resolve => setImmediate(resolve))
test('router: navigation where nothing takes keys, typing where something does, Shift+Esc out of either', () => {
const { r, state } = router()
r.handleKey(key('ArrowLeft')); r.handleKey(up('ArrowLeft')); r.handleKey(key('Enter')); r.handleKey(key('Escape'))
assert.deepEqual(state.gestures, ['swipe-left/watch', 'click/watch', 'double-click/watch'])
// A terminal session: the same keys are its own, Escape included.
state.windowTakesKeys = true; state.gestures.length = 0; state.offered.length = 0
for (const k of ['ArrowLeft', 'Enter', 'Escape', 'a']) { r.handleKey(key(k)); r.handleKey(up(k)) }
assert.deepEqual(state.gestures, [])
assert.deepEqual(state.offered, ['down:ArrowLeft', 'up:ArrowLeft', 'down:Enter', 'up:Enter', 'down:Escape', 'up:Escape', 'down:a', 'up:a'])
// Shift+Esc (or Ctrl, or Alt) backs out, and neither its press nor its release is typed.
state.offered.length = 0
for (const modifier of ['shift', 'ctrl', 'alt']) {
r.handleKey(key('Escape', { modifiers: { [modifier]: true } })); r.handleKey(up('Escape'))
}
assert.deepEqual(state.gestures, ['double-click/watch', 'double-click/watch', 'double-click/watch'])
assert.deepEqual(state.offered, [])
})
test('router: a key the window hands back gets its navigation meaning; one it kept does not', () => {
const { r, state } = router()
state.windowTakesKeys = true
r.handleKey(key('ArrowDown'))
assert.deepEqual(state.gestures, [])
// The terminal was showing its session list: the key comes back.
r.handleUnhandledKey(key('ArrowDown'))
assert.deepEqual(state.gestures, ['swipe-down/watch'])
r.handleUnhandledKey(key('a')); r.handleUnhandledKey(up('ArrowDown'))
assert.equal(state.gestures.length, 1)
// Stale by the time it comes back: the display went dark, or locked.
state.screenOn = false; r.handleUnhandledKey(key('ArrowDown'))
state.screenOn = true; state.locked = true; r.handleUnhandledKey(key('ArrowDown'))
assert.equal(state.gestures.length, 1); assert.equal(state.wakes, 0)
})
test('router: custom keybindings work in a terminal too, and "Nothing" leaves the key to be typed', () => {
const { r, state } = router({ bindings: [
{ chord: chord('AudioVolumeUp'), action: 'scroll-up' },
{ chord: chord('AudioVolumeDown'), action: 'scroll-down' },
{ chord: chord('MediaPlayPause'), action: 'click' },
{ chord: chord('ArrowLeft'), action: 'none' },
] })
state.windowTakesKeys = true
r.handleKey(key('AudioVolumeDown')); r.handleKey(up('AudioVolumeDown')); r.handleKey(key('MediaPlayPause')); r.handleKey(up('MediaPlayPause'))
// A remote bound to scroll is a ring: its select is a ring's tap.
assert.deepEqual(state.gestures, ['scroll-down/ring', 'click/ring']); assert.deepEqual(state.offered, [])
r.handleKey(key('ArrowLeft'))
assert.deepEqual(state.offered, ['down:ArrowLeft'])
// And where nothing takes keys, "Nothing" is nothing.
state.windowTakesKeys = false; state.gestures.length = 0
r.handleKey(key('ArrowLeft')); r.handleUnhandledKey(key('ArrowLeft'))
assert.deepEqual(state.gestures, [])
})
test('router: a dark display only wakes, a locked one stays locked, and nothing happens off the glasses', () => {
const { r, state } = router()
state.screenOn = false
r.handleKey(key('a')); r.handleKey(key('a', { repeat: true })); r.handleKey(up('a'))
assert.equal(state.wakes, 1); assert.deepEqual(state.gestures, []); assert.deepEqual(state.offered, [])
state.locked = true
r.handleKey(key('Enter'))
assert.equal(state.wakes, 2)
state.screenOn = true
r.handleKey(key('Enter')); r.handleKey(key('Escape', { modifiers: { shift: true } }))
assert.equal(state.wakes, 2); assert.deepEqual(state.gestures, [])
state.locked = false; state.ready = false
r.handleKey(key('Enter'))
assert.deepEqual(state.gestures, [])
})
test('router: a held key repeats movement at a rate the display can follow, and never queues behind itself', async () => {
const { r, state } = router()
r.handleKey(key('ArrowDown'))
for (let i = 1; i <= 20; i++) { await flush(); state.now = 1400 + i * 50; r.handleKey(key('ArrowDown', { repeat: true })) }
// Twenty repeats a second arrive; every other one is acted on.
assert.equal(state.gestures.length, 1 + 10)
// While a gesture is still being handled, repeats are dropped rather than queued.
state.gestures.length = 0; state.hold = true; state.now += 1000
r.handleKey(key('ArrowUp'))
for (let i = 1; i <= 5; i++) { state.now += 200; r.handleKey(key('ArrowUp', { repeat: true })) }
assert.equal(state.gestures.length, 1)
state.pending.splice(0).forEach(resolve => resolve()); await flush()
state.now += 200; r.handleKey(key('ArrowUp', { repeat: true }))
assert.equal(state.gestures.length, 2)
// A fresh press is never dropped, even on the heels of another gesture.
r.handleKey(up('ArrowUp')); r.handleKey(key('Enter'))
assert.equal(state.gestures.at(-1), 'click/watch')
})
test('router: capturing a key for a new keybinding takes the chord and nothing else happens', () => {
const { r, state } = router()
const captured = []
r.captureNextKey(c => captured.push(c))
// Modifiers alone are waited through; the key pressed with them is the chord.
r.handleKey(key('Shift', { code: 'ShiftLeft', modifiers: { shift: true } }))
assert.deepEqual(captured, [])
r.handleKey(key('Escape', { modifiers: { shift: true } }))
assert.deepEqual(captured, [chord('Escape', { shift: true })])
// Its release, and the modifier's, do nothing; the next key is ordinary again.
r.handleKey(up('Escape')); r.handleKey(up('Shift', { code: 'ShiftLeft' }))
assert.deepEqual(state.gestures, []); assert.ok(state.activity >= 2)
r.handleKey(key('Enter'))
assert.deepEqual(state.gestures, ['click/watch'])
// Called off: keys go back to meaning what they mean.
const cancel = r.captureNextKey(c => captured.push(c))
cancel()
r.handleKey(key('ArrowUp'))
assert.equal(captured.length, 1); assert.equal(state.gestures.at(-1), 'swipe-up/watch')
// A second capture replaces the first, and the first one's cancel can't undo it.
const first = r.captureNextKey(() => captured.push('first'))
r.captureNextKey(c => captured.push(c))
first()
r.handleKey(key('x', { code: 'KeyX' }))
assert.deepEqual(captured.at(-1), chord('KeyX'))
})
+509
View File
@@ -0,0 +1,509 @@
const test = require('node:test')
const assert = require('node:assert/strict')
const { HidKeys, parseReportMap, reportKeys } = require('../.test-build/app/g2/keyboard/hid.js')
const {
KeyboardRecords, keyboardControl, le16, u16, parseKeyboardAdvert, mergeKeyboardAdverts,
parseKeyboardAddress, formatKeyboardAddress,
} = require('../.test-build/app/g2/keyboard/protocol.js')
const { KeyboardClient, KeyboardClientError, attributeUuid } = require('../.test-build/app/g2/keyboard/client.js')
const { KeyboardBridge } = require('../.test-build/app/g2/keyboard/bridge.js')
// The HID vectors and the simulated HOGP keyboard follow g2flash demos/keyboard.test.ts.
const boot = Uint8Array.from([
0x05,1,0x09,6,0xa1,1,0x05,7,0x19,0xe0,0x29,0xe7,0x15,0,0x25,1,0x75,1,0x95,8,0x81,2,
0x75,8,0x95,1,0x81,1,0x95,6,0x75,8,0x15,0,0x25,0x65,0x05,7,0x19,0,0x29,0x65,0x81,0,0xc0,
])
const numbered = Uint8Array.from([
...boot.slice(0, 6), 0x85,1,...boot.slice(6, -1),
0x85,2,0x05,0x0c,0x15,0,0x25,1,0x75,1,0x95,3,0x09,0xe9,0x09,0xea,0x09,0xe2,0x81,2,
0x75,5,0x95,1,0x81,1,0xc0,
])
function frame(kind, seq, epoch, request, code, handle, data, offset = 0, total = data.length) {
const p = new Uint8Array(24 + data.length), v = new DataView(p.buffer)
p.set([75,66,1,kind]); v.setUint32(4,seq,true); v.setUint16(8,epoch,true); v.setUint16(10,request,true)
v.setUint16(12,code,true); v.setUint16(14,handle,true); v.setUint16(16,total,true); v.setUint16(18,offset,true)
v.setUint32(20,1234,true); p.set(data,24); return p
}
const flush = () => new Promise(resolve => setImmediate(resolve))
async function settle(rounds = 20) { for (let i = 0; i < rounds; i++) await flush() }
test('boot array, modifiers, release, repeats and rollover', () => {
const r = parseReportMap(boot).get(0), keys = new HidKeys()
assert.deepEqual(keys.update(12,r,Uint8Array.of(2,0,4,0,0,0,0,0)), [
{page:7,usage:0xe1,down:true},{page:7,usage:4,down:true},
])
assert.deepEqual(keys.update(12,r,Uint8Array.of(2,0,4,0,0,0,0,0)), [])
assert.throws(() => keys.update(12,r,Uint8Array.of(0,0,1,1,1,1,1,1)), /rollover/)
assert.deepEqual(keys.reset().map(k => k.down), [false,false])
assert.throws(() => reportKeys(r,Uint8Array.of(0)), /length/)
})
test('HOGP report IDs are out of band, with consumer keys', () => {
const maps = parseReportMap(numbered)
assert.deepEqual(reportKeys(maps.get(1),Uint8Array.of(0,0,5,0,0,0,0,0)), [{page:7,usage:5}])
assert.deepEqual(reportKeys(maps.get(2),Uint8Array.of(5)), [{page:12,usage:0xe9},{page:12,usage:0xe2}])
assert.throws(() => reportKeys(maps.get(2),Uint8Array.of(2,5)), /length/)
})
test('NKRO bitmap with non-byte-aligned fields and report union', () => {
const map = Uint8Array.of(5,7,0x19,4,0x29,19,0x15,0,0x25,1,0x75,1,0x95,16,0x81,2)
const r = parseReportMap(map).get(0), keys = new HidKeys()
assert.deepEqual(reportKeys(r,Uint8Array.of(0x81,0x80)), [{page:7,usage:4},{page:7,usage:11},{page:7,usage:19}])
assert.equal(keys.update(10,r,Uint8Array.of(1,0)).length, 1)
assert.deepEqual(keys.update(11,r,Uint8Array.of(1,0)), [])
assert.deepEqual(keys.update(10,r,Uint8Array.of(0,0)), [])
assert.deepEqual(keys.update(11,r,Uint8Array.of(0,0)), [{page:7,usage:4,down:false}])
})
test('array values index usages relative to logical minimum', () => {
const r = parseReportMap(Uint8Array.of(5,7,0x19,4,0x29,6,0x15,1,0x25,3,0x75,8,0x95,1,0x81,0)).get(0)
assert.deepEqual(reportKeys(r,Uint8Array.of(2)), [{page:7,usage:5}])
assert.deepEqual(reportKeys(r,Uint8Array.of(0)), [])
})
test('descriptor resource bounds and malformed items', () => {
for (const data of [new Uint8Array(),new Uint8Array(513),Uint8Array.of(0xfe),Uint8Array.of(0x75),
Uint8Array.of(0xb4),Uint8Array.of(0xc0),Uint8Array.of(0x85,0),Uint8Array.of(0x75,33,0x95,1,0x81,2),
Uint8Array.of(0x75,32,0x96,0,2,0x81,2),Uint8Array.of(0xa1,1)]) assert.throws(() => parseReportMap(data))
// Deterministic malformed corpus; parsing must be bounded and never hang.
let seed = 1
for (let i = 0; i < 1000; i++) {
const data = Uint8Array.from({length:i%128+1}, () => { seed=(Math.imul(seed,1664525)+1013904223)>>>0; return seed>>>24 })
try { parseReportMap(data) } catch (e) { assert.ok(e instanceof Error) }
}
})
test('control records, UUIDs and addresses', () => {
assert.deepEqual([...keyboardControl(4,0x1234,0x5678,[1,2,3,4,5,6,7])], [75,66,1,4,0x34,0x12,0x78,0x56,1,2,3,4,5,6,7])
assert.throws(() => keyboardControl(13,1,1))
assert.throws(() => keyboardControl(11,1,1,new Array(73).fill(0)))
assert.equal(attributeUuid(Uint8Array.of(0xfb,0x34,0x9b,0x5f,0x80,0,0,0x80,0,0x10,0,0,0x12,0x18,0,0)), 0x1812)
const address = parseKeyboardAddress('AA:bb:cc:dd:ee:01')
assert.deepEqual([...address], [1,0xee,0xdd,0xcc,0xbb,0xaa])
assert.equal(formatKeyboardAddress(address), 'aa:bb:cc:dd:ee:01')
assert.equal(parseKeyboardAddress('aa:bb:cc:dd:ee'), null)
assert.equal(parseKeyboardAddress('aa:bb:cc:dd:ee:gg'), null)
})
test('fragments, duplicate delivery, gaps, epochs and sequence wrap', () => {
let gaps = 0; const stream = new KeyboardRecords(() => gaps++)
const data = Uint8Array.from({length:200}, (_,i) => i)
assert.equal(stream.push(frame(3,0xffffffff,1,0,13,33,data.slice(0,96),0,200)), undefined)
assert.equal(stream.push(frame(3,0xffffffff,1,0,13,33,data.slice(96,192),96,200)), undefined)
assert.deepEqual(stream.push(frame(3,0xffffffff,1,0,13,33,data.slice(192),192,200)).data, data)
const status = frame(1,0,1,0,0,0,new Uint8Array(10))
assert.equal(stream.push(status).sequence, 0)
assert.equal(stream.push(status), undefined); assert.equal(gaps, 1)
stream.push(frame(1,2,1,0,0,0,new Uint8Array(10))); assert.equal(gaps, 2)
assert.equal(stream.push(status), undefined); assert.equal(gaps, 2)
stream.push(frame(1,3,2,0,0,0,new Uint8Array(10))); assert.equal(gaps, 3)
})
test('missing or mismatched fragments never emit partial input', () => {
let gaps = 0; const stream = new KeyboardRecords(() => gaps++)
stream.push(frame(3,1,1,0,13,10,new Uint8Array(96),0,100))
assert.equal(stream.push(frame(3,1,1,0,13,11,new Uint8Array(4),96,100)), undefined)
assert.equal(gaps, 2)
assert.equal(stream.push(frame(3,1,1,0,13,10,new Uint8Array(4),96,100)), undefined)
assert.equal(stream.push(new Uint8Array(513)), undefined)
// Another protocol version is not ours to decode.
const future = frame(1,5,1,0,0,0,new Uint8Array(10)); future[2] = 2
assert.equal(stream.push(future), undefined)
})
test('adverts: name from the scan response, HID from the service list or the appearance', () => {
const body = (ad, rssi = -60) => Uint8Array.from([1, 6,5,4,3,2,1, rssi & 255, 0, ad.length, ...ad])
const services = parseKeyboardAdvert(body([2,1,6, 3,3,0x12,0x18]))
assert.deepEqual(services, { addressType: 1, address: '01:02:03:04:05:06', rssi: -60, name: '', hid: true })
const named = parseKeyboardAdvert(body([5,9,0x4b,0x33,0x38,0x30], -48))
assert.equal(named.name, 'K380'); assert.equal(named.hid, false)
assert.deepEqual(mergeKeyboardAdverts(services, named), { ...services, name: 'K380', rssi: -48 })
assert.equal(parseKeyboardAdvert(body([3,0x19,0xc1,0x03])).hid, true)
assert.equal(parseKeyboardAdvert(body([3,0x19,0x41,0x03])).hid, false)
assert.equal(parseKeyboardAdvert(Uint8Array.of(1,2,3)), null)
// A truncated AD structure ends the parse without reading past the body.
assert.equal(parseKeyboardAdvert(body([9,9,0x41])).name, '')
})
/**
* The firmware bridge and a HOGP keyboard behind it, as far as the phone can
* tell: answers control records with the records the real one sends.
*/
function fakeGlasses(deliver) {
const attrs = new Map()
const add = (h, uuid, bytes) => attrs.set(h, { uuid, value: Uint8Array.from(bytes) })
const mockMap = Uint8Array.from([...numbered.slice(0,-1),0x85,3,0x05,6,0x09,0x20,0x15,0,0x25,100,0x75,8,0x95,1,0x81,2,0xc0])
add(1,0x2800,[1,0x18]); add(2,0x2803,[0x20,3,0,5,0x2a]); add(3,0x2a05,[]); add(4,0x2902,[0,0])
add(20,0x2800,[0x12,0x18])
add(21,0x2803,[2,22,0,0x4b,0x2a]); add(22,0x2a4b,mockMap); add(23,0x2907,[0x19,0x2a])
add(24,0x2803,[6,25,0,0x4e,0x2a]); add(25,0x2a4e,[1])
add(26,0x2803,[0x12,27,0,0x4d,0x2a]); add(27,0x2a4d,[]); add(28,0x2902,[0,0]); add(29,0x2908,[1,1])
add(30,0x2803,[0x12,31,0,0x4d,0x2a]); add(31,0x2a4d,[]); add(32,0x2902,[0,0]); add(33,0x2908,[2,1])
add(40,0x2800,[0x0f,0x18]); add(41,0x2803,[0x12,42,0,0x19,0x2a]); add(42,0x2a19,[100]); add(43,0x2902,[0,0]); add(44,0x2908,[3,1])
const g = {
seq: 0, epoch: 0, enabled: 0, conn: 0, connected: 0, encrypted: 0, scanning: 0,
ops: [], writes: [], watches: [], adverts: [], pins: [], compares: [],
reachable: true, bonded: false, pairing: 'just-works', up: true,
// The keyboard's attribute table, and how its stack answers a direct read
// of a characteristic declaration: 'full', 'short' (the properties byte
// alone) or 'refused'.
attrs, add, declarations: 'full',
}
g.emit = (kind, request, code, handle, data = []) =>
deliver(frame(kind, ++g.seq, g.epoch, request, code, handle, Uint8Array.from(data)))
g.status = (request = 0, code = 0) =>
g.emit(1, request, code, 0, [g.enabled, g.conn, g.connected, g.encrypted, g.scanning, 0, 0,0,0,0])
g.dm = (event, status = 0, data = []) => g.emit(4, 0, event | (status << 8), 0, data)
g.close = () => { if (!g.conn) return; g.conn = g.connected = g.encrypted = 0; g.watches = []; g.dm(0x28); g.status() }
g.encrypt = () => { g.encrypted = 1; g.dm(0x2c); g.status() }
g.input = (handle, bytes) => g.emit(3, 0, 13, handle, bytes)
g.send = (record) => {
if (!g.up) return false
const op = record[3], req = u16(record,4), epoch = u16(record,6), h = record.length >= 10 ? u16(record,8) : 0
g.ops.push(op)
if (op !== 0 && op !== 1 && epoch !== g.epoch) { g.status(req, 4); return true }
if (op === 0) g.status(req)
else if (op === 1) { g.enabled = 1; g.status(req) }
else if (op === 2) { g.enabled = 0; g.status(req); g.close() }
else if (op === 3) {
if (g.conn) { g.status(req, 3); return true }
g.scanning = 1; g.status(req)
for (const advert of g.adverts) g.emit(5, 0, 0, 0, advert)
g.scanning = 0; g.status()
} else if (op === 4) {
if (g.conn) { g.status(req, 3); return true }
g.epoch = (g.epoch + 1) & 0xffff; g.conn = 3; g.status(req)
if (!g.reachable) return true
g.connected = 1; g.dm(0x27); g.status()
if (g.bonded) g.encrypt()
} else if (op === 5) { g.status(req); g.close() }
else if (op === 6) {
if (!g.connected) { g.status(req, 6); return true }
g.status(req)
if (g.pairing === 'just-works') { g.dm(0x2a); g.encrypt() }
else if (g.pairing === 'display') g.dm(0x2e, 0, [0, 1])
else if (g.pairing === 'entry') g.dm(0x2e, 0, [0, 0])
else if (g.pairing === 'compare') g.dm(0x35, 0, [0x40, 0xe2, 0x01, 0])
else if (g.pairing === 'fail') { g.dm(0x2b, 5); g.close() }
} else if (op === 7) {
g.pins.push(record[8] | (record[9] << 8) | (record[10] << 16)); g.status(req); g.dm(0x2a); g.encrypt()
} else if (op === 8) {
g.compares.push(record[8]); g.status(req)
if (record[8]) { g.dm(0x2a); g.encrypt() } else { g.dm(0x2b, 4); g.close() }
} else if (op === 9) {
const batch = [...attrs].filter(([handle]) => handle >= h).slice(0,4)
g.emit(2, req, batch.length ? 2 : (10<<8)|2, h, batch.length ? [1, ...batch.flatMap(([handle,a]) => [...le16(handle), ...le16(a.uuid)])] : [])
} else if (op === 10) {
const attr = attrs.get(h), offset = u16(record,10)
if (attr.uuid === 0x2803 && g.declarations === 'refused') { g.emit(2, req, (2<<8)|5, h); return true }
const data = attr.uuid === 0x2803 && g.declarations === 'short' ? attr.value.slice(0,1) : attr.value
g.emit(2, req, offset >= data.length ? (7<<8)|6 : offset ? 6 : 5, h, data.slice(offset, offset+20))
} else if (op === 11) { g.writes.push(h); g.emit(2, req, record[10] ? 10 : 9, h) }
else if (op === 12) { g.watches = Array.from({length:record[8]}, (_,i) => u16(record,9+2*i)); g.status(req) }
else throw new Error(`Unexpected op ${op}`)
return true
}
return g
}
test('client: HOGP discovery, long Report Map, subscriptions, typing and loss recovery', async () => {
const events = []
let client
const g = fakeGlasses(payload => client.accept(payload))
client = new KeyboardClient(g.send, { keys: e => events.push(...e) })
await client.enable(); await client.connect(1, new Uint8Array(6)); const config = await client.configure()
// The battery level (an external report) is found, but it can't carry a
// key, so it isn't subscribed: only the two key reports and Service Changed.
assert.deepEqual(g.watches, [27,31,3]); assert.deepEqual(g.writes, [25,4,28,32])
assert.deepEqual(config.reports.map(r => r.id), [1,2,3]); assert.deepEqual(config.watched, [27,31])
assert.deepEqual(config.reports.map(r => r.properties), [0x12,0x12,0x12])
g.input(27, [0,0,4,0,0,0,0,0]); g.input(31, [1])
assert.deepEqual(events.map(e => [e.usage,e.down]), [[4,true],[0xe9,true]])
g.seq++ // a release lost in the firmware queue or on the way to the phone
g.status()
assert.deepEqual(events.slice(-2).map(e => e.down), [false,false])
// Another client on the same connection can take over with the mapping.
const restored = new KeyboardClient(() => true, { keys: e => events.push(...e) })
restored.restore(config); restored.accept(frame(3, g.seq + 1, g.epoch, 0, 13, 27, Uint8Array.of(0,0,5,0,0,0,0,0)))
assert.deepEqual([events.at(-1).usage, events.at(-1).down], [5, true]); restored.lostPhoneLink()
assert.deepEqual([events.at(-1).usage, events.at(-1).down], [5, false])
// Service Changed voids the handles: no more keys until configure() runs again.
g.emit(3, 0, 14, 3, [1,0,255,255])
const count = events.length; g.input(27, [0,0,6,0,0,0,0,0])
assert.equal(events.length, count)
client.close(); restored.close()
})
// A pointer's report, as a keyboard with a built-in trackpad adds: buttons and relative X/Y.
const mouseCollection = [0x05,1,0x09,2,0xa1,1,0x85,4,0x09,1,0xa1,0,0x05,9,0x19,1,0x29,3,0x15,0,0x25,1,0x75,1,0x95,3,0x81,2,
0x75,5,0x95,1,0x81,1,0x05,1,0x09,0x30,0x09,0x31,0x15,0x81,0x25,0x7f,0x75,8,0x95,2,0x81,6,0xc0,0xc0]
/** Turn the fake into a keyboard with a trackpad, whose battery level has no Report Reference. */
function makeCombo(g) {
g.add(22, 0x2a4b, [...g.attrs.get(22).value, ...mouseCollection])
g.add(34,0x2803,[0x12,35,0,0x4d,0x2a]); g.add(35,0x2a4d,[]); g.add(36,0x2902,[0,0]); g.add(37,0x2908,[4,1])
g.attrs.delete(44)
const sorted = [...g.attrs].sort((a, b) => a[0] - b[0])
g.attrs.clear(); for (const [handle, attr] of sorted) g.attrs.set(handle, attr)
}
for (const declarations of ['short', 'refused']) {
test(`client: a keyboard with a trackpad whose stack answers declaration reads ${declarations} still types`, async () => {
const events = [], logs = []
let client
const g = fakeGlasses(payload => client.accept(payload))
makeCombo(g); g.declarations = declarations
client = new KeyboardClient(g.send, { keys: e => events.push(...e), log: line => logs.push(line) })
await client.enable(); await client.connect(1, new Uint8Array(6)); const config = await client.configure()
// Keys and media keys are subscribed; the pointer and the battery are not.
assert.deepEqual(config.watched, [27,31]); assert.deepEqual(g.watches, [27,31,3]); assert.deepEqual(g.writes, [25,4,28,32])
assert.deepEqual(config.reports.map(r => [r.handle, r.id]), [[27,1],[31,2],[35,4]])
assert.deepEqual(config.reports.map(r => r.properties), declarations === 'short' ? [0x12,0x12,0x12] : [undefined,undefined,undefined])
g.input(27, [0,0,4,0,0,0,0,0])
assert.deepEqual(events.map(e => [e.usage,e.down]), [[4,true]])
// What was skipped, and why, is in the log; so is the table it came from.
assert.ok(logs.some(line => /^gatt 1=2800 2=2803 /.test(line)), logs.join('\n'))
assert.ok(logs.some(line => /report 42 skipped: no Report Reference/.test(line)), logs.join('\n'))
assert.ok(logs.some(line => /report 35 \(id 4\) carries no keys/.test(line)), logs.join('\n'))
assert.ok(logs.some(line => line.startsWith('report map 22: 0501')))
client.close()
})
}
test('client: one unusable report is skipped, and a device with no key report is refused with the reasons', async () => {
let client
const g = fakeGlasses(payload => client.accept(payload))
client = new KeyboardClient(g.send)
g.add(29, 0x2908, [1]) // a Report Reference of the wrong length
await client.enable(); await client.connect(1, new Uint8Array(6))
assert.deepEqual((await client.configure()).watched, [31])
g.add(33, 0x2908, [9,1]) // and one naming a report the map doesn't have
await assert.rejects(client.configure(), /No usable keyboard input report \(27: Report Reference 29 is 01; 31: input report id 9 is not in the Report Map\)/)
assert.equal(client.configuration, undefined)
// Not a HID device at all.
g.add(20, 0x2800, [0x0f,0x18])
await assert.rejects(client.configure(), /no HID service/)
client.close()
})
test('client: the link dropping during setup ends it, rather than being skipped over', async () => {
let client
const g = fakeGlasses(payload => client.accept(payload))
client = new KeyboardClient(g.send)
await client.enable(); await client.connect(1, new Uint8Array(6))
const send = g.send
g.send = (record) => {
// The keyboard goes away as the first Report Reference is read.
if (record[3] === 10 && u16(record, 8) === 29) { g.close(); return true }
return send(record)
}
client = new KeyboardClient(record => g.send(record))
await client.query()
await assert.rejects(client.configure(), /stream gap|link changed/)
client.close()
})
test('client: an unreachable keyboard fails the connect when the glasses give up, not by timeout', async () => {
let client
const g = fakeGlasses(payload => client.accept(payload)); g.reachable = false
client = new KeyboardClient(g.send)
await client.enable()
const pending = client.connect(1, new Uint8Array(6))
await settle(); g.close()
await assert.rejects(pending, /didn't answer/)
client.close()
})
test('client: firmware errors carry their code, and a dead link rejects at once', async () => {
let client
const g = fakeGlasses(payload => client.accept(payload))
client = new KeyboardClient(g.send)
await client.enable(); await client.connect(1, new Uint8Array(6))
await assert.rejects(client.command(4, [1,0,0,0,0,0,0]), e => e instanceof KeyboardClientError && e.code === 3)
g.up = false
await assert.rejects(client.query(), /aren't ready/)
client.close()
await assert.rejects(client.query(), /closed/)
})
function bridgeSetup(saved = null) {
const host = { keys: [], gone: 0, changes: 0, logs: [], prompts: [], saved, reconnect: true }
let bridge
const g = fakeGlasses(payload => bridge.accept(payload))
bridge = new KeyboardBridge({
send: g.send,
loadSaved: () => host.saved,
storeSaved: value => { host.saved = value },
onKeys: events => host.keys.push(...events),
onKeyboardGone: () => { host.gone++ },
onChanged: () => {
host.changes++
const pairing = bridge.snapshot().pairing
if (pairing && host.prompts.at(-1) !== pairing) host.prompts.push(pairing)
},
log: line => host.logs.push(line),
randomPasskey: () => 123456,
shouldReconnect: () => host.reconnect,
})
return { bridge, g, host }
}
const K380 = { address: 'aa:bb:cc:dd:ee:01', addressType: 1, name: 'K380' }
const advertOf = (lastByte, ad) => [1, lastByte,0xee,0xdd,0xcc,0xbb,0xaa, 0xc4, 0, ad.length, ...ad]
test('bridge: scan, pick, pair by typing the displayed passkey, type, forget', async () => {
const { bridge, g, host } = bridgeSetup()
assert.equal(bridge.snapshot().state, 'unavailable')
await assert.rejects(bridge.scan(), /Connect to G2 glasses/)
bridge.linkReady()
g.adverts = [
advertOf(2, [2,1,6]), // some other device
advertOf(1, [2,1,6, 3,3,0x12,0x18]), // the keyboard's advertisement
advertOf(1, [5,9,0x4b,0x33,0x38,0x30]), // and its scan response, with the name
]
const found = await bridge.scan()
assert.deepEqual(found.map(a => [a.address, a.name, a.hid]), [[K380.address,'K380',true],['aa:bb:cc:dd:ee:02','',false]])
assert.equal(bridge.snapshot().state, 'idle')
g.pairing = 'display'
await bridge.connect(K380)
// The passkey went up for the user to type, and to the glasses as the answer.
assert.deepEqual(host.prompts, [{ kind: 'display', pin: 123456 }])
assert.deepEqual(g.pins, [123456])
assert.equal(bridge.snapshot().state, 'connected'); assert.equal(bridge.snapshot().pairing, null)
assert.deepEqual(host.saved, K380); assert.ok(bridge.isConnected())
g.input(27, [2,0,4,0,0,0,0,0])
assert.deepEqual(host.keys.map(k => [k.usage, k.down]), [[0xe1,true],[4,true]])
await bridge.forget()
assert.equal(host.saved, null); assert.equal(host.gone, 1); assert.equal(g.conn, 0); assert.equal(g.enabled, 0)
assert.equal(bridge.snapshot().state, 'idle')
bridge.linkLost()
})
test('bridge: numeric comparison waits for the answer; declining fails the pairing', async () => {
const { bridge, g } = bridgeSetup()
bridge.linkReady(); g.pairing = 'compare'
const pending = bridge.connect(K380)
await settle()
assert.deepEqual(bridge.snapshot().pairing, { kind: 'compare', value: 123456 })
assert.equal(bridge.snapshot().state, 'pairing')
await bridge.answerCompare(false)
await assert.rejects(pending, /Pairing with the keyboard failed/)
assert.equal(bridge.snapshot().state, 'error'); assert.deepEqual(g.compares, [0])
await assert.rejects(bridge.answerCompare(true), /No pairing comparison/)
bridge.linkLost()
})
test('bridge: a keyboard that shows a code is paired with the code typed in', async () => {
const { bridge, g } = bridgeSetup()
bridge.linkReady(); g.pairing = 'entry'
const pending = bridge.connect(K380)
await settle()
assert.deepEqual(bridge.snapshot().pairing, { kind: 'entry' })
await bridge.answerPasskey(42)
await pending
assert.deepEqual(g.pins, [42]); assert.equal(bridge.snapshot().state, 'connected')
bridge.linkLost()
})
test('bridge: the remembered keyboard comes back with the link, and again after it drops', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] })
const { bridge, g, host } = bridgeSetup(K380)
g.bonded = true
bridge.linkReady()
assert.equal(bridge.snapshot().waiting, true)
t.mock.timers.tick(1000); await settle()
assert.equal(bridge.snapshot().state, 'connected'); assert.equal(g.connected, 1)
// The keyboard goes to sleep: held keys are dropped, and it is looked for again.
g.input(27, [0,0,4,0,0,0,0,0])
g.close(); await settle()
assert.equal(host.gone, 1); assert.equal(bridge.snapshot().state, 'idle'); assert.equal(bridge.snapshot().waiting, true)
g.reachable = false
t.mock.timers.tick(2000); await settle()
assert.equal(bridge.snapshot().state, 'connecting')
g.close(); await settle()
// Asleep is the ordinary case, not an error in front of the user.
assert.equal(bridge.snapshot().state, 'idle'); assert.equal(bridge.snapshot().error, '')
g.reachable = true
t.mock.timers.tick(2000); await settle()
assert.equal(bridge.snapshot().state, 'connected')
// Disconnecting by hand stops the retries until asked again.
await bridge.disconnect()
assert.equal(bridge.snapshot().waiting, false); assert.equal(g.enabled, 0)
t.mock.timers.tick(60000); await settle()
assert.equal(bridge.snapshot().state, 'idle'); assert.equal(g.connected, 0)
bridge.linkLost()
})
test('bridge: the glasses kept the keyboard through a phone-side drop, so only discovery is redone', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] })
const { bridge, g, host } = bridgeSetup(K380)
g.bonded = true
bridge.linkReady(); t.mock.timers.tick(1000); await settle()
assert.equal(bridge.snapshot().state, 'connected')
const epoch = g.epoch
bridge.linkLost()
assert.equal(bridge.snapshot().state, 'unavailable'); assert.equal(host.gone, 1)
g.ops.length = 0
bridge.linkReady(); t.mock.timers.tick(1000); await settle()
assert.equal(bridge.snapshot().state, 'connected')
assert.equal(g.epoch, epoch, 'no reconnect of the keyboard itself')
assert.ok(!g.ops.includes(4) && !g.ops.includes(2))
g.input(27, [0,0,7,0,0,0,0,0])
assert.deepEqual([host.keys.at(-1).usage, host.keys.at(-1).down], [7, true])
bridge.linkLost()
})
test('bridge: a scan started by hand takes over from an attempt in flight, and nothing retries while charging', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] })
const { bridge, g, host } = bridgeSetup(K380)
g.reachable = false
bridge.linkReady(); t.mock.timers.tick(1000); await settle()
assert.equal(bridge.snapshot().state, 'connecting'); assert.equal(g.conn, 3)
g.adverts = [advertOf(1, [3,3,0x12,0x18])]
const scan = bridge.scan()
await settle(); t.mock.timers.tick(200); await settle()
assert.equal((await scan).length, 1)
assert.equal(g.conn, 0, 'the pending connection was released first')
assert.equal(bridge.snapshot().state, 'idle'); assert.equal(bridge.snapshot().busy, false)
// Reconnecting waits for the glasses to be in use.
host.reconnect = false
bridge.linkLost(); bridge.linkReady(); g.ops.length = 0
t.mock.timers.tick(1000); await settle()
t.mock.timers.tick(120000); await settle()
assert.deepEqual(g.ops, [])
// A bridge left enabled by an attempt is switched off for the wait, so the
// firmware's timer and its once-a-second status stop.
host.reconnect = true; g.reachable = false
bridge.retryNow(); t.mock.timers.tick(0); await settle()
assert.equal(g.enabled, 1); assert.equal(bridge.snapshot().state, 'connecting')
g.close(); await settle()
host.reconnect = false
t.mock.timers.tick(2000); await settle()
assert.equal(g.enabled, 0)
g.ops.length = 0
t.mock.timers.tick(120000); await settle()
assert.deepEqual(g.ops, [])
// The display woke: no waiting out the rest of the backoff.
host.reconnect = true; g.reachable = true; g.bonded = true
bridge.retryNow()
t.mock.timers.tick(0); await settle()
assert.equal(bridge.snapshot().state, 'connected')
// With the keyboard in use, or none remembered, there is nothing to retry.
g.ops.length = 0
bridge.retryNow(); t.mock.timers.tick(0); await settle()
assert.deepEqual(g.ops, [])
bridge.linkLost()
})
test('bridge: leaving on purpose tells the glasses to let the keyboard go', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] })
const { bridge, g } = bridgeSetup(K380)
g.bonded = true
bridge.linkReady(); t.mock.timers.tick(1000); await settle()
assert.equal(g.connected, 1)
bridge.linkClosing(); bridge.linkLost()
assert.equal(g.enabled, 0); assert.equal(g.conn, 0)
// With no keyboard in use there is nothing to say.
const idle = bridgeSetup()
idle.bridge.linkReady(); idle.bridge.linkClosing(); idle.bridge.linkLost()
assert.deepEqual(idle.g.ops, [])
})
test('bridge: a keyboard forgotten while the glasses were away is released when they return', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] })
const { bridge, g, host } = bridgeSetup(K380)
g.bonded = true
bridge.linkReady(); t.mock.timers.tick(1000); await settle()
assert.equal(g.connected, 1)
bridge.linkLost()
await bridge.forget()
assert.equal(host.saved, null); assert.equal(g.connected, 1, 'out of reach, so still attached')
bridge.linkReady(); await settle()
assert.equal(g.enabled, 0); assert.equal(g.conn, 0)
t.mock.timers.tick(60000); await settle()
assert.equal(bridge.snapshot().state, 'idle'); assert.equal(bridge.snapshot().waiting, false)
bridge.linkLost()
})
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more