mirror of
https://git.undefined-dev.fr/Blendman974/faceclaw.git
synced 2026-11-19 21:03:09 +00:00
Add screen-size setting to Navigate and Terminal apps
This commit is contained in:
1 parent
50f2041eea
commit
1524766996
15 files changed
+501
-56
No files matched your search
@@ -1,5 +1,8 @@
|
||||
# Changelog
|
||||
|
||||
## 0.6.6 - Future
|
||||
* Navigate and terminal app: App-specific screen size/position setting
|
||||
|
||||
## 0.6.5 - 2026-09-04
|
||||
* Changed context menu gestures: — for system, ●— for app context menu.
|
||||
* System and app context menus show gesture help for switching to the other context menu
|
||||
|
||||
@@ -32,6 +32,9 @@ import {
|
||||
navigateDestinationAddressDraftSetting,
|
||||
navigateDestinationNameDraftSetting,
|
||||
navigateRememberRecentSetting,
|
||||
navigateDisplayModeSetting,
|
||||
navigateVerticalPositionSetting,
|
||||
enumSettingMenuItem,
|
||||
type ConfigSettingString,
|
||||
} from "../../ui/dashboard-settings";
|
||||
import {
|
||||
@@ -274,6 +277,15 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
};
|
||||
post({ type: "set-tools", windowId: message.windowId, tools: NAVIGATE_TOOLS });
|
||||
break;
|
||||
case "resize-window":
|
||||
if (!window || window.windowId !== message.windowId) break;
|
||||
if (window.viewportWidth === message.viewport.width && window.viewportHeight === message.viewport.height) break;
|
||||
window.viewportWidth = message.viewport.width;
|
||||
window.viewportHeight = message.viewport.height;
|
||||
window.menu?.resize(message.viewport);
|
||||
window.lastSubmittedFingerprint = "";
|
||||
render();
|
||||
break;
|
||||
case "close-window":
|
||||
if (editing) {
|
||||
// Window closed mid-edit: shut the phone editor down.
|
||||
@@ -838,7 +850,7 @@ function describeRouteStatus(): string {
|
||||
|
||||
/**
|
||||
* The window's context menu: Stop navigation while a route is up, then the
|
||||
* saved-destination settings (Home, Work, custom named places) and the
|
||||
* display and saved-destination settings (Home, Work, custom named places), and the
|
||||
* recent-destinations preference.
|
||||
*/
|
||||
function windowMenuItems(win: NavWindow): MenuItem[] {
|
||||
@@ -853,6 +865,10 @@ function windowMenuItems(win: NavWindow): MenuItem[] {
|
||||
},
|
||||
});
|
||||
}
|
||||
items.push(
|
||||
enumSettingMenuItem(navigateDisplayModeSetting),
|
||||
enumSettingMenuItem(navigateVerticalPositionSetting),
|
||||
);
|
||||
items.push({
|
||||
label: "Saved destinations",
|
||||
onSelect: (ctx) => {
|
||||
|
||||
@@ -308,6 +308,30 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
case "open-window":
|
||||
openWindow(message.windowId, message.surfaceId, message.title, message.viewport);
|
||||
break;
|
||||
case "resize-window": {
|
||||
const window = windows.get(message.windowId);
|
||||
if (!window || (window.viewportWidth === message.viewport.width && window.viewportHeight === message.viewport.height)) break;
|
||||
window.viewportWidth = message.viewport.width;
|
||||
window.viewportHeight = message.viewport.height;
|
||||
window.menu?.resize(message.viewport);
|
||||
window.lastSubmittedFingerprint = "";
|
||||
if (window.kind === "view") {
|
||||
window.gridCols = Math.floor(window.viewportWidth / window.cellWidth);
|
||||
window.gridRows = Math.floor(window.viewportHeight / window.cellHeight);
|
||||
if (window.reconnectTimer) clearTimeout(window.reconnectTimer);
|
||||
window.reconnectTimer = null;
|
||||
window.client.stop();
|
||||
window.client.setViewport(window.gridCols, window.gridRows);
|
||||
window.emulator.dispose();
|
||||
window.emulator = new TerminalEmulator(window.gridCols, window.gridRows);
|
||||
window.receivedData = false;
|
||||
window.archive = [];
|
||||
window.scrollTop = null;
|
||||
reconnectView(window);
|
||||
}
|
||||
scheduleRender(window);
|
||||
break;
|
||||
}
|
||||
case "close-window":
|
||||
closeWindow(message.windowId);
|
||||
break;
|
||||
@@ -1434,8 +1458,7 @@ function openViewWindow(control: ControlConnection, socket: string, label: strin
|
||||
icon: "terminal",
|
||||
iconGlyph: glyph || undefined,
|
||||
focus: true,
|
||||
// Terminal views are the one full-height window kind: more rows matter
|
||||
// more than a small on-screen footprint.
|
||||
// Default to tall sessions; the app display setting can override this.
|
||||
heightMode: "max",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -53,6 +53,10 @@ export class TerminalEmulator {
|
||||
this.term.write(data, onProcessed);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.term.dispose();
|
||||
}
|
||||
|
||||
/** Full reset; snapshots are defined as repainting from a cleared screen. */
|
||||
reset(): void {
|
||||
this.term.reset();
|
||||
|
||||
@@ -66,7 +66,7 @@ import { loadPersistedOpenApps, savePersistedOpenApps } from "../ui/shell/open-a
|
||||
import { appViewportRect, SIDEBAR_WIDTH, sidebarStripVisible, type WindowHeightMode } from "../ui/shell/geometry";
|
||||
import { type LayerActions, type TextSettingsEditToggle } from "../ui/layers";
|
||||
import { type KeyboardInputSession } from "../ui/shell/keyboard-input";
|
||||
import { assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, brightnessSetting, brightnessSettingToLevel, displayModeSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, ringConnectionModeSetting, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, verticalPositionSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
|
||||
import { assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, brightnessSetting, brightnessSettingToLevel, displayModeSetting, navigateDisplayModeSetting, navigateVerticalPositionSetting, terminalDisplayModeSetting, terminalVerticalPositionSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, ringConnectionModeSetting, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, verticalPositionSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
|
||||
import { isIgnoringBatteryOptimizations, requestIgnoreBatteryOptimizations } from "../native/battery-optimization";
|
||||
import {
|
||||
getInstalledEvenHubAppById,
|
||||
@@ -384,6 +384,7 @@ class DashboardController {
|
||||
this.syncEvenHubScreenOffSetting();
|
||||
this.applyVerticalPositionIfChanged();
|
||||
this.applyDisplayModeIfChanged();
|
||||
this.applyAppLayoutsIfChanged();
|
||||
this.syncAssistantBridgeIfChanged();
|
||||
this.syncLockScreenSettingIfChanged();
|
||||
// A Preview color change should show on the mirror at once, not at the
|
||||
@@ -461,8 +462,8 @@ class DashboardController {
|
||||
/**
|
||||
* Display mode changed (Settings > Display, or the phone page's picker):
|
||||
* every window's viewport size changes. In-process windows re-measure in
|
||||
* place; worker windows get their canvas once at open, so they are closed
|
||||
* and launched again at the new size.
|
||||
* place; workers that support resizing receive the new viewport. Other
|
||||
* worker windows are closed and launched again at the new size.
|
||||
*/
|
||||
private applyDisplayModeIfChanged(): void {
|
||||
const mode = displayModeSetting.get();
|
||||
@@ -498,6 +499,31 @@ class DashboardController {
|
||||
});
|
||||
}
|
||||
|
||||
private lastAppLayouts = this.appLayouts();
|
||||
|
||||
private appLayouts(): Record<string, string> {
|
||||
return {
|
||||
navigate: `${navigateDisplayModeSetting.get()}:${navigateVerticalPositionSetting.get()}`,
|
||||
terminal: `${terminalDisplayModeSetting.get()}:${terminalVerticalPositionSetting.get()}`,
|
||||
};
|
||||
}
|
||||
|
||||
private applyAppLayoutsIfChanged(): void {
|
||||
const layouts = this.appLayouts();
|
||||
const changed = Object.keys(layouts).filter((appId) => layouts[appId] !== this.lastAppLayouts[appId]);
|
||||
if (!changed.length) return;
|
||||
this.lastAppLayouts = layouts;
|
||||
void (async () => {
|
||||
for (const window of Array.from(shell.getWindows())) {
|
||||
if (!changed.includes(window.appId)) continue;
|
||||
await this.configureWindowSurface(window.surfaceId, window.windowId === shell.foregroundWindow()?.windowId, window.heightMode);
|
||||
window.relayout?.();
|
||||
}
|
||||
shell.foregroundWindow()?.requestRender();
|
||||
this.requestShellRender();
|
||||
})().catch((error) => this.appendLog(`app layout change failed: ${this.formatError(error)}`));
|
||||
}
|
||||
|
||||
private applyVerticalPositionIfChanged(): void {
|
||||
const position = verticalPositionSetting.get();
|
||||
if (position === this.lastVerticalPosition) return;
|
||||
@@ -1781,7 +1807,7 @@ class DashboardController {
|
||||
}
|
||||
const x = Math.round(Math.min(1, Math.max(0, nx)) * G2_LENS_WIDTH);
|
||||
const y = Math.round(Math.min(1, Math.max(0, ny)) * G2_LENS_HEIGHT);
|
||||
const stripShown = sidebarStripVisible(shell.getFocus());
|
||||
const stripShown = sidebarStripVisible(shell.getFocus(), shell.foregroundWindow()?.appId);
|
||||
this.appendLog(`mirror tap at ${x},${y}`);
|
||||
if (!shell.hasOverlay() && stripShown && x < SIDEBAR_WIDTH) {
|
||||
const target = shell.windowAtSidebarPoint(x, y);
|
||||
@@ -1795,7 +1821,7 @@ class DashboardController {
|
||||
}
|
||||
const window = shell.foregroundWindow();
|
||||
if (window && !shell.hasOverlay()) {
|
||||
const rect = appViewportRect(window.heightMode);
|
||||
const rect = appViewportRect(window.heightMode, window.appId);
|
||||
const inside = x >= rect.x && x < rect.x + rect.width && y >= rect.y && y < rect.y + rect.height;
|
||||
if (shell.getFocus() !== "window") {
|
||||
shell.focusWindow(window.windowId);
|
||||
@@ -2288,7 +2314,7 @@ class DashboardController {
|
||||
): Promise<void> {
|
||||
if (!target) return;
|
||||
await target.configureSurface(surfaceId, {
|
||||
...appViewportRect(heightMode),
|
||||
...appViewportRect(heightMode, shell.getWindows().find((window) => window.surfaceId === surfaceId)?.appId),
|
||||
zOrder: 0,
|
||||
transparency: "opaque",
|
||||
});
|
||||
|
||||
@@ -84,6 +84,7 @@ type TerminalDataKind = "snapshot" | "output";
|
||||
export class G2MirrorClient {
|
||||
private ws: any = null;
|
||||
private listenerProxy: any = null;
|
||||
private connectionGeneration = 0;
|
||||
private phase: G2MirrorPhase = "idle";
|
||||
private status = "Not connected.";
|
||||
private sessions: G2MirrorSession[] = [];
|
||||
@@ -168,14 +169,21 @@ export class G2MirrorClient {
|
||||
return () => this.titleListeners.delete(listener);
|
||||
}
|
||||
|
||||
/** Grid dimensions for the next connection's handshake. */
|
||||
setViewport(cols: number, rows: number): void {
|
||||
this.options.cols = cols;
|
||||
this.options.rows = rows;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this.ws) return;
|
||||
this.stopped = false;
|
||||
const generation = ++this.connectionGeneration;
|
||||
const url = `${this.options.secure ? "wss" : "ws"}://${this.options.host}:${this.options.port}`;
|
||||
this.setState("connecting", `Connecting to ${this.options.host}:${this.options.port}...`);
|
||||
this.listenerProxy = new com.faceclaw.app.FaceclawWebSocketListener({
|
||||
onOpen: () => {
|
||||
if (this.stopped) return;
|
||||
if (this.stopped || generation !== this.connectionGeneration) return;
|
||||
this.setState("connecting", "Authenticating...");
|
||||
this.send({
|
||||
type: "init",
|
||||
@@ -187,15 +195,15 @@ export class G2MirrorClient {
|
||||
});
|
||||
},
|
||||
onTextMessage: (message: string) => {
|
||||
if (this.stopped) return;
|
||||
if (this.stopped || generation !== this.connectionGeneration) return;
|
||||
this.handleMessage(String(message));
|
||||
},
|
||||
onClosed: (code: number, reason: string) => {
|
||||
if (this.stopped) return;
|
||||
if (this.stopped || generation !== this.connectionGeneration) return;
|
||||
this.handleConnectionLost(`Connection closed (${Number(code)}${reason ? `: ${String(reason)}` : ""}).`);
|
||||
},
|
||||
onFailure: (message: string) => {
|
||||
if (this.stopped) return;
|
||||
if (this.stopped || generation !== this.connectionGeneration) return;
|
||||
this.handleConnectionLost(`Connection failed: ${shortenError(String(message))}`);
|
||||
},
|
||||
});
|
||||
@@ -209,6 +217,7 @@ export class G2MirrorClient {
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
++this.connectionGeneration;
|
||||
this.rejectAllPendingLaunches("client stopped");
|
||||
this.clearListRefreshTimer();
|
||||
if (this.ws) {
|
||||
|
||||
@@ -363,9 +363,43 @@ export const verticalPositionSetting = new ConfigSettingEnum<VerticalPosition>({
|
||||
values: ["top", "upper", "middle", "lower", "bottom"],
|
||||
formatValue: (value) => VERTICAL_POSITION_LABELS[value] ?? value,
|
||||
description:
|
||||
"Where standard (reduced-height) windows sit vertically within the display area, to position them within your field of view. Full-height windows such as terminal views always use the whole screen.",
|
||||
"Where standard (reduced-height) windows sit vertically within the display area, to position them within your field of view. Full-height windows use the whole screen. Navigate and Terminal can override these display settings.",
|
||||
});
|
||||
|
||||
/** Per-app layouts can inherit the display preferences or choose their own size. */
|
||||
export type AppDisplayMode = "default" | "global" | DisplayModeSetting;
|
||||
|
||||
function appDisplayModeSetting(appId: string, defaultValue: AppDisplayMode): ConfigSettingEnum<AppDisplayMode> {
|
||||
return new ConfigSettingEnum<AppDisplayMode>({
|
||||
id: `${appId}-display-mode`,
|
||||
label: "Display mode",
|
||||
storageKey: `${appId}.displayMode`,
|
||||
defaultValue,
|
||||
values: appId === "terminal" ? ["default", "global", ...DISPLAY_MODE_VALUES] : ["global", ...DISPLAY_MODE_VALUES],
|
||||
formatValue: (value) => value === "default" ? "Tall sessions (default)" : value === "global" ? "Use global" : displayModeLabel(value),
|
||||
description: appId === "terminal"
|
||||
? "Screen size for Terminal. The default keeps session windows tall and the terminals list at the global size. Use global follows Display settings for all Terminal windows. Resizing an open session reconnects its view at the new size."
|
||||
: "Screen size for Navigate. Choose Band to leave more of your field of view clear, or Use global to follow Display settings. Applies to the current route too.",
|
||||
});
|
||||
}
|
||||
|
||||
function appVerticalPositionSetting(appId: string): ConfigSettingEnum<"global" | VerticalPosition> {
|
||||
return new ConfigSettingEnum<"global" | VerticalPosition>({
|
||||
id: `${appId}-vertical-position`,
|
||||
label: "Vertical position",
|
||||
storageKey: `${appId}.verticalPosition`,
|
||||
defaultValue: "global",
|
||||
values: ["global", "top", "upper", "middle", "lower", "bottom"],
|
||||
formatValue: (value) => value === "global" ? "Use global" : VERTICAL_POSITION_LABELS[value],
|
||||
description: "Where reduced-height windows for this app sit in your field of view. Use global follows Display settings. Full-height windows fill the display vertically.",
|
||||
});
|
||||
}
|
||||
|
||||
export const navigateDisplayModeSetting = appDisplayModeSetting("navigate", "global");
|
||||
export const navigateVerticalPositionSetting = appVerticalPositionSetting("navigate");
|
||||
export const terminalDisplayModeSetting = appDisplayModeSetting("terminal", "default");
|
||||
export const terminalVerticalPositionSetting = appVerticalPositionSetting("terminal");
|
||||
|
||||
export const voiceControlEnabledSetting = new ConfigSettingBoolean({
|
||||
id: "voice-control-enabled",
|
||||
label: "Enable",
|
||||
|
||||
@@ -36,6 +36,10 @@ import {
|
||||
batteryDisplayModeSetting,
|
||||
brightnessSetting,
|
||||
displayModeSetting,
|
||||
navigateDisplayModeSetting,
|
||||
navigateVerticalPositionSetting,
|
||||
terminalDisplayModeSetting,
|
||||
terminalVerticalPositionSetting,
|
||||
elevenLabsApiKeySetting,
|
||||
mapboxApiKeySetting,
|
||||
mirrorTouchSetting,
|
||||
@@ -144,6 +148,8 @@ function settingsSections(): SettingsSection[] {
|
||||
// Connections (g2mirror:// strings) are managed inside the Terminal
|
||||
// app's Manage Connections section, not here.
|
||||
items: [
|
||||
enumSettingMenuItem(terminalDisplayModeSetting),
|
||||
enumSettingMenuItem(terminalVerticalPositionSetting),
|
||||
terminalFontPickerMenuItem(),
|
||||
textSettingMenuItem(terminalLaunchPresetsSetting),
|
||||
toggleSettingMenuItem(terminalAutoReconnectSetting),
|
||||
@@ -155,6 +161,8 @@ function settingsSections(): SettingsSection[] {
|
||||
// Home/Work are plain addresses; other named destinations (and the
|
||||
// recent list) are managed inside the Navigate app's context menu.
|
||||
items: [
|
||||
enumSettingMenuItem(navigateDisplayModeSetting),
|
||||
enumSettingMenuItem(navigateVerticalPositionSetting),
|
||||
textSettingMenuItem(navigateHomeAddressSetting),
|
||||
textSettingMenuItem(navigateWorkAddressSetting),
|
||||
toggleSettingMenuItem(navigateRememberRecentSetting, {
|
||||
|
||||
@@ -69,8 +69,8 @@ function slotPosition(variant: SidebarVariant, listTop: number, position: number
|
||||
}
|
||||
|
||||
/** Top y of the sidebar's icon list (below the band's top bar). */
|
||||
function sidebarListTop(): number {
|
||||
return minWindowTop() + TOP_BAR_HEIGHT + LIST_MARGIN;
|
||||
function sidebarListTop(appId?: string): number {
|
||||
return minWindowTop(appId) + TOP_BAR_HEIGHT + LIST_MARGIN;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -100,6 +100,7 @@ export type ShellChromeState = {
|
||||
focus: "sidebar" | "window";
|
||||
/** Height mode of the foreground window; decides where its top bar sits. */
|
||||
foregroundHeightMode: WindowHeightMode;
|
||||
foregroundAppId?: string;
|
||||
battery: { headset: number | null; headsetCharging: boolean | null };
|
||||
/** App-provided tray images, drawn between notification icons and batteries. */
|
||||
trayIcons: GrayImage[];
|
||||
@@ -191,7 +192,7 @@ export class ShellChromeLayer implements Layer {
|
||||
const state = this.getState();
|
||||
// Full-panel mode: the strip is an overlay, present only while the user
|
||||
// is in it (the window underneath keeps its full width the rest of the time).
|
||||
if (sidebarStripVisible(state.focus)) {
|
||||
if (sidebarStripVisible(state.focus, state.foregroundAppId)) {
|
||||
this.drawSidebar(image, state);
|
||||
}
|
||||
this.drawTopBar(image, state);
|
||||
@@ -212,7 +213,7 @@ export class ShellChromeLayer implements Layer {
|
||||
windowIndexAt(x: number, y: number, windowCount: number): number | null {
|
||||
if (x < 0 || x >= SIDEBAR_WIDTH || windowCount === 0) return null;
|
||||
const variant = sidebarVariant(windowCount);
|
||||
const listTop = sidebarListTop();
|
||||
const listTop = sidebarListTop(this.getState().foregroundAppId);
|
||||
const lastVisible = Math.min(windowCount, this.scrollRow + rowsPerColumn(variant) * variant.columns);
|
||||
for (let index = this.scrollRow; index < lastVisible; index++) {
|
||||
const { column, y: slotY } = slotPosition(variant, listTop, index - this.scrollRow);
|
||||
@@ -225,10 +226,9 @@ export class ShellChromeLayer implements Layer {
|
||||
}
|
||||
|
||||
private drawSidebar(image: GrayImage, state: ShellChromeState): void {
|
||||
// The sidebar always occupies the min-height window band at the preferred
|
||||
// vertical position: it never moves when the foreground window's height
|
||||
// changes, and it lines up exactly with a min-height window's chrome.
|
||||
const bandTop = minWindowTop();
|
||||
// Align the sidebar with the app's preferred band. Legacy tall terminal
|
||||
// sessions keep the sidebar at the global band position.
|
||||
const bandTop = minWindowTop(state.foregroundAppId);
|
||||
const bandBottom = bandTop + MIN_WINDOW_HEIGHT;
|
||||
image.fillRect(0, bandTop, SIDEBAR_WIDTH, MIN_WINDOW_HEIGHT, SHELL_OPAQUE_BLACK);
|
||||
|
||||
@@ -242,7 +242,7 @@ export class ShellChromeLayer implements Layer {
|
||||
const iconMarginX = ((variant.columnWidth - iconSize) / 2) | 0;
|
||||
// Column index of the rightmost column (the one that fills first).
|
||||
const firstColumn = variant.columns - 1;
|
||||
const listTop = sidebarListTop();
|
||||
const listTop = sidebarListTop(state.foregroundAppId);
|
||||
const visibleCount = rowsPerColumn(variant) * variant.columns;
|
||||
this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, state.selectedIndex, visibleCount, count);
|
||||
const lastVisible = Math.min(count, this.scrollRow + visibleCount);
|
||||
@@ -304,10 +304,10 @@ export class ShellChromeLayer implements Layer {
|
||||
// The bar sits at the top edge of the foreground window's band, wherever
|
||||
// its height mode puts that (screen top for max height). It moves when
|
||||
// the foreground switches to a window of a different height.
|
||||
const barTop = windowTop(state.foregroundHeightMode);
|
||||
const barTop = windowTop(state.foregroundHeightMode, state.foregroundAppId);
|
||||
// The bar spans the app viewport; with the sidebar overlaid (full-panel
|
||||
// mode, sidebar focused) it still starts past the strip.
|
||||
const barLeft = sidebarStripVisible(state.focus) ? SIDEBAR_WIDTH : 0;
|
||||
const barLeft = sidebarStripVisible(state.focus, state.foregroundAppId) ? SIDEBAR_WIDTH : 0;
|
||||
image.fillRect(barLeft, barTop, G2_LENS_WIDTH - barLeft, TOP_BAR_HEIGHT, SHELL_OPAQUE_BLACK);
|
||||
image.drawLine(barLeft, barTop + TOP_BAR_HEIGHT - 1, G2_LENS_WIDTH - 1, barTop + TOP_BAR_HEIGHT - 1, BORDER_VALUE);
|
||||
|
||||
|
||||
+42
-26
@@ -1,5 +1,13 @@
|
||||
import { G2_LENS_HEIGHT, G2_LENS_WIDTH } from "../../graphics/image";
|
||||
import { displayModeSetting, type DisplayModeSetting, verticalPositionSetting } from "../dashboard-settings";
|
||||
import {
|
||||
displayModeSetting,
|
||||
type DisplayModeSetting,
|
||||
verticalPositionSetting,
|
||||
navigateDisplayModeSetting,
|
||||
navigateVerticalPositionSetting,
|
||||
terminalDisplayModeSetting,
|
||||
terminalVerticalPositionSetting,
|
||||
} from "../dashboard-settings";
|
||||
|
||||
/** Top bar: 24px notification icons plus a little padding. */
|
||||
export const TOP_BAR_HEIGHT = 28;
|
||||
@@ -13,8 +21,14 @@ export const TOP_BAR_HEIGHT = 28;
|
||||
export const SIDEBAR_WIDTH = 64;
|
||||
|
||||
/** The Display > Display mode setting (see dashboard-settings.ts). */
|
||||
export function displayMode(): DisplayModeSetting {
|
||||
return displayModeSetting.get();
|
||||
function appDisplayMode(appId?: string) {
|
||||
return appId === "navigate" ? navigateDisplayModeSetting.get()
|
||||
: appId === "terminal" ? terminalDisplayModeSetting.get() : "default";
|
||||
}
|
||||
|
||||
export function displayMode(appId?: string): DisplayModeSetting {
|
||||
const mode = appDisplayMode(appId);
|
||||
return mode === "global" || mode === "default" ? displayModeSetting.get() : mode;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -22,24 +36,24 @@ export function displayMode(): DisplayModeSetting {
|
||||
* the strip, or nothing in the full-panel mode (where the chrome paints the
|
||||
* strip over the window while the sidebar has focus).
|
||||
*/
|
||||
export function sidebarWidth(): number {
|
||||
return displayMode() === "640x480" ? 0 : SIDEBAR_WIDTH;
|
||||
export function sidebarWidth(appId?: string): number {
|
||||
return displayMode(appId) === "640x480" ? 0 : SIDEBAR_WIDTH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the sidebar strip is on screen: always when it reserves width; in
|
||||
* the full-panel mode (where it overlays the window) only while it has focus.
|
||||
*/
|
||||
export function sidebarStripVisible(focus: "sidebar" | "window"): boolean {
|
||||
return sidebarWidth() > 0 || focus === "sidebar";
|
||||
export function sidebarStripVisible(focus: "sidebar" | "window", appId?: string): boolean {
|
||||
return sidebarWidth(appId) > 0 || focus === "sidebar";
|
||||
}
|
||||
|
||||
/**
|
||||
* The height an app's requested mode actually gets: the band mode honours
|
||||
* it, the taller modes give every window the whole screen.
|
||||
* Explicit app sizes (including Use global) replace the requested height.
|
||||
* The default keeps legacy per-window heights, such as tall terminal sessions.
|
||||
*/
|
||||
export function effectiveHeightMode(mode: WindowHeightMode): WindowHeightMode {
|
||||
return displayMode() === "576x288" ? mode : "max";
|
||||
export function effectiveHeightMode(mode: WindowHeightMode, appId?: string): WindowHeightMode {
|
||||
return displayMode(appId) === "576x288" ? (appDisplayMode(appId) === "default" ? mode : "min") : "max";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -74,8 +88,8 @@ export const MIN_WINDOW_HEIGHT = 288;
|
||||
export const MIN_WINDOW_MAX_TOP = G2_LENS_HEIGHT - MIN_WINDOW_HEIGHT;
|
||||
|
||||
/** Total height (top bar + content) of a window's band in the given mode. */
|
||||
export function windowBandHeight(mode: WindowHeightMode): number {
|
||||
switch (effectiveHeightMode(mode)) {
|
||||
export function windowBandHeight(mode: WindowHeightMode, appId?: string): number {
|
||||
switch (effectiveHeightMode(mode, appId)) {
|
||||
case "max":
|
||||
return G2_LENS_HEIGHT;
|
||||
case "medium":
|
||||
@@ -90,8 +104,10 @@ export function windowBandHeight(mode: WindowHeightMode): number {
|
||||
* position setting: each band height distributes its own free space by the
|
||||
* same fraction, so all heights sit consistently within the screen.
|
||||
*/
|
||||
function verticalPositionFraction(): number {
|
||||
switch (verticalPositionSetting.get()) {
|
||||
function verticalPositionFraction(appId?: string): number {
|
||||
const position = appId === "navigate" ? navigateVerticalPositionSetting.get()
|
||||
: appId === "terminal" ? terminalVerticalPositionSetting.get() : "global";
|
||||
switch (position === "global" ? verticalPositionSetting.get() : position) {
|
||||
case "top":
|
||||
return 0;
|
||||
case "upper":
|
||||
@@ -109,33 +125,33 @@ function verticalPositionFraction(): number {
|
||||
* Top edge (y) of a min-height window. The sidebar and shell overlays always
|
||||
* align to this band, even while a taller window is foreground.
|
||||
*/
|
||||
export function minWindowTop(): number {
|
||||
return windowTop("min");
|
||||
export function minWindowTop(appId?: string): number {
|
||||
return windowTop("min", appId);
|
||||
}
|
||||
|
||||
/** Top edge (y) of a window's top bar; max-height windows pin to the screen top. */
|
||||
export function windowTop(mode: WindowHeightMode): number {
|
||||
return Math.round((G2_LENS_HEIGHT - windowBandHeight(mode)) * verticalPositionFraction());
|
||||
export function windowTop(mode: WindowHeightMode, appId?: string): number {
|
||||
return Math.round((G2_LENS_HEIGHT - windowBandHeight(mode, appId)) * verticalPositionFraction(appId));
|
||||
}
|
||||
|
||||
/** App-content viewport size for a height mode (independent of vertical position). */
|
||||
export function appViewportSize(mode: WindowHeightMode): { width: number; height: number } {
|
||||
export function appViewportSize(mode: WindowHeightMode, appId?: string): { width: number; height: number } {
|
||||
return {
|
||||
width: G2_LENS_WIDTH - sidebarWidth(),
|
||||
height: windowBandHeight(mode) - TOP_BAR_HEIGHT,
|
||||
width: G2_LENS_WIDTH - sidebarWidth(appId),
|
||||
height: windowBandHeight(mode, appId) - TOP_BAR_HEIGHT,
|
||||
};
|
||||
}
|
||||
|
||||
/** Screen rect of a window's app-content viewport (below its top bar). */
|
||||
export function appViewportRect(mode: WindowHeightMode): {
|
||||
export function appViewportRect(mode: WindowHeightMode, appId?: string): {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
} {
|
||||
return {
|
||||
x: sidebarWidth(),
|
||||
y: windowTop(mode) + TOP_BAR_HEIGHT,
|
||||
...appViewportSize(mode),
|
||||
x: sidebarWidth(appId),
|
||||
y: windowTop(mode, appId) + TOP_BAR_HEIGHT,
|
||||
...appViewportSize(mode, appId),
|
||||
};
|
||||
}
|
||||
@@ -115,7 +115,7 @@ export type ShellWindow = {
|
||||
requestRender: () => void;
|
||||
/**
|
||||
* Re-measure against the current display mode (viewport size / band) and
|
||||
* repaint. Windows without it (workers, whose canvas is fixed at open) are
|
||||
* repaint. Windows without it (workers with a canvas fixed at open) are
|
||||
* closed and relaunched by the controller instead.
|
||||
*/
|
||||
relayout?: () => void;
|
||||
@@ -784,13 +784,14 @@ class Shell {
|
||||
* strip left of the icon columns when the one-column variant is active.
|
||||
*/
|
||||
screenshotCropRect(): { x: number; y: number; width: number; height: number } {
|
||||
const appId = this.foregroundWindow()?.appId;
|
||||
const heightMode = this.foregroundWindow()?.heightMode ?? "min";
|
||||
const x = sidebarContentLeft(this.windows.length);
|
||||
const x = sidebarWidth(appId) === 0 ? 0 : sidebarContentLeft(this.windows.length);
|
||||
return {
|
||||
x,
|
||||
y: windowTop(heightMode),
|
||||
y: windowTop(heightMode, appId),
|
||||
width: G2_LENS_WIDTH - x,
|
||||
height: windowBandHeight(heightMode),
|
||||
height: windowBandHeight(heightMode, appId),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1397,6 +1398,7 @@ class Shell {
|
||||
selectedIndex: this.selectedIndex,
|
||||
focus: this.focus,
|
||||
foregroundHeightMode: this.foregroundWindow()?.heightMode ?? "min",
|
||||
foregroundAppId: this.foregroundWindow()?.appId,
|
||||
battery: this.battery,
|
||||
trayIcons: Array.from(this.trayIcons.keys())
|
||||
.sort()
|
||||
|
||||
@@ -14,6 +14,7 @@ import { shell, type ShellWindow } from "./shell";
|
||||
*/
|
||||
export type WorkerAppMessage =
|
||||
| { type: "open-window"; windowId: string; surfaceId: string; title: string; viewport: { width: number; height: number } }
|
||||
| { type: "resize-window"; windowId: string; viewport: { width: number; height: number } }
|
||||
| { type: "close-window"; windowId: string }
|
||||
| { type: "input"; windowId: string; event: unknown; frameId: number; focused: boolean }
|
||||
| { type: "text-input"; windowId: string; text: string }
|
||||
@@ -338,7 +339,7 @@ export class WorkerAppHost {
|
||||
windowId: spec.windowId,
|
||||
surfaceId,
|
||||
title: spec.title,
|
||||
viewport: appViewportSize(heightMode),
|
||||
viewport: appViewportSize(heightMode, this.options.appId),
|
||||
});
|
||||
const window: ShellWindow = {
|
||||
appId: this.options.appId,
|
||||
@@ -348,6 +349,10 @@ export class WorkerAppHost {
|
||||
closeable: true,
|
||||
acceptsDirectional: spec.acceptsDirectional,
|
||||
heightMode,
|
||||
// These apps can resize their live content without losing route/session state.
|
||||
relayout: this.options.appId === "navigate" || this.options.appId === "terminal"
|
||||
? () => this.post({ type: "resize-window", windowId: spec.windowId, viewport: appViewportSize(heightMode, this.options.appId) })
|
||||
: undefined,
|
||||
hasAppMenu: () => this.windowGestures.get(spec.windowId)?.hasAppMenu ?? false,
|
||||
claimsLongPress: () => this.windowGestures.get(spec.windowId)?.claimsLongPress ?? false,
|
||||
close: () => {
|
||||
|
||||
@@ -73,6 +73,11 @@ export class WindowMenu {
|
||||
|
||||
constructor(private readonly options: WindowMenuOptions) {}
|
||||
|
||||
resize(size: { width: number; height: number }): void {
|
||||
this.options.size = size;
|
||||
this.stack?.setBaseSize(size);
|
||||
}
|
||||
|
||||
isOpen(): boolean {
|
||||
return this.stack !== null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
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');
|
||||
const read = (file) => fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
|
||||
const js = (source) => ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText;
|
||||
|
||||
function geometry() {
|
||||
const settings = Object.fromEntries(Object.entries({
|
||||
displayModeSetting: '576x288', verticalPositionSetting: 'middle',
|
||||
navigateDisplayModeSetting: 'global', navigateVerticalPositionSetting: 'global',
|
||||
terminalDisplayModeSetting: 'default', terminalVerticalPositionSetting: 'global',
|
||||
}).map(([name, value]) => [name, { value, get() { return this.value; } }]));
|
||||
const context = { exports: {}, require: (name) => {
|
||||
if (name === '../../graphics/image') return { G2_LENS_WIDTH: 640, G2_LENS_HEIGHT: 480 };
|
||||
assert.equal(name, '../dashboard-settings');
|
||||
return settings;
|
||||
} };
|
||||
vm.runInNewContext(js(read('app/ui/shell/geometry.ts')), context);
|
||||
const rect = (mode, appId) => ({ ...context.exports.appViewportRect(mode, appId) });
|
||||
return { ...context.exports, settings, rect };
|
||||
}
|
||||
|
||||
test('defaults preserve normal windows, EvenHub height and tall terminal sessions', () => {
|
||||
const g = geometry();
|
||||
assert.deepEqual(g.rect('min', 'navigate'), { x: 64, y: 124, width: 576, height: 260 });
|
||||
assert.deepEqual(g.rect('min', 'terminal'), g.rect('min'));
|
||||
assert.deepEqual(g.rect('max', 'terminal'), { x: 64, y: 28, width: 576, height: 452 });
|
||||
assert.equal(g.windowBandHeight('medium', 'evenhub'), 316);
|
||||
g.settings.displayModeSetting.value = '640x480';
|
||||
assert.deepEqual(g.rect('max', 'terminal'), { x: 0, y: 28, width: 640, height: 452 });
|
||||
});
|
||||
|
||||
test('Navigate can use a small bottom band while other apps fill the panel', () => {
|
||||
const g = geometry();
|
||||
g.settings.displayModeSetting.value = '640x480';
|
||||
g.settings.navigateDisplayModeSetting.value = '576x288';
|
||||
g.settings.navigateVerticalPositionSetting.value = 'bottom';
|
||||
assert.deepEqual(g.rect('min', 'navigate'), { x: 64, y: 220, width: 576, height: 260 });
|
||||
assert.equal(g.minWindowTop('navigate'), 192);
|
||||
assert.equal(g.sidebarStripVisible('window', 'navigate'), true);
|
||||
assert.equal(g.sidebarStripVisible('window', 'other'), false);
|
||||
assert.deepEqual(g.rect('min', 'other'), { x: 0, y: 28, width: 640, height: 452 });
|
||||
});
|
||||
|
||||
test('Terminal can disable its tall default, inherit position or override both dimensions', () => {
|
||||
const g = geometry();
|
||||
g.settings.terminalDisplayModeSetting.value = 'global';
|
||||
assert.deepEqual(g.rect('max', 'terminal'), g.rect('min'));
|
||||
g.settings.verticalPositionSetting.value = 'top';
|
||||
assert.equal(g.windowTop('max', 'terminal'), 0);
|
||||
g.settings.terminalVerticalPositionSetting.value = 'lower';
|
||||
assert.equal(g.windowTop('max', 'terminal'), 144);
|
||||
g.settings.terminalDisplayModeSetting.value = '640x480';
|
||||
assert.deepEqual(g.rect('max', 'terminal'), { x: 0, y: 28, width: 640, height: 452 });
|
||||
assert.equal(g.sidebarStripVisible('window', 'terminal'), false);
|
||||
assert.equal(g.sidebarStripVisible('sidebar', 'terminal'), true);
|
||||
g.settings.terminalDisplayModeSetting.value = '576x480';
|
||||
assert.deepEqual(g.rect('max', 'terminal'), { x: 64, y: 28, width: 576, height: 452 });
|
||||
});
|
||||
|
||||
test('all explicit size/position combinations stay within the display and align content below the bar', () => {
|
||||
const g = geometry();
|
||||
for (const globalMode of ['576x288', '576x480', '640x480']) {
|
||||
g.settings.displayModeSetting.value = globalMode;
|
||||
for (const appId of ['navigate', 'terminal']) {
|
||||
for (const mode of ['global', '576x288', '576x480', '640x480']) {
|
||||
g.settings[`${appId}DisplayModeSetting`].value = mode;
|
||||
for (const position of ['global', 'top', 'upper', 'middle', 'lower', 'bottom']) {
|
||||
g.settings[`${appId}VerticalPositionSetting`].value = position;
|
||||
const rect = g.rect('max', appId);
|
||||
assert.equal(rect.x + rect.width, 640);
|
||||
assert.equal(rect.y, g.windowTop('max', appId) + g.TOP_BAR_HEIGHT);
|
||||
assert.ok(rect.y >= 28 && rect.y + rect.height <= 480);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Exercise the real worker message handler with platform work stubbed out.
|
||||
function resizeHandler(file, globals) {
|
||||
const source = ts.createSourceFile(file, read(file), ts.ScriptTarget.Latest, true);
|
||||
const handler = source.statements.find((s) => ts.isExpressionStatement(s)
|
||||
&& ts.isBinaryExpression(s.expression) && s.expression.left.getText(source) === 'global.onmessage');
|
||||
assert.ok(handler);
|
||||
const context = { global: {}, ...globals };
|
||||
vm.runInNewContext(js(handler.getText(source)), context);
|
||||
return (viewport) => context.global.onmessage({ data: { type: 'resize-window', windowId: 'test', viewport } });
|
||||
}
|
||||
|
||||
test('Navigate resize preserves its active route and window, and remeasures an open menu', () => {
|
||||
let paints = 0;
|
||||
let menuSize;
|
||||
const window = { windowId: 'test', viewportWidth: 640, viewportHeight: 452,
|
||||
menu: { resize: (size) => { menuSize = size; } }, lastSubmittedFingerprint: 'old' };
|
||||
const route = { destination: 'Home' };
|
||||
const resize = resizeHandler('app/apps/navigate/navigate-app.worker.ts', {
|
||||
window, route, render: () => { paints++; },
|
||||
});
|
||||
resize({ width: 576, height: 260 });
|
||||
assert.equal(window.viewportHeight, 260);
|
||||
assert.equal(window.viewportWidth, 576);
|
||||
assert.equal(window.lastSubmittedFingerprint, '');
|
||||
assert.equal(route.destination, 'Home');
|
||||
assert.deepEqual(menuSize, { width: 576, height: 260 });
|
||||
resize({ width: 576, height: 260 });
|
||||
assert.equal(paints, 1);
|
||||
});
|
||||
|
||||
test('Terminal resize keeps the view identity, negotiates its grid and skips position-only changes', () => {
|
||||
const calls = [];
|
||||
const window = { kind: 'view', windowId: 'test', socket: 'session-1',
|
||||
viewportWidth: 576, viewportHeight: 452, cellWidth: 8, cellHeight: 16,
|
||||
menu: null, reconnectTimer: 42, emulator: { dispose: () => calls.push("dispose") },
|
||||
client: { stop: () => calls.push('stop'), setViewport: (...size) => calls.push(size) },
|
||||
};
|
||||
const resize = resizeHandler('app/apps/terminal/terminal-app.worker.ts', {
|
||||
windows: new Map([['test', window]]), clearTimeout: (timer) => calls.push(timer),
|
||||
TerminalEmulator: class { constructor(cols, rows) { this.cols = cols; this.rows = rows; } },
|
||||
reconnectView: (view) => { assert.equal(view, window); calls.push('reconnect'); },
|
||||
scheduleRender: () => calls.push('paint'),
|
||||
});
|
||||
resize({ width: 576, height: 260 });
|
||||
assert.equal(window.socket, 'session-1');
|
||||
assert.equal(window.gridCols, 72);
|
||||
assert.equal(window.gridRows, 16);
|
||||
assert.equal(window.emulator.rows, 16);
|
||||
assert.deepEqual(calls, [42, 'stop', [72, 16], 'dispose', 'reconnect', 'paint']);
|
||||
resize({ width: 576, height: 260 });
|
||||
assert.equal(calls.length, 6);
|
||||
});
|
||||
|
||||
test('resizing a terminal reconnects with the new grid and ignores callbacks from the old socket', () => {
|
||||
const sockets = [];
|
||||
const context = {
|
||||
exports: {}, require: () => ({}),
|
||||
com: { faceclaw: { app: {
|
||||
FaceclawWebSocketListener: class { constructor(callbacks) { return callbacks; } },
|
||||
FaceclawWebSocket: class {
|
||||
constructor(url, listener) { this.listener = listener; this.messages = []; sockets.push(this); }
|
||||
sendText(text) { this.messages.push(JSON.parse(text)); }
|
||||
close() {}
|
||||
},
|
||||
} } },
|
||||
};
|
||||
vm.runInNewContext(js(read('app/native/g2mirror-client.ts')), context);
|
||||
const client = new context.exports.G2MirrorClient({ host: 'localhost', port: 1234, cols: 72, rows: 28 });
|
||||
client.start();
|
||||
const oldSocket = sockets[0];
|
||||
oldSocket.listener.onOpen();
|
||||
assert.equal(oldSocket.messages[0].height, 28);
|
||||
client.stop();
|
||||
client.setViewport(80, 16);
|
||||
client.start();
|
||||
const newSocket = sockets[1];
|
||||
oldSocket.listener.onClosed(1000, 'bye');
|
||||
oldSocket.listener.onFailure('late failure');
|
||||
oldSocket.listener.onTextMessage('{"type":"error","message":"late error"}');
|
||||
assert.equal(client.state().phase, 'connecting');
|
||||
newSocket.listener.onOpen();
|
||||
assert.equal(newSocket.messages[0].width, 80);
|
||||
assert.equal(newSocket.messages[0].height, 16);
|
||||
assert.equal(client.state().status, 'Authenticating...');
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
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');
|
||||
const root = path.resolve(__dirname, '..');
|
||||
const read = (file) => fs.readFileSync(path.join(root, file), 'utf8');
|
||||
const js = (source) => ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText;
|
||||
|
||||
// Run the actual decoder declarations without loading the Android shell.
|
||||
function decoder() {
|
||||
const source = ts.createSourceFile('shell.ts', read('app/ui/shell/shell.ts'), ts.ScriptTarget.Latest, true);
|
||||
const names = new Set(['rawInputEventToPayload', 'eventSourceToString', 'scrollEvent']);
|
||||
const declarations = source.statements.filter((s) => ts.isFunctionDeclaration(s) && names.has(s.name?.text));
|
||||
assert.equal(declarations.length, names.size);
|
||||
const context = { exports: {} };
|
||||
vm.createContext(context);
|
||||
vm.runInContext(js(read('app/g2/events.ts')), context);
|
||||
Object.assign(context, context.exports);
|
||||
vm.runInContext(js(declarations.map((s) => s.getText(source)).join('\n')), context);
|
||||
return context;
|
||||
}
|
||||
|
||||
test('wire edges require explicit left/right temple provenance', () => {
|
||||
const d = decoder();
|
||||
for (const [key, source] of [['TOUCH_EVENT_FROM_GLASSES_L', 'left-arm'], ['TOUCH_EVENT_FROM_GLASSES_R', 'right-arm']]) {
|
||||
const eventSource = d.EventSourceType[key];
|
||||
for (const [eventType, type] of [[12, 'touch-press'], [13, 'touch-release']]) {
|
||||
const event = d.rawInputEventToPayload({ kind: 'sys-event', eventSource, eventType });
|
||||
assert.equal(event.type, type);
|
||||
assert.equal(event.source, source);
|
||||
}
|
||||
assert.equal(d.rawInputEventToPayload({ kind: 'sys-event', eventSource, eventType: 0 }).type, 'click');
|
||||
}
|
||||
for (const eventSource of [undefined, -1, 99, d.EventSourceType.TOUCH_EVENT_FROM_RING]) {
|
||||
assert.equal(d.rawInputEventToPayload({ kind: 'sys-event', eventSource, eventType: 12 }).type, 'unknown');
|
||||
}
|
||||
});
|
||||
|
||||
function worker() {
|
||||
const noop = () => {};
|
||||
const modules = {
|
||||
'@nativescript/core/globals': {},
|
||||
'../../graphics/image': {}, '../../graphics/plane': {}, '../../graphics/glyph-wire': {},
|
||||
'../../graphics/bdffont': { getFont: noop },
|
||||
'../../graphics/ui-fonts': { getDefaultSmallFont: noop },
|
||||
'../../native/frame-timings': { finishFrame: noop, logFrame: noop },
|
||||
'../../native/active-display': {},
|
||||
'../../native/settings-store': { getStringSetting: () => '0', setStringSetting: noop },
|
||||
'../../ui/sound-effects': {}, '../../ui/window-menu': {},
|
||||
'../../ui/gestures': { directionalFallback: (event) => event },
|
||||
'../../util/numeric-util': { clamp: (v, lo, hi) => Math.max(lo, Math.min(hi, v)) },
|
||||
};
|
||||
const context = {
|
||||
exports: {}, console, Date, setInterval: () => 1, clearInterval: noop,
|
||||
global: { postMessage: noop },
|
||||
require: (name) => { assert.ok(name in modules, name); return modules[name]; },
|
||||
};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(js(read('app/apps/pinball/pinball-app.worker.ts')) + `
|
||||
// Stub platform output only; exercise real worker input, physics and lifecycle.
|
||||
renderAndSubmit = () => {};
|
||||
playSfx = () => {};
|
||||
exports.harness = { windows, stepFlippers, resetGame };
|
||||
`, context);
|
||||
const message = (data) => context.global.onmessage({ data });
|
||||
message({ type: 'open-window', windowId: 'test', surfaceId: 'test', title: 'test', viewport: { width: 640, height: 480 } });
|
||||
message({ type: 'foreground', windowId: 'test', foreground: true, focused: true });
|
||||
const w = context.exports.harness.windows.get('test');
|
||||
w.ballState = 'live';
|
||||
const input = (type, source = 'left-arm') => message({ type: 'input', windowId: 'test', focused: true, frameId: 1, event: { type, source, timestampMs: Date.now() } });
|
||||
return { w, input, message, ...context.exports.harness };
|
||||
}
|
||||
|
||||
test('pinball responds on contact, holds independently, and releases before tap', () => {
|
||||
const h = worker();
|
||||
h.input('touch-press');
|
||||
assert.equal(h.w.flippers[0].state, 'rising');
|
||||
assert.equal(h.w.flippers[1].state, 'rest');
|
||||
h.stepFlippers(h.w, 1);
|
||||
h.w.flippers[0].holdUntilMs = 0;
|
||||
h.stepFlippers(h.w, 1);
|
||||
assert.equal(h.w.flippers[0].state, 'hold');
|
||||
h.input('touch-press', 'right-arm');
|
||||
h.input('touch-release');
|
||||
assert.equal(h.w.flippers[0].state, 'falling');
|
||||
assert.equal(h.w.flippers[1].touchHeld, true);
|
||||
h.input('click');
|
||||
assert.equal(h.w.flippers[0].state, 'falling');
|
||||
h.input('touch-release', 'right-arm');
|
||||
assert.equal(h.w.flippers[1].state, 'falling');
|
||||
});
|
||||
|
||||
test('pinball retains old firmware/ring controls and plunger click launch', () => {
|
||||
const h = worker();
|
||||
h.input('click');
|
||||
assert.ok(h.w.flippers.every((f) => f.state === 'rising'));
|
||||
h.resetGame(h.w);
|
||||
h.input('touch-press');
|
||||
h.input('touch-release');
|
||||
assert.equal(h.w.ballState, 'ready');
|
||||
h.input('click');
|
||||
assert.equal(h.w.ballState, 'live');
|
||||
h.input('click', 'ring');
|
||||
assert.ok(h.w.flippers.every((f) => f.state === 'rising'));
|
||||
});
|
||||
|
||||
test('pinball clears held contacts on pause, focus loss, screen-off and menus', () => {
|
||||
for (const cancel of [
|
||||
(h) => h.input('double-click', 'ring'),
|
||||
(h) => h.input('system-menu-opened'),
|
||||
(h) => h.message({ type: 'foreground', windowId: 'test', foreground: false, focused: false }),
|
||||
(h) => h.message({ type: 'render', windowId: 'test', focused: false }),
|
||||
(h) => h.message({ type: 'screen', on: false }),
|
||||
]) {
|
||||
const h = worker();
|
||||
h.input('touch-press');
|
||||
cancel(h);
|
||||
assert.equal(h.w.flippers[0].touchHeld, false);
|
||||
assert.equal(h.w.flippers[0].state, 'falling');
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user