forked from Blendman974/faceclaw
Merge branch 'main' into ring-health-fixes
This commit is contained in:
commit
4f8c082b52
368 files changed
+26238
-3401
No files matched your search
+320
-98
@@ -17,12 +17,15 @@ import {
|
||||
type AssistantModel,
|
||||
} from "~/assistant/models";
|
||||
import { isLocalModelReady } from "../native/llama";
|
||||
import { normalizeWhisperServerUrl } from "../native/whisper-server-stt";
|
||||
import { drawRightValueMenuItem, drawToggleMenuItem, MenuItem, openModalMenu } from "./menu";
|
||||
import { ANIMATION_SPEEDS, animationSpeedLabel, scaleAnimationDuration, type AnimationSpeed } from "./animation-speed";
|
||||
import { MENU_ANIMATION_KEY } from "./menu-animation-pref";
|
||||
import { LIST_ROW_TEXT_INSET, lineStep } from "./metrics";
|
||||
import { Layer, type LayerContext } from "./layers";
|
||||
import { GrayImage } from "~/graphics/image";
|
||||
import type { DataCollectionLevel } from "../analytics/analytics-store";
|
||||
import { IOS_PRIVACY_SUMMARY } from "../analytics/privacy-disclosure";
|
||||
|
||||
export type NightscoutSettings = {
|
||||
siteUrl: string;
|
||||
@@ -32,6 +35,7 @@ export type BatteryDisplayMode = "icon" | "percentage" | "stacked" | "stacked-pe
|
||||
/** When a top-bar battery indicator is shown: always, only below 50%, or never. */
|
||||
export type BatteryIndicatorVisibility = "always" | "low" | "never";
|
||||
export type TimeFormat = "24h" | "12h";
|
||||
export type TemperatureUnit = "fahrenheit" | "celsius";
|
||||
export type ScreenTimeoutSetting = "15s" | "30s" | "1m" | "3m" | "never";
|
||||
// Auto runs Faceclaw's light curve. Numeric values use the calibrated firmware
|
||||
// scale, clamped to 2–100; 2 is also the endpoint for screen fades.
|
||||
@@ -47,6 +51,11 @@ type ConfigSettingOptions<TValue, TId extends string> = {
|
||||
formatValue?: (value: TValue) => string;
|
||||
/** Extended description shown in the Settings panel when the row is selected. */
|
||||
description?: string;
|
||||
/**
|
||||
* Boolean and enum settings only take fixed values, so Full analytics
|
||||
* reports them (fixedChoiceSettingValues); false keeps this one out.
|
||||
*/
|
||||
reportInAnalytics?: boolean;
|
||||
};
|
||||
|
||||
// Fired after any setting changes, in any isolate (storage lives in the Java
|
||||
@@ -74,6 +83,21 @@ onSettingsStoreChanged(() => {
|
||||
}, 0);
|
||||
});
|
||||
|
||||
// Boolean and enum settings by storage key, for fixedChoiceSettingValues.
|
||||
// Settings built repeatedly (per-app or per-slot) just replace themselves.
|
||||
const fixedChoiceSettings = new Map<string, ConfigSetting<boolean> | ConfigSetting<string>>();
|
||||
|
||||
/**
|
||||
* The current value of every boolean and enum setting this isolate has
|
||||
* loaded, keyed by storage key: what Full analytics reports as settings.
|
||||
* Free-text settings never appear.
|
||||
*/
|
||||
export function fixedChoiceSettingValues(): Record<string, boolean | string> {
|
||||
const values: Record<string, boolean | string> = {};
|
||||
for (const [storageKey, setting] of fixedChoiceSettings) values[storageKey] = setting.get();
|
||||
return values;
|
||||
}
|
||||
|
||||
export abstract class ConfigSetting<TValue, TId extends string = string> {
|
||||
readonly id: TId;
|
||||
readonly label: string;
|
||||
@@ -104,6 +128,7 @@ export class ConfigSettingBoolean<TId extends string = string> extends ConfigSet
|
||||
// Widens ConfigSetting's protected constructor.
|
||||
public constructor(options: ConfigSettingOptions<boolean, TId>) {
|
||||
super(options);
|
||||
if (options.reportInAnalytics !== false) fixedChoiceSettings.set(options.storageKey, this);
|
||||
}
|
||||
|
||||
get(): boolean {
|
||||
@@ -134,6 +159,7 @@ export class ConfigSettingEnum<TValue extends string, TId extends string = strin
|
||||
|
||||
constructor(options: ConfigSettingEnumOptions<TValue, TId>) {
|
||||
super(options);
|
||||
if (options.reportInAnalytics !== false) fixedChoiceSettings.set(options.storageKey, this);
|
||||
this.values = options.values;
|
||||
this.disabledPredicate = options.isDisabled ?? (() => false);
|
||||
if (options.normalize) {
|
||||
@@ -305,47 +331,14 @@ export const timeFormatSetting = new ConfigSettingEnum<TimeFormat>({
|
||||
description: "Whether the top-bar clock shows 24-hour or 12-hour time.",
|
||||
});
|
||||
|
||||
/**
|
||||
* How much of the 640x480 panel the UI uses. "576x288" is the stock band
|
||||
* (sidebar + a 288px-tall window at the vertical position); "576x480" keeps
|
||||
* the sidebar and gives every window the full height; "640x480" is the whole
|
||||
* panel, with the sidebar an overlay that shows only while it has focus. The
|
||||
* values name the sizes beside a side strip; with the app switcher along the
|
||||
* bottom, the tall height loses the switcher row (displayModeLabel shows the
|
||||
* actual size).
|
||||
*/
|
||||
export const DISPLAY_MODE_VALUES = ["576x288", "576x480", "640x480"] as const;
|
||||
export type DisplayModeSetting = (typeof DISPLAY_MODE_VALUES)[number];
|
||||
|
||||
const DISPLAY_MODE_NAMES: Record<DisplayModeSetting, string> = {
|
||||
"576x288": "Band",
|
||||
"576x480": "Tall",
|
||||
"640x480": "Full panel",
|
||||
};
|
||||
|
||||
/** Window size per mode with the app switcher along the bottom (see geometry.ts). */
|
||||
const BOTTOM_SWITCHER_SIZES: Record<DisplayModeSetting, string> = {
|
||||
"576x288": "576×288",
|
||||
"576x480": "576×444",
|
||||
"640x480": "640×480",
|
||||
};
|
||||
|
||||
export function displayModeLabel(value: DisplayModeSetting): string {
|
||||
const name = DISPLAY_MODE_NAMES[value];
|
||||
if (!name) return value;
|
||||
const size = appSwitcherPositionSetting.get() === "bottom" ? BOTTOM_SWITCHER_SIZES[value] : value.replace("x", "×");
|
||||
return `${name} · ${size}`;
|
||||
}
|
||||
|
||||
export const displayModeSetting = new ConfigSettingEnum<DisplayModeSetting>({
|
||||
id: "display-mode",
|
||||
label: "Display mode",
|
||||
storageKey: "display.mode",
|
||||
defaultValue: "576x288",
|
||||
values: DISPLAY_MODE_VALUES,
|
||||
formatValue: displayModeLabel,
|
||||
description:
|
||||
"Band: the stock 288px-tall window beside the app switcher. Tall: the app switcher plus full-height windows. Full panel: the whole 640×480 display; the app switcher overlays the app only while you are in it. Open apps reopen in the new size.",
|
||||
export const temperatureUnitSetting = new ConfigSettingEnum<TemperatureUnit>({
|
||||
id: "temperatureUnit",
|
||||
label: "Temperature unit",
|
||||
storageKey: "display.temperatureUnit",
|
||||
defaultValue: "fahrenheit",
|
||||
values: ["fahrenheit", "celsius"],
|
||||
formatValue: (value) => value === "celsius" ? "Celsius" : "Fahrenheit",
|
||||
description: "Whether the Weather app, its top-bar indicator, and the Glanceboard's system card show temperatures in Fahrenheit or Celsius.",
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -373,6 +366,83 @@ export const appSwitcherPositionSetting = new ConfigSettingEnum<AppSwitcherPosit
|
||||
"Where the open-app icons go. Left and right take a column beside windows; bottom puts a row beneath the window, which makes full-height windows a little shorter; popup shows them only while you're in the app switcher, in a box over the dimmed window. Bottom and popup leave room at the sides to set the display's depth. Open apps reopen at their new size when a change resizes windows.",
|
||||
});
|
||||
|
||||
/**
|
||||
* An enum setting that took over from older settings: until it is first
|
||||
* set, its value is derived from theirs.
|
||||
*/
|
||||
class ConfigSettingEnumWithLegacy<TValue extends string> extends ConfigSettingEnum<TValue> {
|
||||
constructor(options: ConfigSettingEnumOptions<TValue, string>, private readonly legacyValue: () => TValue) {
|
||||
super(options);
|
||||
}
|
||||
|
||||
get(): TValue {
|
||||
return getStringSetting(this.storageKey, "") === "" ? this.legacyValue() : super.get();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How much of the 640x480 panel windows use, and where: the stock
|
||||
* 288px-tall band, at one of five heights in the field of view; Tall, every
|
||||
* window the full height; or Full Screen, Tall at the panel's whole 640px
|
||||
* width. The app switcher keeps its own room in every mode. Full Screen
|
||||
* needs a bottom row or popup app switcher (a side strip leaves no width to
|
||||
* spare; there it is Tall), has no window frame, and plays at depth 0,
|
||||
* since its windows reach the panel's edges (geometry.ts).
|
||||
*/
|
||||
export const DISPLAY_LAYOUT_VALUES = [
|
||||
"band-top", "band-high", "band-middle", "band-low", "band-bottom", "tall", "fullscreen",
|
||||
] as const;
|
||||
export type DisplayLayout = (typeof DISPLAY_LAYOUT_VALUES)[number];
|
||||
|
||||
const DISPLAY_LAYOUT_LABELS: Record<DisplayLayout, string> = {
|
||||
"band-top": "Band · Top",
|
||||
"band-high": "Band · High",
|
||||
"band-middle": "Band · Middle",
|
||||
"band-low": "Band · Low",
|
||||
"band-bottom": "Band · Bottom",
|
||||
tall: "Tall",
|
||||
fullscreen: "Full Screen",
|
||||
};
|
||||
|
||||
export function displayLayoutLabel(value: DisplayLayout): string {
|
||||
return DISPLAY_LAYOUT_LABELS[value] ?? value;
|
||||
}
|
||||
|
||||
/** Whether the Full Screen display mode is available: with a bottom row or popup app switcher. */
|
||||
export function fullScreenAvailable(): boolean {
|
||||
const position = appSwitcherPositionSetting.get();
|
||||
return position === "bottom" || position === "popup";
|
||||
}
|
||||
|
||||
// Until 2026-10-10 the display mode ("576x288" band, "576x480" tall,
|
||||
// "640x480" full panel) and the band's vertical position were separate
|
||||
// settings, globally and per app.
|
||||
const LEGACY_MODE_LAYOUTS: Record<string, DisplayLayout> = { "576x480": "tall", "640x480": "fullscreen" };
|
||||
const LEGACY_POSITION_LAYOUTS: Record<string, DisplayLayout> = {
|
||||
top: "band-top", upper: "band-high", middle: "band-middle", lower: "band-low", bottom: "band-bottom",
|
||||
};
|
||||
|
||||
function legacyBand(position: string): DisplayLayout {
|
||||
return LEGACY_POSITION_LAYOUTS[position] ?? "band-middle";
|
||||
}
|
||||
|
||||
function legacyDisplayLayout(): DisplayLayout {
|
||||
const mode = getStringSetting("display.mode", "576x288");
|
||||
return LEGACY_MODE_LAYOUTS[mode] ?? legacyBand(getStringSetting("display.verticalPosition", "middle"));
|
||||
}
|
||||
|
||||
export const displayLayoutSetting = new ConfigSettingEnumWithLegacy<DisplayLayout>({
|
||||
id: "display-mode",
|
||||
label: "Display mode",
|
||||
storageKey: "display.layout",
|
||||
defaultValue: "band-middle",
|
||||
values: DISPLAY_LAYOUT_VALUES,
|
||||
formatValue: displayLayoutLabel,
|
||||
isDisabled: (value) => value === "fullscreen" && !fullScreenAvailable(),
|
||||
description:
|
||||
"Band: the stock 288px-tall window, at the height in your field of view you choose. Tall: full-height windows. Full Screen: full-height windows across the display's whole width; it needs the app switcher at the bottom or as a popup, and turns depth off, since windows reach the display's edges. Navigate and Terminal can override this. Open apps reopen in the new size.",
|
||||
}, legacyDisplayLayout);
|
||||
|
||||
const UI_DEPTH_VALUES = ["-62", "-48", "-32", "-16", "0", "16", "32", "48", "62"] as const;
|
||||
export type UiDepth = (typeof UI_DEPTH_VALUES)[number];
|
||||
|
||||
@@ -382,8 +452,9 @@ export type UiDepth = (typeof UI_DEPTH_VALUES)[number];
|
||||
* directions. Only applies with the app switcher at the bottom or a popup,
|
||||
* where the windows' 576px width leaves 32px at each side: one for the side
|
||||
* of the window's frame and 31 to shift into, hence ±62 (see geometry.ts
|
||||
* uiDepth and windowFramed); values stay even so the per-lens halves of
|
||||
* nested depths add exactly.
|
||||
* uiDepth and windowFramed); not to Full Screen windows, which have no such
|
||||
* margins. Values stay even so the per-lens halves of nested depths add
|
||||
* exactly.
|
||||
*/
|
||||
export const uiDepthSetting = new ConfigSettingEnum<UiDepth>({
|
||||
id: "ui-depth",
|
||||
@@ -396,7 +467,7 @@ export const uiDepthSetting = new ConfigSettingEnum<UiDepth>({
|
||||
return depth === 0 ? "0" : depth > 0 ? `+${depth} (nearer)` : `${depth} (farther)`;
|
||||
},
|
||||
description:
|
||||
"Moves the whole display nearer (positive) or farther away (negative) by shifting it in opposite directions on the two lenses. Available with the app switcher at the bottom or as a popup. Full-panel windows lose a sliver at the edges.",
|
||||
"Moves the whole display nearer (positive) or farther away (negative) by shifting it in opposite directions on the two lenses. Available with the app switcher at the bottom or as a popup; not applied in the Full Screen display mode, whose windows reach the display's edges.",
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -419,7 +490,7 @@ export const statusBarPositionSetting = new ConfigSettingEnum<StatusBarPosition>
|
||||
formatValue: (value) => value === "top" ? "Top"
|
||||
: appSwitcherPositionSetting.get() === "bottom" ? "With app switcher" : "Bottom",
|
||||
description:
|
||||
"Where the clock, notification icons, app widgets and battery indicators go. With the app switcher at the bottom, With app switcher puts them at the right end of its row, and windows grow into the top bar's space; with a popup app switcher, Bottom puts them under the window. Available with the app switcher at the bottom or as a popup; with a bottom app switcher, the full-panel display mode keeps the top bar. Changing it reopens open apps in the new size.",
|
||||
"Where the clock, notification icons, app widgets and battery indicators go. With the app switcher at the bottom, With app switcher puts them at the right end of its row, and windows grow into the top bar's space; with a popup app switcher, Bottom puts them under the window. Available with the app switcher at the bottom or as a popup. Changing it reopens open apps in the new size.",
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -511,6 +582,14 @@ export function getBrightnessPreferences() {
|
||||
curve: autoBrightnessCurveSetting.getValidValue(), fadeMs: scaleAnimationDuration(SCREEN_FADE_MS, screenFadeSetting.get()) };
|
||||
}
|
||||
|
||||
export const wakeToLastAppSetting = new ConfigSettingBoolean({
|
||||
id: "wake-to-last-app",
|
||||
label: "Wake into last app",
|
||||
storageKey: "display.wakeToLastApp",
|
||||
defaultValue: false,
|
||||
description: "Waking the display with a double tap returns to the app you were using. Off: wake into the app switcher.",
|
||||
});
|
||||
|
||||
export const screenTimeoutSetting = new ConfigSettingEnum<ScreenTimeoutSetting>({
|
||||
id: "screen-timeout",
|
||||
label: "Screen timeout",
|
||||
@@ -557,6 +636,19 @@ export const previewColorSetting = new ConfigSettingEnum<PreviewColor>({
|
||||
"How the phone's mirror of the glasses display renders: white/grayscale (clearest), or green to match the physical glasses.",
|
||||
});
|
||||
|
||||
export type PreviewScaling = "scaled" | "raw";
|
||||
|
||||
export const previewScalingSetting = new ConfigSettingEnum<PreviewScaling>({
|
||||
id: "preview-scaling",
|
||||
label: "Preview scaling",
|
||||
storageKey: "phone.previewScaling",
|
||||
defaultValue: "scaled",
|
||||
values: ["scaled", "raw"],
|
||||
formatValue: (value) => (value === "raw" ? "Raw" : "Scaled"),
|
||||
description:
|
||||
"How much of the glasses display the phone's mirror shows: Scaled centers and enlarges the part the current display mode uses; Raw shows the whole 640x480 panel.",
|
||||
});
|
||||
|
||||
export const mirrorTouchSetting = new ConfigSettingBoolean({
|
||||
id: "mirror-touch",
|
||||
label: "Touch mirror",
|
||||
@@ -605,60 +697,81 @@ export const watchMirrorAssistantSetting = new ConfigSettingBoolean({
|
||||
description: "Stream assistant replies and on-glasses alerts to the watch so they can be read from the wrist.",
|
||||
});
|
||||
|
||||
export type VerticalPosition = "top" | "upper" | "middle" | "lower" | "bottom";
|
||||
/**
|
||||
* A per-app display mode (Navigate, Terminal): the global one ("global"),
|
||||
* Terminal's own default ("default": tall sessions, the sessions list at
|
||||
* the global mode), or a mode of its own.
|
||||
*/
|
||||
export type AppDisplayLayout = "default" | "global" | DisplayLayout;
|
||||
|
||||
const VERTICAL_POSITION_LABELS: Record<VerticalPosition, string> = {
|
||||
top: "Top",
|
||||
upper: "Upper",
|
||||
middle: "Middle",
|
||||
lower: "Lower",
|
||||
bottom: "Bottom",
|
||||
};
|
||||
function legacyAppDisplayLayout(appId: string, defaultValue: AppDisplayLayout): AppDisplayLayout {
|
||||
const mode = getStringSetting(`${appId}.displayMode`, defaultValue);
|
||||
const position = getStringSetting(`${appId}.verticalPosition`, "global");
|
||||
if (LEGACY_MODE_LAYOUTS[mode]) return LEGACY_MODE_LAYOUTS[mode];
|
||||
const global = displayLayoutSetting.get();
|
||||
if (mode === "576x288") return position === "global" ? (global.startsWith("band-") ? global : legacyDisplayLayout()) : legacyBand(position);
|
||||
// Following the global mode at a band position of its own.
|
||||
if (mode === "global" && position !== "global" && global.startsWith("band-")) return legacyBand(position);
|
||||
return mode === "default" || mode === "global" ? mode : defaultValue;
|
||||
}
|
||||
|
||||
export const verticalPositionSetting = new ConfigSettingEnum<VerticalPosition>({
|
||||
id: "vertical-position",
|
||||
label: "Vertical position",
|
||||
storageKey: "display.verticalPosition",
|
||||
defaultValue: "middle",
|
||||
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 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>({
|
||||
function appDisplayLayoutSetting(appId: string, defaultValue: AppDisplayLayout): ConfigSettingEnum<AppDisplayLayout> {
|
||||
return new ConfigSettingEnumWithLegacy<AppDisplayLayout>({
|
||||
id: `${appId}-display-mode`,
|
||||
label: "Display mode",
|
||||
storageKey: `${appId}.displayMode`,
|
||||
storageKey: `${appId}.displayLayout`,
|
||||
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),
|
||||
values: appId === "terminal" ? ["default", "global", ...DISPLAY_LAYOUT_VALUES] : ["global", ...DISPLAY_LAYOUT_VALUES],
|
||||
formatValue: (value) => value === "default" ? "Tall sessions (default)" : value === "global" ? "Use global" : displayLayoutLabel(value),
|
||||
isDisabled: (value) => value === "fullscreen" && !fullScreenAvailable(),
|
||||
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.",
|
||||
});
|
||||
? "Display mode for Terminal. The default keeps session windows tall and the terminals list in the global mode. Use global follows Display settings for all Terminal windows. Resizing an open session reconnects its view at the new size."
|
||||
: "Display mode for Navigate. Choose a Band to leave more of your field of view clear, or Use global to follow Display settings. Applies to the current route too.",
|
||||
}, () => legacyAppDisplayLayout(appId, defaultValue));
|
||||
}
|
||||
|
||||
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 navigateDisplayLayoutSetting = appDisplayLayoutSetting("navigate", "global");
|
||||
export const terminalDisplayLayoutSetting = appDisplayLayoutSetting("terminal", "default");
|
||||
|
||||
export type { DataCollectionLevel };
|
||||
|
||||
/** The data-collection setting's key, for observers (app/analytics/analytics.ts). */
|
||||
export const DATA_COLLECTION_KEY = "privacy.dataCollection";
|
||||
|
||||
const DATA_COLLECTION_LABELS: Record<DataCollectionLevel, string> = {
|
||||
none: "None",
|
||||
minimal: "Minimal",
|
||||
full: "Full",
|
||||
};
|
||||
|
||||
// What each level collects is set out in app/analytics/analytics-store.ts and
|
||||
// the privacy policy (PRIVACY); keep these in step with both.
|
||||
const DATA_COLLECTION_SUMMARIES: Record<DataCollectionLevel, string> = {
|
||||
none: "Disable all data sharing",
|
||||
minimal: "Version, devices, and connection reliability statistics",
|
||||
full: "More detailed usage data",
|
||||
};
|
||||
|
||||
/** One-line summary of what a data-collection level sends (onboarding, settings). */
|
||||
export function dataCollectionSummary(level: DataCollectionLevel): string {
|
||||
return DATA_COLLECTION_SUMMARIES[level];
|
||||
}
|
||||
|
||||
export const navigateDisplayModeSetting = appDisplayModeSetting("navigate", "global");
|
||||
export const navigateVerticalPositionSetting = appVerticalPositionSetting("navigate");
|
||||
export const terminalDisplayModeSetting = appDisplayModeSetting("terminal", "default");
|
||||
export const terminalVerticalPositionSetting = appVerticalPositionSetting("terminal");
|
||||
/** Chosen in the on-glasses onboarding; changeable in Settings > Privacy. */
|
||||
export const dataCollectionSetting = new ConfigSettingEnum<DataCollectionLevel>({
|
||||
id: "data-collection",
|
||||
label: "Faceclaw statistics",
|
||||
storageKey: DATA_COLLECTION_KEY,
|
||||
defaultValue: "none",
|
||||
values: ["none", "minimal", "full"],
|
||||
formatValue: (value) => DATA_COLLECTION_LABELS[value],
|
||||
description:
|
||||
(global.isIOS ? IOS_PRIVACY_SUMMARY + " " : "") +
|
||||
"Optional statistics Faceclaw may send its developers once a day, to help fix problems and improve the " +
|
||||
"app. None: no Faceclaw statistics are stored or sent. Minimal: the app version, which devices are " +
|
||||
"paired and in use, and how reliable the connection to them is. Full: also settings chosen from fixed " +
|
||||
"options, and which kinds of API key are set (never the keys themselves).",
|
||||
});
|
||||
|
||||
export const voiceControlEnabledSetting = new ConfigSettingBoolean({
|
||||
id: "voice-control-enabled",
|
||||
@@ -728,14 +841,18 @@ export const ringConnectionModeSetting = new ConfigSettingEnum<RingConnectionMod
|
||||
// runs -- see the same note in native/voice-control.ts. The "whisper" value
|
||||
// keeps its name (it's a persisted setting on real installs) but its label
|
||||
// below now says "OpenAI" to tell the two apart in the picker.
|
||||
export type VoiceProvider = "onboard" | "onboard-whisper" | "elevenlabs" | "whisper" | "soniox";
|
||||
// "whisper-server" is a self-hosted OpenAI-compatible Whisper (e.g. vLLM).
|
||||
export type VoiceProvider = "onboard" | "onboard-whisper" | "elevenlabs" | "whisper" | "soniox" | "whisper-server";
|
||||
|
||||
// On iOS "onboard" is Apple's on-device recognizer, and there is no
|
||||
// "onboard-whisper" (the sherpa-onnx models are Android-only).
|
||||
const voiceProviderLabels: Record<VoiceProvider, string> = {
|
||||
onboard: "On-device (Moonshine)",
|
||||
onboard: global.isIOS ? "On-device (Apple)" : "On-device (Moonshine)",
|
||||
"onboard-whisper": "On-device (Whisper)",
|
||||
elevenlabs: "ElevenLabs",
|
||||
whisper: "OpenAI (Whisper)",
|
||||
soniox: "Soniox",
|
||||
"whisper-server": "Whisper server (self-hosted)",
|
||||
};
|
||||
|
||||
export const voiceProviderSetting = new ConfigSettingEnum<VoiceProvider>({
|
||||
@@ -743,15 +860,20 @@ export const voiceProviderSetting = new ConfigSettingEnum<VoiceProvider>({
|
||||
label: "Transcription Provider",
|
||||
storageKey: "voice.provider",
|
||||
defaultValue: "onboard",
|
||||
values: ["onboard", "onboard-whisper", "elevenlabs", "whisper", "soniox"],
|
||||
values: global.isIOS
|
||||
? ["onboard", "elevenlabs", "whisper", "soniox", "whisper-server"]
|
||||
: ["onboard", "onboard-whisper", "elevenlabs", "whisper", "soniox", "whisper-server"],
|
||||
formatValue: (value) => voiceProviderLabels[value] ?? value,
|
||||
isDisabled: (value) => {
|
||||
if (value === "elevenlabs") return elevenLabsApiKeySetting.get().trim().length === 0;
|
||||
if (value === "whisper") return openAiApiKeySetting.get().trim().length === 0;
|
||||
if (value === "soniox") return sonioxApiKeySetting.get().trim().length === 0;
|
||||
if (value === "whisper-server") return !normalizeWhisperServerUrl(whisperServerUrlSetting.get());
|
||||
return false;
|
||||
},
|
||||
description: "Speech-to-text engine for voice input. ElevenLabs, OpenAI, and Soniox are cloud services that need an API key, with significantly better accuracy than on-device transcription. The two On-device options need their voice model downloaded (below) and never leave the phone.",
|
||||
description: global.isIOS
|
||||
? "Speech-to-text engine for voice input. ElevenLabs, OpenAI, and Soniox are cloud services that need an API key (Settings > API Keys), with significantly better accuracy than on-device transcription. Whisper server is your own OpenAI-compatible Whisper (set its URL below). On-device uses your iPhone's speech language and never leaves the phone."
|
||||
: "Speech-to-text engine for voice input. ElevenLabs, OpenAI, and Soniox are cloud services that need an API key, with significantly better accuracy than on-device transcription. Whisper server is your own OpenAI-compatible Whisper (set its URL below). The two On-device options need their voice model downloaded (below) and never leave the phone.",
|
||||
});
|
||||
|
||||
const wakeWordActionLabels: Record<WakeWordAction, string> = {
|
||||
@@ -770,6 +892,14 @@ export const wakeWordActionSetting = new ConfigSettingEnum<WakeWordAction>({
|
||||
description: "What saying \"Hey Even\" does: start voice input, just turn the screen on, or nothing.",
|
||||
});
|
||||
|
||||
export const saveTranscribeAudioSetting = new ConfigSettingBoolean({
|
||||
id: "save-transcribe-audio",
|
||||
label: "Save Transcribe audio",
|
||||
storageKey: "voice.saveTranscribeAudio",
|
||||
defaultValue: true,
|
||||
description: "Record each Transcribe session's audio as a WAV file in Downloads (about 2 MB per minute), named like its transcript. Recordings are kept until you delete them.",
|
||||
});
|
||||
|
||||
export const saveVoiceRecordingsSetting = new ConfigSettingBoolean({
|
||||
id: "save-voice-recordings",
|
||||
label: "Save voice recordings",
|
||||
@@ -804,6 +934,28 @@ export const assistantBackendSetting = new ConfigSettingEnum<AssistantBackendKin
|
||||
global.isIOS ? "Cloud models called with your OpenAI or Anthropic API key. Add your key in Settings > API Keys." : "Who answers assistant queries: an LLM called from the phone (a cloud API with your key, or the downloaded on-phone model), or your own long-running agent (e.g. OpenClaw) reached through the faceclaw-agent-bridge plugin.",
|
||||
});
|
||||
|
||||
export const assistantHermesUrlSetting = new ConfigSettingString({
|
||||
id: "assistant-hermes-url",
|
||||
label: "Hermes URL",
|
||||
storageKey: "assistant.hermesUrl",
|
||||
defaultValue: "",
|
||||
editorTitle: "Hermes API server (e.g. http://host:8642/v1)",
|
||||
glassesEditTitle: "Edit Hermes URL",
|
||||
formatValue: (value) => value || "(not set)",
|
||||
description: "Address of a Hermes Agent gateway's API server, used when Hermes agent is the assistant model.",
|
||||
});
|
||||
|
||||
export const assistantHermesKeySetting = new ConfigSettingString({
|
||||
id: "assistant-hermes-key",
|
||||
label: "Hermes key",
|
||||
storageKey: "assistant.hermesKey",
|
||||
defaultValue: "",
|
||||
editorTitle: "Hermes API server key",
|
||||
glassesEditTitle: "Edit Hermes key",
|
||||
formatValue: (value) => (value ? `${value.slice(0, 6)}...` : "(not set)"),
|
||||
description: "The API server's key (API_SERVER_KEY in Hermes's .env).",
|
||||
});
|
||||
|
||||
export const assistantBridgeHostSetting = new ConfigSettingString({
|
||||
id: "assistant-bridge-host",
|
||||
label: "Bridge host",
|
||||
@@ -878,6 +1030,54 @@ export const sonioxApiKeySetting = new ConfigSettingString({
|
||||
description: "Soniox API key, used when Soniox is the transcription provider.",
|
||||
});
|
||||
|
||||
export const whisperServerUrlSetting = new ConfigSettingString({
|
||||
id: "whisper-server-url",
|
||||
label: "Whisper server URL",
|
||||
storageKey: "voice.whisperServerUrl",
|
||||
defaultValue: "",
|
||||
editorTitle: "Whisper server URL (e.g. http://100.x.y.z:8004/v1)",
|
||||
glassesEditTitle: "Edit Whisper server URL",
|
||||
formatValue: (value) => value || "(not set)",
|
||||
validate: (value) => (!value.trim() || normalizeWhisperServerUrl(value) ? null : "Enter an http:// or https:// address."),
|
||||
description:
|
||||
"API root of an OpenAI-compatible Whisper server (vLLM, speaches, LocalAI...), used when Whisper server is the transcription provider. On iOS a plain-http address must also be allowed by the app's App Transport Security exceptions.",
|
||||
});
|
||||
|
||||
export const whisperServerModelSetting = new ConfigSettingString({
|
||||
id: "whisper-server-model",
|
||||
label: "Whisper server model",
|
||||
storageKey: "voice.whisperServerModel",
|
||||
defaultValue: "",
|
||||
editorTitle: "Whisper model id (empty: server's first)",
|
||||
glassesEditTitle: "Edit Whisper model",
|
||||
formatValue: (value) => value || "(server default)",
|
||||
description: "Model id sent to the Whisper server. Leave empty to use the first model the server lists.",
|
||||
});
|
||||
|
||||
export const whisperServerLanguageSetting = new ConfigSettingString({
|
||||
id: "whisper-server-language",
|
||||
label: "Whisper language",
|
||||
storageKey: "voice.whisperServerLanguage",
|
||||
defaultValue: "",
|
||||
editorTitle: "Language code, e.g. en or sk (empty: auto)",
|
||||
glassesEditTitle: "Edit Whisper language",
|
||||
formatValue: (value) => value || "Auto-detect",
|
||||
validate: (value) => (!value.trim() || /^[a-z]{2,3}$/i.test(value.trim()) ? null : "Use a language code like en, sk or cs."),
|
||||
description:
|
||||
"Spoken language for the Whisper server. Leave empty to auto-detect; a wrong fixed language makes Whisper translate into it instead of transcribing.",
|
||||
});
|
||||
|
||||
export const whisperServerApiKeySetting = new ConfigSettingString({
|
||||
id: "whisper-server-api-key",
|
||||
label: "Whisper server key",
|
||||
storageKey: "voice.whisperServerApiKey",
|
||||
defaultValue: "",
|
||||
editorTitle: "Whisper server API key (optional)",
|
||||
glassesEditTitle: "Edit Whisper server key",
|
||||
formatValue: (value) => (value ? `${value.slice(0, 6)}...` : "(none)"),
|
||||
description: "Bearer token for the Whisper server, if it requires one.",
|
||||
});
|
||||
|
||||
export const anthropicApiKeySetting = new ConfigSettingString({
|
||||
id: "anthropic-api-key",
|
||||
label: "Anthropic key",
|
||||
@@ -901,6 +1101,7 @@ export const assistantModelSetting = new ConfigSettingEnum<AssistantModel>({
|
||||
if (provider === "anthropic") return anthropicApiKeySetting.get().trim().length === 0;
|
||||
if (provider === "openai") return openAiApiKeySetting.get().trim().length === 0;
|
||||
if (provider === "local") return !isLocalModelReady();
|
||||
if (provider === "hermes") return assistantHermesUrlSetting.get().trim().length === 0;
|
||||
return false;
|
||||
},
|
||||
description:
|
||||
@@ -1086,6 +1287,23 @@ export const nightscoutAlwaysShowInTopBarSetting = new ConfigSettingBoolean({
|
||||
defaultValue: false,
|
||||
description: "Keep the Nightscout glucose graph and warnings in the top bar even when all Nightscout windows are closed.",
|
||||
});
|
||||
export const nightscoutMissedBolusAlertsSetting = new ConfigSettingBoolean({
|
||||
id: "nightscout-missed-bolus-alerts",
|
||||
label: "Missed-bolus alerts",
|
||||
storageKey: "integrations.nightscout.missedBolusAlerts",
|
||||
defaultValue: false,
|
||||
description: "Show a notification on the glasses when glucose rises like an unannounced meal with no bolus or carbs entered. Experimental.",
|
||||
});
|
||||
export const nightscoutMissedBolusCooldownSetting = new ConfigSettingString({
|
||||
id: "nightscout-missed-bolus-cooldown-minutes",
|
||||
label: "Missed-bolus alert cooldown",
|
||||
storageKey: "integrations.nightscout.missedBolusCooldownMinutes",
|
||||
defaultValue: "120",
|
||||
editorTitle: "Missed-bolus alert cooldown (min)",
|
||||
normalize: normalizeNightscoutThreshold,
|
||||
formatValue: (value) => `${value} min`,
|
||||
description: "After a missed-bolus alert, wait at least this many minutes before showing another.",
|
||||
});
|
||||
|
||||
export function loadNightscoutThresholds(): NightscoutThresholds {
|
||||
return {
|
||||
@@ -1265,14 +1483,17 @@ function maskToken(token: string): string {
|
||||
|
||||
type SettingsMenuOptions<T> = {
|
||||
onChange?: (ctx: LayerContext, newValue: T, oldValue: T) => void
|
||||
/** Row label in place of the setting's own (for a setting shown in more than one menu). */
|
||||
label?: string
|
||||
}
|
||||
|
||||
export function enumSettingMenuItem<TValue extends string, TId extends string = string>(
|
||||
setting: ConfigSettingEnum<TValue, TId>,
|
||||
opts?: SettingsMenuOptions<TValue>
|
||||
): MenuItem {
|
||||
const label = opts?.label ?? setting.label;
|
||||
return {
|
||||
label: setting.label,
|
||||
label,
|
||||
description: setting.description,
|
||||
onSelect: (ctx) => {
|
||||
const current = setting.get();
|
||||
@@ -1296,10 +1517,10 @@ export function enumSettingMenuItem<TValue extends string, TId extends string =
|
||||
);
|
||||
},
|
||||
}));
|
||||
openModalMenu(ctx, setting.label, items, Math.max(0, setting.values.indexOf(current)));
|
||||
openModalMenu(ctx, label, items, Math.max(0, setting.values.indexOf(current)));
|
||||
},
|
||||
render: ({ image, x, y, width }) => {
|
||||
drawRightValueMenuItem(image, getDefaultSmallFont(), x, y, width, setting.label, setting.displayValue(setting.get()));
|
||||
drawRightValueMenuItem(image, getDefaultSmallFont(), x, y, width, label, setting.displayValue(setting.get()));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1308,15 +1529,16 @@ export function toggleSettingMenuItem<TId extends string = string>(
|
||||
setting: ConfigSettingBoolean<TId>,
|
||||
opts?: SettingsMenuOptions<boolean>
|
||||
): MenuItem {
|
||||
const label = opts?.label ?? setting.label;
|
||||
return {
|
||||
label: setting.label,
|
||||
label,
|
||||
description: setting.description,
|
||||
onSelect: (ctx) => {
|
||||
setting.set(!setting.get());
|
||||
opts?.onChange?.(ctx, setting.get(), !setting.get());
|
||||
},
|
||||
render: ({ image, x, y, width, selected }) => {
|
||||
drawToggleMenuItem(image, getDefaultSmallFont(), x, y, width, setting.label, setting.get(), selected);
|
||||
drawToggleMenuItem(image, getDefaultSmallFont(), x, y, width, label, setting.get(), selected);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
type AsrModelId,
|
||||
} from "../../native/asr-model";
|
||||
import { TextViewerLayer } from "../../apps/files/text-viewer";
|
||||
import { IOS_PRIVACY_NOTICE } from "../../analytics/privacy-disclosure";
|
||||
import type { LayerContext } from "../layers";
|
||||
import { drawRightValueMenuItem, openModalMenu, submenuItem, type MenuItem } from "../menu";
|
||||
import { shell } from "../shell/shell";
|
||||
@@ -35,6 +36,8 @@ import {
|
||||
uiDepthSetting,
|
||||
assistantAllowProactiveSetting,
|
||||
assistantBackendSetting,
|
||||
assistantHermesKeySetting,
|
||||
assistantHermesUrlSetting,
|
||||
assistantBridgeHostSetting,
|
||||
assistantBridgePortSetting,
|
||||
assistantBridgeTokenSetting,
|
||||
@@ -45,19 +48,26 @@ import {
|
||||
autoBrightnessMinSetting,
|
||||
autoBrightnessMaxSetting,
|
||||
autoBrightnessCurveSetting,
|
||||
dataCollectionSetting,
|
||||
glassesBatteryVisibilitySetting,
|
||||
phoneBatteryVisibilitySetting,
|
||||
ringBatteryVisibilitySetting,
|
||||
watchBatteryVisibilitySetting,
|
||||
displayModeSetting,
|
||||
displayLayoutSetting,
|
||||
elevenLabsApiKeySetting,
|
||||
mapboxApiKeySetting,
|
||||
mirrorTouchSetting,
|
||||
openAiApiKeySetting,
|
||||
previewColorSetting,
|
||||
previewScalingSetting,
|
||||
phoneRotationSetting,
|
||||
ringConnectionModeSetting,
|
||||
sonioxApiKeySetting,
|
||||
saveTranscribeAudioSetting,
|
||||
whisperServerApiKeySetting,
|
||||
whisperServerLanguageSetting,
|
||||
whisperServerModelSetting,
|
||||
whisperServerUrlSetting,
|
||||
screenFadeSetting,
|
||||
enumSettingMenuItem,
|
||||
firmwareDebugFlagsSetting,
|
||||
@@ -66,13 +76,14 @@ import {
|
||||
saveVoiceRecordingsSetting,
|
||||
showBleBandwidthSetting,
|
||||
suspendEvenHubWhenScreenOffSetting,
|
||||
temperatureUnitSetting,
|
||||
textSettingMenuItem,
|
||||
timeFormatSetting,
|
||||
toggleSettingMenuItem,
|
||||
useMicControlSetting,
|
||||
verticalPositionSetting,
|
||||
voiceProviderSetting,
|
||||
screenTimeoutSetting,
|
||||
wakeToLastAppSetting,
|
||||
wakeWordActionSetting,
|
||||
watchCanUnlockSetting,
|
||||
watchCrownClockwiseNextSetting,
|
||||
@@ -104,11 +115,10 @@ function settingsSections(): SettingsSection[] {
|
||||
},
|
||||
}),
|
||||
toggleSettingMenuItem(lockScreenEnabledSetting),
|
||||
// Where min-height windows (and the sidebar) sit vertically on the
|
||||
// screen; the dashboard controller repositions surfaces on change.
|
||||
enumSettingMenuItem(verticalPositionSetting),
|
||||
// Band / tall / full-panel; the dashboard controller reflows windows.
|
||||
enumSettingMenuItem(displayModeSetting),
|
||||
toggleSettingMenuItem(wakeToLastAppSetting),
|
||||
// A band (at one of five heights) / Tall / Full Screen; the
|
||||
// dashboard controller moves or reflows windows on change.
|
||||
enumSettingMenuItem(displayLayoutSetting),
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -124,6 +134,7 @@ function settingsSections(): SettingsSection[] {
|
||||
items: [
|
||||
enumSettingMenuItem(wakeWordActionSetting),
|
||||
enumSettingMenuItem(voiceProviderSetting),
|
||||
...whisperServerMenuItems(),
|
||||
asrModelMenuItem("moonshine"),
|
||||
asrModelMenuItem("whisper-base-en"),
|
||||
],
|
||||
@@ -134,6 +145,8 @@ function settingsSections(): SettingsSection[] {
|
||||
// iOS offers cloud APIs; Android also supports local models and the bridge.
|
||||
enumSettingMenuItem(assistantBackendSetting),
|
||||
enumSettingMenuItem(assistantModelSetting),
|
||||
textSettingMenuItem(assistantHermesUrlSetting),
|
||||
textSettingMenuItem(assistantHermesKeySetting),
|
||||
...(!global.isIOS ? [localModelMenuItem()] : []),
|
||||
toggleSettingMenuItem(assistantSkipConfirmationSetting),
|
||||
// iOS has no local LLM or agent bridge yet.
|
||||
@@ -163,6 +176,7 @@ function settingsSections(): SettingsSection[] {
|
||||
items: [
|
||||
enumSettingMenuItem(phoneRotationSetting),
|
||||
enumSettingMenuItem(previewColorSetting),
|
||||
enumSettingMenuItem(previewScalingSetting),
|
||||
toggleSettingMenuItem(mirrorTouchSetting),
|
||||
],
|
||||
},
|
||||
@@ -191,6 +205,19 @@ function settingsSections(): SettingsSection[] {
|
||||
toggleSettingMenuItem(showBleBandwidthSetting),
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Privacy",
|
||||
items: [
|
||||
// First chosen in the on-glasses onboarding (app/apps/onboarding/).
|
||||
enumSettingMenuItem(dataCollectionSetting),
|
||||
...(global.isIOS ? [{
|
||||
label: "iOS / TestFlight privacy",
|
||||
description: "Apple's beta reports are separate from Faceclaw statistics. Tap to read.",
|
||||
onSelect: (ctx: LayerContext) => ctx.stack.push(new TextViewerLayer(IOS_PRIVACY_NOTICE, "iOS / TestFlight privacy")),
|
||||
}] : []),
|
||||
bundledDocMenuItem("PRIVACY", "Privacy policy"),
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "About",
|
||||
// The version/license blurb (renderDetail) draws above the bundled
|
||||
@@ -220,11 +247,11 @@ function settingsSections(): SettingsSection[] {
|
||||
if (!global.isIOS) return sections;
|
||||
const deferred = new Set(["Watch"]);
|
||||
return sections.map(section => {
|
||||
if (section.label === "Developer") return { ...section, items: [toggleSettingMenuItem(showBleBandwidthSetting)] };
|
||||
if (section.label === "Voice") return { label: "Voice", items: [enumSettingMenuItem(wakeWordActionSetting), {
|
||||
label: "On-device dictation (Apple)", disabled: true, onSelect: () => {},
|
||||
description: "Uses the glasses microphone and your iPhone's speech language. No transcription API key needed. Say Hey Even for hands-free input, or open Voice from the menu and click when finished.",
|
||||
}] };
|
||||
if (section.label === "Developer") return { ...section, items: [enumSettingMenuItem(ringConnectionModeSetting),
|
||||
toggleSettingMenuItem(showBleBandwidthSetting)] };
|
||||
// No downloadable on-device models: iOS's on-device option is Apple's recognizer.
|
||||
if (section.label === "Voice") return { label: "Voice", items: [enumSettingMenuItem(wakeWordActionSetting),
|
||||
enumSettingMenuItem(voiceProviderSetting), toggleSettingMenuItem(saveTranscribeAudioSetting), ...whisperServerMenuItems()] };
|
||||
if (deferred.has(section.label)) return { label: section.label, items: [{
|
||||
label: "Not available on iOS yet", disabled: true, onSelect: () => {},
|
||||
description: `${section.label} integration has not been ported to iOS.`,
|
||||
@@ -263,6 +290,8 @@ function customizationRows(): () => MenuItem[] {
|
||||
animationsMenuItem(),
|
||||
// Controls the top-bar clock (24-hour vs 12-hour).
|
||||
enumSettingMenuItem(timeFormatSetting),
|
||||
// Fahrenheit or Celsius, wherever weather temperatures show.
|
||||
enumSettingMenuItem(temperatureUnitSetting),
|
||||
];
|
||||
const bottomRows = [font, position, depth, statusBar, ...rest];
|
||||
const popupRows = [font, position, depth, statusBar, statusBarVisibility, windowBorder, ...rest];
|
||||
@@ -438,6 +467,19 @@ function asrModelStatusText(id: AsrModelId): string {
|
||||
return "not downloaded";
|
||||
}
|
||||
|
||||
/**
|
||||
* The self-hosted Whisper server's settings. Always listed: the provider
|
||||
* option stays disabled until the URL is set.
|
||||
*/
|
||||
function whisperServerMenuItems(): MenuItem[] {
|
||||
return [
|
||||
textSettingMenuItem(whisperServerUrlSetting),
|
||||
textSettingMenuItem(whisperServerModelSetting),
|
||||
textSettingMenuItem(whisperServerLanguageSetting),
|
||||
textSettingMenuItem(whisperServerApiKeySetting),
|
||||
];
|
||||
}
|
||||
|
||||
/** Download/cancel/delete management for one on-device transcription model. */
|
||||
function asrModelMenuItem(id: AsrModelId): MenuItem {
|
||||
const def = ASR_MODELS[id];
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
import { GrayImage, type UiFont } from "../graphics/image";
|
||||
import { truncateText } from "../graphics/textwrap";
|
||||
import { getDefaultMediumFont, getDefaultSmallFont } from "../graphics/ui-fonts";
|
||||
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL, gestureHints, type InputEvent } from "./gestures";
|
||||
import type { Layer, LayerContext, PaintBelow } from "./layers";
|
||||
import { CONTEXT_MENU_DIM } from "./menu";
|
||||
import { centeredTextY } from "./metrics";
|
||||
|
||||
/** A calendar day with no time or zone attached; month is 0-11, as in Date. */
|
||||
export type CalendarDay = { year: number; month: number; day: number };
|
||||
|
||||
/** The picker's fields, in display and click order. */
|
||||
export const DATE_FIELDS = ["day", "month", "year"] as const;
|
||||
export type DateField = (typeof DATE_FIELDS)[number];
|
||||
|
||||
const MONTH_NAMES = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
||||
const WEEKDAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
|
||||
const WEEKDAY_HEADERS = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
|
||||
/** Year bounds: four digits, and clear of Date's 0-99 => 1900s mapping. */
|
||||
const MIN_YEAR = 1000;
|
||||
const MAX_YEAR = 9999;
|
||||
const DAY_MS = 86_400_000;
|
||||
|
||||
const PADDING = 12;
|
||||
const COLUMN_GAP = 24;
|
||||
const FIELD_GAP = 8;
|
||||
const FIELD_PAD_X = 6;
|
||||
/** Fill and outline of the active field and the selected day (the Timers pickers' field style). */
|
||||
const ACTIVE_FILL = 35;
|
||||
const ACTIVE_STROKE = 130;
|
||||
const TODAY_STROKE = 60;
|
||||
|
||||
export function calendarDayOf(date: Date): CalendarDay {
|
||||
return { year: date.getFullYear(), month: date.getMonth(), day: date.getDate() };
|
||||
}
|
||||
|
||||
/** Local midnight on the given day. */
|
||||
export function calendarDayToDate({ year, month, day }: CalendarDay): Date {
|
||||
return new Date(year, month, day);
|
||||
}
|
||||
|
||||
export function daysInMonth(year: number, month: number): number {
|
||||
return new Date(year, month + 1, 0).getDate();
|
||||
}
|
||||
|
||||
/** Whole days from `from` to `to` (negative when `to` is earlier). */
|
||||
export function daysBetween(from: CalendarDay, to: CalendarDay): number {
|
||||
return Math.round((Date.UTC(to.year, to.month, to.day) - Date.UTC(from.year, from.month, from.day)) / DAY_MS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Step a day by `delta` of a field's unit. Day steps are date arithmetic,
|
||||
* rolling into neighboring months and years. Month and year steps keep the
|
||||
* day of month, clamped to the target month's length; they aim for
|
||||
* `preferredDay` (the day last picked) so stepping from Jan 31 through
|
||||
* February lands on Mar 31 again. A step past the year bounds is refused.
|
||||
*/
|
||||
export function stepCalendarDay(date: CalendarDay, field: DateField, delta: number, preferredDay = date.day): CalendarDay {
|
||||
let next: CalendarDay;
|
||||
if (field === "day") {
|
||||
next = calendarDayOf(new Date(date.year, date.month, date.day + delta));
|
||||
} else {
|
||||
const months = date.year * 12 + date.month + (field === "month" ? delta : delta * 12);
|
||||
const year = Math.floor(months / 12);
|
||||
const month = months - year * 12;
|
||||
next = { year, month, day: Math.min(preferredDay, daysInMonth(year, month)) };
|
||||
}
|
||||
return next.year < MIN_YEAR || next.year > MAX_YEAR ? date : next;
|
||||
}
|
||||
|
||||
/** "today", "yesterday", "in 3 days"... for a day relative to today. */
|
||||
export function relativeDayLabel(date: CalendarDay, today: CalendarDay): string {
|
||||
const days = daysBetween(today, date);
|
||||
if (days === 0) return "today";
|
||||
if (days === -1) return "yesterday";
|
||||
if (days === 1) return "tomorrow";
|
||||
return days < 0 ? `${-days} days ago` : `in ${days} days`;
|
||||
}
|
||||
|
||||
export type DatePickerOptions = {
|
||||
title: string;
|
||||
/** The day to start on (its local calendar day). Default: today. */
|
||||
initial?: Date;
|
||||
/** Hint for the final click, e.g. "open". Default "done". */
|
||||
confirmLabel?: string;
|
||||
/** Called with the picked day, as local midnight, after the picker has closed. */
|
||||
onPick: (date: Date) => void;
|
||||
/** Called when the picker closes without a pick: cancelled, or cleared away by its host. */
|
||||
onCancel?: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* A modal date picker: day, month and year fields beside a month calendar,
|
||||
* in a dialog centered on its stack's base (an app window, or the shell
|
||||
* surface) with the content beneath dimmed like a context menu's. Pushed on
|
||||
* a LayerStack, it works in in-process apps and in worker apps alike (a
|
||||
* worker pushes it from a WindowMenu item, whose stack then hosts it).
|
||||
*
|
||||
* Input follows the Timers app's field pickers: scroll adjusts the active
|
||||
* field (up is later), click moves to the next field and on the last one
|
||||
* picks the date, double-click steps back a field and on the first one
|
||||
* cancels. A watch's swipes move between fields (left / right) and adjust
|
||||
* (up / down). Steps are date arithmetic rather than per-field wrapping (see
|
||||
* stepCalendarDay), so a nearby day needs only the day field.
|
||||
*/
|
||||
export class DatePickerLayer implements Layer {
|
||||
readonly acceptsDirectional = true;
|
||||
readonly dimUnderneath = CONTEXT_MENU_DIM;
|
||||
private date: CalendarDay;
|
||||
/** The day of month to aim for when month or year steps pass through shorter months. */
|
||||
private preferredDay: number;
|
||||
private field = 0;
|
||||
/** Picked or cancelled: onRemoved must not report a cancel. */
|
||||
private finished = false;
|
||||
|
||||
constructor(private readonly options: DatePickerOptions) {
|
||||
this.date = calendarDayOf(options.initial ?? new Date());
|
||||
this.preferredDay = this.date.day;
|
||||
}
|
||||
|
||||
/** The day currently shown. */
|
||||
get value(): CalendarDay {
|
||||
return { ...this.date };
|
||||
}
|
||||
|
||||
get activeField(): DateField {
|
||||
return DATE_FIELDS[this.field]!;
|
||||
}
|
||||
|
||||
onRemoved(): void {
|
||||
if (this.finished) return;
|
||||
this.finished = true;
|
||||
this.options.onCancel?.();
|
||||
}
|
||||
|
||||
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(DATE_FIELDS.length - 1, this.field + 1);
|
||||
return;
|
||||
case "swipe-left":
|
||||
this.field = Math.max(0, this.field - 1);
|
||||
return;
|
||||
case "click":
|
||||
if (this.field < DATE_FIELDS.length - 1) {
|
||||
this.field++;
|
||||
} else {
|
||||
this.finished = true;
|
||||
ctx.stack.pop();
|
||||
this.options.onPick(calendarDayToDate(this.date));
|
||||
}
|
||||
return;
|
||||
case "double-click":
|
||||
if (this.field > 0) this.field--;
|
||||
else ctx.stack.pop();
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private adjust(delta: number): void {
|
||||
const field = this.activeField;
|
||||
this.date = stepCalendarDay(this.date, field, delta, this.preferredDay);
|
||||
if (field === "day") this.preferredDay = this.date.day;
|
||||
}
|
||||
|
||||
private hints(field: number): string {
|
||||
return gestureHints([
|
||||
[GESTURE_SCROLL, "adjust"],
|
||||
[GESTURE_CLICK, field < DATE_FIELDS.length - 1 ? "next" : this.options.confirmLabel ?? "done"],
|
||||
[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();
|
||||
|
||||
// Sized for the widest value each field and line can show, so the dialog
|
||||
// holds still while the date changes.
|
||||
const fieldWidths = [
|
||||
medium.measureText("00"),
|
||||
Math.max(...MONTH_NAMES.map((name) => medium.measureText(name))),
|
||||
medium.measureText("0000"),
|
||||
].map((width, index) => Math.max(width, small.measureText(DATE_FIELDS[index]!)) + 2 * FIELD_PAD_X);
|
||||
const fieldsWidth = fieldWidths.reduce((sum, width) => sum + width, 0) + FIELD_GAP * (fieldWidths.length - 1);
|
||||
const boxHeight = medium.lineHeight + 6;
|
||||
const leftWidth = Math.max(fieldsWidth, small.measureText("Wednesday · 999 days ago"));
|
||||
const leftHeight = boxHeight + 2 + small.lineHeight + 12 + small.lineHeight;
|
||||
const cellWidth = Math.max(small.measureText("00"), ...WEEKDAY_HEADERS.map((name) => small.measureText(name))) + 8;
|
||||
const cellHeight = small.lineHeight + 4;
|
||||
const gridWidth = 7 * cellWidth;
|
||||
// A header row plus six weeks, the most a month spans.
|
||||
const gridHeight = 7 * cellHeight;
|
||||
const hintsWidth = Math.max(...DATE_FIELDS.map((_, index) => small.measureText(this.hints(index))));
|
||||
const chrome = (bodyWidth: number) => Math.max(bodyWidth, hintsWidth, small.measureText(this.options.title)) + 2 * PADDING;
|
||||
const titleHeight = small.lineHeight + 12;
|
||||
const footerHeight = 12 + small.lineHeight + 10;
|
||||
const chromeHeight = 8 + titleHeight + footerHeight;
|
||||
|
||||
// Drop the calendar when the dialog would not fit beside it.
|
||||
let width = chrome(leftWidth + COLUMN_GAP + gridWidth);
|
||||
let bodyHeight = Math.max(leftHeight, gridHeight);
|
||||
const showGrid = width <= base.width - 16 && chromeHeight + bodyHeight <= base.height - 8;
|
||||
if (!showGrid) {
|
||||
width = Math.min(chrome(leftWidth), base.width);
|
||||
bodyHeight = leftHeight;
|
||||
}
|
||||
const height = Math.min(chromeHeight + bodyHeight, base.height);
|
||||
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, truncateText(small, this.options.title, width - 2 * PADDING), 220);
|
||||
|
||||
const bodyTop = y + 8 + titleHeight;
|
||||
const leftX = x + PADDING;
|
||||
const leftTop = bodyTop + Math.floor((bodyHeight - leftHeight) / 2);
|
||||
this.paintFields(image, medium, small, leftX, leftTop, fieldWidths, boxHeight, focused);
|
||||
const today = calendarDayOf(new Date());
|
||||
const weekday = calendarDayToDate(this.date).getDay();
|
||||
const summary = `${WEEKDAY_NAMES[weekday]} · ${relativeDayLabel(this.date, today)}`;
|
||||
image.drawText(small, leftX, leftTop + leftHeight - small.lineHeight,
|
||||
truncateText(small, summary, showGrid ? leftWidth : width - 2 * PADDING), 190);
|
||||
if (showGrid) {
|
||||
this.paintMonth(image, small, x + width - PADDING - gridWidth, bodyTop, cellWidth, cellHeight, today, focused);
|
||||
}
|
||||
image.drawText(small, x + PADDING, y + height - 10 - small.lineHeight, this.hints(this.field), 110);
|
||||
return image;
|
||||
}
|
||||
|
||||
/** The three fields as boxes with captions beneath; the active one highlighted. */
|
||||
private paintFields(image: GrayImage, font: UiFont, captionFont: UiFont, x: number, y: number,
|
||||
widths: number[], boxHeight: number, focused: boolean): void {
|
||||
const values = [String(this.date.day), MONTH_NAMES[this.date.month]!, String(this.date.year)];
|
||||
for (let index = 0; index < DATE_FIELDS.length; index++) {
|
||||
const width = widths[index]!;
|
||||
const active = index === this.field;
|
||||
if (active) {
|
||||
if (focused) image.fillRoundedRect(x, y, width, boxHeight, ACTIVE_FILL, 6);
|
||||
image.drawRoundedRect(x, y, width, boxHeight, ACTIVE_STROKE, 6);
|
||||
}
|
||||
const value = values[index]!;
|
||||
image.drawText(font, x + Math.floor((width - font.measureText(value)) / 2), centeredTextY(font, y, boxHeight),
|
||||
value, active ? 250 : 170);
|
||||
const caption = DATE_FIELDS[index]!;
|
||||
image.drawText(captionFont, x + Math.floor((width - captionFont.measureText(caption)) / 2), y + boxHeight + 2,
|
||||
caption, 110);
|
||||
x += width + FIELD_GAP;
|
||||
}
|
||||
}
|
||||
|
||||
/** The shown month as a Sunday-first grid: the picked day highlighted, today outlined. */
|
||||
private paintMonth(image: GrayImage, font: UiFont, x: number, y: number, cellWidth: number, cellHeight: number,
|
||||
today: CalendarDay, focused: boolean): void {
|
||||
const { year, month, day: picked } = this.date;
|
||||
for (let column = 0; column < 7; column++) {
|
||||
const header = WEEKDAY_HEADERS[column]!;
|
||||
image.drawText(font, x + column * cellWidth + Math.floor((cellWidth - font.measureText(header)) / 2),
|
||||
centeredTextY(font, y, cellHeight), header, 110);
|
||||
}
|
||||
const firstWeekday = new Date(year, month, 1).getDay();
|
||||
const todayInMonth = today.year === year && today.month === month ? today.day : 0;
|
||||
for (let day = 1, count = daysInMonth(year, month); day <= count; day++) {
|
||||
const slot = firstWeekday + day - 1;
|
||||
const cellX = x + (slot % 7) * cellWidth;
|
||||
const cellY = y + (1 + Math.floor(slot / 7)) * cellHeight;
|
||||
const selected = day === picked;
|
||||
if (selected) {
|
||||
if (focused) image.fillRoundedRect(cellX + 1, cellY, cellWidth - 2, cellHeight, ACTIVE_FILL, 4);
|
||||
image.drawRoundedRect(cellX + 1, cellY, cellWidth - 2, cellHeight, ACTIVE_STROKE, 4);
|
||||
} else if (day === todayInMonth) {
|
||||
image.drawRoundedRect(cellX + 1, cellY, cellWidth - 2, cellHeight, TODAY_STROKE, 4);
|
||||
}
|
||||
const text = String(day);
|
||||
image.drawText(font, cellX + Math.floor((cellWidth - font.measureText(text)) / 2),
|
||||
centeredTextY(font, cellY, cellHeight), text, selected ? 255 : day === todayInMonth ? 220 : 170);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,10 +49,18 @@ export class DocumentView {
|
||||
private scrollLine = 0;
|
||||
|
||||
constructor(
|
||||
private readonly width: number,
|
||||
private readonly height: number,
|
||||
private width: number,
|
||||
private height: number,
|
||||
) {}
|
||||
|
||||
/** Re-wrap the document for a region of a new size, keeping the selection in view. */
|
||||
resize(width: number, height: number): void {
|
||||
if (width === this.width && height === this.height) return;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
if (this.root) this.setDocument(this.root);
|
||||
}
|
||||
|
||||
setDocument(root: DocumentRoot): void {
|
||||
const previousId = this.selectedNode()?.id;
|
||||
this.root = root;
|
||||
|
||||
@@ -31,7 +31,8 @@ import { Menu, type MenuDrawArgs } from "./menu-core";
|
||||
import { LIST_ROW_TEXT_INSET, listRowHeight } from "./metrics";
|
||||
import type { Layer, LayerContext } from "./layers";
|
||||
|
||||
const SIZE_CHOICES = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24, 26, 28] as const;
|
||||
/** Pixel sizes offered for TTF faces (also by the onboarding's text-size page). */
|
||||
export const FONT_SIZE_CHOICES = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24, 26, 28] as const;
|
||||
const DEFAULT_TTF_SIZE = 16;
|
||||
const PREVIEW_TEXT = "The quick brown fox jumps over 0123456789";
|
||||
const INHERIT_UI_FONT_LABEL = "Same as UI font";
|
||||
@@ -279,7 +280,7 @@ export class FontPickerLayer implements Layer {
|
||||
const allowed = this.options.sizeAllowed;
|
||||
if (!allowed || allowed(font.path, size)) return size;
|
||||
let best = -1;
|
||||
for (const candidate of SIZE_CHOICES) {
|
||||
for (const candidate of FONT_SIZE_CHOICES) {
|
||||
if (!allowed(font.path, candidate)) continue;
|
||||
if (best < 0 || Math.abs(candidate - size) < Math.abs(best - size)) best = candidate;
|
||||
}
|
||||
@@ -302,7 +303,7 @@ export class FontPickerLayer implements Layer {
|
||||
private openSizeMenu(ctx: LayerContext): void {
|
||||
if (this.draft.kind !== "ttf") return;
|
||||
const draft = this.draft;
|
||||
const sizes = SIZE_CHOICES.filter((size) =>
|
||||
const sizes = FONT_SIZE_CHOICES.filter((size) =>
|
||||
this.options.sizeAllowed === undefined || this.options.sizeAllowed(draft.font.path, size),
|
||||
);
|
||||
const items = sizes.map((size): MenuItem => ({
|
||||
@@ -312,7 +313,7 @@ export class FontPickerLayer implements Layer {
|
||||
innerCtx.stack.pop();
|
||||
},
|
||||
}));
|
||||
openModalMenu(ctx, "Size", items, Math.max(0, sizes.indexOf(draft.size as (typeof SIZE_CHOICES)[number])));
|
||||
openModalMenu(ctx, "Size", items, Math.max(0, sizes.indexOf(draft.size as (typeof FONT_SIZE_CHOICES)[number])));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+21
-4
@@ -1,7 +1,7 @@
|
||||
import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../graphics/image";
|
||||
import { dimPlanes, type Plane } from "../graphics/plane";
|
||||
import { spanCurrent } from "../native/frame-timings";
|
||||
import { type ConfigSettingBoolean, type ConfigSettingString } from "./dashboard-settings";
|
||||
import { type ConfigSettingBoolean, type ConfigSettingString, type VoiceProvider } from "./dashboard-settings";
|
||||
import { directionalFallback, isDirectionalInput, type InputEvent } from "./gestures";
|
||||
|
||||
export type TextSettingsEditToggle = {
|
||||
@@ -9,6 +9,19 @@ export type TextSettingsEditToggle = {
|
||||
label: string;
|
||||
};
|
||||
|
||||
/** A continuous-capture client's needs (see LayerActions.startContinuousVoiceCapture). */
|
||||
export type ContinuousCaptureOptions = {
|
||||
/** Names a WAV of the captured audio in Downloads (iOS, when Save Transcribe audio is on). */
|
||||
recordAs?: string;
|
||||
/**
|
||||
* Transcribe with this provider instead of the Transcription Provider
|
||||
* setting, letting it detect the spoken language (Translate). While any
|
||||
* client asks for one, every capture uses it, and a shared capture running
|
||||
* another provider restarts on it.
|
||||
*/
|
||||
multilingualProvider?: VoiceProvider;
|
||||
};
|
||||
|
||||
export type LayerActions = {
|
||||
/** Ask for a dashboard repaint+transmit, e.g. when async data arrives. */
|
||||
requestRender: () => void;
|
||||
@@ -31,9 +44,13 @@ export type LayerActions = {
|
||||
startVoiceCapture: (endpointing?: boolean) => Promise<void> | void;
|
||||
/** Stop push-to-talk; awaits native recognition, or commits a cloud provider for a final result. */
|
||||
stopVoiceCapture: () => Promise<void> | void;
|
||||
/** Start continuous capture (Transcribe); shares the mic with push-to-talk. */
|
||||
startContinuousVoiceCapture: () => Promise<void> | void;
|
||||
stopContinuousVoiceCapture: () => Promise<void> | void;
|
||||
/**
|
||||
* Start continuous capture on behalf of `client` (one id per window); shares
|
||||
* the mic with push-to-talk, and runs while any client wants it. Calling it
|
||||
* again for the same client replaces its options.
|
||||
*/
|
||||
startContinuousVoiceCapture: (client: string, options?: ContinuousCaptureOptions) => Promise<void> | void;
|
||||
stopContinuousVoiceCapture: (client: string) => Promise<void> | void;
|
||||
/** Play a CFW tone-sequencer payload (see sound-effects.ts). */
|
||||
playBuzzerSequence: (payload: Uint8Array) => Promise<void> | void;
|
||||
};
|
||||
|
||||
+12
-6
@@ -1,4 +1,4 @@
|
||||
import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage, type UiFont } from "../graphics/image";
|
||||
import { G2_LENS_HEIGHT, GrayImage, type UiFont } from "../graphics/image";
|
||||
import { wrapText } from "../graphics/textwrap";
|
||||
import { getDefaultSmallFont } from "../graphics/ui-fonts";
|
||||
import { getStringSetting } from "../native/settings-store";
|
||||
@@ -383,6 +383,8 @@ export function openModalMenu(
|
||||
width: menuWidth,
|
||||
minHeight: menuHeight,
|
||||
maxHeight: menuHeight,
|
||||
// Floats nearer than the content it opens over, like the window and system menus.
|
||||
depth: 4,
|
||||
};
|
||||
ctx.stack.push(new MenuLayer(title, items, layout).selectItem(initialSelectedIndex));
|
||||
}
|
||||
@@ -397,16 +399,20 @@ export class TextPageLayer implements Layer {
|
||||
private readonly body: string,
|
||||
) {}
|
||||
|
||||
paint(_ctx: LayerContext): GrayImage {
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
const font = getDefaultSmallFont();
|
||||
const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
|
||||
// Size to the stack, not the lens: in an app window the stack is the
|
||||
// window's viewport, and the compositor rejects a frame larger than its
|
||||
// surface (leaving the previous frame on screen).
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const image = new GrayImage(width, height, 0);
|
||||
image.drawText(font, 18, 14, this.title, 220);
|
||||
image.drawRect(12, 12, G2_LENS_WIDTH - 24, G2_LENS_HEIGHT - 24, 52);
|
||||
image.drawRect(12, 12, width - 24, height - 24, 52);
|
||||
|
||||
const wrapped = wrapText(font, this.body, G2_LENS_WIDTH - 60);
|
||||
const wrapped = wrapText(font, this.body, width - 60);
|
||||
const step = lineStep(font);
|
||||
const bodyTop = 28 + font.lineHeight;
|
||||
const footerY = G2_LENS_HEIGHT - 48;
|
||||
const footerY = height - 48;
|
||||
const maxBodyLines = Math.max(0, Math.floor((footerY - bodyTop - 8) / step));
|
||||
for (let index = 0; index < Math.min(wrapped.length, maxBodyLines); index++) {
|
||||
image.drawText(font, 24, bodyTop + index * step, wrapped[index]!, 190);
|
||||
|
||||
+111
-43
@@ -10,6 +10,7 @@ import {
|
||||
invokeNotificationAction,
|
||||
readActiveNotifications,
|
||||
readNotificationIconByKey,
|
||||
readNotificationPicture,
|
||||
type AndroidNotification,
|
||||
type AndroidNotificationAction,
|
||||
} from "../native/notification-icons";
|
||||
@@ -44,6 +45,13 @@ const DETAIL_TITLE_Y = 21;
|
||||
/** Gaps below the title's line box and below the icon/app-name header row. */
|
||||
const DETAIL_HEADER_GAP = 3;
|
||||
const DETAIL_BODY_GAP = 4;
|
||||
/** Text lines an attached picture leaves room for above it (when there are that many); it takes the rest. */
|
||||
const DETAIL_PICTURE_TEXT_LINES = 2;
|
||||
/** Gap between the text and an attached picture, and the space kept below the picture. */
|
||||
const DETAIL_PICTURE_GAP = 6;
|
||||
const DETAIL_PICTURE_BOTTOM_MARGIN = 12;
|
||||
/** An attached picture with less height than this to fit in (a large UI font) is left out. */
|
||||
const DETAIL_PICTURE_MIN_HEIGHT = 32;
|
||||
// Disable-source confirmation: actions on top, the explanation below them.
|
||||
const CONFIRM_X = 24;
|
||||
const CONFIRM_Y = 8;
|
||||
@@ -59,6 +67,16 @@ function iconForNotification(key: string): GrayImage | null {
|
||||
return icon;
|
||||
}
|
||||
|
||||
/** Attached picture for a paint pass, fitting maxWidth x maxHeight; allow-stale like iconForNotification. */
|
||||
function pictureForNotification(notification: AndroidNotification, maxWidth: number, maxHeight: number): GrayImage | null {
|
||||
if (!notification.hasPicture || maxHeight < DETAIL_PICTURE_MIN_HEIGHT) return null;
|
||||
const { picture, stale } = readNotificationPicture(notification, maxWidth, maxHeight, renderPassAllowsStaleData());
|
||||
if (stale) {
|
||||
noteStaleDataUsed();
|
||||
}
|
||||
return picture;
|
||||
}
|
||||
|
||||
type CardLayout = {
|
||||
notification: AndroidNotification;
|
||||
height: number;
|
||||
@@ -190,22 +208,7 @@ export class NotificationsListLayer implements Layer {
|
||||
*/
|
||||
export class SingleNotificationLayer implements Layer {
|
||||
/** The action column; its items are rebuilt from the live notification on every paint and input. */
|
||||
private readonly detailMenu = new Menu<DetailMenuItem>({
|
||||
wrap: false,
|
||||
rowGap: DETAIL_MENU_ROW_GAP,
|
||||
highlight: { radius: 6 },
|
||||
getHeight: (item, width) => {
|
||||
const font = getDefaultSmallFont();
|
||||
return detailMenuRowLines(font, item, width).length * lineStep(font) + 8;
|
||||
},
|
||||
draw: ({ image, item, x, y, width, selected }) => {
|
||||
const font = getDefaultSmallFont();
|
||||
const lines = detailMenuRowLines(font, item, width);
|
||||
for (let line = 0; line < lines.length; line++) {
|
||||
image.drawText(font, x + DETAIL_MENU_TEXT_X, y + DETAIL_MENU_TEXT_Y + line * lineStep(font), lines[line]!, selected ? 255 : 185);
|
||||
}
|
||||
},
|
||||
});
|
||||
private readonly detailMenu = createNotificationActionMenu<DetailMenuItem>((item) => item.kind === "disable-source");
|
||||
private confirmation: { source: AndroidNotification; menu: Menu<ConfirmationItem> } | null = null;
|
||||
// The last paint, which a tray-hosted layer repeats once its notification
|
||||
// is gone, until the tray swaps in a neighbour's (see closeUnavailableNotification).
|
||||
@@ -216,6 +219,11 @@ export class SingleNotificationLayer implements Layer {
|
||||
private readonly options: SingleNotificationLayerOptions,
|
||||
) {}
|
||||
|
||||
/** Whether the layer stays up once its notification is gone: the disable-source confirmation dismisses it first. */
|
||||
outlivesNotification(): boolean {
|
||||
return this.confirmation !== null;
|
||||
}
|
||||
|
||||
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
|
||||
if (this.confirmation) return this.paintConfirmation(ctx);
|
||||
const font = getDefaultSmallFont();
|
||||
@@ -229,7 +237,7 @@ export class SingleNotificationLayer implements Layer {
|
||||
|
||||
this.detailMenu.setItems(buildDetailMenu(notification, this.options.origin));
|
||||
drawDetailContent(image, font, notification, iconForNotification(notification.key), width, height);
|
||||
this.detailMenu.paint(image, detailMenuBox(width, height), ctx.stack.isFocused());
|
||||
this.detailMenu.paint(image, notificationActionMenuBox(width, height), ctx.stack.isFocused());
|
||||
this.lastImage = image;
|
||||
return image;
|
||||
}
|
||||
@@ -427,48 +435,114 @@ function drawDetailContent(
|
||||
width: number,
|
||||
height: number,
|
||||
): void {
|
||||
const contentX = DETAIL_CONTENT_X;
|
||||
const menuX = width - DETAIL_MENU_WIDTH - 24;
|
||||
const contentWidth = menuX - contentX - 20;
|
||||
image.drawText(font, contentX, DETAIL_TITLE_Y, "Notification", 220);
|
||||
// The header row (icon + app name) and the body stack below the title's
|
||||
// line box, so a large UI font pushes them down instead of overlapping.
|
||||
const headerTop = DETAIL_TITLE_Y + font.lineHeight + DETAIL_HEADER_GAP;
|
||||
const headerHeight = Math.max(ICON_SIZE, font.lineHeight);
|
||||
let appLineX = contentX;
|
||||
if (icon) {
|
||||
image.bitBlt(icon, contentX, headerTop + ((headerHeight - ICON_SIZE) >> 1), { transparentZero: true });
|
||||
appLineX = contentX + ICON_SIZE + ICON_TEXT_GAP;
|
||||
}
|
||||
image.drawText(font, appLineX, centeredTextY(font, headerTop, headerHeight), `${notification.appName || notification.packageName} ${formatRelativeTime(notification.postTime)}`, 150);
|
||||
const contentX = NOTIFICATION_CONTENT_X;
|
||||
const contentWidth = notificationContentWidth(width);
|
||||
const bodyTop = drawNotificationHeader(image, font, icon, `${notification.appName || notification.packageName} ${formatRelativeTime(notification.postTime)}`);
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push(...wrapText(font, notification.title || "(untitled)", contentWidth));
|
||||
// A picture can be the whole notification (Dexcom's has no text), so it
|
||||
// stands in for the "(untitled)" placeholder.
|
||||
const hasTitle = Boolean(notification.title) || !notification.hasPicture;
|
||||
if (hasTitle) {
|
||||
lines.push(...wrapText(font, notification.title || "(untitled)", contentWidth));
|
||||
}
|
||||
const body = detailNotificationBody(notification);
|
||||
if (body) {
|
||||
lines.push("");
|
||||
if (lines.length) lines.push("");
|
||||
lines.push(...wrapText(font, body, contentWidth));
|
||||
}
|
||||
const meta = [notification.subText, notification.infoText, notification.summaryText].filter(Boolean).join(" ");
|
||||
if (meta) {
|
||||
lines.push("");
|
||||
if (lines.length) lines.push("");
|
||||
lines.push(...wrapText(font, meta, contentWidth));
|
||||
}
|
||||
|
||||
const step = lineStep(font);
|
||||
const bodyTop = headerTop + headerHeight + DETAIL_BODY_GAP;
|
||||
const textValue = (index: number) => index === 0 && hasTitle ? 230 : 190;
|
||||
const reservedTextHeight = Math.min(lines.length, DETAIL_PICTURE_TEXT_LINES) * step;
|
||||
const picture = pictureForNotification(notification, contentWidth,
|
||||
height - DETAIL_PICTURE_BOTTOM_MARGIN - bodyTop - reservedTextHeight - (reservedTextHeight ? DETAIL_PICTURE_GAP : 0));
|
||||
if (picture) {
|
||||
// The text gets whatever the picture leaves, above it, with its last
|
||||
// shown line marked when some is cut off.
|
||||
const roomForText = height - DETAIL_PICTURE_BOTTOM_MARGIN - picture.height - DETAIL_PICTURE_GAP - bodyTop;
|
||||
const shownLines = Math.min(lines.length, Math.max(0, (roomForText / step) | 0));
|
||||
for (let index = 0; index < shownLines; index++) {
|
||||
const line = index === shownLines - 1 && lines.length > shownLines
|
||||
? truncateText(font, lines[index] + "...", contentWidth) : lines[index]!;
|
||||
image.drawText(font, contentX, bodyTop + index * step, line, textValue(index));
|
||||
}
|
||||
image.bitBlt(picture, contentX, bodyTop + shownLines * step + (shownLines ? DETAIL_PICTURE_GAP : 0));
|
||||
return;
|
||||
}
|
||||
|
||||
const maxLines = Math.max(1, ((height - bodyTop - step) / step) | 0);
|
||||
for (let index = 0; index < Math.min(lines.length, maxLines); index++) {
|
||||
const line = lines[index]!;
|
||||
image.drawText(font, contentX, bodyTop + index * step, line, index === 0 ? 230 : 190);
|
||||
image.drawText(font, contentX, bodyTop + index * step, line, textValue(index));
|
||||
}
|
||||
if (lines.length > maxLines) {
|
||||
image.drawText(font, contentX, height - 24, "...", 140);
|
||||
}
|
||||
}
|
||||
|
||||
/** Left edge of a notification detail view's content column. */
|
||||
export const NOTIFICATION_CONTENT_X = DETAIL_CONTENT_X;
|
||||
|
||||
/** Width of a notification detail view's content column, left of the action column. */
|
||||
export function notificationContentWidth(width: number): number {
|
||||
return width - DETAIL_MENU_WIDTH - 24 - NOTIFICATION_CONTENT_X - 20;
|
||||
}
|
||||
|
||||
/**
|
||||
* The top of a notification detail view: the "Notification" title, then the
|
||||
* source's icon and label. Returns the y where the body starts.
|
||||
*/
|
||||
export function drawNotificationHeader(image: GrayImage, font: UiFont, icon: GrayImage | null, sourceLabel: string): number {
|
||||
const contentX = NOTIFICATION_CONTENT_X;
|
||||
image.drawText(font, contentX, DETAIL_TITLE_Y, "Notification", 220);
|
||||
// The header row (icon + app name) and the body stack below the title's
|
||||
// line box, so a large UI font pushes them down instead of overlapping.
|
||||
const headerTop = DETAIL_TITLE_Y + font.lineHeight + DETAIL_HEADER_GAP;
|
||||
const headerHeight = Math.max(ICON_SIZE, font.lineHeight);
|
||||
let sourceX = contentX;
|
||||
if (icon) {
|
||||
image.bitBlt(icon, contentX, headerTop + ((headerHeight - ICON_SIZE) >> 1), { transparentZero: true });
|
||||
sourceX = contentX + ICON_SIZE + ICON_TEXT_GAP;
|
||||
}
|
||||
image.drawText(font, sourceX, centeredTextY(font, headerTop, headerHeight), sourceLabel, 150);
|
||||
return headerTop + headerHeight + DETAIL_BODY_GAP;
|
||||
}
|
||||
|
||||
/**
|
||||
* A notification detail view's right-hand action column. Rows truncate their
|
||||
* label to one line, except those `wraps` picks, which wrap it.
|
||||
*/
|
||||
export function createNotificationActionMenu<T extends { label: string }>(wraps: (item: T) => boolean = () => false): Menu<T> {
|
||||
const rowLines = (font: UiFont, item: T, rowWidth: number): string[] => {
|
||||
const textWidth = rowWidth - 2 * DETAIL_MENU_TEXT_X;
|
||||
return wraps(item) ? wrapText(font, item.label, textWidth) : [truncateText(font, item.label, textWidth)];
|
||||
};
|
||||
return new Menu<T>({
|
||||
wrap: false,
|
||||
rowGap: DETAIL_MENU_ROW_GAP,
|
||||
highlight: { radius: 6 },
|
||||
getHeight: (item, width) => {
|
||||
const font = getDefaultSmallFont();
|
||||
return rowLines(font, item, width).length * lineStep(font) + 8;
|
||||
},
|
||||
draw: ({ image, item, x, y, width, selected }) => {
|
||||
const font = getDefaultSmallFont();
|
||||
const lines = rowLines(font, item, width);
|
||||
for (let line = 0; line < lines.length; line++) {
|
||||
image.drawText(font, x + DETAIL_MENU_TEXT_X, y + DETAIL_MENU_TEXT_Y + line * lineStep(font), lines[line]!, selected ? 255 : 185);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** The action column's row boxes: right of the content, from DETAIL_MENU_TOP to the bottom margin. */
|
||||
function detailMenuBox(width: number, height: number): MenuBox {
|
||||
export function notificationActionMenuBox(width: number, height: number): MenuBox {
|
||||
return {
|
||||
x: width - DETAIL_MENU_WIDTH - 32,
|
||||
y: DETAIL_MENU_TOP,
|
||||
@@ -477,12 +551,6 @@ function detailMenuBox(width: number, height: number): MenuBox {
|
||||
};
|
||||
}
|
||||
|
||||
/** An action row's text lines: the disable-source row wraps, the rest truncate to one line. */
|
||||
function detailMenuRowLines(font: UiFont, item: DetailMenuItem, rowWidth: number): string[] {
|
||||
const textWidth = rowWidth - 2 * DETAIL_MENU_TEXT_X;
|
||||
return item.kind === "disable-source" ? wrapText(font, item.label, textWidth) : [truncateText(font, item.label, textWidth)];
|
||||
}
|
||||
|
||||
function buildDetailMenu(notification: AndroidNotification, origin: SingleNotificationLayerOrigin): DetailMenuItem[] {
|
||||
return [
|
||||
{ kind: "back", label: "Back" },
|
||||
|
||||
+473
-213
@@ -6,7 +6,7 @@ import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/ui-fon
|
||||
import { truncateText } from "../../graphics/textwrap";
|
||||
import { activeAmbientCards } from "./ambient-cards";
|
||||
import { BATTERY_ICON_WIDTH, DENSE_BATTERY_BLOCK_HEIGHT, drawBattery, drawDenseBatteries, type BatteryDevice } from "../../graphics/battery";
|
||||
import { readActiveNotificationIcons } from "../../native/notification-icons";
|
||||
import { ALL_NOTIFICATIONS, readActiveNotificationIcons } from "../../native/notification-icons";
|
||||
import { readPhoneBatteryState } from "../../native/phone-battery";
|
||||
import { noteStaleDataUsed, renderPassAllowsStaleData } from "../../util/render-freshness";
|
||||
import { renderIcon, renderIconWithGlyph, type IconActivity, type IconName } from "../../graphics/icons";
|
||||
@@ -27,8 +27,10 @@ import { scrollToKeepSelectionVisible } from "../menu";
|
||||
import { lineStep } from "../metrics";
|
||||
import {
|
||||
appViewportRect,
|
||||
isImmersive,
|
||||
MIN_WINDOW_HEIGHT,
|
||||
minWindowTop,
|
||||
setSwitcherBarHeight,
|
||||
SHELL_OPAQUE_BLACK,
|
||||
SIDEBAR_WIDTH,
|
||||
sidebarStripVisible,
|
||||
@@ -55,7 +57,8 @@ import {
|
||||
* sidebar. In the two-column variant the column against the app area fills
|
||||
* first and windows past that overflow into the outer column, so the common
|
||||
* case keeps every icon next to the content it belongs to. A bottom row
|
||||
* always uses the roomy slots, laid out left to right.
|
||||
* always uses the roomy slots, laid out left to right, and when they don't
|
||||
* fit beside the status bar, in a second row (see planBottomBar).
|
||||
*/
|
||||
type SidebarVariant = { columns: number; columnWidth: number; iconSize: number };
|
||||
const ONE_COLUMN: SidebarVariant = { columns: 1, columnWidth: 36, iconSize: 32 };
|
||||
@@ -73,16 +76,25 @@ const ROW_STEP = ROW_ICON_SIZE + ICON_SPACING;
|
||||
// The status bar in the switcher row (geometry.ts statusInSwitcherRow) keeps
|
||||
// the top bar's layout, so every element sits as it does there: its 28 rows
|
||||
// (whose last is the divider, which the row has no use for) centred in the
|
||||
// row below its separator line.
|
||||
// row below its separator line. A second row of status items sits a top
|
||||
// bar's height under the first, or, beside two rows of windows, a row's
|
||||
// height under it, level with the second row of windows.
|
||||
const ROW_STATUS_TOP = 1 + ((SWITCHER_ROW_HEIGHT - TOP_BAR_HEIGHT) >> 1);
|
||||
// Its clock ends flush with the row's right end, which is the window's
|
||||
// right edge; batteries keep the top bar's clock-to-icons gap from it.
|
||||
// right edge; batteries keep the top bar's clock-to-icons gap from it, as
|
||||
// does whatever else comes right before the clock.
|
||||
const ROW_CLOCK_GAP = 16;
|
||||
// Between the windows' end of the row (its scroll chevron) and the status.
|
||||
const ROW_STATUS_GAP = 8;
|
||||
// Notification icons stop short of room for this many windows' slots (or
|
||||
// all of them, when there are fewer); the windows take whatever is left.
|
||||
// When the windows have to scroll anyway (planBottomBar's last layout),
|
||||
// notification icons stop short of room for this many windows' slots in a
|
||||
// row (or all of them, when there are fewer); the windows take whatever is
|
||||
// left.
|
||||
const ROW_MIN_WINDOW_SLOTS = 3;
|
||||
// After an app widget (tray icon), and between the last notification icon
|
||||
// and what follows it, as in the top bar.
|
||||
const TRAY_ICON_GAP = 10;
|
||||
const NOTIFICATIONS_GAP = 8;
|
||||
|
||||
// The popup switcher (geometry.ts "popup"): a box centred over the
|
||||
// foreground window's content, holding a row of window icons above the
|
||||
@@ -154,29 +166,34 @@ type SwitcherLayout = {
|
||||
|
||||
/**
|
||||
* Switcher geometry for the foreground window (a bottom row sits under it).
|
||||
* `windowsRight` is where a bottom row's window icons must end: short of
|
||||
* the status bar when it shares the row. `scrollRow` is the first visible
|
||||
* window's index.
|
||||
* A bottom switcher's window icons take `bar`'s slots (planBottomBar), the
|
||||
* row against the window first, then the one under it. `scrollRow` is the
|
||||
* first visible window's index.
|
||||
*/
|
||||
function switcherLayout(windowCount: number, heightMode: WindowHeightMode, appId?: string, windowsRight?: number, scrollRow = 0): SwitcherLayout {
|
||||
function switcherLayout(windowCount: number, heightMode: WindowHeightMode, appId: string | undefined, bar: BottomBarPlan | null, scrollRow = 0): SwitcherLayout {
|
||||
const position = switcherPosition();
|
||||
if (position === "bottom") {
|
||||
const row = switcherRect(heightMode, appId);
|
||||
const width = (windowsRight ?? row.x + row.width) - row.x;
|
||||
const { windowColumns, windowRows } = bar ?? planBottomBar(row.width, windowCount, []);
|
||||
const columns = Math.max(1, windowColumns);
|
||||
// Under a framed window the first window's cell (the launcher's) starts
|
||||
// at the frame's left side, one pixel outside the window, so a selection
|
||||
// tab there carries the side straight down (drawWindowFrame squares that
|
||||
// corner for it). Scrolled past it, the cells keep the margin the left
|
||||
// chevron needs. The count of slots stays the same either way.
|
||||
// chevron needs. The count of slots stays the same either way. Only the
|
||||
// first row's cells touch the separator; a second row's lines up under it.
|
||||
const first = windowFramed(appId) && scrollRow === 0 ? row.x - 1 : row.x + LIST_MARGIN - 2;
|
||||
return {
|
||||
position,
|
||||
iconSize: ROW_ICON_SIZE,
|
||||
visibleCount: Math.max(1, ((width - 2 * LIST_MARGIN + ICON_SPACING) / ROW_STEP) | 0),
|
||||
cell: (slot) => ({
|
||||
x: first + slot * ROW_STEP, y: row.y, width: ROW_ICON_SIZE + 4, height: SWITCHER_ROW_HEIGHT,
|
||||
atSeparator: true,
|
||||
}),
|
||||
visibleCount: columns * windowRows,
|
||||
cell: (slot) => {
|
||||
const line = (slot / columns) | 0;
|
||||
return {
|
||||
x: first + (slot % columns) * ROW_STEP, y: row.y + line * SWITCHER_ROW_HEIGHT,
|
||||
width: ROW_ICON_SIZE + 4, height: SWITCHER_ROW_HEIGHT, atSeparator: line === 0,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
// Slots fill the column against the separator top to bottom, then
|
||||
@@ -201,6 +218,126 @@ function switcherLayout(windowCount: number, heightMode: WindowHeightMode, appId
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* One of the status bar's items as the bottom switcher lays it out (see
|
||||
* planBottomBar): left to right, the notification icons, app widgets (tray
|
||||
* icons), the battery block and the clock.
|
||||
*/
|
||||
type RowStatusSize = { kind: "notification" | "tray" | "batteries" | "clock"; width: number };
|
||||
|
||||
/** A status item ready to draw with its left edge at x, in the top bar's layout from `top`. */
|
||||
type RowStatusItem = RowStatusSize & { draw: (image: GrayImage, x: number, top: number) => void };
|
||||
|
||||
/**
|
||||
* A layout of the bottom switcher (planBottomBar): its window icons in
|
||||
* `windowRows` rows of `windowColumns` slots, scrolling when there are more
|
||||
* windows than that; the status bar's items in `statusRows` (top first),
|
||||
* each right-aligned against the switcher's end, `statusPitch` apart; and
|
||||
* the height it all takes.
|
||||
*/
|
||||
export type BottomBarPlan<T extends RowStatusSize = RowStatusSize> = {
|
||||
/** Which of planBottomBar's layouts this is, 1 (the roomiest) to 4. */
|
||||
level: number;
|
||||
height: number;
|
||||
windowRows: number;
|
||||
windowColumns: number;
|
||||
statusRows: T[][];
|
||||
/** Width of the widest status row; the windows take what it leaves. */
|
||||
statusWidth: number;
|
||||
statusPitch: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Lay out the bottom switcher, `width` wide, for `windowCount` windows and
|
||||
* the status bar's items (none unless it shares the switcher; notification
|
||||
* icons first), trying denser layouts in turn until one fits:
|
||||
*
|
||||
* 1. One row: the windows, then the status bar's items.
|
||||
* 2. The status bar's items in two rows, broken where the two come nearest
|
||||
* the same width, beside the one row of windows. The extra height comes
|
||||
* out of the slack under a window band, or a full-height window's height
|
||||
* (geometry.ts windowTop).
|
||||
* 3. The windows in two rows too.
|
||||
* 4. As 3, but with only as many windows showing as fit, scrolling to the
|
||||
* rest, and notification icons dropped from the end as need be to leave
|
||||
* the windows room for a few slots a row.
|
||||
*
|
||||
* A layout fails when its windows don't all fit beside its status rows; the
|
||||
* last can't fail.
|
||||
*/
|
||||
export function planBottomBar<T extends RowStatusSize>(width: number, windowCount: number, status: T[]): BottomBarPlan<T> {
|
||||
const plan = (level: number, windowRows: number, statusRows: T[][]): BottomBarPlan<T> => {
|
||||
const statusWidth = Math.max(0, ...statusRows.map(statusRowWidth));
|
||||
return {
|
||||
level,
|
||||
height: windowRows > 1 ? windowRows * SWITCHER_ROW_HEIGHT
|
||||
: SWITCHER_ROW_HEIGHT + Math.max(0, statusRows.length - 1) * TOP_BAR_HEIGHT,
|
||||
windowRows,
|
||||
windowColumns: rowWindowColumns(width - (statusWidth > 0 ? statusWidth + ROW_STATUS_GAP : 0)),
|
||||
statusRows,
|
||||
statusWidth,
|
||||
statusPitch: windowRows > 1 ? SWITCHER_ROW_HEIGHT : TOP_BAR_HEIGHT,
|
||||
};
|
||||
};
|
||||
const twoRows = splitStatusRows(status);
|
||||
for (const candidate of [plan(1, 1, status.length ? [status] : []), plan(2, 1, twoRows), plan(3, 2, twoRows)]) {
|
||||
if (candidate.windowColumns * candidate.windowRows >= windowCount && candidate.statusWidth <= width) return candidate;
|
||||
}
|
||||
const notifications = status.filter((item) => item.kind === "notification").length;
|
||||
const room = width - ROW_STATUS_GAP - rowWindowsWidth(Math.min(Math.ceil(windowCount / 2), ROW_MIN_WINDOW_SLOTS));
|
||||
let last = plan(4, 2, twoRows);
|
||||
for (let kept = notifications - 1; kept >= 0 && last.statusWidth > room; kept--) {
|
||||
last = plan(4, 2, splitStatusRows([...status.slice(0, kept), ...status.slice(notifications)]));
|
||||
}
|
||||
return { ...last, windowColumns: Math.max(1, last.windowColumns) };
|
||||
}
|
||||
|
||||
/** Width `columns` window slots take in the bottom switcher, with its end margins. */
|
||||
function rowWindowsWidth(columns: number): number {
|
||||
return columns > 0 ? 2 * LIST_MARGIN + columns * ROW_STEP - ICON_SPACING : 0;
|
||||
}
|
||||
|
||||
/** How many window slots fit across `width` of the bottom switcher. */
|
||||
function rowWindowColumns(width: number): number {
|
||||
return Math.max(0, ((width - 2 * LIST_MARGIN + ICON_SPACING) / ROW_STEP) | 0);
|
||||
}
|
||||
|
||||
/** Space between two neighbouring status items, as the top bar spaces them. */
|
||||
function statusGap(left: RowStatusSize, right: RowStatusSize): number {
|
||||
if (right.kind === "clock" || left.kind === "batteries") return ROW_CLOCK_GAP;
|
||||
if (left.kind === "tray") return TRAY_ICON_GAP;
|
||||
return right.kind === "notification" ? NOTIFICATION_ICON_STEP - NOTIFICATION_ICON_SIZE : NOTIFICATIONS_GAP;
|
||||
}
|
||||
|
||||
/** Width of a row of status items, from the first's left edge to the last's right. */
|
||||
function statusRowWidth(items: readonly RowStatusSize[]): number {
|
||||
let width = 0;
|
||||
for (let index = 0; index < items.length; index++) {
|
||||
width += items[index]!.width + (index > 0 ? statusGap(items[index - 1]!, items[index]!) : 0);
|
||||
}
|
||||
return width;
|
||||
}
|
||||
|
||||
/**
|
||||
* Status items in two rows (one when there are fewer than two), broken
|
||||
* where the wider row is narrowest, so the two come out about as wide.
|
||||
*/
|
||||
function splitStatusRows<T extends RowStatusSize>(items: T[]): T[][] {
|
||||
if (items.length < 2) return items.length ? [items] : [];
|
||||
const total = statusRowWidth(items);
|
||||
let best = 1, bestWidth = Infinity, before = 0;
|
||||
for (let index = 1; index < items.length; index++) {
|
||||
// Items before `index` take the first row; the gap at the break goes.
|
||||
before += items[index - 1]!.width + (index > 1 ? statusGap(items[index - 2]!, items[index - 1]!) : 0);
|
||||
const widest = Math.max(before, total - before - statusGap(items[index - 1]!, items[index]!));
|
||||
if (widest < bestWidth) {
|
||||
best = index;
|
||||
bestWidth = widest;
|
||||
}
|
||||
}
|
||||
return [items.slice(0, best), items.slice(best)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Popup switcher geometry for the foreground window: its box, centred over
|
||||
* the window's content (geometry.ts switcherRect), as wide as the icons
|
||||
@@ -250,7 +387,7 @@ export function sidebarContentSpan(windowCount: number): { left: number; right:
|
||||
|
||||
/**
|
||||
* Horizontal extent of the top bar: the foreground window's, short of a side
|
||||
* strip overlaid on it (full-panel mode, sidebar focused).
|
||||
* strip overlaid on it (an immersive window, sidebar focused).
|
||||
*/
|
||||
function topBarSpan(state: ShellChromeState): { left: number; right: number } {
|
||||
const viewport = appViewportRect(state.foregroundHeightMode, state.foregroundAppId);
|
||||
@@ -275,14 +412,15 @@ type StatusBarPlacement = { left: number; right: number; top: number; contentTop
|
||||
|
||||
/**
|
||||
* The status bar's placement for the foreground window, or null when it
|
||||
* isn't drawn as a bar: when it shares a bottom switcher row, or when it
|
||||
* overlays the window (geometry.ts statusBarOverlays) and the popup
|
||||
* switcher isn't up. An overlaying bar sits inside a window frame, whose
|
||||
* side runs along its outer row, so it keeps its divider.
|
||||
* isn't drawn as a bar: when the window is immersive, when it shares a
|
||||
* bottom switcher row, or when it overlays the window (geometry.ts
|
||||
* statusBarOverlays) and the popup switcher isn't up. An overlaying bar
|
||||
* sits inside a window frame, whose side runs along its outer row, so it
|
||||
* keeps its divider.
|
||||
*/
|
||||
function statusBarPlacement(state: ShellChromeState): StatusBarPlacement | null {
|
||||
const appId = state.foregroundAppId;
|
||||
if (statusInSwitcherRow(appId)) return null;
|
||||
if (isImmersive(appId) || statusInSwitcherRow(appId)) return null;
|
||||
const overlays = statusBarOverlays();
|
||||
if (overlays && !sidebarStripVisible(state.focus, appId)) return null;
|
||||
const { left, right } = topBarSpan(state);
|
||||
@@ -294,6 +432,9 @@ function statusBarPlacement(state: ShellChromeState): StatusBarPlacement | null
|
||||
|
||||
const NOTIFICATION_ICON_SIZE = 24;
|
||||
const NOTIFICATION_ICON_STEP = NOTIFICATION_ICON_SIZE + 4;
|
||||
// Notification icons' top, in the top bar's layout (where any status icon's
|
||||
// selection box starts, a row above).
|
||||
const NOTIFICATION_ICON_TOP = ((TOP_BAR_HEIGHT - NOTIFICATION_ICON_SIZE) / 2) | 0;
|
||||
// The box round a selected notification icon: clear of it by 2px either
|
||||
// side, and by 1px above and below, all a top bar leaves above its divider.
|
||||
const NOTIFICATION_BOX_MARGIN_X = 2;
|
||||
@@ -308,15 +449,31 @@ export type ShellChromeWindow = {
|
||||
drawIcon: (image: GrayImage, x: number, y: number, size: number, inverted?: boolean) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* A status bar item the app switcher's selection can move onto (see
|
||||
* Shell.moveSelection): a notification's icon, by notification key, or an
|
||||
* app widget (a tray icon), by its owner's id.
|
||||
*/
|
||||
export type StatusItem = { kind: "notification" | "widget"; key: string };
|
||||
|
||||
/** Whether two status bar items are the same one. */
|
||||
export function sameStatusItem(a: StatusItem | null | undefined, b: StatusItem | null | undefined): boolean {
|
||||
return !!a && !!b && a.kind === b.kind && a.key === b.key;
|
||||
}
|
||||
|
||||
/** An app's tray icon, by its owner's id (see Shell.setTrayIcon). */
|
||||
export type ShellChromeTrayIcon = { ownerId: string; icon: GrayImage };
|
||||
|
||||
export type ShellChromeState = {
|
||||
windows: ShellChromeWindow[];
|
||||
/** The selected window's index, or -1 while the selection is on a notification. */
|
||||
/** The selected window's index, or -1 while the selection is on a status bar item. */
|
||||
selectedIndex: number;
|
||||
/**
|
||||
* The notification (by key) whose icon the switcher's selection is on
|
||||
* instead of a window, if any (see Shell.moveSelection).
|
||||
* The status bar item (a notification's icon or an app widget) the
|
||||
* switcher's selection is on instead of a window, if any (see
|
||||
* Shell.moveSelection).
|
||||
*/
|
||||
selectedNotificationKey?: string | null;
|
||||
selectedStatusItem?: StatusItem | null;
|
||||
focus: "sidebar" | "window";
|
||||
/** Height mode of the foreground window; decides where its top bar sits. */
|
||||
foregroundHeightMode: WindowHeightMode;
|
||||
@@ -331,7 +488,7 @@ export type ShellChromeState = {
|
||||
watchCharging: boolean | null;
|
||||
};
|
||||
/** App-provided tray images, drawn between notification icons and batteries. */
|
||||
trayIcons: GrayImage[];
|
||||
trayIcons: ShellChromeTrayIcon[];
|
||||
};
|
||||
|
||||
/** Placeholder window icon: rounded outline with a single letter. */
|
||||
@@ -347,23 +504,56 @@ export function makeLetterWindowIcon(letter: string): ShellChromeWindow["drawIco
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Perceptual gamma for inverting icon shades. The G2's levels are roughly
|
||||
* linear in brightness while lightness is perceived roughly as brightness's
|
||||
* 1/2.2 power, so flipping the levels themselves (15 - n) turns a dim stroke
|
||||
* into one barely darker than the white box: level 1 would invert to 14.
|
||||
*/
|
||||
const ICON_INVERSION_GAMMA = 2.2;
|
||||
|
||||
let invertedShadeLut: Uint8Array | null = null;
|
||||
|
||||
/**
|
||||
* Gray8 value → its perceptual negative, by the display level it packs to
|
||||
* (so faint fringe values that show as black stay invisible on the white
|
||||
* box): level 1 inverts to 7, and level 6 and up to 1 or 0. Written back as
|
||||
* n*16, which packs to n, except that white is 255 (the box's fill) and
|
||||
* black is SHELL_OPAQUE_BLACK (1) rather than 0, the surface's transparent
|
||||
* color key.
|
||||
*/
|
||||
function invertedShades(): Uint8Array {
|
||||
if (!invertedShadeLut) {
|
||||
invertedShadeLut = new Uint8Array(256);
|
||||
for (let value = 1; value < 256; value++) {
|
||||
const lightness = Math.pow(grayToNibble(value) / 15, 1 / ICON_INVERSION_GAMMA);
|
||||
const level = Math.round(15 * Math.pow(1 - lightness, ICON_INVERSION_GAMMA));
|
||||
invertedShadeLut[value] = level === 0 ? SHELL_OPAQUE_BLACK : level === 15 ? 255 : level * 16;
|
||||
}
|
||||
}
|
||||
return invertedShadeLut;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inverted (black-on-white) variant of an icon raster, for the focused tab:
|
||||
* coverage becomes darkness, with full coverage mapping to SHELL_OPAQUE_BLACK
|
||||
* (1) rather than 0, since 0 is the surface's transparent color key. Memoized
|
||||
* per source object so the variant is a stable image the texture cache can
|
||||
* key on (mode-13's inverse LUT can't reproduce this mapping exactly, so it
|
||||
* is simply a separate cached image).
|
||||
* each shade becomes its perceptual negative (invertedShades), so full
|
||||
* coverage is SHELL_OPAQUE_BLACK. Memoized per source object so the variant
|
||||
* is a stable image the texture cache can key on (mode-13's inverse LUT can't
|
||||
* reproduce this mapping, so it is simply a separate cached image). Deferred
|
||||
* draws (an app widget's text) are baked in first, to be inverted with the
|
||||
* rest.
|
||||
*/
|
||||
const invertedIconCache = new WeakMap<GrayImage, GrayImage>();
|
||||
function invertedIcon(icon: GrayImage): GrayImage {
|
||||
let inverted = invertedIconCache.get(icon);
|
||||
if (!inverted) {
|
||||
const flat = icon.withDrawsBaked();
|
||||
const shades = invertedShades();
|
||||
inverted = new GrayImage(icon.width, icon.height, 0);
|
||||
for (let i = 0; i < icon.pixels.length; i++) {
|
||||
const coverage = icon.pixels[i]!;
|
||||
for (let i = 0; i < flat.pixels.length; i++) {
|
||||
const coverage = flat.pixels[i]!;
|
||||
if (coverage > 0) {
|
||||
inverted.pixels[i] = Math.max(SHELL_OPAQUE_BLACK, 255 - coverage);
|
||||
inverted.pixels[i] = shades[coverage]!;
|
||||
}
|
||||
}
|
||||
invertedIconCache.set(icon, inverted);
|
||||
@@ -414,26 +604,35 @@ export class ShellChromeLayer implements Layer {
|
||||
private scrollRow = 0;
|
||||
// The popup switcher's shell surface.
|
||||
private popupKey: number | undefined;
|
||||
// Where the last paint ended a bottom row's window icons, for hit testing.
|
||||
private rowWindowsRight: number | undefined;
|
||||
// The bottom switcher's layout as the last paint planned it, for hit testing.
|
||||
private bottomBar: BottomBarPlan<RowStatusItem> | null = null;
|
||||
// Whether the last paint's selection tab carries the window frame's left
|
||||
// side down, so the frame's bottom-left corner is square.
|
||||
private frameCornerSquare = false;
|
||||
// The notification icons the last paint drew, left to right: what the
|
||||
// switcher's selection can move onto, and mirror touches hit.
|
||||
private notificationEntries: NotificationEntry[] = [];
|
||||
// The status bar icons (notifications' and app widgets') the last paint
|
||||
// drew: what the switcher's selection can move onto, and mirror touches hit.
|
||||
private statusEntries: StatusEntry[] = [];
|
||||
|
||||
constructor(private readonly getState: () => ShellChromeState) {}
|
||||
/**
|
||||
* `onBottomBarHeightChanged` is called, during a paint, when the bottom
|
||||
* switcher's layout changes its height so that windows have to move or
|
||||
* resize (see layoutBottomBar).
|
||||
*/
|
||||
constructor(
|
||||
private readonly getState: () => ShellChromeState,
|
||||
private readonly onBottomBarHeightChanged: () => void = () => {},
|
||||
) {}
|
||||
|
||||
paint(): GrayImage {
|
||||
const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
|
||||
const state = this.getState();
|
||||
this.notificationEntries = [];
|
||||
this.statusEntries = [];
|
||||
this.bottomBar = this.layoutBottomBar(state);
|
||||
const statusInRow = statusInSwitcherRow(state.foregroundAppId);
|
||||
const popup = switcherPosition() === "popup";
|
||||
// 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); a popup only ever shows then.
|
||||
// Over an immersive window the strip is an overlay, present only while
|
||||
// the user is in it (the window underneath keeps the whole panel the
|
||||
// rest of the time); a popup only ever shows then.
|
||||
const switcherShown = sidebarStripVisible(state.focus, state.foregroundAppId);
|
||||
if (switcherShown && !popup) {
|
||||
this.drawSidebar(image, state, statusInRow ? image : undefined);
|
||||
@@ -449,7 +648,8 @@ export class ShellChromeLayer implements Layer {
|
||||
|
||||
paintParts(): Plane[] {
|
||||
const state = this.getState(), parts: Plane[] = [];
|
||||
this.notificationEntries = [];
|
||||
this.statusEntries = [];
|
||||
this.bottomBar = this.layoutBottomBar(state);
|
||||
const statusInRow = statusInSwitcherRow(state.foregroundAppId);
|
||||
const canvas = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
|
||||
const span = topBarSpan(state);
|
||||
@@ -532,7 +732,7 @@ export class ShellChromeLayer implements Layer {
|
||||
if (windowCount === 0) return null;
|
||||
const state = this.getState();
|
||||
const layout = switcherPosition() === "popup" ? popupLayout(windowCount, state)
|
||||
: switcherLayout(windowCount, state.foregroundHeightMode, state.foregroundAppId, this.rowWindowsRight, this.scrollRow);
|
||||
: switcherLayout(windowCount, state.foregroundHeightMode, state.foregroundAppId, this.bottomBar, this.scrollRow);
|
||||
const lastVisible = Math.min(windowCount, this.scrollRow + layout.visibleCount);
|
||||
for (let index = this.scrollRow; index < lastVisible; index++) {
|
||||
const cell = layout.cell(index - this.scrollRow);
|
||||
@@ -543,22 +743,27 @@ export class ShellChromeLayer implements Layer {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Keys of the notifications whose icons the last paint drew, left to right. */
|
||||
notificationKeys(): string[] {
|
||||
return this.notificationEntries.map((entry) => entry.key);
|
||||
/**
|
||||
* The status bar items whose icons the last paint drew, in reading order:
|
||||
* left to right, then a second row's. Notifications come before app
|
||||
* widgets wherever the status bar is.
|
||||
*/
|
||||
statusItems(): StatusItem[] {
|
||||
return [...this.statusEntries].sort((a, b) => a.y - b.y || a.x - b.x).map(({ kind, key }) => ({ kind, key }));
|
||||
}
|
||||
|
||||
/** Which notification's icon is under (x, y) on screen, if any (mirror touches). */
|
||||
notificationKeyAt(x: number, y: number): string | null {
|
||||
const entry = this.notificationEntries.find((e) => x >= e.x && x < e.x + e.width && y >= e.y && y < e.y + e.height);
|
||||
return entry?.key ?? null;
|
||||
/** Which status bar item's icon is under (x, y) on screen, if any (mirror touches). */
|
||||
statusItemAt(x: number, y: number): StatusItem | null {
|
||||
const entry = this.statusEntries.find((e) => x >= e.x && x < e.x + e.width && y >= e.y && y < e.y + e.height);
|
||||
return entry ? { kind: entry.kind, key: entry.key } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the switcher strip or row. Given `statusImage`, a bottom row shares
|
||||
* its right end with the status bar, drawn there (into that image, which
|
||||
* may be this one) first, and the window icons take what it leaves.
|
||||
* Returns the status bar's left edge, or null without one.
|
||||
* Draw the switcher strip or row. Given `statusImage`, a bottom switcher
|
||||
* shares its right end with the status bar, drawn there (into that image,
|
||||
* which may be this one) first, and the window icons take what it leaves
|
||||
* (see planBottomBar). Returns the status bar's left edge, or null without
|
||||
* one.
|
||||
*/
|
||||
private drawSidebar(image: GrayImage, state: ShellChromeState, statusImage?: GrayImage): number | null {
|
||||
// A side strip aligns with the app's preferred band (legacy tall
|
||||
@@ -571,18 +776,17 @@ export class ShellChromeLayer implements Layer {
|
||||
// windows off-screen before/after. Sidebar icons fill the column against
|
||||
// the separator top to bottom, then overflow into the outer one, so a
|
||||
// visible slot's column is decided by its position within the scrolled
|
||||
// window.
|
||||
// window; a bottom switcher's two rows likewise fill the top one first.
|
||||
const count = state.windows.length;
|
||||
const statusLeft = statusImage && switcherPosition() === "bottom"
|
||||
? this.drawRowStatus(statusImage, state, strip, count) : null;
|
||||
const bar = this.bottomBar;
|
||||
const statusLeft = statusImage && bar?.statusRows.length ? this.drawRowStatus(statusImage, strip, bar) : null;
|
||||
const windowsRight = statusLeft === null ? strip.x + strip.width : statusLeft - ROW_STATUS_GAP;
|
||||
this.rowWindowsRight = windowsRight;
|
||||
const visibleCount = switcherLayout(count, state.foregroundHeightMode, state.foregroundAppId, windowsRight).visibleCount;
|
||||
const visibleCount = switcherLayout(count, state.foregroundHeightMode, state.foregroundAppId, bar).visibleCount;
|
||||
// With the selection out on a notification, the windows stay scrolled as they were.
|
||||
this.scrollRow = state.selectedIndex >= 0
|
||||
? scrollToKeepSelectionVisible(this.scrollRow, state.selectedIndex, visibleCount, count)
|
||||
: Math.min(this.scrollRow, Math.max(0, count - visibleCount));
|
||||
const layout = switcherLayout(count, state.foregroundHeightMode, state.foregroundAppId, windowsRight, this.scrollRow);
|
||||
const layout = switcherLayout(count, state.foregroundHeightMode, state.foregroundAppId, bar, this.scrollRow);
|
||||
const { iconSize, position } = layout;
|
||||
const lastVisible = Math.min(count, this.scrollRow + layout.visibleCount);
|
||||
const cellOf = (index: number) => layout.cell(index - this.scrollRow);
|
||||
@@ -598,7 +802,7 @@ export class ShellChromeLayer implements Layer {
|
||||
const selCell = selVisible ? cellOf(state.selectedIndex) : null;
|
||||
drawSeparator(image, state, strip, selCell?.atSeparator ? selCell : null);
|
||||
const frame = position === "bottom" ? windowFrameRect(state) : null;
|
||||
this.frameCornerSquare = !!frame && selCell?.x === frame.x;
|
||||
this.frameCornerSquare = !!frame && !!selCell?.atSeparator && selCell.x === frame.x;
|
||||
|
||||
for (let index = this.scrollRow; index < lastVisible; index++) {
|
||||
const window = state.windows[index]!;
|
||||
@@ -628,13 +832,14 @@ export class ShellChromeLayer implements Layer {
|
||||
}
|
||||
|
||||
if (position === "bottom") {
|
||||
// Chevrons sit in the margins at either end of the icons, pointing off them.
|
||||
const chevronY = strip.y + ((strip.height / 2) | 0);
|
||||
// Chevrons sit in the margins at either end of the icons, pointing off
|
||||
// them: before the first row's, and after the last row's.
|
||||
const rowMiddle = (line: number) => strip.y + line * SWITCHER_ROW_HEIGHT + (SWITCHER_ROW_HEIGHT >> 1);
|
||||
if (this.scrollRow > 0) {
|
||||
drawChevron(image, strip.x + 6, chevronY, "left");
|
||||
drawChevron(image, strip.x + 6, rowMiddle(0), "left");
|
||||
}
|
||||
if (lastVisible < count) {
|
||||
drawChevron(image, windowsRight - 6, chevronY, "right");
|
||||
drawChevron(image, windowsRight - 6, rowMiddle((bar?.windowRows ?? 1) - 1), "right");
|
||||
}
|
||||
return statusLeft;
|
||||
}
|
||||
@@ -652,39 +857,75 @@ export class ShellChromeLayer implements Layer {
|
||||
}
|
||||
|
||||
/**
|
||||
* The status bar at the right end of the switcher row, right to left:
|
||||
* date and time, batteries, app widgets, then notification icons, each as
|
||||
* it sits in the top bar (see ROW_STATUS_TOP). Notification icons stop
|
||||
* short of room for a few window slots; the windows get the rest, and
|
||||
* whatever they leave over is free space between the two. Returns the
|
||||
* left edge of what it drew.
|
||||
* Lay out the bottom switcher for this paint (planBottomBar) under the
|
||||
* foreground window, with the status bar's items when it shares the
|
||||
* switcher, and record its height in geometry.ts, telling the shell when
|
||||
* that moves or resizes windows. Null for the other switcher positions.
|
||||
*/
|
||||
private drawRowStatus(image: GrayImage, state: ShellChromeState, row: Rect, windowCount: number): number {
|
||||
image.fillRect(row.x, row.y + 1, row.width, row.height - 1, SHELL_OPAQUE_BLACK);
|
||||
const top = row.y + ROW_STATUS_TOP;
|
||||
const font = getDefaultMediumFont();
|
||||
const clock = clockText();
|
||||
// A TTF face measures fractionally; the status surface's crop edges need whole pixels.
|
||||
const clockX = row.x + row.width - Math.ceil(font.measureText(clock));
|
||||
image.drawText(font, clockX, top + Math.max(0, ((TOP_BAR_HEIGHT - font.lineHeight) / 2) | 0), clock, 210);
|
||||
// The battery block keeps its usual right margin inside the edge it's given.
|
||||
const batteryLeft = this.drawTopBarBatteries(image, state, top, clockX - ROW_CLOCK_GAP + BATTERY_BLOCK_RIGHT_MARGIN);
|
||||
const trayLeft = drawTrayIcons(image, state.trayIcons, batteryLeft, top);
|
||||
private layoutBottomBar(state: ShellChromeState): BottomBarPlan<RowStatusItem> | null {
|
||||
if (switcherPosition() !== "bottom") return null;
|
||||
const appId = state.foregroundAppId;
|
||||
const status = statusInSwitcherRow(appId) ? this.rowStatusItems(state) : [];
|
||||
const plan = planBottomBar(switcherRect(state.foregroundHeightMode, appId).width, state.windows.length, status);
|
||||
if (setSwitcherBarHeight(plan.height, appId)) this.onBottomBarHeightChanged();
|
||||
return plan;
|
||||
}
|
||||
|
||||
// Right-aligned against the widgets, with the top bar's spacing.
|
||||
const slots = Math.min(windowCount, ROW_MIN_WINDOW_SLOTS);
|
||||
const windowsFloor = row.x + 2 * LIST_MARGIN + Math.max(0, slots * ROW_STEP - ICON_SPACING) + ROW_STATUS_GAP;
|
||||
const iconsRight = trayLeft - 8, step = NOTIFICATION_ICON_STEP;
|
||||
const maxIcons = Math.max(0, ((iconsRight - windowsFloor + 4) / step) | 0);
|
||||
if (maxIcons === 0) return trayLeft;
|
||||
const { icons, keys, stale } = readActiveNotificationIcons(maxIcons, renderPassAllowsStaleData());
|
||||
/**
|
||||
* The status bar's items for the bottom switcher, left to right: every
|
||||
* notification icon, the app widgets, the battery block, and the date and
|
||||
* time, each to draw as it sits in the top bar.
|
||||
*/
|
||||
private rowStatusItems(state: ShellChromeState): RowStatusItem[] {
|
||||
const items: RowStatusItem[] = [];
|
||||
const { icons, keys, stale } = readActiveNotificationIcons(ALL_NOTIFICATIONS, renderPassAllowsStaleData());
|
||||
if (stale) {
|
||||
noteStaleDataUsed();
|
||||
}
|
||||
if (!icons.length) return trayLeft;
|
||||
const iconsLeft = iconsRight - icons.length * step + 4;
|
||||
this.drawNotificationIcons(image, state, icons, keys, iconsLeft, top + (((TOP_BAR_HEIGHT - NOTIFICATION_ICON_SIZE) / 2) | 0));
|
||||
return iconsLeft;
|
||||
icons.forEach((icon, index) => items.push({
|
||||
kind: "notification", width: NOTIFICATION_ICON_SIZE,
|
||||
draw: (image, x, top) => this.drawStatusIcon(image, state, notificationItem(keys[index]), icon, x, top),
|
||||
}));
|
||||
for (const tray of state.trayIcons) {
|
||||
items.push({ kind: "tray", width: tray.icon.width, draw: (image, x, top) => this.drawTrayIcon(image, state, tray, x, top) });
|
||||
}
|
||||
const batteries = batteryItems(state);
|
||||
if (batteries.length) {
|
||||
// Measured by drawing it: each battery style lays itself out as it draws.
|
||||
const scratch = new GrayImage(G2_LENS_WIDTH, TOP_BAR_HEIGHT, 0);
|
||||
const width = G2_LENS_WIDTH - BATTERY_BLOCK_RIGHT_MARGIN - drawBatteryBlock(scratch, batteries, 0, G2_LENS_WIDTH);
|
||||
// The block keeps its usual right margin inside the edge it's given.
|
||||
items.push({ kind: "batteries", width,
|
||||
draw: (image, x, top) => drawBatteryBlock(image, batteries, top, x + width + BATTERY_BLOCK_RIGHT_MARGIN) });
|
||||
}
|
||||
const font = getDefaultMediumFont();
|
||||
const clock = clockText();
|
||||
// A TTF face measures fractionally; the status surface's crop edges need whole pixels.
|
||||
items.push({ kind: "clock", width: Math.ceil(font.measureText(clock)),
|
||||
draw: (image, x, top) => image.drawText(font, x, top + Math.max(0, ((TOP_BAR_HEIGHT - font.lineHeight) / 2) | 0), clock, 210) });
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* The status bar at the right end of the bottom switcher: its rows as
|
||||
* planned (planBottomBar), each right-aligned against the switcher's end,
|
||||
* the first row ROW_STATUS_TOP under its top. Whatever the windows leave
|
||||
* over is free space between the two. Returns the left edge of the widest
|
||||
* row.
|
||||
*/
|
||||
private drawRowStatus(image: GrayImage, row: Rect, bar: BottomBarPlan<RowStatusItem>): number {
|
||||
image.fillRect(row.x, row.y + 1, row.width, row.height - 1, SHELL_OPAQUE_BLACK);
|
||||
const right = row.x + row.width;
|
||||
bar.statusRows.forEach((items, line) => {
|
||||
const top = row.y + ROW_STATUS_TOP + line * bar.statusPitch;
|
||||
let x = right - statusRowWidth(items);
|
||||
items.forEach((item, index) => {
|
||||
if (index > 0) x += statusGap(items[index - 1]!, item);
|
||||
item.draw(image, x, top);
|
||||
x += item.width;
|
||||
});
|
||||
});
|
||||
return right - bar.statusWidth;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -742,7 +983,7 @@ export class ShellChromeLayer implements Layer {
|
||||
// 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. It spans the app viewport;
|
||||
// with a side strip overlaid (full-panel mode, sidebar focused) it still
|
||||
// with a side strip overlaid (an immersive window, sidebar focused) it still
|
||||
// stops at the strip.
|
||||
const { left: barLeft, right: barRight } = bar;
|
||||
image.fillRect(barLeft, bar.top, barRight - barLeft, TOP_BAR_HEIGHT, SHELL_OPAQUE_BLACK);
|
||||
@@ -757,118 +998,146 @@ export class ShellChromeLayer implements Layer {
|
||||
const textY = barTop + Math.max(0, ((TOP_BAR_HEIGHT - font.lineHeight) / 2) | 0);
|
||||
image.drawText(font, clockX, textY, clock, 210);
|
||||
|
||||
const batteryLeft = this.drawTopBarBatteries(image, state, barTop, barRight);
|
||||
const trayLeft = drawTrayIcons(image, state.trayIcons, batteryLeft, barTop);
|
||||
const batteryLeft = drawBatteryBlock(image, batteryItems(state), barTop, barRight);
|
||||
const trayLeft = this.drawTrayIcons(image, state, batteryLeft, barTop);
|
||||
|
||||
const iconsX = clockX + Math.ceil(font.measureText(clock)) + 16;
|
||||
const maxIcons = Math.max(0, ((trayLeft - 8 - iconsX) / NOTIFICATION_ICON_STEP) | 0);
|
||||
const maxIcons = Math.max(0, ((trayLeft - NOTIFICATIONS_GAP - iconsX) / NOTIFICATION_ICON_STEP) | 0);
|
||||
if (maxIcons > 0) {
|
||||
const { icons, keys, stale } = readActiveNotificationIcons(maxIcons, renderPassAllowsStaleData());
|
||||
if (stale) {
|
||||
noteStaleDataUsed();
|
||||
}
|
||||
this.drawNotificationIcons(image, state, icons, keys, iconsX, barTop + (((TOP_BAR_HEIGHT - NOTIFICATION_ICON_SIZE) / 2) | 0));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the notification icons left to right from `left`, noting each as a
|
||||
* notification entry. The one the switcher's selection is on
|
||||
* (state.selectedNotificationKey) sits in a rounded box like a sidebar
|
||||
* overflow icon's: filled, with the icon inverted, while the switcher has
|
||||
* focus, and outlined while its detail view in the foreground window has.
|
||||
*/
|
||||
private drawNotificationIcons(image: GrayImage, state: ShellChromeState, icons: GrayImage[], keys: string[], left: number, iconY: number): void {
|
||||
for (let index = 0; index < icons.length; index++) {
|
||||
const x = left + index * NOTIFICATION_ICON_STEP;
|
||||
const key = keys[index];
|
||||
const box = {
|
||||
x: x - NOTIFICATION_BOX_MARGIN_X, y: iconY - NOTIFICATION_BOX_MARGIN_Y,
|
||||
width: NOTIFICATION_ICON_SIZE + 2 * NOTIFICATION_BOX_MARGIN_X, height: NOTIFICATION_ICON_SIZE + 2 * NOTIFICATION_BOX_MARGIN_Y,
|
||||
};
|
||||
if (key) this.notificationEntries.push({ key, ...box });
|
||||
const selected = !!key && key === state.selectedNotificationKey;
|
||||
const focused = selected && state.focus === "sidebar";
|
||||
if (selected) drawSelectionBox(image, box.x, box.y, box.width, box.height, focused);
|
||||
image.drawImage(focused ? invertedIcon(icons[index]!) : icons[index]!, x, iconY);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Labelled battery indicators for the phone, Wear OS watch, G2, and R1,
|
||||
* right-aligned in the top bar. The watch one exists only while a watch
|
||||
* running the Faceclaw watch app is reachable (no placeholder otherwise).
|
||||
* The Settings > Customization > Battery indicators submenu picks the
|
||||
* style (label beside a gauge icon or percentage, stacked above either, or
|
||||
* dense: device icons beside gauges, two per column) and, per device,
|
||||
* whether the indicator shows always, only below 50%, or never. `barRight`
|
||||
* is the bar's right edge (short of a right-hand sidebar). Returns the left
|
||||
* edge of the battery block.
|
||||
*/
|
||||
private drawTopBarBatteries(image: GrayImage, state: ShellChromeState, barTop: number, barRight: number): number {
|
||||
const mode = batteryDisplayModeSetting.get();
|
||||
const items: BatteryItem[] = [];
|
||||
const phone = readPhoneBatteryState();
|
||||
if (phone.battery !== null && Number.isFinite(phone.battery)) {
|
||||
pushBatteryItem(items, phoneBatteryVisibilitySetting.get(), "Phone", "phone", phone.battery, Boolean(phone.charging));
|
||||
}
|
||||
if (state.battery.watch !== null && Number.isFinite(state.battery.watch)) {
|
||||
pushBatteryItem(items, watchBatteryVisibilitySetting.get(), "Watch", "watch", state.battery.watch,
|
||||
Boolean(state.battery.watchCharging));
|
||||
}
|
||||
if (state.battery.headset !== null && Number.isFinite(state.battery.headset)) {
|
||||
pushBatteryItem(items, glassesBatteryVisibilitySetting.get(), "G2", "glasses", state.battery.headset,
|
||||
Boolean(state.battery.headsetCharging));
|
||||
}
|
||||
if (state.battery.ring !== null && Number.isInteger(state.battery.ring)
|
||||
&& state.battery.ring >= 0 && state.battery.ring <= 100) {
|
||||
pushBatteryItem(items, ringBatteryVisibilitySetting.get(), "R1", "ring", state.battery.ring,
|
||||
Boolean(state.battery.ringCharging));
|
||||
}
|
||||
if (!items.length) return barRight;
|
||||
if (mode === "stacked" || mode === "stacked-percentage") {
|
||||
return drawStackedBatteries(image, items, barTop, barRight, mode === "stacked-percentage");
|
||||
}
|
||||
if (mode === "dense") {
|
||||
return drawDenseBatteries(image, items, barRight - BATTERY_BLOCK_RIGHT_MARGIN, barTop + DENSE_TOP);
|
||||
}
|
||||
|
||||
const font = getDefaultSmallFont();
|
||||
const percentageMode = mode === "percentage";
|
||||
const labelGap = 5;
|
||||
const itemGap = 12;
|
||||
const textY = barTop + Math.max(0, ((TOP_BAR_HEIGHT - font.lineHeight) / 2) | 0);
|
||||
let x = barRight - BATTERY_BLOCK_RIGHT_MARGIN;
|
||||
for (let index = items.length - 1; index >= 0; index--) {
|
||||
const item = items[index]!;
|
||||
const percentText = `${item.percent}%`;
|
||||
const valueWidth = percentageMode ? Math.ceil(font.measureText(percentText)) : BATTERY_ICON_WIDTH;
|
||||
const labelWidth = Math.ceil(font.measureText(item.label));
|
||||
x -= labelWidth + labelGap + valueWidth;
|
||||
image.drawText(font, x, textY, item.label, BATTERY_LABEL_VALUE);
|
||||
const valueX = x + labelWidth + labelGap;
|
||||
if (percentageMode) {
|
||||
if (item.charging) {
|
||||
// Inverted text marks charging, matching the dashboard card.
|
||||
image.fillRect(valueX - 2, textY - 1, valueWidth + 4, font.lineHeight + 2, 255);
|
||||
image.drawText(font, valueX, textY, percentText, 1);
|
||||
} else {
|
||||
image.drawText(font, valueX, textY, percentText, 200);
|
||||
}
|
||||
} else {
|
||||
const icon = drawBattery(item.percent, item.charging);
|
||||
image.bitBlt(icon, valueX, barTop + Math.max(0, ((TOP_BAR_HEIGHT - icon.height) / 2) | 0), {
|
||||
transparentZero: true,
|
||||
});
|
||||
for (let index = 0; index < icons.length; index++) {
|
||||
this.drawStatusIcon(image, state, notificationItem(keys[index]), icons[index]!, iconsX + index * NOTIFICATION_ICON_STEP, barTop);
|
||||
}
|
||||
x -= itemGap;
|
||||
}
|
||||
return x + itemGap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw app tray icons right-to-left, ending just left of the battery
|
||||
* block; returns the left edge of the tray region.
|
||||
*/
|
||||
private drawTrayIcons(image: GrayImage, state: ShellChromeState, rightEdge: number, barTop: number): number {
|
||||
let x = rightEdge;
|
||||
for (let index = state.trayIcons.length - 1; index >= 0; index--) {
|
||||
const tray = state.trayIcons[index]!;
|
||||
x -= tray.icon.width + TRAY_ICON_GAP;
|
||||
this.drawTrayIcon(image, state, tray, x, barTop);
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
/** Draw an app tray icon (an app widget's) with its left edge at x, as drawStatusIcon does. */
|
||||
private drawTrayIcon(image: GrayImage, state: ShellChromeState, tray: ShellChromeTrayIcon, x: number, barTop: number): void {
|
||||
this.drawStatusIcon(image, state, { kind: "widget", key: tray.ownerId }, tray.icon, x, barTop);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw a status bar item's icon with its left edge at x, centred in the
|
||||
* top bar's layout from `barTop`, noting it as a status entry (unless
|
||||
* `item` is null). The one the switcher's selection is on
|
||||
* (state.selectedStatusItem) sits in a rounded box like a sidebar
|
||||
* overflow icon's: filled, with the icon inverted, while the switcher has
|
||||
* focus, and outlined while its window has. The box is a notification
|
||||
* icon's height whatever the icon's, clear of the top bar's divider.
|
||||
*/
|
||||
private drawStatusIcon(image: GrayImage, state: ShellChromeState, item: StatusItem | null, icon: GrayImage, x: number, barTop: number): void {
|
||||
const iconY = barTop + Math.max(0, ((TOP_BAR_HEIGHT - icon.height) / 2) | 0);
|
||||
const box = {
|
||||
x: x - NOTIFICATION_BOX_MARGIN_X, y: barTop + NOTIFICATION_ICON_TOP - NOTIFICATION_BOX_MARGIN_Y,
|
||||
width: icon.width + 2 * NOTIFICATION_BOX_MARGIN_X, height: NOTIFICATION_ICON_SIZE + 2 * NOTIFICATION_BOX_MARGIN_Y,
|
||||
};
|
||||
if (item) this.statusEntries.push({ ...item, ...box });
|
||||
const selected = sameStatusItem(item, state.selectedStatusItem);
|
||||
const focused = selected && state.focus === "sidebar";
|
||||
if (selected) drawSelectionBox(image, box.x, box.y, box.width, box.height, focused);
|
||||
image.drawImage(focused ? invertedIcon(icon) : icon, x, iconY);
|
||||
}
|
||||
}
|
||||
|
||||
type BatteryItem = { label: string; device: BatteryDevice; percent: number; charging: boolean };
|
||||
|
||||
/**
|
||||
* Labelled battery indicators for the phone, Wear OS watch, G2, and R1. The
|
||||
* watch one exists only while a watch running the Faceclaw watch app is
|
||||
* reachable (no placeholder otherwise). The Settings > Customization >
|
||||
* Battery indicators submenu picks, per device, whether the indicator shows
|
||||
* always, only below 50%, or never.
|
||||
*/
|
||||
function batteryItems(state: ShellChromeState): BatteryItem[] {
|
||||
const items: BatteryItem[] = [];
|
||||
const phone = readPhoneBatteryState();
|
||||
if (phone.battery !== null && Number.isFinite(phone.battery)) {
|
||||
pushBatteryItem(items, phoneBatteryVisibilitySetting.get(), "Phone", "phone", phone.battery, Boolean(phone.charging));
|
||||
}
|
||||
if (state.battery.watch !== null && Number.isFinite(state.battery.watch)) {
|
||||
pushBatteryItem(items, watchBatteryVisibilitySetting.get(), "Watch", "watch", state.battery.watch,
|
||||
Boolean(state.battery.watchCharging));
|
||||
}
|
||||
if (state.battery.headset !== null && Number.isFinite(state.battery.headset)) {
|
||||
pushBatteryItem(items, glassesBatteryVisibilitySetting.get(), "G2", "glasses", state.battery.headset,
|
||||
Boolean(state.battery.headsetCharging));
|
||||
}
|
||||
if (state.battery.ring !== null && Number.isInteger(state.battery.ring)
|
||||
&& state.battery.ring >= 0 && state.battery.ring <= 100) {
|
||||
pushBatteryItem(items, ringBatteryVisibilitySetting.get(), "R1", "ring", state.battery.ring,
|
||||
Boolean(state.battery.ringCharging));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* The battery indicators (batteryItems), right-aligned in the top bar's
|
||||
* layout from `barTop`, in the style the Battery indicators submenu picks:
|
||||
* label beside a gauge icon or percentage, stacked above either, or dense
|
||||
* (device icons beside gauges, two per column). `barRight` is the bar's
|
||||
* right edge (short of a right-hand sidebar). Returns the left edge of the
|
||||
* battery block, or `barRight` with no indicators.
|
||||
*/
|
||||
function drawBatteryBlock(image: GrayImage, items: BatteryItem[], barTop: number, barRight: number): number {
|
||||
const mode = batteryDisplayModeSetting.get();
|
||||
if (!items.length) return barRight;
|
||||
if (mode === "stacked" || mode === "stacked-percentage") {
|
||||
return drawStackedBatteries(image, items, barTop, barRight, mode === "stacked-percentage");
|
||||
}
|
||||
if (mode === "dense") {
|
||||
return drawDenseBatteries(image, items, barRight - BATTERY_BLOCK_RIGHT_MARGIN, barTop + DENSE_TOP);
|
||||
}
|
||||
|
||||
const font = getDefaultSmallFont();
|
||||
const percentageMode = mode === "percentage";
|
||||
const labelGap = 5;
|
||||
const itemGap = 12;
|
||||
const textY = barTop + Math.max(0, ((TOP_BAR_HEIGHT - font.lineHeight) / 2) | 0);
|
||||
let x = barRight - BATTERY_BLOCK_RIGHT_MARGIN;
|
||||
for (let index = items.length - 1; index >= 0; index--) {
|
||||
const item = items[index]!;
|
||||
const percentText = `${item.percent}%`;
|
||||
const valueWidth = percentageMode ? Math.ceil(font.measureText(percentText)) : BATTERY_ICON_WIDTH;
|
||||
const labelWidth = Math.ceil(font.measureText(item.label));
|
||||
x -= labelWidth + labelGap + valueWidth;
|
||||
image.drawText(font, x, textY, item.label, BATTERY_LABEL_VALUE);
|
||||
const valueX = x + labelWidth + labelGap;
|
||||
if (percentageMode) {
|
||||
if (item.charging) {
|
||||
// Inverted text marks charging, matching the dashboard card.
|
||||
image.fillRect(valueX - 2, textY - 1, valueWidth + 4, font.lineHeight + 2, 255);
|
||||
image.drawText(font, valueX, textY, percentText, 1);
|
||||
} else {
|
||||
image.drawText(font, valueX, textY, percentText, 200);
|
||||
}
|
||||
} else {
|
||||
const icon = drawBattery(item.percent, item.charging);
|
||||
image.bitBlt(icon, valueX, barTop + Math.max(0, ((TOP_BAR_HEIGHT - icon.height) / 2) | 0), {
|
||||
transparentZero: true,
|
||||
});
|
||||
}
|
||||
x -= itemGap;
|
||||
}
|
||||
return x + itemGap;
|
||||
}
|
||||
|
||||
/** The status bar's date and time. */
|
||||
function clockText(): string {
|
||||
const now = new Date();
|
||||
@@ -999,20 +1268,6 @@ function drawAmbientCards(image: GrayImage, right: number, parts?: Plane[]): voi
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw app tray icons right-to-left, ending just left of the battery block;
|
||||
* returns the left edge of the tray region.
|
||||
*/
|
||||
function drawTrayIcons(image: GrayImage, trayIcons: GrayImage[], rightEdge: number, barTop: number): number {
|
||||
let x = rightEdge;
|
||||
for (let index = trayIcons.length - 1; index >= 0; index--) {
|
||||
const icon = trayIcons[index]!;
|
||||
x -= icon.width + 10;
|
||||
image.drawImage(icon, x, barTop + Math.max(0, ((TOP_BAR_HEIGHT - icon.height) / 2) | 0));
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
/** The sidebar attention marker, cached per fill value (deferred-image source). */
|
||||
const attentionDots = new Map<number, GrayImage>();
|
||||
function attentionDot(value: number): GrayImage {
|
||||
@@ -1027,8 +1282,13 @@ function attentionDot(value: number): GrayImage {
|
||||
|
||||
type Rect = { x: number; y: number; width: number; height: number };
|
||||
|
||||
/** A notification icon as drawn: its notification's key, and its selection box. */
|
||||
type NotificationEntry = Rect & { key: string };
|
||||
/** A status bar item's icon as drawn: the item, and its selection box. */
|
||||
type StatusEntry = Rect & StatusItem;
|
||||
|
||||
/** A notification's status item, if its icon came with a key. */
|
||||
function notificationItem(key: string | undefined): StatusItem | null {
|
||||
return key ? { kind: "notification", key } : null;
|
||||
}
|
||||
|
||||
/** Corner radius of the foreground window's frame. */
|
||||
const FRAME_RADIUS = 8;
|
||||
|
||||
+197
-80
@@ -2,13 +2,10 @@ import { G2_LENS_HEIGHT, G2_LENS_WIDTH } from "../../graphics/image";
|
||||
import {
|
||||
appSwitcherPositionSetting,
|
||||
type AppSwitcherPosition,
|
||||
displayModeSetting,
|
||||
type DisplayModeSetting,
|
||||
verticalPositionSetting,
|
||||
navigateDisplayModeSetting,
|
||||
navigateVerticalPositionSetting,
|
||||
terminalDisplayModeSetting,
|
||||
terminalVerticalPositionSetting,
|
||||
displayLayoutSetting,
|
||||
type DisplayLayout,
|
||||
navigateDisplayLayoutSetting,
|
||||
terminalDisplayLayoutSetting,
|
||||
statusBarPositionSetting,
|
||||
statusBarVisibilitySetting,
|
||||
uiDepthSetting,
|
||||
@@ -21,23 +18,46 @@ export const TOP_BAR_HEIGHT = 28;
|
||||
* Width of the sidebar strip as painted (the app switcher on the left or
|
||||
* right edge). App windows get the other 576px — the surface width EvenHub
|
||||
* apps expect — and keep that width with the switcher at the bottom or a
|
||||
* popup too, except in the full-panel display mode, where the switcher
|
||||
* overlays the app (see sidebarWidth). Icon column layout within the strip
|
||||
* (one wide column vs. two narrow ones) is the chrome layer's business.
|
||||
* popup too, except in the Full Screen display mode (640 wide; never beside
|
||||
* a strip) and immersive windows, which the switcher overlays (see
|
||||
* sidebarWidth). Icon column layout within the strip (one wide column vs.
|
||||
* two narrow ones) is the chrome layer's business.
|
||||
*/
|
||||
export const SIDEBAR_WIDTH = 64;
|
||||
|
||||
/**
|
||||
* Height of the app switcher as a row under the window: one tall tab, the
|
||||
* Height of one row of the app switcher under the window: one tall tab, the
|
||||
* same 36px (a 32px icon plus 2px either side) as a one-column sidebar slot.
|
||||
* The row is wide enough that it never needs the sidebar's smaller
|
||||
* two-column icons. It comes out of the height available to windows; their
|
||||
* width stays 576, centred, leaving SIDEBAR_WIDTH / 2 at each side: one
|
||||
* pixel for the side of the window's frame (windowFramed), the rest for the
|
||||
* whole display's stereo shift (uiDepth).
|
||||
* whole display's stereo shift (uiDepth). Full Screen windows take those
|
||||
* margins too, giving up both. When the row's contents don't fit, the
|
||||
* switcher grows a second row (see setSwitcherBarHeight).
|
||||
*/
|
||||
export const SWITCHER_ROW_HEIGHT = 36;
|
||||
|
||||
/**
|
||||
* Height of the bottom switcher as its contents last laid out (chrome-layer.ts
|
||||
* planBottomBar): SWITCHER_ROW_HEIGHT, or more once the status bar's items
|
||||
* or the window icons take a second row. One for the switcher reserved
|
||||
* under windows, one for the switcher overlaying an immersive window.
|
||||
*/
|
||||
const switcherBarHeights = { reserved: SWITCHER_ROW_HEIGHT, overlay: SWITCHER_ROW_HEIGHT };
|
||||
|
||||
/**
|
||||
* Set the bottom switcher's height for its current layout under the given
|
||||
* (foreground) app's window: the overlay's over an immersive window, else
|
||||
* the row reserved under windows. True if that moves or resizes windows.
|
||||
*/
|
||||
export function setSwitcherBarHeight(height: number, appId?: string): boolean {
|
||||
const which = isImmersive(appId) ? "overlay" : "reserved";
|
||||
if (switcherBarHeights[which] === height) return false;
|
||||
switcherBarHeights[which] = height;
|
||||
return which === "reserved";
|
||||
}
|
||||
|
||||
/** Which edge the app switcher is on, or a popup (Settings > Customization). */
|
||||
export function switcherPosition(): AppSwitcherPosition {
|
||||
return appSwitcherPositionSetting.get();
|
||||
@@ -49,48 +69,89 @@ function sideStrip(): boolean {
|
||||
return position === "left" || position === "right";
|
||||
}
|
||||
|
||||
/** The Display > Display mode setting (see dashboard-settings.ts). */
|
||||
function appDisplayMode(appId?: string) {
|
||||
return appId === "navigate" ? navigateDisplayModeSetting.get()
|
||||
: appId === "terminal" ? terminalDisplayModeSetting.get() : "default";
|
||||
/** An app's own Display mode setting (Navigate, Terminal); "default" for the rest. */
|
||||
function appDisplayLayout(appId?: string) {
|
||||
return appId === "navigate" ? navigateDisplayLayoutSetting.get()
|
||||
: appId === "terminal" ? terminalDisplayLayoutSetting.get() : "default";
|
||||
}
|
||||
|
||||
export function displayMode(appId?: string): DisplayModeSetting {
|
||||
const mode = appDisplayMode(appId);
|
||||
return mode === "global" || mode === "default" ? displayModeSetting.get() : mode;
|
||||
/**
|
||||
* The display mode an app's windows use (see dashboard-settings.ts
|
||||
* DisplayLayout): its own, or the global one. Full Screen needs the width a
|
||||
* side strip takes, so beside one it is Tall.
|
||||
*/
|
||||
export function displayLayout(appId?: string): DisplayLayout {
|
||||
const own = appDisplayLayout(appId);
|
||||
const layout = own === "global" || own === "default" ? displayLayoutSetting.get() : own;
|
||||
return layout === "fullscreen" && sideStrip() ? "tall" : layout;
|
||||
}
|
||||
|
||||
/** The full-panel mode: windows fill the panel; the switcher overlays them only while it has focus. */
|
||||
function fullPanel(appId?: string): boolean {
|
||||
return displayMode(appId) === "640x480";
|
||||
/** Fraction of the slack above a window band in each band display mode. */
|
||||
const BAND_FRACTIONS: Partial<Record<DisplayLayout, number>> = {
|
||||
"band-top": 0,
|
||||
"band-high": 0.25,
|
||||
"band-middle": 0.5,
|
||||
"band-low": 0.75,
|
||||
"band-bottom": 1,
|
||||
};
|
||||
|
||||
/** A band display mode's fraction of the slack above the band; undefined for Tall and Full Screen. */
|
||||
function bandFraction(layout: DisplayLayout): number | undefined {
|
||||
return BAND_FRACTIONS[layout];
|
||||
}
|
||||
|
||||
/**
|
||||
* Apps whose windows are immersive right now: the whole panel, with no
|
||||
* status bar, window frame or room kept for the switcher (which overlays
|
||||
* them only while it has focus), at depth 0. An app switches it at runtime
|
||||
* (InProcessWindow.setImmersive; the onboarding's first pages), so it is
|
||||
* per app, like the per-app display modes.
|
||||
*/
|
||||
const immersiveApps = new Set<string>();
|
||||
|
||||
/** Mark an app's windows immersive or not; true if that changed anything. */
|
||||
export function setAppImmersive(appId: string, immersive: boolean): boolean {
|
||||
if (immersiveApps.has(appId) === immersive) return false;
|
||||
if (immersive) immersiveApps.add(appId);
|
||||
else immersiveApps.delete(appId);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function isImmersive(appId?: string): boolean {
|
||||
return appId !== undefined && immersiveApps.has(appId);
|
||||
}
|
||||
|
||||
/** Whether an app's windows span the panel's whole width: Full Screen, or immersive. */
|
||||
function fullWidth(appId?: string): boolean {
|
||||
return isImmersive(appId) || displayLayout(appId) === "fullscreen";
|
||||
}
|
||||
|
||||
/**
|
||||
* How much of the screen's width the sidebar takes away from app windows:
|
||||
* the strip, or nothing when the switcher is a bottom row or a popup or in
|
||||
* the full-panel mode (where the chrome paints the strip over the window
|
||||
* the strip, or nothing when the switcher is a bottom row or a popup or the
|
||||
* window is immersive (where the chrome paints the strip over the window
|
||||
* while the sidebar has focus).
|
||||
*/
|
||||
export function sidebarWidth(appId?: string): number {
|
||||
return !fullPanel(appId) && sideStrip() ? SIDEBAR_WIDTH : 0;
|
||||
return !isImmersive(appId) && sideStrip() ? SIDEBAR_WIDTH : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* How much of the screen's height a bottom switcher row takes away from app
|
||||
* windows: the row, or nothing beside a side strip or in the full-panel mode
|
||||
* (where the row overlays the window's bottom edge while it has focus).
|
||||
* How much of the screen's height a bottom switcher takes away from app
|
||||
* windows: its rows (one, or two when the layout needs them), or nothing
|
||||
* beside a side strip or under an immersive window (where the switcher
|
||||
* overlays the window's bottom edge while it has focus).
|
||||
*/
|
||||
export function switcherRowHeight(appId?: string): number {
|
||||
return !fullPanel(appId) && switcherPosition() === "bottom" ? SWITCHER_ROW_HEIGHT : 0;
|
||||
return !isImmersive(appId) && switcherPosition() === "bottom" ? switcherBarHeights.reserved : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the switcher is on screen: always when it reserves room; as a
|
||||
* popup, or in the full-panel mode (where it overlays the window), only
|
||||
* while it has focus.
|
||||
* popup, or over an immersive window, only while it has focus.
|
||||
*/
|
||||
export function sidebarStripVisible(focus: "sidebar" | "window", appId?: string): boolean {
|
||||
return (!fullPanel(appId) && switcherPosition() !== "popup") || focus === "sidebar";
|
||||
return (!isImmersive(appId) && switcherPosition() !== "popup") || focus === "sidebar";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,24 +159,26 @@ export function sidebarStripVisible(focus: "sidebar" | "window", appId?: string)
|
||||
* band (like the shell overlays). A bottom row sits right under the given
|
||||
* (foreground) window and spans its width, so a band shorter than the
|
||||
* screen has no gap below it; it moves when the foreground switches to a
|
||||
* window of another height, as the top bar does. In the full-panel mode the
|
||||
* row overlays the bottom edge of the screen. A popup's is the area it
|
||||
* centres in, the foreground window's content (the chrome layer sizes the
|
||||
* box itself).
|
||||
* window of another height, as the top bar does. Over an immersive window
|
||||
* the row overlays the bottom edge of the screen. Either way it is as tall
|
||||
* as its layout (setSwitcherBarHeight). A popup's is the area it centres
|
||||
* in, the foreground window's content (the chrome layer sizes the box
|
||||
* itself).
|
||||
*/
|
||||
export function switcherRect(heightMode: WindowHeightMode, appId?: string): { x: number; y: number; width: number; height: number } {
|
||||
switch (switcherPosition()) {
|
||||
case "popup":
|
||||
return appViewportRect(heightMode, appId);
|
||||
case "bottom":
|
||||
case "bottom": {
|
||||
const reserved = switcherRowHeight(appId);
|
||||
const height = reserved || switcherBarHeights.overlay;
|
||||
return {
|
||||
x: appViewportLeft(appId),
|
||||
y: switcherRowHeight(appId) > 0
|
||||
? windowTop(heightMode, appId) + windowBandHeight(heightMode, appId)
|
||||
: G2_LENS_HEIGHT - SWITCHER_ROW_HEIGHT,
|
||||
y: reserved > 0 ? windowTop(heightMode, appId) + windowBandHeight(heightMode, appId) : G2_LENS_HEIGHT - height,
|
||||
width: appViewportWidth(appId),
|
||||
height: SWITCHER_ROW_HEIGHT,
|
||||
height,
|
||||
};
|
||||
}
|
||||
case "right":
|
||||
return { x: G2_LENS_WIDTH - SIDEBAR_WIDTH, y: minWindowTop(appId), width: SIDEBAR_WIDTH, height: MIN_WINDOW_HEIGHT };
|
||||
default:
|
||||
@@ -126,9 +189,9 @@ export function switcherRect(heightMode: WindowHeightMode, appId?: string): { x:
|
||||
/**
|
||||
* Whether the foreground window's content gets a rounded frame (drawn by
|
||||
* the chrome layer). Its left and right sides take the pixel just outside
|
||||
* the 576-wide window; there's no room in the full-panel mode, nor need
|
||||
* beside a side strip. With a reserved bottom switcher row it always has
|
||||
* one: the row's top edge is the frame's bottom side, as the window
|
||||
* the 576-wide window; there's no room around a Full Screen or immersive
|
||||
* window, nor need beside a side strip. With a reserved bottom switcher row
|
||||
* it otherwise always has one: the row's top edge is the frame's bottom side, as the window
|
||||
* header's last row is its top. With a popup switcher it's the Window
|
||||
* border setting's choice, and its top and bottom take a header or footer
|
||||
* row of their own, except where the status bar's row next to the window
|
||||
@@ -137,9 +200,9 @@ export function switcherRect(heightMode: WindowHeightMode, appId?: string): { x:
|
||||
export function windowFramed(appId?: string): boolean {
|
||||
switch (switcherPosition()) {
|
||||
case "bottom":
|
||||
return switcherRowHeight(appId) > 0;
|
||||
return switcherRowHeight(appId) > 0 && !fullWidth(appId);
|
||||
case "popup":
|
||||
return !fullPanel(appId) && windowBorderSetting.get();
|
||||
return !fullWidth(appId) && windowBorderSetting.get();
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
@@ -148,7 +211,8 @@ export function windowFramed(appId?: string): boolean {
|
||||
/**
|
||||
* Whether the status bar shares the bottom switcher row instead of topping
|
||||
* each window (Settings > Customization > Status bar position): only beside
|
||||
* a reserved row, as the full-panel mode's row shows just while it has focus.
|
||||
* a reserved row, as the row over an immersive window shows just while it
|
||||
* has focus.
|
||||
*/
|
||||
export function statusInSwitcherRow(appId?: string): boolean {
|
||||
return switcherRowHeight(appId) > 0 && statusBarPositionSetting.get() === "bottom";
|
||||
@@ -176,11 +240,13 @@ export function statusBarOverlays(): boolean {
|
||||
* Rows the shell draws along one edge of each window's content: the status
|
||||
* bar's (the top bar, as a header), the frame's side, or none. A bottom
|
||||
* switcher row's band has no footer: the frame's bottom side is the row's
|
||||
* top edge.
|
||||
* top edge. An immersive window has neither.
|
||||
*/
|
||||
function windowEdgeHeight(edge: "top" | "bottom", appId?: string): number {
|
||||
if (isImmersive(appId)) return 0;
|
||||
if (switcherPosition() !== "popup") {
|
||||
return edge === "bottom" ? 0 : statusInSwitcherRow(appId) ? 1 : TOP_BAR_HEIGHT;
|
||||
if (edge === "bottom") return 0;
|
||||
return !statusInSwitcherRow(appId) ? TOP_BAR_HEIGHT : windowFramed(appId) ? 1 : 0;
|
||||
}
|
||||
if (!statusBarOverlays() && statusBarEdge() === edge) return TOP_BAR_HEIGHT;
|
||||
return windowFramed(appId) ? 1 : 0;
|
||||
@@ -233,9 +299,9 @@ export function isOnSwitcherEdge(x: number, y: number, heightMode: WindowHeightM
|
||||
}
|
||||
}
|
||||
|
||||
/** Width of app windows: the panel's in the full-panel mode, else 576 (see SIDEBAR_WIDTH). */
|
||||
/** Width of app windows: the panel's when Full Screen or immersive, else 576 (see SIDEBAR_WIDTH). */
|
||||
function appViewportWidth(appId?: string): number {
|
||||
return fullPanel(appId) ? G2_LENS_WIDTH : G2_LENS_WIDTH - SIDEBAR_WIDTH;
|
||||
return fullWidth(appId) ? G2_LENS_WIDTH : G2_LENS_WIDTH - SIDEBAR_WIDTH;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -244,7 +310,7 @@ function appViewportWidth(appId?: string): number {
|
||||
* edge.
|
||||
*/
|
||||
export function appViewportLeft(appId?: string): number {
|
||||
if (fullPanel(appId)) return 0;
|
||||
if (fullWidth(appId)) return 0;
|
||||
switch (switcherPosition()) {
|
||||
case "left":
|
||||
return SIDEBAR_WIDTH;
|
||||
@@ -261,18 +327,23 @@ export function appViewportLeft(appId?: string): number {
|
||||
* the firmware's depth units; the shell scene carries it to the compositor,
|
||||
* which shifts the screen and everything drawn over it per lens. Only with
|
||||
* the switcher at the bottom or a popup, where the windows' side margins,
|
||||
* less the window frame's pixel, leave room for the shift.
|
||||
* less the window frame's pixel, leave room for the shift; not while the
|
||||
* given (foreground) app's windows are Full Screen or immersive, which have
|
||||
* no margins.
|
||||
*/
|
||||
export function uiDepth(): number {
|
||||
return sideStrip() ? 0 : Number(uiDepthSetting.get());
|
||||
export function uiDepth(appId?: string): number {
|
||||
return sideStrip() || fullWidth(appId) ? 0 : Number(uiDepthSetting.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Explicit app sizes (including Use global) replace the requested height.
|
||||
* The default keeps legacy per-window heights, such as tall terminal sessions.
|
||||
* In a band display mode, explicit app modes (including Use global) replace
|
||||
* the requested height; the default keeps legacy per-window heights, such
|
||||
* as tall terminal sessions. Tall, Full Screen and immersive windows are
|
||||
* always the whole height.
|
||||
*/
|
||||
export function effectiveHeightMode(mode: WindowHeightMode, appId?: string): WindowHeightMode {
|
||||
return displayMode(appId) === "576x288" ? (appDisplayMode(appId) === "default" ? mode : "min") : "max";
|
||||
if (isImmersive(appId) || bandFraction(displayLayout(appId)) === undefined) return "max";
|
||||
return appDisplayLayout(appId) === "default" ? mode : "min";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -297,7 +368,7 @@ export const SHELL_OPAQUE_BLACK = 1;
|
||||
* firmware uses, leaving most of the field of view clear; "medium" is one
|
||||
* header (and footer) taller, so the content area between them is a full
|
||||
* 288px (the EvenHub app surface height); "max" uses the whole 480px screen
|
||||
* (terminal views), less a bottom switcher row. All include the header the
|
||||
* (terminal views), less a bottom switcher's rows. All include the header the
|
||||
* shell draws at the window's top edge (windowHeaderHeight) and any footer
|
||||
* at its bottom (windowFooterHeight).
|
||||
*/
|
||||
@@ -308,7 +379,7 @@ export const MIN_WINDOW_HEIGHT = 288;
|
||||
|
||||
/**
|
||||
* Height of the screen area windows are placed in: the whole screen, less
|
||||
* a bottom switcher row's height.
|
||||
* a bottom switcher's height.
|
||||
*/
|
||||
function windowAreaHeight(appId?: string): number {
|
||||
return G2_LENS_HEIGHT - switcherRowHeight(appId);
|
||||
@@ -327,25 +398,13 @@ export function windowBandHeight(mode: WindowHeightMode, appId?: string): number
|
||||
}
|
||||
|
||||
/**
|
||||
* Fraction of the slack above a window band, from the Display > Vertical
|
||||
* position setting: each band height distributes its own free space by the
|
||||
* same fraction, so all heights sit consistently within the screen.
|
||||
* Fraction of the slack above a window band, from the band display mode's
|
||||
* position: each band height distributes its own free space by the same
|
||||
* fraction, so all heights sit consistently within the screen. Tall and
|
||||
* Full Screen windows leave no slack.
|
||||
*/
|
||||
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":
|
||||
return 0.25;
|
||||
case "lower":
|
||||
return 0.75;
|
||||
case "bottom":
|
||||
return 1;
|
||||
default:
|
||||
return 0.5;
|
||||
}
|
||||
return bandFraction(displayLayout(appId)) ?? 0.5;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -358,11 +417,17 @@ export function minWindowTop(appId?: string): number {
|
||||
|
||||
/**
|
||||
* Top edge (y) of a window's header; max-height windows pin to the screen
|
||||
* top. A bottom switcher row hangs under the band, so the band and row
|
||||
* together distribute the screen's slack.
|
||||
* top. A bottom switcher row hangs under the band, so the band and a
|
||||
* one-row switcher together distribute the screen's slack. A switcher of
|
||||
* more rows takes its extra height out of the slack under it, pushing the
|
||||
* band up only as far as there is too little, so the band doesn't move as
|
||||
* the switcher's layout changes unless it has to.
|
||||
*/
|
||||
export function windowTop(mode: WindowHeightMode, appId?: string): number {
|
||||
return Math.round((windowAreaHeight(appId) - windowBandHeight(mode, appId)) * verticalPositionFraction(appId));
|
||||
const band = windowBandHeight(mode, appId);
|
||||
const oneRowArea = G2_LENS_HEIGHT - (switcherRowHeight(appId) > 0 ? SWITCHER_ROW_HEIGHT : 0);
|
||||
const top = Math.round((oneRowArea - band) * verticalPositionFraction(appId));
|
||||
return Math.min(top, windowAreaHeight(appId) - band);
|
||||
}
|
||||
|
||||
/** App-content viewport size for a height mode (independent of vertical position). */
|
||||
@@ -386,3 +451,55 @@ export function appViewportRect(mode: WindowHeightMode, appId?: string): {
|
||||
...appViewportSize(mode, appId),
|
||||
};
|
||||
}
|
||||
|
||||
export type ScreenRect = { x: number; y: number; width: number; height: number };
|
||||
|
||||
function unionRect(a: ScreenRect, b: ScreenRect): ScreenRect {
|
||||
const x = Math.min(a.x, b.x);
|
||||
const y = Math.min(a.y, b.y);
|
||||
return {
|
||||
x,
|
||||
y,
|
||||
width: Math.max(a.x + a.width, b.x + b.width) - x,
|
||||
height: Math.max(a.y + a.height, b.y + b.height) - y,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The part of the screen the shell draws in while the given (foreground)
|
||||
* window is up: the window's band, plus the frame's side pixels; the
|
||||
* min-height band the shell overlays align to; and a side strip or bottom
|
||||
* row (a popup shows within the window's content). An immersive window has
|
||||
* the whole panel. The phone mirror's Scaled preview zooms to this.
|
||||
*/
|
||||
export function usedScreenRect(heightMode: WindowHeightMode, appId?: string): ScreenRect {
|
||||
if (isImmersive(appId)) return { x: 0, y: 0, width: G2_LENS_WIDTH, height: G2_LENS_HEIGHT };
|
||||
const frame = windowFramed(appId) ? 1 : 0;
|
||||
const x = appViewportLeft(appId) - frame;
|
||||
const width = appViewportWidth(appId) + 2 * frame;
|
||||
let used = unionRect(
|
||||
{ x, y: windowTop(heightMode, appId), width, height: windowBandHeight(heightMode, appId) },
|
||||
{ x, y: minWindowTop(appId), width, height: MIN_WINDOW_HEIGHT },
|
||||
);
|
||||
if (switcherPosition() !== "popup") used = unionRect(used, switcherRect(heightMode, appId));
|
||||
return used;
|
||||
}
|
||||
|
||||
/**
|
||||
* The screen area the phone mirror shows to present `used` as large as it
|
||||
* fits, centred, at the panel's own 4:3 aspect (so the mirror keeps its
|
||||
* shape whatever the display mode): `used` grown along one axis, past the
|
||||
* panel's edges if need be (the mirror shows black there).
|
||||
*/
|
||||
export function phonePreviewRect(used: ScreenRect): ScreenRect {
|
||||
// Whole 4:3 units, so the aspect is exact.
|
||||
const units = Math.ceil(Math.max(used.width / 4, used.height / 3));
|
||||
const width = units * 4;
|
||||
const height = units * 3;
|
||||
return {
|
||||
x: Math.round(used.x + (used.width - width) / 2),
|
||||
y: Math.round(used.y + (used.height - height) / 2),
|
||||
width,
|
||||
height,
|
||||
};
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import { type MenuItem } from "../menu";
|
||||
import { WindowMenuLayer } from "../window-menu";
|
||||
import { windowIcon } from "./chrome-layer";
|
||||
import { type IconName } from "../../graphics/icons";
|
||||
import { appViewportSize, type WindowHeightMode } from "./geometry";
|
||||
import { appViewportSize, setAppImmersive, type WindowHeightMode } from "./geometry";
|
||||
import { shell, type ShellWindow } from "./shell";
|
||||
|
||||
/**
|
||||
@@ -30,6 +30,8 @@ export type InProcessWindowOptions = {
|
||||
closeable: boolean;
|
||||
/** Window height: the standard 288px band ("min", default) or full screen ("max"). */
|
||||
heightMode?: WindowHeightMode;
|
||||
/** Open immersive: the whole panel, without the status bar (see geometry.ts isImmersive). */
|
||||
immersive?: boolean;
|
||||
/**
|
||||
* The window's tap-then-hold context menu: app-specific entries only (the
|
||||
* shared Focus app switcher / Voice input / Close window entries live in
|
||||
@@ -73,6 +75,12 @@ export type InProcessWindow = {
|
||||
requestRender: () => void;
|
||||
/** Change the window's height band at runtime (resizes the viewport + surface). */
|
||||
setHeightMode: (mode: WindowHeightMode) => void;
|
||||
/**
|
||||
* Enter or leave immersive mode at runtime (resizes the viewport +
|
||||
* surface). It is per app (geometry.ts isImmersive), so an app with several
|
||||
* windows switches them all.
|
||||
*/
|
||||
setImmersive: (immersive: boolean) => void;
|
||||
};
|
||||
|
||||
/** The controller-provided plumbing common to every in-process app window. */
|
||||
@@ -102,10 +110,12 @@ export function createInProcessWindow(options: InProcessWindowOptions): InProces
|
||||
// Handed to app code as a bare callback, so it takes no arguments.
|
||||
const requestRender = () => renderInNewFrame(0);
|
||||
let heightMode = options.heightMode ?? "min";
|
||||
setAppImmersive(options.appId, options.immersive ?? false);
|
||||
const viewportSize = () => appViewportSize(heightMode, options.appId);
|
||||
const stack = new LayerStack(
|
||||
options.baseLayer,
|
||||
{ ...options.actions, requestRender },
|
||||
appViewportSize(heightMode),
|
||||
viewportSize(),
|
||||
() => shell.isWindowFocused(options.windowId),
|
||||
);
|
||||
|
||||
@@ -172,6 +182,7 @@ export function createInProcessWindow(options: InProcessWindowOptions): InProces
|
||||
hasAppMenu: () => appMenuItems().length > 0,
|
||||
close: () => {
|
||||
closed = true;
|
||||
setAppImmersive(options.appId, false);
|
||||
// Fire onRemoved for any pushed layers so they release resources (e.g. a
|
||||
// demo that enabled a hardware stream) even when closed from within.
|
||||
stack.clearToBase();
|
||||
@@ -210,7 +221,7 @@ export function createInProcessWindow(options: InProcessWindowOptions): InProces
|
||||
},
|
||||
requestRender,
|
||||
relayout: () => {
|
||||
stack.setBaseSize(appViewportSize(heightMode));
|
||||
stack.setBaseSize(viewportSize());
|
||||
options.reconfigureSurface?.(heightMode);
|
||||
requestRender();
|
||||
},
|
||||
@@ -226,15 +237,21 @@ export function createInProcessWindow(options: InProcessWindowOptions): InProces
|
||||
options.onForegroundChanged?.(foreground);
|
||||
},
|
||||
};
|
||||
const resize = () => {
|
||||
stack.setBaseSize(viewportSize());
|
||||
options.reconfigureSurface?.(heightMode);
|
||||
requestRender();
|
||||
};
|
||||
const setHeightMode = (mode: WindowHeightMode) => {
|
||||
if (heightMode === mode) return;
|
||||
heightMode = mode;
|
||||
window.heightMode = mode;
|
||||
stack.setBaseSize(appViewportSize(mode));
|
||||
options.reconfigureSurface?.(mode);
|
||||
requestRender();
|
||||
resize();
|
||||
};
|
||||
return { window, stack, requestRender, setHeightMode };
|
||||
const setImmersive = (immersive: boolean) => {
|
||||
if (!closed && setAppImmersive(options.appId, immersive)) resize();
|
||||
};
|
||||
return { window, stack, requestRender, setHeightMode, setImmersive };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -74,6 +74,17 @@ export class NotificationModalQueue<M> {
|
||||
this.openNext(current.wokeScreen);
|
||||
}
|
||||
|
||||
/**
|
||||
* The notification went away on the phone (its source cancelled it, or it
|
||||
* was dismissed there). Drops it from the queue, and returns the open modal
|
||||
* if that is the one showing it, for the host to close (via closed()).
|
||||
*/
|
||||
withdrawn(notificationKey: string): M | null {
|
||||
const index = this.queued.findIndex((entry) => entry.notificationKey === notificationKey);
|
||||
if (index >= 0) this.queued.splice(index, 1);
|
||||
return this.current?.notificationKey === notificationKey ? this.current.modal : null;
|
||||
}
|
||||
|
||||
/** Notifications waiting behind the open modal (for diagnostics and tests). */
|
||||
queuedKeys(): string[] {
|
||||
return this.queued.map((entry) => entry.notificationKey);
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* Holds each newly posted notification back briefly before it pops up on the
|
||||
* glasses, so one that its source withdraws right away never shows (nor wakes
|
||||
* the screen). Google Messages, for one, posts a "Messages is working in the
|
||||
* background" foreground-service notification whenever it handles an incoming
|
||||
* message or a background sync, then cancels it a second or two later, after
|
||||
* posting the message's own notification under a different key (if any).
|
||||
*/
|
||||
|
||||
/** Delay for ordinary notifications: enough to skip one withdrawn or replaced as soon as it is posted. */
|
||||
export const NOTIFICATION_POPUP_DELAY_MS = 500;
|
||||
/**
|
||||
* Delay for foreground-service notifications. They are "app is working"
|
||||
* status, often gone within seconds; Android itself defers showing them for
|
||||
* 10s for the same reason. Messages' lasts up to ~2s (Pixel usage-stats timings).
|
||||
*/
|
||||
export const FOREGROUND_SERVICE_POPUP_DELAY_MS = 5000;
|
||||
|
||||
/** Categories that must pop up promptly even from a foreground service (an incoming call, a ringing alarm). */
|
||||
const URGENT_CATEGORIES = new Set(["call", "alarm"]);
|
||||
|
||||
export function notificationPopupDelayMs(notification: { foregroundService?: boolean; category: string }): number {
|
||||
return notification.foregroundService && !URGENT_CATEGORIES.has(notification.category)
|
||||
? FOREGROUND_SERVICE_POPUP_DELAY_MS : NOTIFICATION_POPUP_DELAY_MS;
|
||||
}
|
||||
|
||||
/** Runs `run` after `delayMs`; returns a function that cancels it. */
|
||||
export type ScheduleFn = (run: () => void, delayMs: number) => () => void;
|
||||
|
||||
const scheduleTimeout: ScheduleFn = (run, delayMs) => {
|
||||
const timer = setTimeout(run, delayMs);
|
||||
return () => clearTimeout(timer);
|
||||
};
|
||||
|
||||
export class NotificationPopupDelay {
|
||||
private readonly pending = new Map<string, { dueAtMs: number; cancel: () => void }>();
|
||||
|
||||
/** `ready` receives each notification that survived its delay, to re-check and pop up. */
|
||||
constructor(
|
||||
private readonly ready: (notificationKey: string) => void,
|
||||
private readonly schedule: ScheduleFn = scheduleTimeout,
|
||||
private readonly now: () => number = Date.now,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* A notification was posted, to pop up after `delayMs`. A repost while it
|
||||
* waits can only bring the popup forward: a notification its source keeps
|
||||
* updating is not held back indefinitely, and one rewritten from a
|
||||
* foreground-service placeholder into a real message (same key) gets the
|
||||
* shorter delay.
|
||||
*/
|
||||
post(notificationKey: string, delayMs: number): void {
|
||||
const dueAtMs = this.now() + delayMs;
|
||||
const existing = this.pending.get(notificationKey);
|
||||
if (existing) {
|
||||
if (existing.dueAtMs <= dueAtMs) return;
|
||||
existing.cancel();
|
||||
}
|
||||
const cancel = this.schedule(() => {
|
||||
this.pending.delete(notificationKey);
|
||||
this.ready(notificationKey);
|
||||
}, delayMs);
|
||||
this.pending.set(notificationKey, { dueAtMs, cancel });
|
||||
}
|
||||
|
||||
/** The notification went away before popping up; returns whether it was waiting. */
|
||||
withdraw(notificationKey: string): boolean {
|
||||
const existing = this.pending.get(notificationKey);
|
||||
if (!existing) return false;
|
||||
existing.cancel();
|
||||
this.pending.delete(notificationKey);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Notifications waiting out their delay (for diagnostics and tests). */
|
||||
pendingKeys(): string[] {
|
||||
return Array.from(this.pending.keys());
|
||||
}
|
||||
}
|
||||
+309
-140
@@ -31,6 +31,8 @@ import type { AssistantContext } from "../../assistant/types";
|
||||
import { SingleNotificationLayer } from "../notifications";
|
||||
import {
|
||||
anthropicApiKeySetting,
|
||||
assistantHermesKeySetting,
|
||||
assistantHermesUrlSetting,
|
||||
assistantBackendSetting,
|
||||
assistantBridgeHostSetting,
|
||||
assistantBridgePortSetting,
|
||||
@@ -45,10 +47,18 @@ import {
|
||||
statusBarVisibilitySetting,
|
||||
timeFormatSetting,
|
||||
wakeWordActionSetting,
|
||||
wakeToLastAppSetting,
|
||||
windowBorderSetting,
|
||||
} from "../dashboard-settings";
|
||||
import { onAmbientCardsChanged } from "./ambient-cards";
|
||||
import { ShellChromeLayer, sidebarContentSpan, type ShellChromeState, type ShellChromeWindow } from "./chrome-layer";
|
||||
import {
|
||||
sameStatusItem,
|
||||
ShellChromeLayer,
|
||||
sidebarContentSpan,
|
||||
type ShellChromeState,
|
||||
type ShellChromeWindow,
|
||||
type StatusItem,
|
||||
} from "./chrome-layer";
|
||||
import { ShellModalLayer } from "./modal-layer";
|
||||
import { NotificationModalQueue } from "./notification-modal-queue";
|
||||
import { ALL_NOTIFICATIONS, readActiveNotifications } from "../../native/notification-icons";
|
||||
@@ -143,9 +153,10 @@ export type ShellWindow = {
|
||||
/** Repaint and resubmit this window's surface. */
|
||||
requestRender: () => void;
|
||||
/**
|
||||
* Re-measure against the current display mode (viewport size / band) and
|
||||
* repaint. Windows without it (workers with a canvas fixed at open) are
|
||||
* closed and relaunched by the controller instead.
|
||||
* Re-measure against the current display mode and app switcher (viewport
|
||||
* size / band) and repaint. Windows without it are closed and relaunched
|
||||
* by the controller instead on a display mode change, and left at the size
|
||||
* they opened with when the bottom switcher changes height.
|
||||
*/
|
||||
relayout?: () => void;
|
||||
/**
|
||||
@@ -201,6 +212,12 @@ export type ShellConfig = {
|
||||
onScreenStateChanged: (on: boolean) => void;
|
||||
/** Window registered/removed or foreground changed (persists the open-app list). */
|
||||
onWindowsChanged?: () => void;
|
||||
/**
|
||||
* The bottom switcher's layout changed its height (geometry.ts
|
||||
* setSwitcherBarHeight): windows have to move, or resize, to suit. Called
|
||||
* after the shell paint that found it.
|
||||
*/
|
||||
onSwitcherBarHeightChanged?: () => void;
|
||||
/**
|
||||
* The Notifications app's window, opened in the background (neither
|
||||
* foregrounded nor focused) unless it is open already, for the switcher
|
||||
@@ -211,21 +228,44 @@ export type ShellConfig = {
|
||||
};
|
||||
|
||||
/**
|
||||
* The app switcher's selection while it is on a notification's icon rather
|
||||
* than a window's (bottom switcher only; see Shell.moveSelection). The
|
||||
* Notifications app's window is the foreground window meanwhile, with the
|
||||
* notification's detail view on top of its stack.
|
||||
* What makes an app's tray icon (see Shell.setTrayIcon) a widget the app
|
||||
* switcher's selection can move onto, as it can onto a notification's icon
|
||||
* (bottom switcher only; see Shell.moveSelection).
|
||||
*/
|
||||
type NotificationSelection = {
|
||||
key: string;
|
||||
/** Where the notification's icon sat among them, for once it has gone. */
|
||||
index: number;
|
||||
host: InProcessWindow;
|
||||
layer: SingleNotificationLayer;
|
||||
export type TrayWidget = {
|
||||
/**
|
||||
* The Notifications window was opened for the selection: it has no
|
||||
* switcher icon of its own, and closes once the selection moves off the
|
||||
* notifications.
|
||||
* The window to show while the selection is on the widget, opened in the
|
||||
* background (neither foregrounded nor focused) unless it is open
|
||||
* already; `opened` says this call opened it, and the shell closes it
|
||||
* again once the selection moves on. Null when it can't be opened.
|
||||
*/
|
||||
openWindow: () => { window: ShellWindow; opened: boolean } | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* A new-notification popup: the shell modal, and the notification view inside
|
||||
* it (null for an app notification, which brings its own layer).
|
||||
*/
|
||||
type NotificationPopup = { modal: ShellModalLayer; content: SingleNotificationLayer | null };
|
||||
|
||||
/**
|
||||
* The app switcher's selection while it is on a status bar item rather than
|
||||
* a window's icon (bottom switcher only; see Shell.moveSelection): a
|
||||
* notification's icon or an app widget. The item's window is the
|
||||
* foreground window meanwhile: a notification's is the Notifications app's,
|
||||
* with the notification's detail view on top of its stack; a widget's is
|
||||
* whatever window it gives (TrayWidget.openWindow).
|
||||
*/
|
||||
type StatusSelection = {
|
||||
item: StatusItem;
|
||||
/** Where the item sat among the selectable ones, for once it has gone. */
|
||||
index: number;
|
||||
host: ShellWindow;
|
||||
/** A notification's detail view, and the host's stack it is on. */
|
||||
detail: { stack: LayerStack; layer: SingleNotificationLayer } | null;
|
||||
/**
|
||||
* The host window was opened for the selection: it has no switcher icon
|
||||
* of its own, and closes once the selection moves off it.
|
||||
*/
|
||||
transient: boolean;
|
||||
/** The window selected before, to go back to when the screen sleeps. */
|
||||
@@ -248,6 +288,18 @@ export type AssistantActivityEvent = {
|
||||
|
||||
export type FocusKind = "sidebar" | "window";
|
||||
|
||||
/**
|
||||
* A notification an app posts itself, rather than one Android posted. It
|
||||
* opens in the same modal (and waits in the same queue) as Android
|
||||
* notifications, but is not listed in the Notifications app.
|
||||
*/
|
||||
export type AppNotification = {
|
||||
/** Unique per notification; must not collide with Android notification keys. */
|
||||
key: string;
|
||||
/** The modal's content; `close` takes the modal down. */
|
||||
createLayer: (close: () => void) => Layer;
|
||||
};
|
||||
|
||||
const noopActions: LayerActions = noopLayerActions;
|
||||
|
||||
/**
|
||||
@@ -271,7 +323,7 @@ class ShellOverlayMenuLayer extends MenuLayer {
|
||||
// Aligned to the min-height window band (like the sidebar), wherever the
|
||||
// vertical position setting currently puts it; centered over the
|
||||
// application area, i.e. the part of the screen beside a side strip
|
||||
// (the whole width with a bottom row, or in the full-panel mode, where
|
||||
// (the whole width with a bottom row, or over an immersive window, where
|
||||
// the strip overlays).
|
||||
const width = 272;
|
||||
const area = appViewportRect("min");
|
||||
@@ -394,17 +446,21 @@ class Shell {
|
||||
private battery: ShellChromeState["battery"] = {
|
||||
headset: null, headsetCharging: null, ring: null, ringCharging: null, watch: null, watchCharging: null,
|
||||
};
|
||||
private readonly batteryListeners = new Set<() => void>();
|
||||
private attention = new Map<string, boolean>();
|
||||
/** Set while the switcher's selection is on a notification (see NotificationSelection). */
|
||||
private selectedNotification: NotificationSelection | null = null;
|
||||
/** Set while the switcher's selection is on a status bar item (see StatusSelection). */
|
||||
private selectedStatus: StatusSelection | null = null;
|
||||
// App-provided top-bar tray icons, keyed by owner id; drawn between the
|
||||
// notification icons and the battery indicators.
|
||||
private readonly trayIcons = new Map<string, GrayImage>();
|
||||
private readonly trayIcons = new Map<string, { icon: GrayImage; widget?: TrayWidget }>();
|
||||
private activeVoiceLayer: VoiceInputLayer | null = null;
|
||||
private activeKeyboardLayer: KeyboardInputLayer | null = null;
|
||||
private readonly notificationModals = new NotificationModalQueue<ShellModalLayer>({
|
||||
// App-posted notifications that are open or queued, by key.
|
||||
private readonly appNotifications = new Map<string, AppNotification>();
|
||||
private readonly notificationModals = new NotificationModalQueue<NotificationPopup>({
|
||||
open: (notificationKey) => this.pushNotificationModal(notificationKey),
|
||||
isAvailable: (notificationKey) => {
|
||||
if (this.appNotifications.has(notificationKey)) return true;
|
||||
const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === notificationKey);
|
||||
return !!notification && shouldShowNotificationOnGlasses(notification.packageName);
|
||||
},
|
||||
@@ -444,8 +500,9 @@ class Shell {
|
||||
requestShellRender: () => {},
|
||||
onScreenStateChanged: () => {},
|
||||
};
|
||||
private readonly chrome = new ShellChromeLayer(() => this.chromeState());
|
||||
private readonly chrome = new ShellChromeLayer(() => this.chromeState(), () => this.switcherBarHeightChanged());
|
||||
private readonly stack = new LayerStack(this.chrome, this.actions);
|
||||
private switcherBarChangePending = false;
|
||||
|
||||
// Top-bar settings we mirror into the chrome; a change to any of them
|
||||
// repaints the shell surface so the top bar reflects it immediately.
|
||||
@@ -493,6 +550,21 @@ class Shell {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The chrome found, mid-paint, that the bottom switcher's height changed.
|
||||
* The controller moves or resizes windows once the paint is over: a
|
||||
* window's relayout repaints it, which mustn't happen inside the shell's
|
||||
* own paint.
|
||||
*/
|
||||
private switcherBarHeightChanged(): void {
|
||||
if (this.switcherBarChangePending) return;
|
||||
this.switcherBarChangePending = true;
|
||||
setTimeout(() => {
|
||||
this.switcherBarChangePending = false;
|
||||
this.config.onSwitcherBarHeightChanged?.();
|
||||
}, 0);
|
||||
}
|
||||
|
||||
/** Add a window (or replace one with the same windowId, keeping its slot). */
|
||||
registerWindow(window: ShellWindow): void {
|
||||
const existing = this.windows.findIndex((w) => w.windowId === window.windowId);
|
||||
@@ -524,9 +596,9 @@ class Shell {
|
||||
removeWindow(windowId: string): void {
|
||||
const index = this.windows.findIndex((w) => w.windowId === windowId);
|
||||
if (index < 0) return;
|
||||
// Closing the Notifications window under a selected notification (from
|
||||
// the system menu) takes the selection with it.
|
||||
if (this.selectedNotification?.host.window.windowId === windowId) this.selectedNotification = null;
|
||||
// Closing the window under a selected status bar item (from the system
|
||||
// menu) takes the selection with it.
|
||||
if (this.selectedStatus?.host.windowId === windowId) this.selectedStatus = null;
|
||||
const wasSelected = index === this.selectedIndex;
|
||||
this.windows.splice(index, 1);
|
||||
this.attention.delete(windowId);
|
||||
@@ -584,20 +656,38 @@ class Shell {
|
||||
}
|
||||
|
||||
setBatteryLevels(levels: Partial<ShellChromeState["battery"]>): void {
|
||||
this.battery = { ...this.battery, ...levels };
|
||||
const next = { ...this.battery, ...levels };
|
||||
const keys = Object.keys(next) as (keyof ShellChromeState["battery"])[];
|
||||
if (keys.every((key) => next[key] === this.battery[key])) return;
|
||||
this.battery = next;
|
||||
for (const listener of Array.from(this.batteryListeners)) listener();
|
||||
}
|
||||
|
||||
/** Called after any battery level or charging state changes. Returns an unsubscribe function. */
|
||||
onBatteryLevelsChanged(listener: () => void): () => void {
|
||||
this.batteryListeners.add(listener);
|
||||
return () => {
|
||||
this.batteryListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Set or clear an app's top-bar tray icon (a small grayscale image, drawn
|
||||
* between the notification icons and the battery indicators). Small and
|
||||
* infrequently updated by design; not a framebuffer.
|
||||
* infrequently updated by design; not a framebuffer. With `widget`, the
|
||||
* switcher's selection can move onto it. A widget that goes, or stops
|
||||
* being one, while the selection is on it leaves the selection on its
|
||||
* window, as an ordinary window.
|
||||
*/
|
||||
setTrayIcon(ownerId: string, icon: GrayImage | null): void {
|
||||
setTrayIcon(ownerId: string, icon: GrayImage | null, widget?: TrayWidget): void {
|
||||
if (icon) {
|
||||
this.trayIcons.set(ownerId, icon);
|
||||
this.trayIcons.set(ownerId, { icon, widget });
|
||||
} else if (!this.trayIcons.delete(ownerId)) {
|
||||
return;
|
||||
}
|
||||
if ((!icon || !widget) && sameStatusItem(this.selectedStatus?.item, { kind: "widget", key: ownerId })) {
|
||||
this.endStatusSelection(true);
|
||||
}
|
||||
this.config.requestShellRender();
|
||||
}
|
||||
|
||||
@@ -642,16 +732,19 @@ class Shell {
|
||||
}
|
||||
|
||||
/**
|
||||
* A touch from the phone's mirror on a selectable notification's icon:
|
||||
* select it and go into its detail view, as a touch on a window's icon
|
||||
* focuses that window. False when there is no such icon at (x, y).
|
||||
* A touch from the phone's mirror on a selectable status bar item's icon
|
||||
* (a notification's or an app widget's): select it and go into its
|
||||
* window, as a touch on a window's icon focuses that window. False when
|
||||
* there is no such icon at (x, y).
|
||||
*/
|
||||
focusNotificationAt(x: number, y: number): boolean {
|
||||
const keys = this.selectableNotificationKeys();
|
||||
const key = this.chrome.notificationKeyAt(x, y);
|
||||
if (!key || !keys.includes(key)) return false;
|
||||
this.selectNotification(key, keys.indexOf(key));
|
||||
const host = this.selectedNotification?.key === key ? this.selectedNotification.host.window : null;
|
||||
focusStatusItemAt(x: number, y: number): boolean {
|
||||
const items = this.selectableStatusItems();
|
||||
const touched = this.chrome.statusItemAt(x, y);
|
||||
const index = items.findIndex((item) => sameStatusItem(item, touched));
|
||||
if (index < 0) return false;
|
||||
this.selectStatusItem(items[index]!, index);
|
||||
const selected = this.selectedStatus;
|
||||
const host = selected && sameStatusItem(selected.item, touched) ? selected.host : null;
|
||||
if (!host) return false;
|
||||
const alreadyFocused = this.isFocusTarget(host);
|
||||
this.focus = "window";
|
||||
@@ -719,11 +812,11 @@ class Shell {
|
||||
|
||||
/**
|
||||
* Turn the screen off, closing any shell overlays. Sidebar selection is
|
||||
* kept, except that one on a notification goes back to its window.
|
||||
* kept, except that one on a status bar item goes back to its window.
|
||||
*/
|
||||
sleep(): void {
|
||||
if (!this.screenOn) return;
|
||||
this.returnFromNotification();
|
||||
this.returnFromStatusItem();
|
||||
this.cancelEscapeMenuTimer();
|
||||
this.screenOn = false;
|
||||
this.stack.clearToBase();
|
||||
@@ -741,9 +834,9 @@ class Shell {
|
||||
const target = this.windows[index];
|
||||
const alreadyFocused = this.isFocusTarget(target);
|
||||
this.setSelectedIndex(index);
|
||||
// Asked for by id, the Notifications window stays, whether or not it
|
||||
// was opened for a selected notification.
|
||||
this.endNotificationSelection(target === this.selectedNotification?.host.window);
|
||||
// Asked for by id, a status bar item's window stays, whether or not it
|
||||
// was opened for the selection.
|
||||
this.endStatusSelection(target === this.selectedStatus?.host);
|
||||
this.focus = "window";
|
||||
if (!alreadyFocused) target?.onFocus?.(this.lastInput);
|
||||
this.syncInputFocus();
|
||||
@@ -784,25 +877,59 @@ class Shell {
|
||||
this.config.requestShellRender();
|
||||
}
|
||||
|
||||
private pushNotificationModal(notificationKey: string): ShellModalLayer {
|
||||
const modal: ShellModalLayer = new ShellModalLayer(
|
||||
new SingleNotificationLayer(notificationKey, {
|
||||
origin: "new-notification-modal",
|
||||
onClose: () => this.closeNotificationModal(modal),
|
||||
}),
|
||||
this.config.actions,
|
||||
() => this.notificationModals.removed(modal, this.screenOn),
|
||||
);
|
||||
this.stack.push(modal);
|
||||
return modal;
|
||||
/**
|
||||
* A notification went away on the phone: cancelled by its source (e.g. a
|
||||
* placeholder replaced moments later by the real notification under another
|
||||
* key), or dismissed. A popup queued for it is dropped, and one showing it
|
||||
* closes so the next one opens, as if the user had closed it -- unless it
|
||||
* is asking to confirm turning off its source, which outlives the
|
||||
* notification it dismissed.
|
||||
*/
|
||||
notificationRemoved(notificationKey: string): void {
|
||||
const popup = this.notificationModals.withdrawn(notificationKey);
|
||||
if (popup && !popup.content?.outlivesNotification()) {
|
||||
this.closeNotificationModal(popup, notificationKey);
|
||||
}
|
||||
}
|
||||
|
||||
private closeNotificationModal(modal: ShellModalLayer): void {
|
||||
/**
|
||||
* Show an app's own notification the way new Android notifications are
|
||||
* shown: in the notification modal, waking the screen for it if it was off.
|
||||
*/
|
||||
postAppNotification(notification: AppNotification): void {
|
||||
this.appNotifications.set(notification.key, notification);
|
||||
const wokeScreen = this.screenOn ? false : this.wake("sidebar");
|
||||
this.openNotificationModal(notification.key, wokeScreen);
|
||||
}
|
||||
|
||||
private pushNotificationModal(notificationKey: string): NotificationPopup {
|
||||
const appNotification = this.appNotifications.get(notificationKey);
|
||||
const close = () => this.closeNotificationModal(popup, notificationKey);
|
||||
const content = appNotification
|
||||
? null
|
||||
: new SingleNotificationLayer(notificationKey, { origin: "new-notification-modal", onClose: close });
|
||||
const popup: NotificationPopup = {
|
||||
content,
|
||||
modal: new ShellModalLayer(
|
||||
appNotification ? appNotification.createLayer(close) : content!,
|
||||
this.config.actions,
|
||||
() => {
|
||||
this.appNotifications.delete(notificationKey);
|
||||
this.notificationModals.removed(popup, this.screenOn);
|
||||
},
|
||||
),
|
||||
};
|
||||
this.stack.push(popup.modal);
|
||||
return popup;
|
||||
}
|
||||
|
||||
private closeNotificationModal(popup: NotificationPopup, notificationKey: string): void {
|
||||
this.appNotifications.delete(notificationKey);
|
||||
// The queue first: it opens the next notification or puts the screen back
|
||||
// to sleep, and then ignores the removal below. remove() rather than a
|
||||
// pop, so a menu opened over the modal doesn't leave it stuck.
|
||||
this.notificationModals.closed(modal);
|
||||
this.stack.remove(modal);
|
||||
this.notificationModals.closed(popup);
|
||||
this.stack.remove(popup.modal);
|
||||
this.config.requestShellRender();
|
||||
}
|
||||
|
||||
@@ -818,10 +945,13 @@ class Shell {
|
||||
|
||||
/**
|
||||
* Paint the shell surface: transparent chrome, or all-transparent when
|
||||
* asleep. The scene also carries the whole display's stereo depth.
|
||||
* asleep. The scene also carries the whole display's stereo depth (none
|
||||
* under a Full Screen or immersive window).
|
||||
*/
|
||||
paintScene(): Uint8Array {
|
||||
return this.screenOn ? encodeShellScene(this.stack.paintUndimmed(), uiDepth()) : encodeShellScene([]);
|
||||
return this.screenOn
|
||||
? encodeShellScene(this.stack.paintUndimmed(), uiDepth(this.foregroundWindow()?.appId))
|
||||
: encodeShellScene([]);
|
||||
}
|
||||
|
||||
paintSurface(): Plane[] {
|
||||
@@ -876,7 +1006,7 @@ class Shell {
|
||||
// "wake". Keep that directionality if delivery is delayed or duplicated.
|
||||
if (event.type === "display-wake") {
|
||||
this.lastInputAtMs = Date.now();
|
||||
const wokeScreen = !this.screenOn && this.wake("sidebar");
|
||||
const wokeScreen = !this.screenOn && this.wake(this.userWakeFocus());
|
||||
return { shell: wokeScreen, window: false };
|
||||
}
|
||||
|
||||
@@ -915,7 +1045,7 @@ class Shell {
|
||||
|
||||
if (!this.screenOn) {
|
||||
if (event.type === "double-click") {
|
||||
this.wake("sidebar");
|
||||
this.wake(this.userWakeFocus());
|
||||
return { shell: true, window: false };
|
||||
}
|
||||
return { shell: false, window: false };
|
||||
@@ -1018,6 +1148,11 @@ class Shell {
|
||||
return { shell: false, window: false };
|
||||
}
|
||||
|
||||
/** Where a user's double-tap wake lands: the last app, or the switcher (setting). */
|
||||
userWakeFocus(): FocusKind {
|
||||
return wakeToLastAppSetting.get() && this.foregroundWindow() ? "window" : "sidebar";
|
||||
}
|
||||
|
||||
foregroundWindow(): ShellWindow | undefined {
|
||||
return this.windows[this.selectedIndex] ?? this.windows[0];
|
||||
}
|
||||
@@ -1125,115 +1260,143 @@ class Shell {
|
||||
|
||||
/**
|
||||
* Step the switcher's selection through the windows and then, with a
|
||||
* bottom switcher, on through the notifications whose icons are showing,
|
||||
* wrapping round at either end.
|
||||
* bottom switcher, on through the status bar's selectable items whose
|
||||
* icons are showing (notifications, then app widgets), wrapping round at
|
||||
* either end.
|
||||
*/
|
||||
private moveSelection(delta: number): void {
|
||||
const windows = this.switcherWindows();
|
||||
const keys = this.selectableNotificationKeys();
|
||||
const count = windows.length + keys.length;
|
||||
const items = this.selectableStatusItems();
|
||||
const count = windows.length + items.length;
|
||||
if (!count) return;
|
||||
let current = this.selectedIndex;
|
||||
const selected = this.selectedNotification;
|
||||
const selected = this.selectedStatus;
|
||||
if (selected) {
|
||||
// Once its notification has gone, the selection stands between the
|
||||
// Once its item has gone, the selection stands between the
|
||||
// neighbours it left.
|
||||
const at = keys.indexOf(selected.key);
|
||||
current = windows.length + (at >= 0 ? at : Math.min(selected.index, keys.length) - (delta > 0 ? 1 : 0));
|
||||
const at = items.findIndex((item) => sameStatusItem(item, selected.item));
|
||||
current = windows.length + (at >= 0 ? at : Math.min(selected.index, items.length) - (delta > 0 ? 1 : 0));
|
||||
}
|
||||
const next = (((current + delta) % count) + count) % count;
|
||||
if (next < windows.length) {
|
||||
this.selectSwitcherWindow(windows[next]!);
|
||||
} else {
|
||||
this.selectNotification(keys[next - windows.length]!, next - windows.length);
|
||||
this.selectStatusItem(items[next - windows.length]!, next - windows.length);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Windows with an icon in the switcher: all of them, except a
|
||||
* Notifications window opened just to show a selected notification.
|
||||
* Windows with an icon in the switcher: all of them, except a window
|
||||
* opened just to show a selected status bar item.
|
||||
*/
|
||||
private switcherWindows(): ShellWindow[] {
|
||||
const hidden = this.selectedNotification?.transient ? this.selectedNotification.host.window : null;
|
||||
const hidden = this.selectedStatus?.transient ? this.selectedStatus.host : null;
|
||||
return hidden ? this.windows.filter((window) => window !== hidden) : this.windows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keys of the notifications the switcher's selection can move onto, left
|
||||
* to right: those whose icons are showing, with a bottom switcher (the
|
||||
* selection reaches them past the last window).
|
||||
* The status bar items the switcher's selection can move onto, in order:
|
||||
* with a bottom switcher (the selection reaches them past the last
|
||||
* window), those whose icons are showing that have a window to show,
|
||||
* which notifications have where the host gives the Notifications window,
|
||||
* and app widgets always do.
|
||||
*/
|
||||
private selectableNotificationKeys(): string[] {
|
||||
return this.config.openNotificationsWindow && switcherPosition() === "bottom" ? this.chrome.notificationKeys() : [];
|
||||
private selectableStatusItems(): StatusItem[] {
|
||||
if (switcherPosition() !== "bottom") return [];
|
||||
return this.chrome.statusItems().filter((item) => item.kind === "notification"
|
||||
? !!this.config.openNotificationsWindow
|
||||
: !!this.trayIcons.get(item.key)?.widget);
|
||||
}
|
||||
|
||||
/** Move the switcher's selection onto a window, off a notification if it was on one. */
|
||||
/** Move the switcher's selection onto a window, off a status bar item if it was on one. */
|
||||
private selectSwitcherWindow(window: ShellWindow): void {
|
||||
// Foreground first, so a Notifications window closing with the
|
||||
// notification selection can't hand the foreground elsewhere first.
|
||||
// Foreground first, so a status bar item's window closing with its
|
||||
// selection can't hand the foreground elsewhere first.
|
||||
this.setSelectedIndex(this.windows.indexOf(window));
|
||||
this.endNotificationSelection(window === this.selectedNotification?.host.window);
|
||||
this.endStatusSelection(window === this.selectedStatus?.host);
|
||||
}
|
||||
|
||||
/**
|
||||
* Move the switcher's selection onto a notification: the Notifications
|
||||
* window (opened in the background first, if need be) comes to the
|
||||
* foreground showing its detail view.
|
||||
* Move the switcher's selection onto a status bar item: its window
|
||||
* (opened in the background first, if need be) comes to the foreground,
|
||||
* a notification's showing its detail view. The window the selection was
|
||||
* on before is left as endStatusSelection leaves it, unless it is this
|
||||
* one too.
|
||||
*/
|
||||
private selectNotification(key: string, index: number): void {
|
||||
const selected = this.selectedNotification;
|
||||
if (selected) {
|
||||
selected.index = index;
|
||||
if (selected.key === key) return;
|
||||
selected.host.stack.popThrough(selected.layer);
|
||||
selected.key = key;
|
||||
selected.layer = this.notificationDetailLayer(key);
|
||||
selected.host.stack.push(selected.layer);
|
||||
selected.host.requestRender();
|
||||
private selectStatusItem(item: StatusItem, index: number): void {
|
||||
const previous = this.selectedStatus;
|
||||
if (previous && sameStatusItem(previous.item, item)) {
|
||||
previous.index = index;
|
||||
return;
|
||||
}
|
||||
const returnWindowId = this.foregroundWindow()?.windowId ?? null;
|
||||
const opened = this.config.openNotificationsWindow?.();
|
||||
const hostIndex = opened ? this.windows.indexOf(opened.window.window) : -1;
|
||||
const returnWindowId = previous ? previous.returnWindowId : (this.foregroundWindow()?.windowId ?? null);
|
||||
const opened = this.openStatusItemWindow(item);
|
||||
const hostIndex = opened ? this.windows.indexOf(opened.window) : -1;
|
||||
if (!opened || hostIndex < 0) return;
|
||||
const host = opened.window;
|
||||
const layer = this.notificationDetailLayer(key);
|
||||
host.stack.push(layer);
|
||||
this.selectedNotification = { key, index, host, layer, transient: opened.opened, returnWindowId };
|
||||
const sameHost = previous?.host === host;
|
||||
if (sameHost && previous.detail) previous.detail.stack.popThrough(previous.detail.layer);
|
||||
const detail = item.kind === "notification" && opened.stack
|
||||
? { stack: opened.stack, layer: this.notificationDetailLayer(item.key) } : null;
|
||||
if (detail) detail.stack.push(detail.layer);
|
||||
this.selectedStatus = {
|
||||
item, index, host, detail, returnWindowId,
|
||||
transient: sameHost ? previous.transient : opened.opened,
|
||||
};
|
||||
if (hostIndex === this.selectedIndex) {
|
||||
host.requestRender();
|
||||
} else {
|
||||
this.setSelectedIndex(hostIndex);
|
||||
}
|
||||
if (previous && !sameHost) this.releaseStatusWindow(previous, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Take the switcher's selection off its notification: the Notifications
|
||||
* window drops the detail view (and anything opened over it), and closes
|
||||
* if it was opened for the selection, unless `keepWindow` (it is the
|
||||
* window being selected instead).
|
||||
* The window a status bar item shows in, opened in the background unless
|
||||
* it is open already (`opened` says this call opened it), and for a
|
||||
* notification, the stack its detail view goes on.
|
||||
*/
|
||||
private endNotificationSelection(keepWindow = false): void {
|
||||
const selected = this.selectedNotification;
|
||||
if (!selected) return;
|
||||
this.selectedNotification = null;
|
||||
selected.host.stack.popThrough(selected.layer);
|
||||
if (selected.transient && !keepWindow) {
|
||||
this.closeWindow(selected.host.window.windowId);
|
||||
return;
|
||||
}
|
||||
selected.host.requestRender();
|
||||
// A window opened for the selection is now one with an icon of its own.
|
||||
if (selected.transient) this.config.onWindowsChanged?.();
|
||||
private openStatusItemWindow(item: StatusItem): { window: ShellWindow; opened: boolean; stack?: LayerStack } | null {
|
||||
if (item.kind === "widget") return this.trayIcons.get(item.key)?.widget?.openWindow() ?? null;
|
||||
const opened = this.config.openNotificationsWindow?.();
|
||||
return opened ? { window: opened.window.window, opened: opened.opened, stack: opened.window.stack } : null;
|
||||
}
|
||||
|
||||
/** End a notification selection by going back to the window selected before it. */
|
||||
private returnFromNotification(): void {
|
||||
const selected = this.selectedNotification;
|
||||
/**
|
||||
* Take the switcher's selection off its status bar item, leaving its
|
||||
* window as releaseStatusWindow does.
|
||||
*/
|
||||
private endStatusSelection(keepWindow = false): void {
|
||||
const selected = this.selectedStatus;
|
||||
if (!selected) return;
|
||||
this.selectedStatus = null;
|
||||
this.releaseStatusWindow(selected, keepWindow);
|
||||
}
|
||||
|
||||
/**
|
||||
* A status bar item's window, once the selection has left the item: it
|
||||
* drops a notification's detail view (and anything opened over it), and
|
||||
* closes if it was opened for the selection, unless `keepWindow` (it is
|
||||
* the window being selected instead).
|
||||
*/
|
||||
private releaseStatusWindow(selection: StatusSelection, keepWindow: boolean): void {
|
||||
if (selection.detail) selection.detail.stack.popThrough(selection.detail.layer);
|
||||
if (selection.transient && !keepWindow) {
|
||||
this.closeWindow(selection.host.windowId);
|
||||
return;
|
||||
}
|
||||
selection.host.requestRender();
|
||||
// A window opened for the selection is now one with an icon of its own.
|
||||
if (selection.transient) this.config.onWindowsChanged?.();
|
||||
}
|
||||
|
||||
/** End a status bar item selection by going back to the window selected before it. */
|
||||
private returnFromStatusItem(): void {
|
||||
const selected = this.selectedStatus;
|
||||
if (!selected) return;
|
||||
const back = this.windows.find((window) => window.windowId === selected.returnWindowId);
|
||||
if (back) this.setSelectedIndex(this.windows.indexOf(back));
|
||||
this.endNotificationSelection(back === selected.host.window);
|
||||
this.endStatusSelection(back === selected.host);
|
||||
}
|
||||
|
||||
private notificationDetailLayer(key: string): SingleNotificationLayer {
|
||||
@@ -1248,25 +1411,25 @@ class Shell {
|
||||
* A selected notification's detail view asked to close. Back (or a
|
||||
* double-tap) hands focus back to the switcher, its selection still on
|
||||
* the notification. Once the notification is gone (dismissed, or removed
|
||||
* by an action), the selection also moves on to the one that took its
|
||||
* place, or back to the windows when there are none left; that waits for
|
||||
* the current paint to finish, since a vanished notification closes its
|
||||
* view from inside its paint.
|
||||
* by an action), the selection also moves on to the status bar item that
|
||||
* took its place, or back to the windows when there are none left; that
|
||||
* waits for the current paint to finish, since a vanished notification
|
||||
* closes its view from inside its paint.
|
||||
*/
|
||||
private notificationDetailClosed(layer: SingleNotificationLayer, gone: boolean): void {
|
||||
if (!gone) {
|
||||
if (this.selectedNotification?.layer === layer) this.yieldFocusToSidebar();
|
||||
if (this.selectedStatus?.detail?.layer === layer) this.yieldFocusToSidebar();
|
||||
return;
|
||||
}
|
||||
setTimeout(() => {
|
||||
const selected = this.selectedNotification;
|
||||
if (selected?.layer !== layer) return;
|
||||
const selected = this.selectedStatus;
|
||||
if (selected?.detail?.layer !== layer) return;
|
||||
this.focus = "sidebar";
|
||||
const keys = this.selectableNotificationKeys().filter((key) => key !== selected.key);
|
||||
const items = this.selectableStatusItems().filter((item) => !sameStatusItem(item, selected.item));
|
||||
const windows = this.switcherWindows();
|
||||
if (keys.length) {
|
||||
const index = Math.min(selected.index, keys.length - 1);
|
||||
this.selectNotification(keys[index]!, index);
|
||||
if (items.length) {
|
||||
const index = Math.min(selected.index, items.length - 1);
|
||||
this.selectStatusItem(items[index]!, index);
|
||||
} else if (windows.length) {
|
||||
this.selectSwitcherWindow(windows[windows.length - 1]!);
|
||||
}
|
||||
@@ -1397,16 +1560,20 @@ class Shell {
|
||||
* 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
|
||||
* start-voice-input message). The menu click already ended the press, so
|
||||
* the dialog finishes on click instead of long-press-release.
|
||||
* the dialog finishes on click instead of long-press-release. Returns
|
||||
* false when the dialog can't open now (voice input disabled, screen off,
|
||||
* another dialog or overlay up); true means it is opening, though a
|
||||
* microphone-permission prompt can still stop it.
|
||||
*/
|
||||
startVoiceInput(): void {
|
||||
if (this.config.voiceInputEnabled === false) return;
|
||||
if (!this.screenOn || this.activeVoiceLayer || !this.stack.isAtBase()) return;
|
||||
startVoiceInput(): boolean {
|
||||
if (this.config.voiceInputEnabled === false || this.voiceDialogPending) return false;
|
||||
if (!this.screenOn || this.activeVoiceLayer || !this.stack.isAtBase()) return false;
|
||||
// The transcript is aimed at the window whose menu requested it; the menu
|
||||
// entry point defaults the highlight to Type Into App.
|
||||
this.focus = "window";
|
||||
this.openVoiceDialog({ finishOnClick: true, defaultTarget: "app" });
|
||||
this.config.requestShellRender();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1521,6 +1688,8 @@ class Shell {
|
||||
const llm = resolveAssistantModel(model, {
|
||||
anthropic: anthropicApiKeySetting.get(),
|
||||
openai: openAiApiKeySetting.get(),
|
||||
hermesUrl: assistantHermesUrlSetting.get(),
|
||||
hermesKey: assistantHermesKeySetting.get(),
|
||||
});
|
||||
if (llm && reasoning !== "default" && llm.effort) llm.effort = reasoning;
|
||||
return llm ? { kind: "direct", llm } : null;
|
||||
@@ -1806,15 +1975,15 @@ class Shell {
|
||||
attention: Boolean(this.attention.get(window.windowId)),
|
||||
drawIcon: window.drawIcon,
|
||||
})),
|
||||
selectedIndex: this.selectedNotification ? -1 : this.selectedIndex,
|
||||
selectedNotificationKey: this.selectedNotification?.key ?? null,
|
||||
selectedIndex: this.selectedStatus ? -1 : this.selectedIndex,
|
||||
selectedStatusItem: this.selectedStatus?.item ?? null,
|
||||
focus: this.focus,
|
||||
foregroundHeightMode: this.foregroundWindow()?.heightMode ?? "min",
|
||||
foregroundAppId: this.foregroundWindow()?.appId,
|
||||
battery: this.battery,
|
||||
trayIcons: Array.from(this.trayIcons.keys())
|
||||
.sort()
|
||||
.map((key) => this.trayIcons.get(key)!),
|
||||
.map((ownerId) => ({ ownerId, icon: this.trayIcons.get(ownerId)!.icon })),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
/**
|
||||
* A tiny global signal for whether a voice-input modal (the assistant dialog)
|
||||
* is currently open. The shell sets it; the EvenHub mic router reads it to
|
||||
* decide whether an app may hold the glasses microphone — an app receives no
|
||||
* audio while the assistant is active, since both share the one G2 mic.
|
||||
* A tiny global signal for whether speech capture owns the glasses
|
||||
* microphone: the assistant's voice dialog, a dictation draft, or
|
||||
* Transcribe's continuous capture. The EvenHub mic router and the
|
||||
* Microphones app read it to yield the one G2 mic while it is active — an
|
||||
* app receives no audio meanwhile, since they all share it.
|
||||
*
|
||||
* Each user holds it under its own name, so one finishing doesn't clear
|
||||
* another's hold. Set it before starting the capture and clear it after
|
||||
* releasing, so other mic users stand down first and resume after.
|
||||
*
|
||||
* Kept as a dependency-free leaf so both the shell and the EvenHub layer can
|
||||
* import it without a cycle.
|
||||
@@ -10,16 +15,19 @@
|
||||
|
||||
type Listener = (active: boolean) => void;
|
||||
|
||||
let active = false;
|
||||
const holders = new Set<string>();
|
||||
const listeners = new Set<Listener>();
|
||||
|
||||
export const voiceActivity = {
|
||||
isActive(): boolean {
|
||||
return active;
|
||||
return holders.size > 0;
|
||||
},
|
||||
setActive(next: boolean): void {
|
||||
if (active === next) return;
|
||||
active = next;
|
||||
setActive(next: boolean, holder = "voice-input"): void {
|
||||
const was = holders.size > 0;
|
||||
if (next) holders.add(holder);
|
||||
else holders.delete(holder);
|
||||
const active = holders.size > 0;
|
||||
if (active === was) return;
|
||||
listeners.forEach((listener) => listener(active));
|
||||
},
|
||||
subscribe(listener: Listener): () => void {
|
||||
|
||||
@@ -460,10 +460,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,
|
||||
// Every app worker resizes its live content in place, keeping its state
|
||||
// (a game in progress, a route): the bottom switcher's height changes
|
||||
// with what it holds, and full-height windows give way to it.
|
||||
relayout: () => this.post({ type: "resize-window", windowId: spec.windowId, viewport: appViewportSize(heightMode, this.options.appId) }),
|
||||
hasAppMenu: () => this.windowGestures.get(spec.windowId)?.hasAppMenu ?? false,
|
||||
claimsLongPress: () => this.windowGestures.get(spec.windowId)?.claimsLongPress ?? false,
|
||||
close: () => {
|
||||
|
||||
@@ -99,9 +99,10 @@ export class WindowMenu {
|
||||
/**
|
||||
* Open the menu, or the shell's system menu when this window has no
|
||||
* entries. `items` (and optionally `title`) override the window's own for
|
||||
* an app that reuses this host for another list (a per-row action menu).
|
||||
* an app that reuses this host for another list (a per-row action menu),
|
||||
* and `selectedIndex` starts a picker on its current value.
|
||||
*/
|
||||
open(items: MenuItem[] = this.options.items(), title: string = this.options.title()): void {
|
||||
open(items: MenuItem[] = this.options.items(), title: string = this.options.title(), selectedIndex?: number): void {
|
||||
if (this.stack) return;
|
||||
if (!items.length) {
|
||||
this.options.post({ type: "open-system-menu", windowId: this.options.windowId });
|
||||
@@ -112,7 +113,9 @@ export class WindowMenu {
|
||||
handleInput: () => {},
|
||||
};
|
||||
const stack = new LayerStack(base, this.layerActions(), this.options.size, this.options.isFocused);
|
||||
stack.push(new WindowMenuLayer(title, items));
|
||||
const layer = new WindowMenuLayer(title, items);
|
||||
if (selectedIndex !== undefined) layer.selectItem(selectedIndex);
|
||||
stack.push(layer);
|
||||
this.stack = stack;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user