This commit is contained in:
James Babcock committed 2026-11-07 22:29:39 -08:00
commit 43738b181d
28 files changed
+1062 -95

No files matched your search

@@ -167,6 +167,7 @@ class FontFileRenderer private constructor() {
* [width u16][height u16]
* [width*height coverage bytes, gamma-mapped]
* An ink-free glyph (space) has width = height = 0 but a valid advance.
* A color glyph (emoji) carries its ColorGlyphArt shade as its coverage.
* Empty array when the font cannot be loaded or the render fails.
*/
@JvmStatic
@@ -196,11 +197,16 @@ class FontFileRenderer private constructor() {
}
val penX = pad - bounds.left
val baselineY = pad - bounds.top
val bitmap = Bitmap.createBitmap(bw, bh, Bitmap.Config.ALPHA_8)
// Drawn in color: an emoji the system fallback supplies from a color font
// would keep only its silhouette in an alpha-only bitmap. ColorGlyphArt shades
// color glyphs and passes white ones through as their alpha.
val bitmap = Bitmap.createBitmap(bw, bh, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
canvas.drawText(text, penX.toFloat(), baselineY.toFloat(), paint)
val pixels = alpha8Pixels(bitmap, bw, bh)
val argb = IntArray(bw * bh)
bitmap.getPixels(argb, 0, bw, 0, 0, bw, bh)
bitmap.recycle()
val pixels = ColorGlyphArt.coverage(argb)
// Trim to the tight ink box; bearing/inkTop become pen- and
// line-relative inside the shared packer.
+30 -9
View File
@@ -1,6 +1,7 @@
#import "FaceclawFontRenderer.h"
#import <CoreText/CoreText.h>
#import <CoreGraphics/CoreGraphics.h>
#import <FaceclawKit/FaceclawKit.h>
#import <math.h>
// Immutable font descriptors may be shared; layout objects never cross threads.
@@ -42,8 +43,9 @@ static BOOL HasColorRun(CTLineRef line) {
}
// iOS falls back to Apple Color Emoji for default-text symbols the face lacks
// (▶ U+25B6 in Roboto), where Android's minikin picks a text font; the
// alpha-only raster keeps just the emoji's silhouette (▶ becomes a solid
// rounded square). Request text presentation (U+FE0E) for each lone codepoint
// emoji is a tile (▶ becomes a rounded square: a silhouette in the alpha-only
// line rasters, a shaded tile in glyph cells), which reads worse than the
// text symbol. Request text presentation (U+FE0E) for each lone codepoint
// that fell back to a color font, wherever a text font can supply it. Returns
// `text` itself when nothing changes.
static NSString *PreferTextPresentation(CTFontRef font, NSString *text, CTLineRef line, BOOL glyphLayout) {
@@ -78,18 +80,34 @@ static BOOL ValidText(NSString *text) { return text != nil && text.length <= 100
static BOOL ValidRaster(NSInteger width, NSInteger height) {
return width > 0 && height > 0 && width <= 65535 && height <= 65535 && width * height <= 4000000;
}
static void ConfigureTextContext(CGContextRef ctx) {
CGContextSetShouldAntialias(ctx, true);
CGContextSetShouldSmoothFonts(ctx, false); // Grayscale coverage, never LCD subpixel color.
CGContextSetShouldSubpixelPositionFonts(ctx, true);
CGContextSetShouldSubpixelQuantizeFonts(ctx, false);
CGContextSetTextMatrix(ctx, CGAffineTransformIdentity);
}
static CGContextRef CreateContext(NSMutableData *pixels, NSInteger width, NSInteger height) CF_RETURNS_RETAINED {
CGContextRef ctx = CGBitmapContextCreate(pixels.mutableBytes, width, height, 8, width, NULL, (CGBitmapInfo)kCGImageAlphaOnly);
if (ctx) {
CGContextSetShouldAntialias(ctx, true);
CGContextSetShouldSmoothFonts(ctx, false); // Grayscale coverage, never LCD subpixel color.
CGContextSetShouldSubpixelPositionFonts(ctx, true);
CGContextSetShouldSubpixelQuantizeFonts(ctx, false);
CGContextSetTextMatrix(ctx, CGAffineTransformIdentity);
ConfigureTextContext(ctx);
CGContextSetGrayFillColor(ctx, 1, 1);
}
return ctx;
}
// Premultiplied RGBA bytes, for a line with a color (emoji) run: an alpha-only raster keeps
// just the emoji's silhouette, so its colors go to ColorGlyphArt to be shaded instead.
static CGContextRef CreateColorContext(NSMutableData *pixels, NSInteger width, NSInteger height) CF_RETURNS_RETAINED {
CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
CGContextRef ctx = CGBitmapContextCreate(pixels.mutableBytes, width, height, 8, width * 4, space,
(CGBitmapInfo)kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(space);
if (ctx) {
ConfigureTextContext(ctx);
CGContextSetRGBFillColor(ctx, 1, 1, 1, 1);
}
return ctx;
}
static void U16(uint8_t *out, NSInteger value) { out[0] = value & 255; out[1] = (value >> 8) & 255; }
static void GammaCopy(uint8_t *dst, const uint8_t *src, NSInteger count, double gamma) {
if (!isfinite(gamma) || gamma <= 0) gamma = 1;
@@ -150,10 +168,13 @@ static NSData *ImagePacket(NSData *pixels, NSInteger width, NSInteger height, do
NSInteger bottom = floor(CGRectGetMinY(bounds)) - 2;
NSInteger width = ceil(CGRectGetMaxX(bounds)) + 2 - left, height = top - bottom;
if (!ValidRaster(width, height)) { CFRelease(line); CFRelease(font); return [NSData data]; }
NSMutableData *pixels = [NSMutableData dataWithLength:width * height];
CGContextRef ctx = CreateContext(pixels, width, height);
BOOL color = HasColorRun(line);
NSMutableData *raster = [NSMutableData dataWithLength:width * height * (color ? 4 : 1)];
CGContextRef ctx = color ? CreateColorContext(raster, width, height) : CreateContext(raster, width, height);
if (!ctx) { CFRelease(line); CFRelease(font); return [NSData data]; }
CGContextSetTextPosition(ctx, -left, -bottom); CTLineDraw(line, ctx); CGContextRelease(ctx);
NSData *pixels = color ? [[FaceclawKitIosColorGlyph shared] shadeRgba:raster] : raster;
if ((NSInteger)pixels.length != width * height) { CFRelease(line); CFRelease(font); return [NSData data]; }
const uint8_t *src = pixels.bytes;
NSInteger x0 = width, y0 = height, x1 = -1, y1 = -1;
for (NSInteger y = 0; y < height; y++) for (NSInteger x = 0; x < width; x++) if (src[y * width + x]) {
+36 -8
View File
@@ -20,11 +20,11 @@ const PERM_GAP = 4;
* Cancel (or double-click) backs out. A privacy-policy-only app still reaches
* this dialog so the user can review the policy before allowing first run.
*
* When the list overflows the viewport the dialog scrolls: scroll events move
* through the content row by row, and only once the bottom is fully visible do
* further scrolls move the action selection. The actions are inert until then
* (a click just scrolls), so the user can't Allow without having had the whole
* list on screen.
* When the list overflows the viewport the dialog scrolls a page at a time,
* keeping one line of overlap (the last line of one page is the first of the
* next), and only once the bottom is fully visible do further scrolls move the
* action selection. The actions are inert until then (a click just pages
* down), so the user can't Allow without having had the whole list on screen.
*/
export class EvenHubPermissionDialogLayer implements Layer {
/** Floats in front of the window content, like the context menus. */
@@ -35,6 +35,9 @@ export class EvenHubPermissionDialogLayer implements Layer {
private firstRow = 0;
/** Scroll position at which the last row is fully visible; set by paint. */
private maxFirstRow = 0;
/** Heights of the content rows and of the viewport they scroll in, as last painted (for paging). */
private rowHeights: number[] = [];
private visibleHeight = 0;
private resolved = false;
constructor(
@@ -125,6 +128,8 @@ export class EvenHubPermissionDialogLayer implements Layer {
}
this.maxFirstRow = maxFirstRow;
this.firstRow = Math.max(0, Math.min(this.firstRow, maxFirstRow));
this.rowHeights = rows.map((row) => row.height);
this.visibleHeight = visibleHeight;
// Fill 1 (transparent color key is 0), outline for the dialog edge.
image.fillRoundedRect(dialogX, dialogY, dialogWidth, height, 1);
@@ -159,19 +164,19 @@ export class EvenHubPermissionDialogLayer implements Layer {
if (this.atBottom() && this.selectedIndex > 0) {
this.selectedIndex -= 1;
} else if (this.firstRow > 0) {
this.firstRow -= 1;
this.pageUp();
}
return;
case "scroll-down":
if (!this.atBottom()) {
this.firstRow += 1;
this.pageDown();
} else {
this.selectedIndex = Math.min(actions.length - 1, this.selectedIndex + 1);
}
return;
case "click":
if (!this.atBottom()) {
this.firstRow += 1;
this.pageDown();
return;
}
if (actions[this.selectedIndex] === "Privacy policy") {
@@ -188,6 +193,29 @@ export class EvenHubPermissionDialogLayer implements Layer {
}
}
/** Scroll so the last fully visible row becomes the first (one row of overlap). */
private pageDown(): void {
let y = 0;
let lastVisible = this.firstRow;
for (let index = this.firstRow; index < this.rowHeights.length; index++) {
y += this.rowHeights[index]!;
if (y > this.visibleHeight) break;
lastVisible = index;
}
this.firstRow = Math.min(this.maxFirstRow, Math.max(this.firstRow + 1, lastVisible));
}
/** Scroll so the current first row becomes the last fully visible one (one row of overlap). */
private pageUp(): void {
let first = this.firstRow;
let y = this.rowHeights[first] ?? 0;
while (first > 0 && y + this.rowHeights[first - 1]! <= this.visibleHeight) {
first -= 1;
y += this.rowHeights[first]!;
}
this.firstRow = Math.max(0, Math.min(this.firstRow - 1, first));
}
onRemoved(): void {
// Dismissed some other way (window closed, back button): treat as cancel.
if (!this.resolved) {
+72 -18
View File
@@ -1,7 +1,7 @@
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import { GrayImage, type UiFont } from "../../graphics/image";
import { truncateText, wrapText } from "../../graphics/textwrap";
import { GESTURE_CLICK, type InputEvent } from "../../ui/gestures";
import { directionalFallback, GESTURE_CLICK, isDirectionalInput, type InputEvent } from "../../ui/gestures";
import { type Layer, type LayerActions, type LayerContext, type LayerStack } from "../../ui/layers";
import { drawSelectionHighlight, type MenuItem } from "../../ui/menu";
import { Menu } from "../../ui/menu-core";
@@ -55,7 +55,32 @@ type StoreRow =
/** The Search tab's first row: shows the query and opens the phone editor. */
| { kind: "search-query" }
/** A registry entry whose package is gone and which the store no longer lists. */
| { kind: "orphan"; update: EvenHubAppUpdate };
| { kind: "orphan"; update: EvenHubAppUpdate }
/** The Updates tab's first row while any update is installable; `busy` while Update All runs. */
| { kind: "update-all"; count: number; busy: boolean };
type AppRow = Extract<StoreRow, { kind: "app" }>;
/** An Updates row that installing the store's version would satisfy. */
function isUpdatableRow(row: StoreRow): row is AppRow {
return row.kind === "app" && row.update !== undefined;
}
/** An Updates row for one installed app (not the Update All row). */
function isInstalledAppRow(row: StoreRow): boolean {
return row.kind === "app" || row.kind === "orphan";
}
function rowPackageId(row: StoreRow): string | undefined {
switch (row.kind) {
case "app":
return row.app.packageId;
case "orphan":
return row.update.installed.packageId;
default:
return undefined;
}
}
type TabState = {
rows: StoreRow[];
@@ -118,10 +143,13 @@ export type EvenHubStoreLayerOptions = {
* The EvenHub storefront: Top (leaderboard), New (by first publication),
* Search, and Updates (installed apps that are stale or whose package is
* missing). The tab row is its own focus level above the list: double-click
* in the list focuses the tabs, scrolling there switches tabs, and a click
* returns to the list.
* in the list focuses the tabs, scrolling (or a watch swipe in any direction)
* there switches tabs, and a click returns to the list.
*/
export class EvenHubStoreLayer implements Layer {
/** Swipes left/right switch tabs on the tab strip; elsewhere they get the usual fallback. */
readonly acceptsDirectional = true;
private readonly tabs: Record<StoreTab, TabState> = {
top: emptyTab(),
new: emptyTab(),
@@ -229,7 +257,7 @@ export class EvenHubStoreLayer implements Layer {
const label = TABS.find((entry) => entry.id === tab)!.label;
if (tab !== "updates") return label;
const updates = this.tabs.updates;
const count = updates.rows.filter((row) => row.kind !== "search-query").length;
const count = updates.rows.filter(isInstalledAppRow).length;
return updates.loaded && count > 0 ? `${label} (${count})` : label;
}
@@ -245,9 +273,11 @@ export class EvenHubStoreLayer implements Layer {
if (!state.query) return "Search public apps";
return results === 1 ? `1 result for "${state.query}"` : `${results} results for "${state.query}"`;
}
case "updates":
case "updates": {
if (!state.loaded) return "Installed apps with newer versions";
return count === 0 ? "All installed apps are up to date" : count === 1 ? "1 app needs attention" : `${count} apps need attention`;
const apps = state.rows.filter(isInstalledAppRow).length;
return apps === 0 ? "All installed apps are up to date" : apps === 1 ? "1 app needs attention" : `${apps} apps need attention`;
}
}
}
@@ -263,7 +293,10 @@ export class EvenHubStoreLayer implements Layer {
}
}
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
async handleInput(rawEvent: InputEvent, ctx: LayerContext): Promise<void> {
const tabSwipe = !this.showingLogin && this.focus === "tabs"
&& (rawEvent.type === "swipe-left" || rawEvent.type === "swipe-right");
const event = isDirectionalInput(rawEvent) && !tabSwipe ? directionalFallback(rawEvent) : rawEvent;
if (this.showingLogin) {
if (event.type === "click" && !this.loginBusy) {
this.openCredentialEditor(ctx);
@@ -301,9 +334,11 @@ export class EvenHubStoreLayer implements Layer {
const index = TABS.findIndex((tab) => tab.id === this.activeTab);
switch (event.type) {
case "scroll-up":
case "swipe-left":
this.switchTab(ctx, TABS[Math.max(0, index - 1)]!.id);
return;
case "scroll-down":
case "swipe-right":
this.switchTab(ctx, TABS[Math.min(TABS.length - 1, index + 1)]!.id);
return;
case "click":
@@ -333,6 +368,9 @@ export class EvenHubStoreLayer implements Layer {
case "search-query":
this.openSearchEditor(ctx);
return;
case "update-all":
void this.updateAll(ctx);
return;
case "orphan": {
// Nothing can be reinstalled; the only useful action is to drop the
// dead registry entry so the launcher stops offering it.
@@ -532,8 +570,7 @@ export class EvenHubStoreLayer implements Layer {
const rows: StoreRow[] = updates.map((update) =>
update.latest ? { kind: "app", app: update.latest, update } : { kind: "orphan", update },
);
state.rows = rows;
state.menu.setItems(rows, 0);
this.setUpdateRows(state, rows, 0);
state.menu.scrollTop = 0;
state.status = "";
state.exhausted = true;
@@ -548,10 +585,20 @@ export class EvenHubStoreLayer implements Layer {
}
}
private updatableRows(): Extract<StoreRow, { kind: "app" }>[] {
return this.tabs.updates.rows.filter(
(row): row is Extract<StoreRow, { kind: "app" }> => row.kind === "app" && row.update !== undefined,
);
private updatableRows(): AppRow[] {
return this.tabs.updates.rows.filter(isUpdatableRow);
}
/**
* Replace the Updates rows, putting an Update All row on top while any of
* them can be installed (and dropping it once none can).
*/
private setUpdateRows(state: TabState, entries: readonly StoreRow[], selectedIndex?: number): void {
const rows = entries.filter(isInstalledAppRow);
const count = rows.filter(isUpdatableRow).length;
if (count > 0) rows.unshift({ kind: "update-all", count, busy: this.updatingAll });
state.rows = rows;
state.menu.setItems(rows, selectedIndex);
}
/** Install every pending update in turn; a declined permission dialog skips that app. */
@@ -559,6 +606,7 @@ export class EvenHubStoreLayer implements Layer {
if (this.updatingAll) return;
this.updatingAll = true;
const state = this.tabs.updates;
this.setUpdateRows(state, state.rows);
const pending = this.updatableRows();
let installed = 0;
const failures: string[] = [];
@@ -593,6 +641,7 @@ export class EvenHubStoreLayer implements Layer {
: installed === 1 ? "Updated 1 app." : `Updated ${installed} apps.`;
} finally {
this.updatingAll = false;
this.setUpdateRows(this.tabs.updates, this.tabs.updates.rows);
if (!this.closed) ctx.actions.requestRender();
}
}
@@ -609,10 +658,7 @@ export class EvenHubStoreLayer implements Layer {
private removeUpdateRow(packageId: string): void {
const state = this.tabs.updates;
state.rows = state.rows.filter((row) =>
row.kind === "search-query" ? true : row.kind === "app" ? row.app.packageId !== packageId : row.update.installed.packageId !== packageId,
);
state.menu.setItems(state.rows);
this.setUpdateRows(state, state.rows.filter((row) => rowPackageId(row) !== packageId));
}
// ---- login and phone editors --------------------------------------------
@@ -751,6 +797,14 @@ function rowText(row: StoreRow): { title: string; detail: string; titleValue: nu
titleValue: 200,
};
}
case "update-all":
return {
title: row.busy ? "Updating..." : "Update All",
detail: row.busy
? "Installing updates; progress is shown above."
: row.count === 1 ? "Install the 1 available update" : `Install all ${row.count} available updates`,
titleValue: row.busy ? 150 : 230,
};
case "orphan":
return {
title: row.update.installed.name,
+24 -6
View File
@@ -61,9 +61,28 @@ export const glanceboardEnabledSetting = new ConfigSettingBoolean({
"While the display is asleep, a tap, a long-press or a head-tilt shows the Glanceboard instead of the regular UI. Double-tap still wakes the regular UI.",
});
export type GlanceTapDuration = "off" | "3s" | "5s" | "7s" | "10s";
const TAP_DURATION_SECONDS = {
"3s": 3,
"5s": 5,
"7s": 7,
"10s": 10,
"20s": 20,
"30s": 30,
"1min": 60,
} as const;
const DEFAULT_TAP_DURATION: GlanceTapDuration = "5s";
type GlanceTapDurationTimed = keyof typeof TAP_DURATION_SECONDS;
export type GlanceTapDuration = "off" | GlanceTapDurationTimed;
const TAP_DURATION_VALUES: readonly GlanceTapDuration[] = ["off", ...(Object.keys(TAP_DURATION_SECONDS) as GlanceTapDurationTimed[])];
const DEFAULT_TAP_DURATION: GlanceTapDurationTimed = "5s";
function formatTapDuration(value: GlanceTapDuration): string {
if (value === "off") return "Disabled";
const seconds = TAP_DURATION_SECONDS[value];
return seconds % 60 === 0 ? `${seconds / 60} min` : `${seconds} s`;
}
/**
* How long a tap (or head-tilt) keeps the board up; each further tap restarts
@@ -75,8 +94,8 @@ export const glanceTapDurationSetting = new ConfigSettingEnum<GlanceTapDuration>
label: "Show on tap",
storageKey: "glanceboard.tapDuration",
defaultValue: DEFAULT_TAP_DURATION,
values: ["off", "3s", "5s", "7s", "10s"],
formatValue: (value) => (value === "off" ? "Disabled" : value.replace("s", " s")),
values: TAP_DURATION_VALUES,
formatValue: formatTapDuration,
description:
"How long a single tap (or a head-tilt) keeps the Glanceboard on screen. Disabled: a single tap does not show the Glanceboard.",
});
@@ -88,8 +107,7 @@ export function glanceShowOnTap(): boolean {
export function glanceTapTimeoutMs(): number {
const duration = glanceTapDurationSetting.get();
const seconds = duration === "off" ? DEFAULT_TAP_DURATION : duration;
return Number.parseInt(seconds, 10) * 1000;
return TAP_DURATION_SECONDS[duration === "off" ? DEFAULT_TAP_DURATION : duration] * 1000;
}
/** A long-press holds the board up until the press is released. */
+6 -1
View File
@@ -14,7 +14,12 @@ const notificationsApp: AppDefinition = {
if (listenerState === "no-access" || listenerState === "stuck") {
requestNotificationListenerAccess();
}
return ctx.launchInProcessApp(NOTIFICATIONS_WINDOW_ID, NOTIFICATIONS_SURFACE_ID, createNotificationsAppWindow);
return ctx.launchInProcessApp(NOTIFICATIONS_WINDOW_ID, NOTIFICATIONS_SURFACE_ID, (options) =>
createNotificationsAppWindow(options, (section) => {
void ctx.launchApp("settings", { section }).catch((error) => {
ctx.appendLog(`settings launch failed: ${error}`);
});
}));
},
};
+9 -5
View File
@@ -1,5 +1,5 @@
import { NotificationsListLayer } from "../../ui/notifications";
import { NotificationFilterLayer } from "../../ui/notification-filter";
import { NOTIFICATIONS_SETTINGS_SECTION } from "../../ui/dashboard/settings-menus";
import { onAndroidNotificationsChanged } from "../../native/notification-icons";
import {
createInProcessWindow,
@@ -14,9 +14,13 @@ export const NOTIFICATIONS_SURFACE_ID = "window:notifications";
/**
* The Notifications app: the Android-notification list (previously a
* dashboard page) in its own in-process window; selecting a notification
* opens the detail view with its quick actions.
* opens the detail view with its quick actions. `openSettings` opens a
* Settings section (the menu's "Settings" goes to Notifications).
*/
export function createNotificationsAppWindow(options: InProcessAppOptions): InProcessWindow {
export function createNotificationsAppWindow(
options: InProcessAppOptions,
openSettings: (section: string) => void,
): InProcessWindow {
// Newly posted notifications repaint the list while the window is open.
let offNotificationsChanged: (() => void) | null = null;
const created = createInProcessWindow({
@@ -27,10 +31,10 @@ export function createNotificationsAppWindow(options: InProcessAppOptions): InPr
icon: "bell",
closeable: true,
menuItems: () => [{
label: "Notification filter",
label: "Settings",
onSelect: (ctx) => {
ctx.stack.pop();
ctx.stack.push(new NotificationFilterLayer());
openSettings(NOTIFICATIONS_SETTINGS_SECTION);
},
}],
actions: options.actions,
+13 -10
View File
@@ -16,7 +16,6 @@ import { mediaControllerBridge } from "../native/media-controller";
import { nightscoutBridge } from "../native/nightscout-bridge";
import { weatherBridge } from "../native/weather";
import { ALL_NOTIFICATIONS, onAndroidNotificationPosted, onAndroidNotificationRemoved, readActiveNotifications } from "../native/notification-icons";
import { shouldShowNotificationOnGlasses } from "../native/notification-sources";
import { watchNotificationListenerBinding } from "../native/notification-access";
import { openEvenAppSettings, readEvenAppNotificationState } from "../native/even-app-conflict";
import { defaultRingName, setGlassesRingLink } from "../native/ring-status";
@@ -78,7 +77,7 @@ import { loadPersistedOpenApps, savePersistedOpenApps } from "../ui/shell/open-a
import { appViewportRect, isOnSwitcherEdge, screenHeight, screenWidth, sidebarStripVisible, type ScreenRect, type WindowHeightMode } from "../ui/shell/geometry";
import { type ContinuousCaptureOptions, type LayerActions, type TextSettingsEditToggle, type TranscriptionChoice } from "../ui/layers";
import { type KeyboardInputSession } from "../ui/shell/keyboard-input";
import { appSwitcherPositionSetting, glassesTypeSetting, statusBarPositionSetting, statusBarVisibilitySetting, windowBorderSetting, assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, getBrightnessPreferences, displayLayoutSetting, navigateDisplayLayoutSetting, terminalDisplayLayoutSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, whisperServerApiKeySetting, whisperServerLanguageSetting, whisperServerModelSetting, whisperServerUrlSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, effectiveRingConnectionMode, type RingConnectionMode, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
import { appSwitcherPositionSetting, glassesTypeSetting, statusBarPositionSetting, statusBarVisibilitySetting, windowBorderSetting, assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, getBrightnessPreferences, displayLayoutSetting, navigateDisplayLayoutSetting, terminalDisplayLayoutSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, whisperServerApiKeySetting, whisperServerLanguageSetting, whisperServerModelSetting, whisperServerUrlSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, effectiveRingConnectionMode, type RingConnectionMode, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, shouldPopUpNewNotification, suspendEvenHubWhenScreenOffSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
import { isIgnoringBatteryOptimizations, requestIgnoreBatteryOptimizations } from "../native/battery-optimization";
import {
getInstalledEvenHubAppById,
@@ -449,7 +448,8 @@ class DashboardController {
this.emit();
},
openNotificationsWindow: () =>
this.openInProcessAppInBackground(NOTIFICATIONS_WINDOW_ID, NOTIFICATIONS_SURFACE_ID, createNotificationsAppWindow),
this.openInProcessAppInBackground(NOTIFICATIONS_WINDOW_ID, NOTIFICATIONS_SURFACE_ID,
(options) => createNotificationsAppWindow(options, (section) => this.openSettings(section))),
onSwitcherBarHeightChanged: () => this.applySwitcherBarHeight(),
onScreenStateChanged: (on) => {
// Any wake of the regular UI replaces a showing Glanceboard.
@@ -2644,11 +2644,7 @@ class DashboardController {
setSurfaceVisible: (surfaceId, visible) => this.setWindowSurfaceVisible(surfaceId, visible),
removeSurface: (surfaceId) => this.removeWindowSurface(surfaceId),
requestShellRender: () => this.requestShellRender(),
openSettings: (section) => {
void this.launchApp("settings", { section }).catch((error) => {
this.appendLog(`settings launch failed: ${this.formatError(error)}`);
});
},
openSettings: (section) => this.openSettings(section),
startTextSettingEdit: (settingId) => {
const setting = getStringSettingById(settingId);
if (setting) {
@@ -2732,6 +2728,13 @@ class DashboardController {
this.requestShellRender();
}
/** Open or focus the Settings app, optionally on a section (by label). */
private openSettings(section?: string): void {
void this.launchApp("settings", { section }).catch((error) => {
this.appendLog(`settings launch failed: ${this.formatError(error)}`);
});
}
/**
* Launch an app by id: the launcher grid, assistant tools, window-menu
* Settings item, and open-apps restore all come through here. Apps with an
@@ -2948,7 +2951,7 @@ class DashboardController {
// The tray shows the notification at once; its popup waits out a short
// delay, so one withdrawn right away (see NotificationPopupDelay) never shows.
const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === notificationKey);
if (notification && shouldShowNotificationOnGlasses(notification.packageName)) {
if (notification && shouldPopUpNewNotification(notification.packageName)) {
this.notificationPopups.post(notificationKey, notificationPopupDelayMs(notification));
}
this.requestShellRender();
@@ -2970,7 +2973,7 @@ class DashboardController {
private popUpAndroidNotification(notificationKey: string): void {
try {
const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === notificationKey);
if (!notification || !shouldShowNotificationOnGlasses(notification.packageName)) return;
if (!notification || !shouldPopUpNewNotification(notification.packageName)) return;
// New notifications open a shell modal over the app viewport; if the
// screen was off, wake for it and go back to sleep when it is closed.
// Waking while already on would steal focus, so only wake from sleep.
+4 -4
View File
@@ -2,7 +2,6 @@ import { startRemoteInput } from "../remote/service"
import type { KeyboardInputSession } from '../ui/shell/keyboard-input'
import { acceptInput, resetRingInputFilter } from "../ui/input-monitor";
import { bindIosNotifications, iosNotificationsChanged, onIosNotificationPopup, readActiveNotifications } from '../native/notification-icons.ios'
import { shouldShowNotificationOnGlasses } from '../native/notification-sources'
import { launcherEntries } from '../apps/launcher'
import { discardZeroedEvenHubPackage, getInstalledEvenHubAppById, installedEvenHubPackageId, uninstallEvenHubPackage } from '../apps/evenhub/installed-apps'
import { isInstalledPackagePresent } from '../apps/evenhub/updates'
@@ -54,7 +53,7 @@ import { onAnySettingChanged,
previewColorSetting, lockScreenEnabledSetting, getBrightnessPreferences, getStringSettingById,
nightscoutSiteUrlSetting, nightscoutApiTokenSetting, voiceProviderSetting, elevenLabsApiKeySetting,
openAiApiKeySetting, sonioxApiKeySetting, whisperServerApiKeySetting, whisperServerLanguageSetting,
whisperServerModelSetting, whisperServerUrlSetting, ringConnectionModeSetting, saveTranscribeAudioSetting, glassesTypeSetting } from '../ui/dashboard-settings'
whisperServerModelSetting, whisperServerUrlSetting, ringConnectionModeSetting, saveTranscribeAudioSetting, glassesTypeSetting, shouldPopUpNewNotification } from '../ui/dashboard-settings'
import { transcriptionKey, type VoiceProviderSelection } from '../native/cloud-stt-provider'
import type { PhoneGesture } from '../phone-ui/phone-gestures'
import { claimGlassesOnboardingAutoLaunch, ONBOARDING_APP_ID } from '../apps/onboarding/onboarding-progress'
@@ -216,7 +215,8 @@ export class IosPreviewController {
requestShellRender: () => this.requestShellRender(),
onWindowsChanged: () => { this.requestShellRender(); this.syncEvenHubPhoneUi(); this.wearRemote?.schedulePublish() },
openNotificationsWindow: () =>
this.openInProcessAppInBackground(NOTIFICATIONS_WINDOW_ID, NOTIFICATIONS_SURFACE_ID, createNotificationsAppWindow),
this.openInProcessAppInBackground(NOTIFICATIONS_WINDOW_ID, NOTIFICATIONS_SURFACE_ID,
options => createNotificationsAppWindow(options, section => { void this.launchApp('settings', { section }) })),
onSwitcherBarHeightChanged: () => {
this.relayout()
shell.foregroundWindow()?.requestRender()
@@ -248,7 +248,7 @@ export class IosPreviewController {
shell.focusWindow(launcher.windowId)
onIosNotificationPopup(key => {
const notification = readActiveNotifications(128).find(n => n.key === key)
if (this.glassesLocked || !notification || !shouldShowNotificationOnGlasses(notification.packageName)) return
if (this.glassesLocked || !notification || !shouldPopUpNewNotification(notification.packageName)) return
const woke = !shell.isScreenOn() && shell.wake('sidebar')
shell.openNotificationModal(key, woke)
this.requestShellRender()
+48
View File
@@ -17,6 +17,7 @@ import {
type AssistantModel,
} from "~/assistant/models";
import { isLocalModelReady } from "../native/local-llm";
import { shouldShowNotificationOnGlasses } from "../native/notification-sources";
import { normalizeWhisperServerUrl } from "../native/whisper-server-stt";
import { normalizeOpenAiCompatibleUrl } from "../native/openai-chat";
import { isValidSpotifyClientId, SPOTIFY_CLIENT_ID_KEY } from "../native/spotify-auth";
@@ -40,6 +41,8 @@ export type TimeFormat = "24h" | "12h";
export type TemperatureUnit = "fahrenheit" | "celsius";
export type DistanceUnit = "miles" | "kilometers";
export type ScreenTimeoutSetting = "15s" | "30s" | "1m" | "3m" | "never";
/** Whether new phone notifications pop up on the glasses, and for how long without interaction. */
export type NewNotificationDisplay = "off" | "until-dismissed" | "5s" | "15s" | "1m";
// 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.
export const BRIGHTNESS_VALUES = ["auto", "2", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"] as const;
@@ -663,6 +666,23 @@ export const screenTimeoutSetting = new ConfigSettingEnum<ScreenTimeoutSetting>(
description: "How long the display stays on after the last input before turning itself off. \"Never\" keeps it on until turned off manually.",
});
export const newNotificationDisplaySetting = new ConfigSettingEnum<NewNotificationDisplay>({
id: "new-notification-display",
label: "Display new notifications",
storageKey: "notifications.newNotificationDisplay",
defaultValue: "15s",
values: ["off", "until-dismissed", "5s", "15s", "1m"],
formatValue: newNotificationDisplayLabel,
description:
"Pop up new phone notifications on the glasses. A timed popup closes once left untouched that long; " +
"the notification stays on the phone and in the status bar.",
});
/** Whether a newly posted phone notification from this app pops up on the glasses (the global setting, then the app's filter toggle). */
export function shouldPopUpNewNotification(packageName: string): boolean {
return newNotificationDisplaySetting.get() !== "off" && shouldShowNotificationOnGlasses(packageName);
}
export const lockScreenEnabledSetting = new ConfigSettingBoolean({
id: "lock-screen-enabled",
label: "Enable lock screen",
@@ -1571,6 +1591,34 @@ export function screenTimeoutSettingToMs(value: ScreenTimeoutSetting): number |
}
}
/** How long an untouched new-notification popup stays up; null keeps it until dismissed (and for "off", which never opens one). */
export function newNotificationDisplayTimeoutMs(value: NewNotificationDisplay): number | null {
switch (value) {
case "5s":
return 5_000;
case "15s":
return 15_000;
case "1m":
return 60_000;
case "off":
case "until-dismissed":
return null;
}
}
export function newNotificationDisplayLabel(value: NewNotificationDisplay): string {
switch (value) {
case "off":
return "Off";
case "until-dismissed":
return "Until dismissed";
case "1m":
return "1min";
default:
return value;
}
}
export function brightnessLabel(value: BrightnessSetting): string {
return value === "auto" ? "Auto" : value;
}
+24
View File
@@ -78,6 +78,7 @@ import {
firmwareDebugFlagsSetting,
lockScreenEnabledSetting,
menuAnimationSetting,
newNotificationDisplaySetting,
saveVoiceRecordingsSetting,
showBleBandwidthSetting,
suspendEvenHubWhenScreenOffSetting,
@@ -100,9 +101,13 @@ import {
import { wearBridge } from "../../native/wear-bridge";
import { openSettingsSubMenu, SettingsPanelLayer, type SettingsSection } from "./settings-panel";
import { uiFontPickerMenuItem } from "../font-picker";
import { NotificationFilterLayer } from "../notification-filter";
import { compatibleModelDiscoveryMenuItem } from "../openai-compatible-model-picker";
import { isVeniceApiBaseUrl } from "../../native/openai-chat";
/** The Settings section the Notifications app's "Settings" menu item opens. */
export const NOTIFICATIONS_SETTINGS_SECTION = "Notifications";
/** The Settings app's master-detail panel (sections on the left, contents on the right). */
export function createSettingsPanelLayer(): SettingsPanelLayer {
return new SettingsPanelLayer(settingsSections());
@@ -138,6 +143,14 @@ function settingsSections(): SettingsSection[] {
return customizationItems();
},
},
{
// Also opened from the Notifications app's menu (deep link by label).
label: NOTIFICATIONS_SETTINGS_SECTION,
items: [
enumSettingMenuItem(newNotificationDisplaySetting),
notificationFilterMenuItem(),
],
},
{
label: "Voice",
items: [
@@ -334,6 +347,17 @@ function customizationRows(): () => MenuItem[] {
};
}
/** Notifications > Notification filter: per-app toggles for which notifications pop up. */
function notificationFilterMenuItem(): MenuItem {
return submenuItem(
"Notification filter",
(ctx) => {
ctx.stack.push(new NotificationFilterLayer());
},
{ description: "Choose which apps' new notifications pop up on the glasses. All of them still appear in the Notifications app." },
);
}
function autoBrightnessMenuItem(): MenuItem {
return submenuItem(
"Auto-brightness",
+12 -2
View File
@@ -40,12 +40,21 @@ export function modalRect(): { x: number; y: number; width: number; height: numb
export class ShellModalLayer implements Layer {
private readonly stack: LayerStack;
constructor(baseLayer: Layer, actions: LayerActions, private readonly removed?: () => void) {
constructor(
baseLayer: Layer,
actions: LayerActions,
private readonly hooks: {
/** The modal left the shell stack, however it went. */
removed?: () => void;
/** Input reached the modal (before its inner stack handles it). */
input?: (event: InputEvent) => void;
} = {},
) {
this.stack = new LayerStack(baseLayer, actions, modalInterior());
}
onRemoved(): void {
this.removed?.();
this.hooks.removed?.();
}
paint(_ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
@@ -73,6 +82,7 @@ export class ShellModalLayer implements Layer {
}
async handleInput(event: InputEvent, _ctx: LayerContext): Promise<void> {
this.hooks.input?.(event);
await this.stack.handleInput(event);
}
}
+1 -1
View File
@@ -27,7 +27,7 @@ export function notificationPopupDelayMs(notification: { foregroundService?: boo
/** Runs `run` after `delayMs`; returns a function that cancels it. */
export type ScheduleFn = (run: () => void, delayMs: number) => () => void;
const scheduleTimeout: ScheduleFn = (run, delayMs) => {
export const scheduleTimeout: ScheduleFn = (run, delayMs) => {
const timer = setTimeout(run, delayMs);
return () => clearTimeout(timer);
};
@@ -0,0 +1,38 @@
import { scheduleTimeout, type ScheduleFn } from "./notification-popup-delay";
/**
* Closes a new-notification popup that is left untouched for its timeout
* ("Display new notifications"). The host restarts the countdown when the
* popup opens and on each interaction with it (any input, including moving
* its menu selection), and stops it when the popup goes away.
*/
export class NotificationPopupTimeout {
private cancel: (() => void) | null = null;
/** `timeoutMs` null never expires (the popup stays until dismissed). */
constructor(
private readonly timeoutMs: number | null,
private readonly expired: () => void,
private readonly schedule: ScheduleFn = scheduleTimeout,
) {}
/** Start the countdown over. */
restart(): void {
this.stop();
if (this.timeoutMs === null) return;
this.cancel = this.schedule(() => {
this.cancel = null;
this.expired();
}, this.timeoutMs);
}
stop(): void {
this.cancel?.();
this.cancel = null;
}
/** Whether a countdown is running (for tests). */
isRunning(): boolean {
return this.cancel !== null;
}
}
+26 -5
View File
@@ -45,8 +45,11 @@ import {
veniceWebSearchSetting,
batteryIndicatorSettingsKey,
brightnessSetting,
newNotificationDisplaySetting,
newNotificationDisplayTimeoutMs,
onAnySettingChanged,
openAiApiKeySetting,
shouldPopUpNewNotification,
statusBarPositionSetting,
statusBarVisibilitySetting,
timeFormatSetting,
@@ -65,8 +68,8 @@ import {
} from "./chrome-layer";
import { ShellModalLayer } from "./modal-layer";
import { NotificationModalQueue } from "./notification-modal-queue";
import { NotificationPopupTimeout } from "./notification-popup-timeout";
import { ALL_NOTIFICATIONS, readActiveNotifications } from "../../native/notification-icons";
import { shouldShowNotificationOnGlasses } from "../../native/notification-sources";
import { ToolDebugMenuLayer } from "./tool-debug-layer";
import type { InProcessWindow } from "./in-process-window";
import { BrightnessPickerLayer } from "./brightness-picker-layer";
@@ -483,7 +486,7 @@ class Shell {
isAvailable: (notificationKey) => {
if (this.appNotifications.has(notificationKey)) return true;
const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === notificationKey);
return !!notification && shouldShowNotificationOnGlasses(notification.packageName);
return !!notification && shouldPopUpNewNotification(notification.packageName);
},
sleep: () => this.sleep(),
});
@@ -929,18 +932,36 @@ class Shell {
const content = appNotification
? null
: new SingleNotificationLayer(notificationKey, { origin: "new-notification-modal", onClose: close });
// A phone notification's popup closes once left untouched for the
// "Display new notifications" time, as if closed by hand: the notification
// stays on the phone and in the status bar. An app's own notification
// (e.g. a Nightscout alert) is nowhere else to be found, so it stays up.
const timeout = new NotificationPopupTimeout(
appNotification ? null : newNotificationDisplayTimeoutMs(newNotificationDisplaySetting.get()),
() => {
// Something over the popup (a voice dialog, the system menu) is in
// use; count that as interaction rather than closing underneath it.
if (this.stack.topMatches((layer) => layer === popup.modal)) close();
else timeout.restart();
},
);
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);
{
removed: () => {
timeout.stop();
this.appNotifications.delete(notificationKey);
this.notificationModals.removed(popup, this.screenOn);
},
input: () => timeout.restart(),
},
),
};
this.stack.push(popup.modal);
timeout.restart();
return popup;
}
+1 -1
View File
@@ -13,7 +13,7 @@ local `@faceclaw/kotlin` plugin. Generated binaries and Gradle caches are ignore
primitives, sha256/clock/log/file expects), `g2protocol/FirmwareImage`,
`audio/` (Lc3PacketFramer, AudioSegmentation, VoicePrint, WavPcmReader),
`graphics/` (GrayPacket, PreviewPalette, StatusIconArt, NotificationIconArt,
GlyphPacket, OpenTypeNames, SvgIconSource), `net/` (HttpIdentity, SseStream,
ColorGlyphArt, GlyphPacket, OpenTypeNames, SvgIconSource), `net/` (HttpIdentity, SseStream,
ResumableDownload, RemoteInputSession), `evenhub/EvenHubAssetServer`,
`alarms/` (AlarmSchedule, AlarmRingingPolicy), `settings/SettingsChangeHub`,
the stock-firmware flows over a `StockLink` GATT port (`g2protocol/StockLinkSession`,
@@ -0,0 +1,120 @@
package com.faceclaw.app
import kotlin.jvm.JvmStatic
import kotlin.math.max
import kotlin.math.pow
import kotlin.math.roundToInt
/**
* Turns a color glyph (an emoji from a color font the text stack fell back to) into the
* lit-on-black coverage the glyph pipeline carries, so it keeps its internal detail instead of
* showing as its alpha silhouette (a face as a plain disc, ✅ as a plain square). Platform
* rasterizers draw the glyph in white and pass unpremultiplied ARGB; this object owns the
* pixel math so Android and iOS agree.
*
* Shading is by OKLab lightness relative to the glyph's body, its median lightness:
* - the body lights fully, so a one-color emoji (❤️, ⭐, 🖤) reads as its shape at full
* brightness whatever its color, the way the alpha did, rather than dim for being dark;
* - darker detail (eyes, mouths, the digits on 📅) falls toward [DARKEST_LIT], never off, so
* the silhouette stays whole;
* - when a fair share of the glyph is clearly lighter than the body (the check on ✅, the
* circle on 🎱, the eyes on 💩) the body dims toward [DIMMEST_BODY] to leave that detail
* room above it. Small highlights (❤️'s glint) don't count.
* Lit values go through the notification icons' tone curve ([NotificationIconArt.GAMMA]),
* then scale by the pixel's alpha, which stays the glyph's coverage.
*/
object ColorGlyphArt {
/** A pixel this opaque that is not white means the glyph was not drawn in the paint's white. */
private const val MIN_COLOR_ALPHA = 32
/** How far below 255 a channel may sit and still count as white (unpremultiply rounding). */
private const val WHITE_TOLERANCE = 24
/** Lit level of the glyph's darkest detail, before the tone curve. */
private const val DARKEST_LIT = 0.3
/** Lit level the body dims to when the glyph has plenty of detail lighter than it. */
private const val DIMMEST_BODY = 0.6
/** Lightness quantile that must be clearly above the body for the body to dim: about the lightest 10%. */
private const val LIGHT_DETAIL_QUANTILE = 0.9
/** OKLab lightness above the body where light detail starts to dim the body, and the span to fully dimmed. */
private const val LIGHT_DETAIL_START = 0.05
private const val LIGHT_DETAIL_SPAN = 0.2
/**
* The smallest lightness spans the ramps above and below the body stretch over, so faint
* shading on a nearly one-color glyph stays faint instead of stretching to the full range.
*/
private const val MIN_LIGHT_SPAN = 0.15
private const val MIN_DARK_SPAN = 0.3
/**
* Whether a glyph drawn in white came out in other colors, i.e. came from a color font.
* Ordinary glyphs are white wherever they have coverage.
*/
@JvmStatic
fun isColor(argb: IntArray): Boolean {
val threshold = 255 - WHITE_TOLERANCE
for (p in argb) {
if (alpha(p) < MIN_COLOR_ALPHA) continue
if (((p shr 16) and 0xff) < threshold || ((p shr 8) and 0xff) < threshold || (p and 0xff) < threshold) {
return true
}
}
return false
}
/**
* Coverage (one byte per pixel) of a glyph drawn in white as unpremultiplied ARGB: its alpha,
* or for a color glyph its [shade].
*/
@JvmStatic
fun coverage(argb: IntArray): ByteArray =
if (isColor(argb)) shade(argb) else ByteArray(argb.size) { alpha(argb[it]).toByte() }
/** Lit-on-black shade (one byte per pixel) of a color glyph as unpremultiplied ARGB. */
@JvmStatic
fun shade(argb: IntArray): ByteArray {
var peak = 0
for (p in argb) peak = max(peak, alpha(p))
val out = ByteArray(argb.size)
if (peak == 0) return out
// Statistics over the solid part, so antialiased edges don't skew the body.
val cutoff = max(1, (peak + 1) / 2)
var solid = 0
for (p in argb) if (alpha(p) >= cutoff) solid += 1
val sorted = DoubleArray(solid)
var next = 0
for (p in argb) if (alpha(p) >= cutoff) sorted[next++] = Oklab.lightness(p)
sorted.sort()
val body = quantile(sorted, 0.5)
val darkest = quantile(sorted, 0.05)
val lightest = quantile(sorted, 0.95)
val lightDetail = quantile(sorted, LIGHT_DETAIL_QUANTILE) - body
val dimming = ((lightDetail - LIGHT_DETAIL_START) / LIGHT_DETAIL_SPAN).coerceIn(0.0, 1.0)
val bodyLit = 1.0 - (1.0 - DIMMEST_BODY) * dimming
val lightSpan = max(lightest - body, MIN_LIGHT_SPAN)
val darkSpan = max(body - darkest, MIN_DARK_SPAN)
for (i in argb.indices) {
val p = argb[i]
val a = alpha(p)
if (a == 0) continue
val l = Oklab.lightness(p)
val lit = if (l >= body) {
bodyLit + (1.0 - bodyLit) * ((l - body) / lightSpan).coerceAtMost(1.0)
} else {
bodyLit - (bodyLit - DARKEST_LIT) * ((body - l) / darkSpan).coerceAtMost(1.0)
}
out[i] = (a * lit.pow(NotificationIconArt.GAMMA)).roundToInt().coerceIn(0, 255).toByte()
}
return out
}
private fun quantile(sorted: DoubleArray, q: Double): Double = sorted[((sorted.size - 1) * q).roundToInt()]
private fun alpha(p: Int): Int = (p ushr 24) and 0xff
}
@@ -2,7 +2,6 @@ package com.faceclaw.app
import kotlin.jvm.JvmStatic
import kotlin.math.abs
import kotlin.math.cbrt
import kotlin.math.max
import kotlin.math.min
import kotlin.math.pow
@@ -72,12 +71,6 @@ object NotificationIconArt {
class Art(val kind: Kind, val gray: ByteArray)
/** sRGB byte value to linear light. */
private val SRGB_TO_LINEAR = DoubleArray(256) { value ->
val c = value / 255.0
if (c <= 0.04045) c / 12.92 else ((c + 0.055) / 1.055).pow(2.4)
}
/**
* Classify and convert an icon rendered at (outputSize * ANALYSIS_SCALE) square, row-major
* ARGB (not premultiplied).
@@ -232,7 +225,7 @@ object NotificationIconArt {
private fun readTile(argb: IntArray, mask: BooleanArray, size: Int, maxAlpha: Int, outputSize: Int): Art {
val lab = DoubleArray(argb.size * 3)
for (i in argb.indices) {
if (mask[i]) toOklab(argb[i], lab, i * 3)
if (mask[i]) Oklab.toOklab(argb[i], lab, i * 3)
}
// The background is the color of the tile's rim, about one output pixel deep.
@@ -347,18 +340,6 @@ object NotificationIconArt {
return gray
}
private fun toOklab(pixel: Int, out: DoubleArray, offset: Int) {
val r = SRGB_TO_LINEAR[(pixel shr 16) and 0xff]
val g = SRGB_TO_LINEAR[(pixel shr 8) and 0xff]
val b = SRGB_TO_LINEAR[pixel and 0xff]
val l = cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)
val m = cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)
val s = cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)
out[offset] = 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s
out[offset + 1] = 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s
out[offset + 2] = 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s
}
private fun distance(lab: DoubleArray, index: Int, background: DoubleArray): Double {
val dl = lab[index * 3] - background[0]
val da = lab[index * 3 + 1] - background[1]
@@ -0,0 +1,40 @@
package com.faceclaw.app
import kotlin.math.cbrt
import kotlin.math.pow
/**
* OKLab, a perceptual color space: L is lightness (0 = black, 1 = white) and equal distances
* look about equally different. The color analysis of icons and color glyphs works in it.
*/
internal object Oklab {
/** sRGB byte value to linear light. */
private val SRGB_TO_LINEAR = DoubleArray(256) { value ->
val c = value / 255.0
if (c <= 0.04045) c / 12.92 else ((c + 0.055) / 1.055).pow(2.4)
}
/** Writes the (L, a, b) of an ARGB pixel's color (its alpha ignored) at out[offset]. */
fun toOklab(pixel: Int, out: DoubleArray, offset: Int) {
val r = SRGB_TO_LINEAR[(pixel shr 16) and 0xff]
val g = SRGB_TO_LINEAR[(pixel shr 8) and 0xff]
val b = SRGB_TO_LINEAR[pixel and 0xff]
val l = cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)
val m = cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)
val s = cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)
out[offset] = 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s
out[offset + 1] = 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s
out[offset + 2] = 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s
}
/** The OKLab lightness of an ARGB pixel's color (its alpha ignored). */
fun lightness(pixel: Int): Double {
val r = SRGB_TO_LINEAR[(pixel shr 16) and 0xff]
val g = SRGB_TO_LINEAR[(pixel shr 8) and 0xff]
val b = SRGB_TO_LINEAR[pixel and 0xff]
val l = cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)
val m = cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)
val s = cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)
return 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s
}
}
@@ -0,0 +1,28 @@
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package com.faceclaw.app
import platform.Foundation.NSData
/** ColorGlyphArt for FaceclawFontRenderer.m, which draws color glyphs with CoreGraphics. */
object IosColorGlyph {
/**
* The shade (one byte per pixel) of a color glyph drawn as premultiplied RGBA bytes, as a
* kCGImageAlphaPremultipliedLast context lays them out. Empty data for a malformed buffer
* rather than an exception, which would terminate the app on its way into Objective-C.
*/
fun shade(rgba: NSData): NSData {
val bytes = rgba.byteArray()
if (bytes.isEmpty() || bytes.size % 4 != 0) return NSData()
val argb = IntArray(bytes.size / 4) { i ->
val a = bytes[i * 4 + 3].toInt() and 0xff
fun channel(offset: Int): Int {
if (a == 0) return 0
val premultiplied = bytes[i * 4 + offset].toInt() and 0xff
return ((premultiplied * 255 + a / 2) / a).coerceAtMost(255)
}
(a shl 24) or (channel(0) shl 16) or (channel(1) shl 8) or channel(2)
}
return ColorGlyphArt.shade(argb).data()
}
}
+1
View File
@@ -283,6 +283,7 @@ function shellEnv({ wakeAction = 'voice-input', skipConfirmation = false } = {})
'../notifications': {}, '../dashboard-settings': settings, './ambient-cards': {},
'./chrome-layer': { ShellChromeLayer: class {} }, './modal-layer': {}, './tool-debug-layer': {},
'./brightness-picker-layer': {}, './notification-modal-queue': load('app/ui/shell/notification-modal-queue.ts', {}),
'./notification-popup-timeout': {},
'../../native/notification-icons': {}, '../../native/notification-sources': {},
'../../assistant/tool-registry': {}, './geometry': {
sidebarWidth: () => 64, minWindowTop: () => 96, switcherPosition: () => 'left', uiDepth: () => 0,
@@ -73,6 +73,7 @@ function settingsEnv(initialUrl = '', initialModel = 'openai-compatible') {
openSettingsSubMenu() {},
},
'../font-picker': { uiFontPickerMenuItem: () => ({ label: 'Font' }) },
'../notification-filter': { NotificationFilterLayer: class {} },
'../openai-compatible-model-picker': {
compatibleModelDiscoveryMenuItem: () => ({ label: 'Discover models' }),
},
+3 -1
View File
@@ -17,6 +17,8 @@ const setting = (initial = '') => {
class AuthError extends Error {}
const gestures = loader({}, {})('app/ui/gestures.ts');
/**
* Load the store layer, by default with a signed-out account and no stored
* credentials. `api` overrides evenHubApi methods; text the layer paints is
@@ -34,7 +36,7 @@ const loadStoreLayer = ({ configured = false, api = {} } = {}) => {
'../../graphics/image': { GrayImage: class { drawText(_f, _x, _y, text) { drawn.push(text); } fillRect() {} } },
'../../graphics/textwrap': { truncateText: (_f, text) => text, wrapText: (_f, text) => [text] },
'../../util/numeric-util': { clamp: (v, lo, hi) => Math.min(hi, Math.max(lo, v)) },
'../../ui/gestures': { GESTURE_CLICK: 'click' },
'../../ui/gestures': { ...gestures, GESTURE_CLICK: 'click' },
'../../ui/menu': { drawSelectionHighlight() {} },
'../../ui/menu-core': require('../.test-build/app/ui/menu-core.js'),
'../../ui/shell/shell': { shell: { yieldFocusToSidebar() {} } },
+262
View File
@@ -0,0 +1,262 @@
// EvenHub store navigation: watch swipes on the tab strip, the Updates tab's
// Update All row, and page-at-a-time scrolling in the permission dialog.
//
// The real layers run with their dependencies mocked; what they paint is
// collected as text, so these assert what the user would see.
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
const gestures = loader({}, {})('app/ui/gestures.ts');
const font = { lineHeight: 10, measureText: (text) => text.length * 6 };
/** Records drawn text; every other drawing call is a no-op. */
const makeImageClass = (drawn) => class {
drawText(_font, _x, _y, text) { drawn.push(text); }
fillRect() {}
fillRoundedRect() {}
drawRoundedRect() {}
};
/** Stand-in for ui/menu-core's Menu: draws every row in order, scrolls the selection by one. */
class FakeMenu {
constructor(options) {
this.options = options;
this.items = options.items;
this.selectedIndex = 0;
this.scrollTop = 0;
}
setItems(items, selectedIndex) {
this.items = items;
if (selectedIndex !== undefined) this.selectedIndex = selectedIndex;
this.selectedIndex = Math.max(0, Math.min(this.selectedIndex, items.length - 1));
}
get selectedItem() { return this.items[this.selectedIndex] ?? null; }
handleInput(event) {
if (event.type === 'scroll-down') this.selectedIndex = Math.min(this.items.length - 1, this.selectedIndex + 1);
if (event.type === 'scroll-up') this.selectedIndex = Math.max(0, this.selectedIndex - 1);
}
paint(image, box) {
this.items.forEach((item, index) => this.options.draw({ image, item, index, x: box.x, y: box.y, width: box.width }));
}
drawScrollbar() {}
}
const storeApp = (packageId, name, version) => ({
id: 1, packageId, name, version, creatorName: '', tagline: '', description: '', categories: [],
installCount: 0, likeCount: 0, firstPublishedAt: '', iconPath: '', changelog: '', fileSize: 0,
});
const emptyPage = { apps: [], total: 0, page: 1, pageSize: 20 };
/** A signed-in store layer; `updates` is what the update check reports. */
const loadStore = ({ updates = [] } = {}) => {
const drawn = [];
const installs = [];
const setting = { get: () => '', set() {} };
const load = loader({}, {
'../../graphics/ui-fonts': { getDefaultSmallFont: () => font },
'../../graphics/image': { GrayImage: makeImageClass(drawn) },
'../../graphics/textwrap': { truncateText: (_f, text) => text, wrapText: (_f, text) => [text] },
'../../ui/gestures': { ...gestures, GESTURE_CLICK: 'click' },
'../../ui/menu': { drawSelectionHighlight() {} },
'../../ui/menu-core': { Menu: FakeMenu },
'../../ui/shell/shell': { shell: { yieldFocusToSidebar() {} } },
'../../ui/metrics': { lineStep: () => 12 },
'../../ui/dashboard-settings': {
ConfigSettingString: class { constructor(options) { this.value = options.defaultValue ?? ''; }
get() { return this.value; } set(next) { this.value = next; return next; } },
},
'./even-api': {
evenHubApi: { listApps: async () => emptyPage, listNewApps: async () => emptyPage, searchApps: async () => emptyPage },
EvenHubAuthenticationError: class extends Error {},
isEvenHubStoreConfigured: () => true,
},
'./credentials': {
evenHubLoginEmailSetting: setting, evenHubLoginPasswordSetting: setting, evenHubRememberMeSetting: setting,
clearEvenHubLoginForm() {}, resetEvenHubLoginForm() {}, clearEvenHubSession() {}, clearTransientEvenHubSession() {},
},
'./installed-apps': { getInstalledEvenHubApps: () => updates.map((update) => update.installed), uninstallEvenHubPackage: () => true },
'./store-detail-layer': { EvenHubStoreDetailLayer: class {} },
'./store-install': {
cleanError: (error) => String(error?.message ?? error),
installStoreApp: async (_ctx, app) => { installs.push(app.packageId); return { packageId: app.packageId }; },
},
'./updates': {
checkForEvenHubUpdates: async () => updates,
describeUpdate: () => ({ updateAvailable: false, packageMissing: false }),
},
});
const { EvenHubStoreLayer } = load('app/apps/evenhub/store-layer.ts');
const layer = new EvenHubStoreLayer({ launchApp: async () => {}, appendLog: () => {} });
return { layer, drawn, installs };
};
const makeCtx = () => ({
stack: {
getBaseSize: () => ({ width: 576, height: 288 }),
isFocused: () => true,
clearToBase() {},
push() {},
pop() {},
},
actions: { requestRender() {}, endTextSettingEdit() {}, startTextSettingsEdit() {} },
});
const settle = () => new Promise((resolve) => setImmediate(resolve));
/** Repaint and return the drawn text. */
const repaint = (layer, drawn, ctx) => {
drawn.length = 0;
layer.paint(ctx);
return [...drawn];
};
const watch = (type) => ({ type, source: 'watch', timestampMs: 0 });
test('watch swipes left and right switch tabs while the tab strip is focused', async () => {
const { layer, drawn } = loadStore();
const ctx = makeCtx();
layer.paint(ctx);
await settle();
assert.ok(repaint(layer, drawn, ctx).includes('Public apps by popularity'));
// In the list, a right swipe is "select" and must not change tabs.
await layer.handleInput(watch('swipe-right'), ctx);
await settle();
assert.ok(repaint(layer, drawn, ctx).includes('Public apps by popularity'), 'still on Top');
// A left swipe in the list is "back", which focuses the tab strip.
await layer.handleInput(watch('swipe-left'), ctx);
await layer.handleInput(watch('swipe-right'), ctx);
await settle();
assert.ok(repaint(layer, drawn, ctx).includes('Recently published apps'), 'right moved to New');
await layer.handleInput(watch('swipe-left'), ctx);
await settle();
assert.ok(repaint(layer, drawn, ctx).includes('Public apps by popularity'), 'left moved back to Top');
// Up/down still switch tabs too.
await layer.handleInput(watch('swipe-down'), ctx);
await settle();
assert.ok(repaint(layer, drawn, ctx).includes('Recently published apps'), 'down moved to New');
});
/** Open the store and move to the Updates tab, with focus back in its list. */
const openUpdatesTab = async (layer, ctx) => {
layer.paint(ctx);
await settle();
await layer.handleInput({ type: 'double-click', source: 'ring' }, ctx);
for (let i = 0; i < 3; i++) await layer.handleInput({ type: 'scroll-down' }, ctx);
await settle();
await layer.handleInput({ type: 'click', source: 'ring' }, ctx);
};
test('the Updates tab lists Update All first and it installs every update', async () => {
const updates = [
{ installed: { packageId: 'a', name: 'Alpha', version: '1' }, latest: storeApp('a', 'Alpha', '2'), packageMissing: false },
{ installed: { packageId: 'b', name: 'Beta', version: '1' }, latest: storeApp('b', 'Beta', '3'), packageMissing: false },
{ installed: { packageId: 'c', name: 'Gamma', version: '1' } },
];
const { layer, drawn, installs } = loadStore({ updates });
const ctx = makeCtx();
await openUpdatesTab(layer, ctx);
const painted = repaint(layer, drawn, ctx);
assert.ok(painted.includes('Updates (3)'), `the tab count is apps, not rows: ${JSON.stringify(painted)}`);
assert.ok(painted.includes('3 apps need attention'));
const updateAll = painted.indexOf('Update All');
assert.ok(updateAll >= 0, `painted: ${JSON.stringify(painted)}`);
assert.ok(painted.includes('Install all 2 available updates'), 'the orphan is not counted');
assert.ok(updateAll < painted.indexOf('Alpha') && updateAll < painted.indexOf('Gamma'), 'Update All is the first row');
// The list opens on Update All; clicking it installs both updatable apps.
await layer.handleInput({ type: 'click', source: 'ring' }, ctx);
await settle();
assert.deepEqual(installs, ['a', 'b']);
const after = repaint(layer, drawn, ctx);
assert.ok(!after.includes('Update All'), 'nothing left to update, so the row goes');
assert.ok(after.includes('Gamma'), 'the missing package stays listed');
assert.ok(after.includes('Updated 2 apps.'));
});
test('the Updates tab has no Update All row when nothing can be installed', async () => {
const updates = [{ installed: { packageId: 'c', name: 'Gamma', version: '1' } }];
const { layer, drawn } = loadStore({ updates });
const ctx = makeCtx();
await openUpdatesTab(layer, ctx);
const painted = repaint(layer, drawn, ctx);
assert.ok(painted.includes('Gamma'));
assert.ok(!painted.includes('Update All'));
});
// ---- permission dialog ---------------------------------------------------
const loadDialog = (detailLines) => {
const drawn = [];
const load = loader({}, {
'../../graphics/ui-fonts': { getDefaultSmallFont: () => font },
'../../graphics/image': { GrayImage: makeImageClass(drawn) },
'../../graphics/textwrap': { truncateText: (_f, text) => text, wrapText: (_f, text) => text.split('|') },
'../../ui/gestures': gestures,
'../../ui/layers': {},
'../../ui/menu': { drawListScrollbar() {}, drawSelectionHighlight() {} },
'./permissions': { permissionDetail: (permission) => permission.detail, permissionLabel: (name) => name },
'./privacy-policy': { openPrivacyPolicyOnPhone() {} },
'../../ui/metrics': { lineStep: () => 12, listRowHeight: () => 20 },
});
const { EvenHubPermissionDialogLayer } = load('app/apps/evenhub/permission-dialog.ts');
const ImageClass = makeImageClass(drawn);
const outcome = { confirmed: null };
const dialog = new EvenHubPermissionDialogLayer(
'Demo',
[{ name: 'network', detail: detailLines.join('|') }],
'',
() => { outcome.confirmed = true; },
() => { outcome.confirmed = false; },
);
const ctx = { stack: { getBaseSize: () => ({ width: 576, height: 136 }), isFocused: () => true, pop() {} } };
const paint = () => {
drawn.length = 0;
dialog.paint(ctx, () => new ImageClass());
return [...drawn];
};
return { dialog, ctx, paint, outcome };
};
test('the permission dialog scrolls a page at a time with one line of overlap', () => {
const lines = Array.from({ length: 30 }, (_, i) => `line ${i + 1}`);
const { dialog, ctx, paint, outcome } = loadDialog(lines);
const pages = [paint()];
while (!pages[pages.length - 1].includes('Allow')) {
assert.ok(pages.length < 20, 'paging reaches the actions');
dialog.handleInput({ type: 'scroll-down' }, ctx);
pages.push(paint());
}
assert.ok(pages.length >= 3, `the list is long enough to need several pages (${pages.length})`);
// Every page but the last (which stops at the bottom) starts on the line the previous one ended on.
for (let page = 1; page < pages.length - 1; page++) {
const previous = pages[page - 1];
assert.equal(pages[page][0], previous[previous.length - 1], `page ${page + 1} overlaps page ${page} by one line`);
assert.ok(pages[page].length > 2, 'a page moves by more than one line');
}
// Every line was on screen on some page.
for (const line of lines) assert.ok(pages.some((page) => page.includes(line)), `${line} was shown`);
// Paging up from the bottom: the old first line becomes the new last one.
const bottom = pages[pages.length - 1];
dialog.handleInput({ type: 'scroll-up' }, ctx);
const up = paint();
assert.equal(up[up.length - 1], bottom[0], 'one line of overlap going up');
assert.ok(up.length > 2);
for (let i = 0; i < pages.length; i++) dialog.handleInput({ type: 'scroll-up' }, ctx);
assert.deepEqual(paint(), pages[0], 'back at the top');
// A click before the bottom pages down rather than allowing; scrolling up returns.
dialog.handleInput({ type: 'click', source: 'ring' }, ctx);
assert.deepEqual(paint(), pages[1]);
assert.equal(outcome.confirmed, null);
dialog.handleInput({ type: 'scroll-up' }, ctx);
assert.deepEqual(paint(), pages[0]);
});
@@ -0,0 +1,108 @@
package com.faceclaw.app
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlin.test.*
class ColorGlyphArtTest {
private val size = 16
private val clear = 0
private val white = argb(255, 255, 255, 255)
private val yellow = argb(255, 255, 204, 50)
private val brown = argb(255, 90, 50, 20)
private val darkGray = argb(255, 60, 60, 60)
private val green = argb(255, 120, 170, 60)
private val red = argb(255, 230, 60, 50)
private val lightRed = argb(255, 250, 140, 130)
private fun argb(a: Int, r: Int, g: Int, b: Int): Int = (a shl 24) or (r shl 16) or (g shl 8) or b
private fun glyph(pixel: (x: Int, y: Int) -> Int): IntArray = IntArray(size * size) { pixel(it % size, it / size) }
private fun inDisc(x: Int, y: Int): Boolean {
val dx = x + 0.5 - size / 2.0
val dy = y + 0.5 - size / 2.0
return dx * dx + dy * dy <= 7.0 * 7.0
}
private fun at(shade: ByteArray, x: Int, y: Int): Int = shade[y * size + x].toInt() and 0xff
private fun lit(level: Double): Int = (255 * level.pow(NotificationIconArt.GAMMA)).roundToInt()
@Test fun whiteGlyphIsItsAlpha() {
// An ordinary glyph drawn in white: antialiased edges, no color anywhere.
val pixels = glyph { x, y -> if (x in 4..11) argb(if (x == 4 || x == 11) 90 else 255, 255, 255, 255) else clear }
assertFalse(ColorGlyphArt.isColor(pixels))
assertContentEquals(ByteArray(pixels.size) { ((pixels[it] ushr 24) and 0xff).toByte() }, ColorGlyphArt.coverage(pixels))
}
@Test fun faintColorFringeIsNotColor() {
// Unpremultiplying a nearly transparent pixel can land anywhere; only real ink counts.
val pixels = glyph { x, _ -> if (x == 3) argb(8, 0, 0, 0) else if (x in 4..11) white else clear }
assertFalse(ColorGlyphArt.isColor(pixels))
}
@Test fun oneColorGlyphLightsFully() {
// 🖤: dark by lightness, but its shape is what matters.
val pixels = glyph { x, y -> if (inDisc(x, y)) darkGray else clear }
assertTrue(ColorGlyphArt.isColor(pixels))
val shade = ColorGlyphArt.coverage(pixels)
assertEquals(255, at(shade, 8, 8))
assertEquals(0, at(shade, 0, 0))
}
@Test fun darkDetailOnALightBodyStaysVisibleButDim() {
// 😀: a yellow disc with dark eyes and mouth; the body stays full, the features dim.
val pixels = glyph { x, y ->
when {
!inDisc(x, y) -> clear
(y in 5..6 && (x == 5 || x == 10)) || (y == 11 && x in 5..10) -> brown
else -> yellow
}
}
val shade = ColorGlyphArt.coverage(pixels)
assertEquals(255, at(shade, 8, 8))
assertEquals(lit(0.3), at(shade, 5, 5))
assertTrue(at(shade, 5, 5) > 0)
}
@Test fun lightDetailOnADarkerBodyDimsTheBody() {
// ✅: a green tile with a large white check; the check lights fully above a dimmer tile.
val pixels = glyph { x, y ->
when {
x !in 1..14 || y !in 1..14 -> clear
(x in 4..7 && y in 9..11) || (x in 7..12 && y in 4..8) -> white
else -> green
}
}
val shade = ColorGlyphArt.coverage(pixels)
assertEquals(255, at(shade, 9, 6))
assertEquals(lit(0.6), at(shade, 2, 2))
}
@Test fun smallHighlightLeavesTheBodyFull() {
// ❤️: a red body with a small glint; the glint is not detail worth dimming the body for.
val pixels = glyph { x, y ->
when {
!inDisc(x, y) -> clear
x in 4..5 && y in 4..5 -> lightRed
else -> red
}
}
val shade = ColorGlyphArt.coverage(pixels)
assertEquals(255, at(shade, 8, 8))
assertEquals(255, at(shade, 4, 4))
}
@Test fun edgeAlphaScalesTheShade() {
val pixels = glyph { x, y -> if (x == 2) argb(128, 60, 60, 60) else if (x in 3..12 && y in 3..12) darkGray else clear }
val shade = ColorGlyphArt.coverage(pixels)
assertEquals(128, at(shade, 2, 8))
assertEquals(0, at(shade, 1, 8))
}
@Test fun emptyGlyphIsEmpty() {
assertTrue(ColorGlyphArt.shade(IntArray(size * size)).all { it.toInt() == 0 })
}
}
+51 -2
View File
@@ -23,6 +23,41 @@ function store(settings = new Map()) {
}
const mail = { packageName: 'com.mail', appName: 'Mail' };
/** dashboard-settings.ts over the same in-memory store, with `prefs` as its notification-sources. */
function dashboardSettings(settings, prefs) {
return evaluate(source('app/ui/dashboard-settings.ts'), (id) => {
if (id.includes('settings-store')) return {
onSettingsStoreChanged() {}, getStringSetting: (key, fallback) => settings.get(key) ?? fallback,
setStringSetting: (key, value) => settings.set(key, value),
getBooleanSetting: (key, fallback) => settings.get(key) ?? fallback, setBooleanSetting: (key, value) => settings.set(key, value),
};
if (id.includes('notification-sources')) return prefs;
if (id.includes('brightness-curve')) return require('../.test-build/app/g2/brightness-curve.js');
if (id.includes('animation-speed')) return require('../.test-build/app/ui/animation-speed.js');
return { Layer: class {}, ASSISTANT_MODEL_CHOICES: [] };
}, { global: { isIOS: false } });
}
test('"Display new notifications" defaults to 15s; Off stops every popup, the filter still mutes single apps', () => {
const settings = new Map();
const prefs = store(settings);
const api = dashboardSettings(settings, prefs);
assert.equal(api.newNotificationDisplaySetting.get(), '15s');
// Array.from: the module's arrays come from its own VM realm.
const values = Array.from(api.newNotificationDisplaySetting.values);
assert.deepEqual(values.map((value) => api.newNotificationDisplaySetting.displayValue(value)),
['Off', 'Until dismissed', '5s', '15s', '1min']);
assert.deepEqual(values.map(api.newNotificationDisplayTimeoutMs), [null, null, 5_000, 15_000, 60_000]);
assert.equal(api.shouldPopUpNewNotification(mail.packageName), true);
prefs.setNotificationSourceEnabled(mail, false);
assert.equal(api.shouldPopUpNewNotification(mail.packageName), false);
assert.equal(api.shouldPopUpNewNotification('com.other'), true);
api.newNotificationDisplaySetting.set('off');
assert.equal(api.shouldPopUpNewNotification('com.other'), false);
api.newNotificationDisplaySetting.set('until-dismissed');
assert.equal(api.shouldPopUpNewNotification('com.other'), true);
});
test('sources default on and retain per-package choices and names across restart and rediscovery', () => {
const settings = new Map();
let prefs = store(settings);
@@ -194,14 +229,16 @@ test('controller filters before waking or opening a popup, and still refreshes t
const members = ['handleAndroidNotificationPosted', 'handleAndroidNotificationRemoved', 'popUpAndroidNotification']
.map((name) => controller.members.find((node) => node.name?.getText(file) === name).getText(file));
const { NotificationPopupDelay, notificationPopupDelayMs } = require('../.test-build/app/ui/shell/notification-popup-delay.js');
const prefs = store();
const settings = new Map();
const prefs = store(settings);
const { newNotificationDisplaySetting, shouldPopUpNewNotification } = dashboardSettings(settings, prefs);
let active = [{ ...mail, key: 'key' }];
let wakes = 0, popups = 0, renders = 0;
const removed = [];
const { Harness } = evaluate(`export class Harness { ${members.join('\n')} }`, null, {
ALL_NOTIFICATIONS: 0x7fffffff,
readActiveNotifications: () => active,
shouldShowNotificationOnGlasses: prefs.shouldShowNotificationOnGlasses,
shouldPopUpNewNotification,
notificationPopupDelayMs,
shell: {
isScreenOn: () => false,
@@ -253,4 +290,16 @@ test('controller filters before waking or opening a popup, and still refreshes t
prefs.setNotificationSourceEnabled(mail, false);
elapse();
assert.equal(popups, 1);
// "Display new notifications: Off" holds back every app's popup, also once the delay is over.
prefs.setNotificationSourceEnabled(mail, true);
newNotificationDisplaySetting.set('off');
instance.handleAndroidNotificationPosted('key');
elapse();
newNotificationDisplaySetting.set('15s');
instance.handleAndroidNotificationPosted('key');
newNotificationDisplaySetting.set('off');
elapse();
assert.equal(wakes, 1);
assert.equal(popups, 1);
});
+94
View File
@@ -0,0 +1,94 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const { NotificationPopupTimeout } = require("../.test-build/app/ui/shell/notification-popup-timeout.js");
/** A manual clock: schedule() queues timers that advance() fires when due. */
function makeClock() {
const clock = {
nowMs: 0,
timers: [],
schedule(run, delayMs) {
const timer = { dueAtMs: clock.nowMs + delayMs, run, cancelled: false };
clock.timers.push(timer);
return () => { timer.cancelled = true; };
},
advance(ms) {
const until = clock.nowMs + ms;
for (;;) {
const due = clock.timers.filter((timer) => !timer.cancelled && timer.dueAtMs <= until)
.sort((a, b) => a.dueAtMs - b.dueAtMs)[0];
if (!due) break;
clock.nowMs = due.dueAtMs;
due.cancelled = true;
due.run();
}
clock.nowMs = until;
},
};
return clock;
}
function makeTimeout(timeoutMs) {
const clock = makeClock();
let expiries = 0;
const timeout = new NotificationPopupTimeout(timeoutMs, () => { expiries++; }, clock.schedule);
return { clock, timeout, expiries: () => expiries };
}
test("an untouched popup expires once its timeout passes", () => {
const { clock, timeout, expiries } = makeTimeout(15_000);
timeout.restart();
clock.advance(14_999);
assert.equal(expiries(), 0);
clock.advance(1);
assert.equal(expiries(), 1);
assert.equal(timeout.isRunning(), false);
clock.advance(60_000);
assert.equal(expiries(), 1);
});
test("each interaction starts the countdown over", () => {
const { clock, timeout, expiries } = makeTimeout(5_000);
timeout.restart();
clock.advance(4_000);
timeout.restart(); // e.g. scrolling the action menu
clock.advance(4_000);
assert.equal(expiries(), 0);
clock.advance(1_000);
assert.equal(expiries(), 1);
});
test("a popup that goes away first never expires", () => {
const { clock, timeout, expiries } = makeTimeout(5_000);
timeout.restart();
clock.advance(2_000);
timeout.stop();
clock.advance(10_000);
assert.equal(expiries(), 0);
});
test("until-dismissed (no timeout) never schedules anything", () => {
const { clock, timeout, expiries } = makeTimeout(null);
timeout.restart();
assert.equal(timeout.isRunning(), false);
assert.equal(clock.timers.length, 0);
clock.advance(1_000_000);
assert.equal(expiries(), 0);
});
test("the expiry callback can restart the countdown (something was over the popup)", () => {
const clock = makeClock();
let expiries = 0;
const timeout = new NotificationPopupTimeout(5_000, () => {
expiries++;
if (expiries === 1) timeout.restart();
}, clock.schedule);
timeout.restart();
clock.advance(5_000);
assert.equal(expiries, 1);
assert.equal(timeout.isRunning(), true);
clock.advance(5_000);
assert.equal(expiries, 2);
assert.equal(timeout.isRunning(), false);
});
+1
View File
@@ -39,6 +39,7 @@
"../app/g2/glance-state.ts",
"../app/ui/shell/notification-modal-queue.ts",
"../app/ui/shell/notification-popup-delay.ts",
"../app/ui/shell/notification-popup-timeout.ts",
"../app/apps/glanceboard/layout.ts",
"../app/apps/files/video-layout.ts",
"../app/g2/pairing-candidates.ts",