forked from Blendman974/faceclaw
Add options to load an app from a URL or a QR code
(The QR code reading does not work yet)
This commit is contained in:
1 parent
6e4ece5dc7
commit
92cd05b6ca
22 files changed
+685
-93
No files matched your search
@@ -0,0 +1,143 @@
|
||||
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 { GESTURE_DOUBLE_CLICK } from "../../ui/gestures";
|
||||
import { Layer, type DashboardInputEvent, type LayerContext } from "../../ui/layers";
|
||||
import { shell } from "../../ui/shell/shell";
|
||||
|
||||
// IMU report pace. This is NOT a literal Hz — the firmware only accepts the
|
||||
// ImuReportPace codes 100..1000 (step 100); the real delivery rate is
|
||||
// device-defined. An out-of-range value makes the firmware stream empty
|
||||
// (all-zero) samples. 200 matches the reference EvenHub running-tracker app.
|
||||
const IMU_REPORT_PACE = 200;
|
||||
// How often to reconcile the IMU on/off state with window visibility.
|
||||
const RECONCILE_INTERVAL_MS = 400;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* The IMU stream is experimental — the firmware may never populate it — so the
|
||||
* page also reports how many samples have arrived.
|
||||
*/
|
||||
export class AccelerometerDemoLayer implements Layer {
|
||||
private reading: ImuReading | null = null;
|
||||
private sampleCount = 0;
|
||||
private peak = 0;
|
||||
private enabled = false;
|
||||
private removed = false;
|
||||
private reconcileTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private unsubscribe: (() => void) | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly windowId: string,
|
||||
private readonly requestRender: () => void,
|
||||
) {
|
||||
this.start();
|
||||
}
|
||||
|
||||
private start(): void {
|
||||
this.unsubscribe = addImuListener((reading) => {
|
||||
if (this.removed) return;
|
||||
this.reading = reading;
|
||||
this.sampleCount++;
|
||||
this.peak = Math.max(this.peak, Math.abs(reading.x), Math.abs(reading.y), Math.abs(reading.z));
|
||||
this.requestRender();
|
||||
});
|
||||
this.reconcileTimer = setInterval(() => this.reconcile(), RECONCILE_INTERVAL_MS);
|
||||
this.reconcile();
|
||||
}
|
||||
|
||||
/** Match the IMU on/off state to whether this page is currently visible. */
|
||||
private reconcile(): void {
|
||||
if (this.removed) return;
|
||||
const visible = shell.isWindowVisible(this.windowId);
|
||||
if (visible === this.enabled) return;
|
||||
this.enabled = visible;
|
||||
setImuReportEnabled(visible, IMU_REPORT_PACE);
|
||||
this.requestRender();
|
||||
}
|
||||
|
||||
onRemoved(): void {
|
||||
this.removed = true;
|
||||
if (this.reconcileTimer !== null) {
|
||||
clearInterval(this.reconcileTimer);
|
||||
this.reconcileTimer = null;
|
||||
}
|
||||
this.unsubscribe?.();
|
||||
this.unsubscribe = null;
|
||||
if (this.enabled) {
|
||||
setImuReportEnabled(false, IMU_REPORT_PACE);
|
||||
this.enabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
const small = getDefaultSmallFont();
|
||||
const medium = getDefaultMediumFont();
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const image = new GrayImage(width, height, 0);
|
||||
|
||||
image.drawText(small, 20, 8, "Accelerometer", 220);
|
||||
const status = this.enabled ? "IMU on" : "IMU off";
|
||||
image.drawText(small, width - 20 - small.measureText(status), 8, status, 150);
|
||||
|
||||
if (this.reading) {
|
||||
const axes: Array<[string, number]> = [
|
||||
["X", this.reading.x],
|
||||
["Y", this.reading.y],
|
||||
["Z", this.reading.z],
|
||||
];
|
||||
const barX = 118;
|
||||
const barW = width - barX - 24;
|
||||
const scale = Math.max(this.peak, 1e-6);
|
||||
let y = 40;
|
||||
for (const [label, value] of axes) {
|
||||
image.drawText(medium, 22, y, label, 210);
|
||||
image.drawText(medium, 44, y, value.toFixed(3), 235);
|
||||
drawCenteredBar(image, barX, y + 2, barW, 12, clamp(value / scale, -1, 1));
|
||||
y += 30;
|
||||
}
|
||||
image.drawText(
|
||||
small,
|
||||
22,
|
||||
y + 6,
|
||||
`source: ${imuSourceLabel(this.reading.source)} samples: ${this.sampleCount}`,
|
||||
130,
|
||||
);
|
||||
} else {
|
||||
const message = this.enabled
|
||||
? "Waiting for IMU data…"
|
||||
: "Paused (page not visible).";
|
||||
image.drawText(small, 22, 44, message, 190);
|
||||
image.drawText(small, 22, 66, "The firmware may not report the", 120);
|
||||
image.drawText(small, 22, 82, "accelerometer at all — experimental.", 120);
|
||||
}
|
||||
|
||||
image.drawText(small, 20, height - 16, `${GESTURE_DOUBLE_CLICK} back`, 110);
|
||||
return image;
|
||||
}
|
||||
|
||||
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
|
||||
if (event.type === "double-click") {
|
||||
ctx.stack.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Horizontal bar centered at its midpoint; frac in [-1, 1] fills left/right. */
|
||||
function drawCenteredBar(image: GrayImage, x: number, y: number, width: number, height: number, frac: number): void {
|
||||
const mid = x + Math.round(width / 2);
|
||||
image.fillRect(x, y, width, height, 20);
|
||||
image.setPixel(mid, y - 1, 90);
|
||||
image.setPixel(mid, y + height, 90);
|
||||
const half = width / 2;
|
||||
const px = Math.round(clamp(frac, -1, 1) * half);
|
||||
if (px >= 0) {
|
||||
image.fillRect(mid, y, Math.max(1, px), height, 200);
|
||||
} else {
|
||||
image.fillRect(mid + px, y, -px, height, 200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { clamp } from "../../util/numeric-util";
|
||||
import { Layer, type DashboardInputEvent, type LayerActions, type LayerContext } from "../../ui/layers";
|
||||
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL } from "../../ui/gestures";
|
||||
import { drawSelectionHighlight, scrollToKeepSelectionVisible } from "../../ui/menu";
|
||||
import { tightRowHeight } from "../../ui/metrics";
|
||||
import {
|
||||
buildSoundSequencePayload,
|
||||
CFW_SEQ_MAX,
|
||||
effectPhrases,
|
||||
phraseDurationMs,
|
||||
SOUND_EFFECTS,
|
||||
type SoundEffect,
|
||||
} from "../../ui/sound-effects";
|
||||
|
||||
const HEADER_HEIGHT = 30;
|
||||
const LIST_X = 20;
|
||||
const FOOTER_HEIGHT = 22;
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
/**
|
||||
* Buzzer demo: pick a sound effect from the catalog and play it on the
|
||||
* glasses' piezo. Multi-phrase effects are paced phrase-by-phrase so each
|
||||
* sequencer message lands as the previous phrase finishes.
|
||||
*/
|
||||
export class BuzzerDemoLayer implements Layer {
|
||||
private selectedIndex = 0;
|
||||
private scrollRow = 0;
|
||||
private playing: string | null = null;
|
||||
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
const font = getDefaultSmallFont();
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const image = new GrayImage(width, height, 0);
|
||||
|
||||
image.drawText(font, 20, 8, "Buzzer demo", 220);
|
||||
const status = this.playing ? `Playing: ${this.playing}` : `${GESTURE_CLICK} play`;
|
||||
image.drawText(font, width - 24 - font.measureText(status), 8, status, 140);
|
||||
|
||||
const listHeight = height - HEADER_HEIGHT - FOOTER_HEIGHT;
|
||||
const rowH = tightRowHeight(font);
|
||||
const visibleRows = Math.max(1, (listHeight / rowH) | 0);
|
||||
this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.selectedIndex, visibleRows, SOUND_EFFECTS.length);
|
||||
|
||||
const lastVisible = Math.min(SOUND_EFFECTS.length, this.scrollRow + visibleRows);
|
||||
for (let index = this.scrollRow; index < lastVisible; index++) {
|
||||
const effect = SOUND_EFFECTS[index]!;
|
||||
const y = HEADER_HEIGHT + (index - this.scrollRow) * rowH;
|
||||
const selected = index === this.selectedIndex;
|
||||
if (selected) {
|
||||
drawSelectionHighlight(image, LIST_X - 6, y - 1, width - 2 * LIST_X + 12, rowH - 1, ctx.stack.isFocused(), 4);
|
||||
}
|
||||
image.drawText(font, LIST_X, y + 1, effect.name, selected ? 255 : 200);
|
||||
image.drawText(font, LIST_X + 110, y + 1, effect.desc, selected ? 180 : 120);
|
||||
}
|
||||
|
||||
image.drawText(font, 20, height - 16, `${GESTURE_SCROLL} select ${GESTURE_CLICK} play ${GESTURE_DOUBLE_CLICK} back`, 110);
|
||||
return image;
|
||||
}
|
||||
|
||||
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
|
||||
switch (event.type) {
|
||||
case "scroll-up":
|
||||
this.selectedIndex = Math.max(0, this.selectedIndex - 1);
|
||||
return;
|
||||
case "scroll-down":
|
||||
this.selectedIndex = Math.min(SOUND_EFFECTS.length - 1, this.selectedIndex + 1);
|
||||
return;
|
||||
case "click": {
|
||||
const effect = SOUND_EFFECTS[clamp(this.selectedIndex, 0, SOUND_EFFECTS.length - 1)];
|
||||
if (effect && !this.playing) {
|
||||
// Fire-and-forget: playback paces itself with sleeps between
|
||||
// phrases; awaiting it here would stall input for seconds.
|
||||
void this.playEffect(effect, ctx.actions).catch((error) => {
|
||||
console.warn(`buzzer effect failed: ${error}`);
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "double-click":
|
||||
ctx.stack.pop();
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private async playEffect(effect: SoundEffect, actions: LayerActions): Promise<void> {
|
||||
this.playing = effect.name;
|
||||
actions.requestRender();
|
||||
try {
|
||||
for (const phrase of effectPhrases(effect.make())) {
|
||||
// Safety net: chop any over-long phrase into <=48-step messages.
|
||||
for (let index = 0; index < phrase.length; index += CFW_SEQ_MAX) {
|
||||
const chunk = phrase.slice(index, index + CFW_SEQ_MAX);
|
||||
await actions.playBuzzerSequence(buildSoundSequencePayload(chunk));
|
||||
await sleep(phraseDurationMs(chunk));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.playing = null;
|
||||
actions.requestRender();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import { MenuLayer, drawSubmenuIndicator, type MenuItem } from "../../ui/menu";
|
||||
import { ScreenTestLayer } from "./screen-test";
|
||||
import { BuzzerDemoLayer } from "./buzzer-demo";
|
||||
import { AccelerometerDemoLayer } from "./accelerometer-demo";
|
||||
import { ResourceUsageLayer } from "./resource-usage";
|
||||
import { LoadAppFromQrLayer, LoadAppFromUrlLayer } from "./load-app";
|
||||
import { type AppContext } from "../app-definition";
|
||||
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { appViewportSize } from "../../ui/shell/geometry";
|
||||
import { LIST_ROW_TEXT_INSET } from "../../ui/metrics";
|
||||
import {
|
||||
createInProcessWindow,
|
||||
YieldAtRootLayer,
|
||||
type InProcessAppOptions,
|
||||
type InProcessWindow,
|
||||
} from "../../ui/shell/in-process-window";
|
||||
|
||||
export const DEVELOPER_WINDOW_ID = "developer";
|
||||
export const DEVELOPER_SURFACE_ID = "window:developer";
|
||||
|
||||
const MENU_LAYOUT = {
|
||||
x: 8,
|
||||
y: 8,
|
||||
width: 272,
|
||||
showBorder: false,
|
||||
minHeight: 0,
|
||||
maxHeight: appViewportSize("min").height - 16,
|
||||
};
|
||||
|
||||
/** A row that opens a nested page: the label plus a right-edge ">". */
|
||||
function submenuItem(label: string, onSelect: MenuItem["onSelect"]): MenuItem {
|
||||
return {
|
||||
label,
|
||||
onSelect,
|
||||
render: ({ image, x, y, width, height, selected, disabled, text }) => {
|
||||
const font = getDefaultSmallFont();
|
||||
const value = disabled ? 70 : selected ? 255 : 200;
|
||||
image.drawText(font, x, y + LIST_ROW_TEXT_INSET, text, value);
|
||||
drawSubmenuIndicator(image, font, x, y, width, height, value);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The diagnostic demos, one level down from the root menu. */
|
||||
function debugTestsMenu(): MenuLayer {
|
||||
return new MenuLayer(
|
||||
"Debug tests",
|
||||
[
|
||||
{
|
||||
label: "Dither test",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.push(new ScreenTestLayer());
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Buzzer demo",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.push(new BuzzerDemoLayer());
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Accelerometer demo",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.push(new AccelerometerDemoLayer(DEVELOPER_WINDOW_ID, ctx.actions.requestRender));
|
||||
},
|
||||
},
|
||||
],
|
||||
MENU_LAYOUT,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Developer app: tools for building and debugging on the glasses. The two
|
||||
* "Load app" entries run an EvenHub app straight off a web server, without
|
||||
* packaging it into an .ehpk first; the diagnostic demos live one level down
|
||||
* under "Debug tests".
|
||||
*/
|
||||
export function createDeveloperAppWindow(appContext: AppContext, options: InProcessAppOptions): InProcessWindow {
|
||||
const menu = new MenuLayer(
|
||||
"Developer",
|
||||
[
|
||||
{
|
||||
label: "Load app from URL",
|
||||
onSelect: (ctx) => {
|
||||
const layer = new LoadAppFromUrlLayer(appContext);
|
||||
ctx.stack.push(layer);
|
||||
layer.open(ctx);
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Load app from QR code",
|
||||
onSelect: (ctx) => {
|
||||
const layer = new LoadAppFromQrLayer(appContext);
|
||||
ctx.stack.push(layer);
|
||||
layer.open(ctx);
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Show resource usage",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.push(new ResourceUsageLayer(DEVELOPER_WINDOW_ID, ctx.actions.requestRender));
|
||||
},
|
||||
},
|
||||
submenuItem("Debug tests", (ctx) => {
|
||||
ctx.stack.push(debugTestsMenu());
|
||||
}),
|
||||
],
|
||||
MENU_LAYOUT,
|
||||
);
|
||||
let created: InProcessWindow | null = null;
|
||||
created = createInProcessWindow({
|
||||
appId: "developer",
|
||||
windowId: DEVELOPER_WINDOW_ID,
|
||||
title: "Developer",
|
||||
iconLetter: "Dv",
|
||||
icon: "wrench",
|
||||
closeable: true,
|
||||
actions: options.actions,
|
||||
// Dictating a URL is the one thing worth speaking at in this app; the
|
||||
// load pages take the text and every other page ignores it.
|
||||
receiveTextInput: (text) => {
|
||||
if (created?.stack.receiveTextInput(text)) created.requestRender();
|
||||
},
|
||||
baseLayer: new YieldAtRootLayer(menu),
|
||||
submitFrame: options.submitFrame,
|
||||
setSurfaceVisible: options.setSurfaceVisible,
|
||||
removeSurface: options.removeSurface,
|
||||
onClosed: options.onClosed,
|
||||
});
|
||||
return created;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { type AppDefinition } from "../app-definition";
|
||||
import { createDeveloperAppWindow, DEVELOPER_SURFACE_ID, DEVELOPER_WINDOW_ID } from "./developer-app";
|
||||
|
||||
const developerApp: AppDefinition = {
|
||||
appId: "developer",
|
||||
title: "Developer",
|
||||
icon: "wrench",
|
||||
launch: (ctx) =>
|
||||
ctx.launchInProcessApp(DEVELOPER_WINDOW_ID, DEVELOPER_SURFACE_ID, (options) =>
|
||||
createDeveloperAppWindow(ctx, options),
|
||||
),
|
||||
};
|
||||
|
||||
export default developerApp;
|
||||
@@ -0,0 +1,207 @@
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { wrapText } from "../../graphics/textwrap";
|
||||
import { type AppContext } from "../app-definition";
|
||||
import { isLoadableAppUrl, openEvenHubUrl } from "../evenhub";
|
||||
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK } from "../../ui/gestures";
|
||||
import { Layer, type DashboardInputEvent, type LayerContext } from "../../ui/layers";
|
||||
import { lineStep } from "../../ui/metrics";
|
||||
import { developerAppUrlSetting } from "../../ui/dashboard-settings";
|
||||
import { isQrScannerAvailable, scanQrCode } from "../../native/qr-scan";
|
||||
|
||||
const MARGIN = 20;
|
||||
|
||||
/**
|
||||
* "Load app from URL": the glasses side of the phone text editor. Entering the
|
||||
* page opens the editor on developerAppUrlSetting, the typed URL echoes here
|
||||
* as it changes, and a click (or the phone keyboard's done key) launches it as
|
||||
* an EvenHub app. The draft persists, so reloading after an edit-and-rebuild is
|
||||
* one click.
|
||||
*/
|
||||
export class LoadAppFromUrlLayer implements Layer {
|
||||
private error = "";
|
||||
private launching = false;
|
||||
|
||||
constructor(private readonly ctx: AppContext) {}
|
||||
|
||||
/** Opens the phone editor; call right after pushing the layer. */
|
||||
open(ctx: LayerContext): void {
|
||||
void ctx.actions.startTextSettingsEdit([developerAppUrlSetting], "Load app from URL", () => {
|
||||
void this.launch(ctx);
|
||||
});
|
||||
}
|
||||
|
||||
/** Leaving the page by any route closes the phone editor with it. */
|
||||
onRemoved(): void {
|
||||
void this.ctx.actions.endTextSettingEdit();
|
||||
}
|
||||
|
||||
/** Dictated text fills the draft, same as typing it on the phone. */
|
||||
receiveTextInput(text: string): void {
|
||||
developerAppUrlSetting.set(text);
|
||||
this.error = "";
|
||||
}
|
||||
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
const font = getDefaultSmallFont();
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const image = new GrayImage(width, height, 0);
|
||||
const step = lineStep(font);
|
||||
const textWidth = width - 2 * MARGIN;
|
||||
|
||||
image.drawText(font, MARGIN, 8, "Load app from URL", 220);
|
||||
let y = 8 + step + 6;
|
||||
image.drawText(font, MARGIN, y, "Type the app's URL in the phone app", 150);
|
||||
y += step;
|
||||
image.drawText(font, MARGIN, y, "(or use voice input from the menu).", 150);
|
||||
y += step + 8;
|
||||
|
||||
const url = developerAppUrlSetting.get();
|
||||
for (const line of wrapText(font, url || "(empty)", textWidth).slice(0, 3)) {
|
||||
image.drawText(font, MARGIN, y, line, url ? 230 : 110);
|
||||
y += step;
|
||||
}
|
||||
if (this.error) {
|
||||
y += 4;
|
||||
for (const line of wrapText(font, this.error, textWidth).slice(0, 2)) {
|
||||
image.drawText(font, MARGIN, y, line, 150);
|
||||
y += step;
|
||||
}
|
||||
}
|
||||
|
||||
const footer = this.launching
|
||||
? "Loading..."
|
||||
: `${GESTURE_CLICK} load ${GESTURE_DOUBLE_CLICK} cancel`;
|
||||
image.drawText(font, MARGIN, height - font.lineHeight - 12, footer, 110);
|
||||
return image;
|
||||
}
|
||||
|
||||
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
|
||||
switch (event.type) {
|
||||
case "click":
|
||||
void this.launch(ctx);
|
||||
return;
|
||||
case "double-click":
|
||||
ctx.stack.pop();
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private async launch(ctx: LayerContext): Promise<void> {
|
||||
if (this.launching) return;
|
||||
const url = developerAppUrlSetting.get();
|
||||
if (!isLoadableAppUrl(url)) {
|
||||
this.error = url ? "Not an http:// or https:// URL." : "Enter a URL first.";
|
||||
ctx.actions.requestRender();
|
||||
return;
|
||||
}
|
||||
this.launching = true;
|
||||
this.error = "";
|
||||
ctx.actions.requestRender();
|
||||
try {
|
||||
await openEvenHubUrl(this.ctx, url);
|
||||
ctx.stack.pop();
|
||||
} catch (error) {
|
||||
this.error = cleanError(error);
|
||||
this.ctx.appendLog(`evenhub url launch failed: ${this.error}`);
|
||||
} finally {
|
||||
this.launching = false;
|
||||
ctx.actions.requestRender();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* "Load app from QR code": hand off to an installed scanner app, then launch
|
||||
* whatever URL it decodes. The scanned URL is kept in developerAppUrlSetting so
|
||||
* the URL page can reload it later without rescanning.
|
||||
*/
|
||||
export class LoadAppFromQrLayer implements Layer {
|
||||
private status = "Starting scanner...";
|
||||
private busy = false;
|
||||
|
||||
constructor(private readonly ctx: AppContext) {}
|
||||
|
||||
/** Launches the scanner; call right after pushing the layer. */
|
||||
open(ctx: LayerContext): void {
|
||||
if (!isQrScannerAvailable()) {
|
||||
this.status = "No QR scanner app is installed on the phone.";
|
||||
ctx.actions.requestRender();
|
||||
return;
|
||||
}
|
||||
this.busy = true;
|
||||
void this.scan(ctx);
|
||||
}
|
||||
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
const font = getDefaultSmallFont();
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const image = new GrayImage(width, height, 0);
|
||||
const step = lineStep(font);
|
||||
|
||||
image.drawText(font, MARGIN, 8, "Load app from QR code", 220);
|
||||
let y = 8 + step + 6;
|
||||
for (const line of wrapText(font, this.status, width - 2 * MARGIN).slice(0, 5)) {
|
||||
image.drawText(font, MARGIN, y, line, 170);
|
||||
y += step;
|
||||
}
|
||||
|
||||
const footer = this.busy ? `${GESTURE_DOUBLE_CLICK} back` : `${GESTURE_CLICK} scan again ${GESTURE_DOUBLE_CLICK} back`;
|
||||
image.drawText(font, MARGIN, height - font.lineHeight - 12, footer, 110);
|
||||
return image;
|
||||
}
|
||||
|
||||
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
|
||||
switch (event.type) {
|
||||
case "click":
|
||||
if (!this.busy && isQrScannerAvailable()) {
|
||||
this.busy = true;
|
||||
this.status = "Starting scanner...";
|
||||
ctx.actions.requestRender();
|
||||
void this.scan(ctx);
|
||||
}
|
||||
return;
|
||||
case "double-click":
|
||||
ctx.stack.pop();
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private async scan(ctx: LayerContext): Promise<void> {
|
||||
try {
|
||||
this.status = "Point the phone camera at the QR code.";
|
||||
ctx.actions.requestRender();
|
||||
const scanned = await scanQrCode();
|
||||
if (scanned === null) {
|
||||
this.status = "Scan cancelled.";
|
||||
return;
|
||||
}
|
||||
if (!isLoadableAppUrl(scanned)) {
|
||||
this.status = `Not a URL: ${scanned}`;
|
||||
return;
|
||||
}
|
||||
developerAppUrlSetting.set(scanned);
|
||||
this.status = `Loading ${scanned}`;
|
||||
ctx.actions.requestRender();
|
||||
await openEvenHubUrl(this.ctx, scanned);
|
||||
ctx.stack.pop();
|
||||
} catch (error) {
|
||||
this.status = cleanError(error);
|
||||
this.ctx.appendLog(`evenhub qr launch failed: ${this.status}`);
|
||||
} finally {
|
||||
this.busy = false;
|
||||
ctx.actions.requestRender();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function cleanError(error: unknown): string {
|
||||
return String((error as Error)?.message ?? error)
|
||||
.replace(/[\x00-\x1f]+/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { clamp } from "../../util/numeric-util";
|
||||
import { GESTURE_DOUBLE_CLICK } from "../../ui/gestures";
|
||||
import { Layer, type DashboardInputEvent, type LayerContext } from "../../ui/layers";
|
||||
import { shell } from "../../ui/shell/shell";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
const SAMPLE_INTERVAL_MS = 1_000;
|
||||
const HISTORY_MS = 60_000;
|
||||
const MAX_SAMPLES = Math.ceil(HISTORY_MS / SAMPLE_INTERVAL_MS) + 2;
|
||||
|
||||
type ResourceSample = {
|
||||
atMs: number;
|
||||
rssMb: number;
|
||||
nativeMb: number;
|
||||
javaMb: number;
|
||||
javaCommittedMb: number;
|
||||
cpuPercent: number;
|
||||
threads: number;
|
||||
};
|
||||
|
||||
type Series = {
|
||||
value: (sample: ResourceSample) => number;
|
||||
shade: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* One-minute process monitor. Sampling deliberately continues while another
|
||||
* window is foreground so switching back reveals the resource cost of that
|
||||
* workload. Repaints remain visibility-gated to avoid creating hidden frames.
|
||||
*/
|
||||
export class ResourceUsageLayer implements Layer {
|
||||
private readonly samples: ResourceSample[] = [];
|
||||
private timer: ReturnType<typeof setInterval> | null = null;
|
||||
private removed = false;
|
||||
private previousElapsedMs = 0;
|
||||
private previousCpuMs = 0;
|
||||
private sampleError = "";
|
||||
|
||||
constructor(
|
||||
private readonly windowId: string,
|
||||
private readonly requestRender: () => void,
|
||||
) {
|
||||
this.takeSample();
|
||||
this.timer = setInterval(() => this.takeSample(), SAMPLE_INTERVAL_MS);
|
||||
}
|
||||
|
||||
onRemoved(): void {
|
||||
this.removed = true;
|
||||
if (this.timer !== null) {
|
||||
clearInterval(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
}
|
||||
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
const font = getDefaultSmallFont();
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const image = new GrayImage(width, height, 0);
|
||||
const latest = this.samples[this.samples.length - 1];
|
||||
|
||||
image.drawText(font, 16, 5, "Resource usage — last minute", 230);
|
||||
if (!latest) {
|
||||
image.drawText(font, 16, 30, this.sampleError || "Waiting for first sample…", 170);
|
||||
image.drawText(font, 16, height - 16, `${GESTURE_DOUBLE_CLICK} back`, 110);
|
||||
return image;
|
||||
}
|
||||
|
||||
image.drawText(
|
||||
font,
|
||||
16,
|
||||
21,
|
||||
`RSS ${formatMb(latest.rssMb)} native ${formatMb(latest.nativeMb)} Java ${formatMb(latest.javaMb)}/${formatMb(latest.javaCommittedMb)}`,
|
||||
190,
|
||||
);
|
||||
image.drawText(
|
||||
font,
|
||||
width - 16 - font.measureText(`CPU ${formatPercent(latest.cpuPercent)} threads ${latest.threads}`),
|
||||
37,
|
||||
`CPU ${formatPercent(latest.cpuPercent)} threads ${latest.threads}`,
|
||||
155,
|
||||
);
|
||||
|
||||
const memoryPeak = Math.max(...this.samples.map((sample) => sample.rssMb), 64);
|
||||
const memoryScale = roundUp(memoryPeak * 1.08, 64);
|
||||
image.drawText(font, 16, 48, `Memory 0–${formatMb(memoryScale)}`, 140);
|
||||
drawLegend(image, font, width, 48, [
|
||||
["RSS", 240],
|
||||
["native", 155],
|
||||
["Java", 80],
|
||||
]);
|
||||
drawChart(image, this.samples, latest.atMs, { x: 16, y: 64, width: width - 32, height: 70 }, memoryScale, [
|
||||
{ value: (sample) => sample.rssMb, shade: 240 },
|
||||
{ value: (sample) => sample.nativeMb, shade: 155 },
|
||||
{ value: (sample) => sample.javaMb, shade: 80 },
|
||||
]);
|
||||
|
||||
const cpuPeak = Math.max(...this.samples.map((sample) => sample.cpuPercent), 100);
|
||||
const cpuScale = roundUp(cpuPeak * 1.08, 25);
|
||||
image.drawText(font, 16, 144, `CPU 0–${Math.round(cpuScale)}% (one core)`, 140);
|
||||
drawChart(image, this.samples, latest.atMs, { x: 16, y: 160, width: width - 32, height: 60 }, cpuScale, [
|
||||
{ value: (sample) => sample.cpuPercent, shade: 220 },
|
||||
]);
|
||||
|
||||
image.drawText(font, 16, height - 16, `-60s`, 80);
|
||||
const nowLabel = `now ${GESTURE_DOUBLE_CLICK} back`;
|
||||
image.drawText(font, width - 16 - font.measureText(nowLabel), height - 16, nowLabel, 110);
|
||||
return image;
|
||||
}
|
||||
|
||||
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
|
||||
if (event.type === "double-click") {
|
||||
ctx.stack.pop();
|
||||
}
|
||||
}
|
||||
|
||||
private takeSample(): void {
|
||||
if (this.removed) return;
|
||||
try {
|
||||
const raw = com.faceclaw.app.FaceclawResourceUsage.sample();
|
||||
const atMs = Number(raw[0]);
|
||||
const cpuMs = Number(raw[1]);
|
||||
const elapsedDelta = atMs - this.previousElapsedMs;
|
||||
const cpuDelta = cpuMs - this.previousCpuMs;
|
||||
const cpuPercent = this.previousElapsedMs > 0 && elapsedDelta > 0
|
||||
? Math.max(0, cpuDelta / elapsedDelta * 100)
|
||||
: 0;
|
||||
this.previousElapsedMs = atMs;
|
||||
this.previousCpuMs = cpuMs;
|
||||
this.samples.push({
|
||||
atMs,
|
||||
cpuPercent,
|
||||
rssMb: kbToMb(Number(raw[2])),
|
||||
nativeMb: kbToMb(Number(raw[3])),
|
||||
javaMb: kbToMb(Number(raw[4])),
|
||||
javaCommittedMb: kbToMb(Number(raw[5])),
|
||||
threads: Number(raw[6]),
|
||||
});
|
||||
const cutoff = atMs - HISTORY_MS;
|
||||
while (this.samples.length > 1 && this.samples[0]!.atMs < cutoff) this.samples.shift();
|
||||
while (this.samples.length > MAX_SAMPLES) this.samples.shift();
|
||||
this.sampleError = "";
|
||||
} catch (error) {
|
||||
this.sampleError = `Sampling failed: ${(error as Error)?.message ?? error}`;
|
||||
}
|
||||
if (shell.isWindowVisible(this.windowId)) {
|
||||
this.requestRender();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function drawChart(
|
||||
image: GrayImage,
|
||||
samples: readonly ResourceSample[],
|
||||
nowMs: number,
|
||||
bounds: { x: number; y: number; width: number; height: number },
|
||||
scale: number,
|
||||
series: readonly Series[],
|
||||
): void {
|
||||
image.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 45);
|
||||
const midY = bounds.y + Math.round((bounds.height - 1) / 2);
|
||||
image.drawLine(bounds.x + 1, midY, bounds.x + bounds.width - 2, midY, 24);
|
||||
const startMs = nowMs - HISTORY_MS;
|
||||
for (const item of series) {
|
||||
let previous: { x: number; y: number } | null = null;
|
||||
for (const sample of samples) {
|
||||
if (sample.atMs < startMs) continue;
|
||||
const x = bounds.x + Math.round(clamp((sample.atMs - startMs) / HISTORY_MS, 0, 1) * (bounds.width - 1));
|
||||
const y = bounds.y + bounds.height - 1
|
||||
- Math.round(clamp(item.value(sample) / Math.max(1, scale), 0, 1) * (bounds.height - 1));
|
||||
if (previous) image.drawLine(previous.x, previous.y, x, y, item.shade);
|
||||
else image.setPixel(x, y, item.shade);
|
||||
previous = { x, y };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function drawLegend(
|
||||
image: GrayImage,
|
||||
font: ReturnType<typeof getDefaultSmallFont>,
|
||||
width: number,
|
||||
y: number,
|
||||
entries: ReadonlyArray<readonly [string, number]>,
|
||||
): void {
|
||||
const totalWidth = entries.reduce((sum, [label]) => sum + font.measureText(label) + 14, 0);
|
||||
let x = width - 16 - totalWidth;
|
||||
for (const [label, shade] of entries) {
|
||||
image.drawLine(x, y + 6, x + 8, y + 6, shade);
|
||||
x += 12;
|
||||
image.drawText(font, x, y, label, shade);
|
||||
x += font.measureText(label) + 2;
|
||||
}
|
||||
}
|
||||
|
||||
function kbToMb(kb: number): number {
|
||||
return Math.max(0, kb) / 1024;
|
||||
}
|
||||
|
||||
function roundUp(value: number, step: number): number {
|
||||
return Math.max(step, Math.ceil(value / step) * step);
|
||||
}
|
||||
|
||||
function formatMb(value: number): string {
|
||||
if (value >= 1024) return `${(value / 1024).toFixed(1)}G`;
|
||||
return `${Math.round(value)}M`;
|
||||
}
|
||||
|
||||
function formatPercent(value: number): string {
|
||||
return `${value < 10 ? value.toFixed(1) : Math.round(value)}%`;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { Layer, type DashboardInputEvent, type LayerContext } from "../../ui/layers";
|
||||
import { drawListScrollbar } from "../../ui/menu";
|
||||
|
||||
const COLOR_VALUE_COUNT = 256;
|
||||
const COLOR_VALUE_STEP = 1;
|
||||
const GRID_COLUMNS = 16;
|
||||
const CELL_HEIGHT = 30;
|
||||
const LABEL_Y_OFFSET = 0;
|
||||
const SWATCH_Y_OFFSET = 12;
|
||||
const SWATCH_WIDTH = 24;
|
||||
const SWATCH_HEIGHT = 16;
|
||||
const GRID_ROWS = Math.ceil(COLOR_VALUE_COUNT / GRID_COLUMNS);
|
||||
|
||||
export class ScreenTestLayer implements Layer {
|
||||
private scrollRow = 0;
|
||||
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
// Sized to the hosting stack (the Developer app viewport).
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const image = new GrayImage(width, height, 0);
|
||||
const font = getDefaultSmallFont();
|
||||
const cellWidth = Math.floor(width / GRID_COLUMNS);
|
||||
const gridX = Math.floor((width - cellWidth * GRID_COLUMNS) / 2);
|
||||
const visibleRows = Math.max(1, Math.ceil(height / CELL_HEIGHT));
|
||||
const maxScrollRow = Math.max(0, GRID_ROWS - visibleRows);
|
||||
this.scrollRow = Math.max(0, Math.min(maxScrollRow, this.scrollRow));
|
||||
|
||||
for (let value = 0; value < COLOR_VALUE_COUNT; value += COLOR_VALUE_STEP) {
|
||||
const slot = value / COLOR_VALUE_STEP;
|
||||
const col = slot % GRID_COLUMNS;
|
||||
const row = Math.floor(slot / GRID_COLUMNS);
|
||||
const cellX = gridX + col * cellWidth;
|
||||
const cellY = (row - this.scrollRow) * CELL_HEIGHT;
|
||||
if (cellY >= height || cellY + CELL_HEIGHT <= 0) continue;
|
||||
const label = String(value);
|
||||
const labelX = cellX + Math.max(0, Math.floor((cellWidth - font.measureText(label)) / 2));
|
||||
const swatchX = cellX + Math.floor((cellWidth - SWATCH_WIDTH) / 2);
|
||||
|
||||
image.drawText(font, labelX, cellY + LABEL_Y_OFFSET, label, 185);
|
||||
fillSwatch(image, swatchX, cellY + SWATCH_Y_OFFSET, SWATCH_WIDTH, SWATCH_HEIGHT, value);
|
||||
}
|
||||
|
||||
if (GRID_ROWS > visibleRows) {
|
||||
drawListScrollbar(image, width - 4, 2, height - 4, this.scrollRow, visibleRows, GRID_ROWS);
|
||||
}
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
|
||||
switch (event.type) {
|
||||
case "scroll-up":
|
||||
this.scrollRow = Math.max(0, this.scrollRow - 1);
|
||||
return;
|
||||
case "scroll-down": {
|
||||
const { height } = ctx.stack.getBaseSize();
|
||||
const visibleRows = Math.max(1, Math.ceil(height / CELL_HEIGHT));
|
||||
this.scrollRow = Math.min(Math.max(0, GRID_ROWS - visibleRows), this.scrollRow + 1);
|
||||
return;
|
||||
}
|
||||
case "double-click":
|
||||
ctx.stack.pop();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function fillSwatch(image: GrayImage, x: number, y: number, width: number, height: number, value: number): void {
|
||||
// Values will ultimately be rounded up to the nearest multiple of 16 (since they're transmitted as 4-bit)
|
||||
// grayscale). So, for intermediate values, dither.
|
||||
if (value % 16 !== 0) {
|
||||
const baseValue = value & 0xf0;
|
||||
const fillFraction = value & 0x0f;
|
||||
for (let i = 0; i < height; i++) {
|
||||
for (let j = 0; j < width; j++) {
|
||||
const ditheredValue = ditherPattern(j, i, fillFraction)
|
||||
image.setPixel(x + j, y + i, ditheredValue ? baseValue + 16 : baseValue);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
image.fillRect(x, y, width, height, value);
|
||||
}
|
||||
}
|
||||
|
||||
function ditherPattern(x: number, y: number, fillFraction: number): number {
|
||||
const pattern = [
|
||||
[0, 8, 2, 10],
|
||||
[12, 4, 14, 6],
|
||||
[3, 11, 1, 9],
|
||||
[15, 7, 13, 5],
|
||||
];
|
||||
const patternValue = pattern[y % 4][x % 4];
|
||||
return (fillFraction > patternValue) ? 1 : 0;
|
||||
}
|
||||
Reference in new issue
Block a user