Merge branch 'main' of https://github.com/jimrandomh/faceclaw into microphone-fixes

This commit is contained in:
James Babcock committed 2026-09-27 17:57:23 -07:00
commit 80f16c0cd6
40 files changed
+975 -160

No files matched your search

@@ -0,0 +1,22 @@
package com.faceclaw.app
import android.util.Log
import android.webkit.ConsoleMessage
import android.webkit.WebChromeClient
/**
* Surfaces a hosted EvenHub app's console in logcat (tag FaceclawEvenHubConsole).
* Native rather than a NativeScript-extended WebChromeClient: chatty apps log
* many lines a second, and each one used to cost a Java->JS callback plus three
* JS->Java calls back to read the message, all on the main thread.
*/
class FaceclawEvenHubChromeClient : WebChromeClient() {
override fun onConsoleMessage(message: ConsoleMessage): Boolean {
Log.i(TAG, "${message.message()} (${message.sourceId()}:${message.lineNumber()})")
return true
}
private companion object {
const val TAG = "FaceclawEvenHubConsole"
}
}
@@ -23,4 +23,10 @@ class FaceclawEvenHubJsBridge(private val listener: FaceclawEvenHubListener) {
listener.onEvenAppMessage(handlerName, argsJson, callId)
}
}
/** The page's timer shim has work due before the host's next tick. */
@JavascriptInterface
fun wakeTimers() {
FaceclawEvenHubWebViewHost.getInstance().wakeTimers()
}
}
@@ -1,6 +1,7 @@
package com.faceclaw.app
import android.app.Activity
import android.content.MutableContextWrapper
import android.os.Build
import android.os.Handler
import android.os.Looper
@@ -10,6 +11,7 @@ import android.webkit.WebView
import android.widget.FrameLayout
import java.util.ArrayList
import java.util.HashMap
/**
* Keeps EvenHub app WebViews alive and rendering while the phone shows the
@@ -38,9 +40,11 @@ import java.util.ArrayList
* crawl even though the renderer is still alive. Host-initiated
* evaluateJavascript is NOT subject to that throttle, so we drive the app's
* timers ourselves: a document-start shim replaces setTimeout/setInterval (and
* requestAnimationFrame) with JS queues fired by window.__fcTimerTick() /
* __fcRafTick(), and this host ticks those on the main thread at a fixed rate
* regardless of screen state. The main Looper keeps running under the
* requestAnimationFrame) with JS queues fired by window.__fcTick(), and this
* host ticks those on the main thread regardless of screen state. The tick
* returns when the page next has work, so an idle page isn't evaluated at
* 60Hz; work scheduled between ticks wakes the host through
* FaceclawEvenHubJsBridge.wakeTimers. The main Looper keeps running under the
* foreground service, so the tick survives the screen turning off. (Matches the
* official Even app's approach.)
*
@@ -54,30 +58,87 @@ import java.util.ArrayList
* timers/onResume asserted on attach. The main Looper keeps ticking under the
* foreground service, so apps keep driving their glasses windows in the
* background.
*
* Activity recreation: this host outlives any one activity (it is a process
* singleton, and apps keep running while the activity is destroyed and
* recreated, e.g. after an app update or a config change). The overlay lives in
* one activity's content view, so attach and showOnPhone first move it, with
* every WebView in it, into the activity they are given if it isn't already
* there; otherwise "show" would raise it in a dead window. WebViews are created
* on a MutableContextWrapper whose base is re-pointed at the same time, so the
* dialogs Chromium opens from the page (e.g. a <select>'s picker) use the live
* activity too.
*/
class FaceclawEvenHubWebViewHost {
private var overlay: FrameLayout? = null
private var overlayActivity: Activity? = null
private var shown = false
private val mainHandler = Handler(Looper.getMainLooper())
private val webViews: MutableList<WebView> = ArrayList()
private var ticking = false
private val ticker: Runnable = object : Runnable {
private val tickers: MutableMap<WebView, Ticker> = HashMap()
/**
* Drives one page's timer/rAF queues (window.__fcTick). Each tick's result
* says when the page next has work; the ticker sleeps until then, or until
* the page wakes it. It also re-ticks after IDLE_POLL_MS regardless, so a
* lost evaluateJavascript callback (e.g. mid-navigation) or a page whose
* wake didn't reach us stalls its timers for at most that long.
*/
private inner class Ticker(private val web: WebView) : Runnable {
private var inFlight = false
private var wakePending = false
private var stopped = false
override fun run() {
for (i in 0 until webViews.size) {
webViews[i].evaluateJavascript(
"window.__fcTimerTick&&__fcTimerTick();window.__fcRafTick&&__fcRafTick()", null)
if (stopped) return
inFlight = true
web.evaluateJavascript(TICK_JS) { result -> onTicked(result) }
schedule(IDLE_POLL_MS)
}
private fun onTicked(result: String?) {
inFlight = false
if (stopped) return
// -1 (nothing pending) and null (shim not installed yet) both leave
// only the idle poll; the page wakes us when it schedules work.
val next = result?.toDoubleOrNull()?.toLong() ?: -1L
val delay = when {
wakePending -> 0L
next < 0 -> IDLE_POLL_MS
else -> next.coerceIn(TICK_MS, IDLE_POLL_MS)
}
if (ticking) mainHandler.postDelayed(this, TICK_MS)
wakePending = false
schedule(delay)
}
fun wake() {
if (stopped) return
if (inFlight) wakePending = true else schedule(0)
}
fun stop() {
stopped = true
mainHandler.removeCallbacks(this)
}
private fun schedule(delayMs: Long) {
mainHandler.removeCallbacks(this)
mainHandler.postDelayed(this, delayMs)
}
}
companion object {
private var instance: FaceclawEvenHubWebViewHost? = null
/** How often the host fires the JS timer queue. 60Hz keeps games smooth. */
/** Shortest interval between ticks. 60Hz keeps games smooth. */
private const val TICK_MS = 16L
/** Longest a page goes without a tick, as a backstop for missed wakes. */
private const val IDLE_POLL_MS = 1000L
private const val TICK_JS = "window.__fcTick?__fcTick():null"
@JvmStatic
@Synchronized
fun getInstance(): FaceclawEvenHubWebViewHost {
@@ -86,20 +147,38 @@ class FaceclawEvenHubWebViewHost {
}
}
/** The overlay, in [activity]'s content view (moved there, with its WebViews, if it was elsewhere). */
private fun ensureOverlay(activity: Activity): FrameLayout {
overlay?.let { return it }
val existing = overlay
if (existing != null && overlayActivity === activity && existing.parent != null) return existing
val content = activity.findViewById<ViewGroup>(android.R.id.content)
val created = FrameLayout(activity)
if (existing != null) {
(existing.parent as ViewGroup?)?.removeView(existing)
for (web in webViews) {
existing.removeView(web)
rebaseContext(web, activity)
created.addView(web, FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
}
}
overlay = created
// index 0 = behind the NativeScript content view.
overlayActivity = activity
// index 0 = behind the NativeScript content view (raised again below if shown).
content.addView(created, 0, FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
if (shown) created.bringToFront()
return created
}
private fun rebaseContext(web: WebView, activity: Activity) {
(web.context as? MutableContextWrapper)?.baseContext = activity
}
/** Add a WebView to the host, full-size and rendering, hidden behind the UI. */
fun attach(activity: Activity, web: WebView) {
val o = ensureOverlay(activity)
rebaseContext(web, activity)
web.visibility = View.VISIBLE
if (web.parent == null) {
o.addView(web, FrameLayout.LayoutParams(
@@ -118,15 +197,27 @@ class FaceclawEvenHubWebViewHost {
web.setRendererPriorityPolicy(WebView.RENDERER_PRIORITY_IMPORTANT, false)
}
if (!webViews.contains(web)) webViews.add(web)
if (!ticking) {
ticking = true
if (!tickers.containsKey(web)) {
val ticker = Ticker(web)
tickers[web] = ticker
mainHandler.postDelayed(ticker, TICK_MS)
}
}
/** Bring an app's WebView to the front so it is visible on the phone. */
fun showOnPhone(web: WebView) {
val o = overlay ?: return
/**
* A page scheduled a timer or animation frame due before its next tick.
* Called from the JavaBridge thread; which page asked doesn't matter, as
* an extra tick for another page is harmless.
*/
fun wakeTimers() {
mainHandler.post {
for (ticker in tickers.values) ticker.wake()
}
}
/** Bring an app's WebView to the front of [activity] so it is visible on the phone. */
fun showOnPhone(activity: Activity?, web: WebView) {
val o = if (activity != null) ensureOverlay(activity) else overlay ?: return
web.bringToFront()
o.bringToFront()
shown = true
@@ -150,10 +241,7 @@ class FaceclawEvenHubWebViewHost {
/** Remove and destroy a WebView (its app is closing). */
fun detach(web: WebView) {
webViews.remove(web)
if (webViews.isEmpty() && ticking) {
ticking = false
mainHandler.removeCallbacks(ticker)
}
tickers.remove(web)?.stop()
overlay?.removeView(web)
web.destroy()
}
+22 -1
View File
@@ -1,16 +1,23 @@
# Changelog
## 0.7.3 - Future
## 0.8.1 - Future
* Add config settings to disable animation categories
* EvenHub compatibility uses menu animations and is closer to style matched
## 0.8.0 - 2026-09-26
### Depth and Animation
* A new display-list system for glasses-side drawing, unlocking z-effects and animation
* Menus animate when changing selection and scrolling
* Menus bounce at the ends, and show part of the next row when there is more below
* The launcher and Files app icon grids animate sliding, scrolling and bouncing
* Fade-in/out effects when turning the screen on/off
* Custom auto-brightness control algorithm, with configurable min, max and curve
* Depth effects for the window switcher, top bar, and modals
* Glanceboard has configurable distance
* Dimmed background behind the system context menu dithers rather than hiding minimum-brightness underlays
### Other Features and Bugfixes
@@ -20,12 +27,26 @@
* EvenHub: Fix login form being stuck open without a cancel button
* Calendar: Fix a timezone issue that could cause all-day events to appear on the preceding day
* Compass: Make the calibration readiness visible by default
* Terminal app: Tap a host heading to launch a shell there (alternative to the app context menu)
* Nightscout: Move the "Always show in top bar" setting earlier in the form so it's harder to miss
* EvenHub: Fix the sign-in form reopening on every launch after an unfinished sign-in
* EvenHub: Fix the installer not rerendering when an app finishes downloading
* Fix a frozen menu in the notification modal
* Fix a race when restoring open apps at startup, which could leave the previously-foreground window covering the new one
* Reduce phone CPU usage
* Fix a memory leak
* Better handling of silent mode
* Tweak the layout of the voice input dialog
* Add GitHub workflows for automated tests
### iOS port:
* Add iOS calendar integration
* iOS main screen matches the Android version's styling
* Hub apps on iOS no longer have their timers stopped while the phone app is in the background
* Some settings that were Android-only are now available on iOS
* Move a lot more of the iOS implementation onto shared Kotlin code
* Converted most Android-specific duplicative code to shared code
## 0.7.2 - 2026-09-19
+6 -39
View File
@@ -7,8 +7,10 @@
* match what apps expect.
*
* Known deviations from stock, acceptable for now:
* - List rendering is a plain vertical list; itemWidth-based horizontal
* layouts are not implemented yet.
* - List rendering is a plain vertical list. A non-zero itemWidth sets the
* selection outline's width and truncates long items to fit, as on stock;
* whether stock also lays narrow items out side by side is unknown.
* - Lists scroll with our menus' animation and bounce (see list-menu.ts).
*/
import { GrayImage } from "../../graphics/image";
import { EvenHubFont } from "../../graphics/evenhub-font";
@@ -19,12 +21,12 @@ import {
type EvenHubPage,
type EvenHubTextContainer,
} from "./containers";
import { paintListItems } from "./list-menu";
export const EVENHUB_SCREEN_WIDTH = 576;
export const EVENHUB_SCREEN_HEIGHT = 288;
const TEXT_WHITE = 255;
const LIST_ROW_PADDING = 4;
/**
* SDK 0.0.14 textColor levels 0..4 as grey values. Level 4 is the default and
@@ -90,44 +92,9 @@ function paintImageContainer(image: GrayImage, container: EvenHubImageContainer)
}
}
/** Horizontal padding between the selection outline and the item text. */
const LIST_SELECT_PADDING = 8;
const LIST_SELECT_RADIUS = 8;
function paintListContainer(image: GrayImage, container: EvenHubListContainer, focused: boolean): void {
paintBorder(image, container);
const font = EvenHubFont.get();
const inset = container.borderWidth + container.paddingLength;
const rowHeight = font.lineHeight + LIST_ROW_PADDING;
const left = container.x + inset;
const top = container.y + inset;
const innerWidth = Math.max(1, container.width - 2 * inset);
// Text is indented by the selection padding so the outline sits inside the list.
const textX = left + LIST_SELECT_PADDING;
const visibleRows = Math.max(1, Math.floor((container.height - 2 * inset) / rowHeight));
// Keep the selection in view.
let firstRow = 0;
if (container.selectedIndex >= visibleRows) firstRow = container.selectedIndex - visibleRows + 1;
for (let row = 0; row < visibleRows; row++) {
const index = firstRow + row;
if (index >= container.itemNames.length) break;
const name = container.itemNames[index]!;
const y = top + row * rowHeight;
if (index === container.selectedIndex) {
// Selection: a rounded outline sized to the text (not the full row width),
// with padding on each side and no fill — matching stock's appearance.
const textWidth = font.measureLine(name);
image.drawRoundedRect(
left,
y,
Math.min(textWidth + 2 * LIST_SELECT_PADDING, innerWidth),
rowHeight - 1,
focused ? TEXT_WHITE : 130,
LIST_SELECT_RADIUS,
);
}
font.drawText(image, textX, y + Math.floor(LIST_ROW_PADDING / 2), name, TEXT_WHITE);
}
paintListItems(image, container, EvenHubFont.get(), focused);
}
/** Bottom-to-top paint order for a page's containers. */
+11 -2
View File
@@ -57,7 +57,9 @@ export type EvenHubListContainer = {
zOrderIndex: number | undefined;
preserve: boolean;
itemNames: string[];
/** Fixed width of each item's selection outline; 0 is auto (the outline hugs the text). */
itemWidth: number;
/** isItemSelectBorderEn: whether the selected item is outlined. A protobuf field, so absent means off. */
selectBorder: boolean;
/** Selection is host-local: scroll moves it with no app round-trip. */
selectedIndex: number;
@@ -82,6 +84,9 @@ export type EvenHubPage = {
menuItems: EvenHubMenuItem[];
};
/** Stock draws at most a 5px border; wider requests are clamped. */
const MAX_BORDER_WIDTH = 5;
/** Firmware brightness levels for text; 4 is the device default. */
const MIN_TEXT_BRIGHTNESS = 0;
const MAX_TEXT_BRIGHTNESS = 4;
@@ -129,6 +134,10 @@ export function asRecord(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
}
function readBorderWidth(json: Record<string, unknown>): number {
return Math.max(0, Math.min(MAX_BORDER_WIDTH, readNumber(json, "borderWidth", 0)));
}
function parseTextContainer(json: Record<string, unknown>): EvenHubTextContainer {
return {
kind: "text",
@@ -138,7 +147,7 @@ function parseTextContainer(json: Record<string, unknown>): EvenHubTextContainer
y: readNumber(json, "yPosition", 0),
width: readNumber(json, "width", 0),
height: readNumber(json, "height", 0),
borderWidth: readNumber(json, "borderWidth", 0),
borderWidth: readBorderWidth(json),
borderRadius: readNumber(json, "borderRadius", 0),
paddingLength: readNumber(json, "paddingLength", 0),
isEventCapture: readNumber(json, "isEventCapture", 0) !== 0,
@@ -230,7 +239,7 @@ function parseListContainer(json: Record<string, unknown>): EvenHubListContainer
y: readNumber(json, "yPosition", 0),
width: readNumber(json, "width", 0),
height: readNumber(json, "height", 0),
borderWidth: readNumber(json, "borderWidth", 0),
borderWidth: readBorderWidth(json),
borderRadius: readNumber(json, "borderRadius", 0),
paddingLength: readNumber(json, "paddingLength", 0),
isEventCapture: readNumber(json, "isEventCapture", 0) !== 0,
+126
View File
@@ -0,0 +1,126 @@
/**
* EvenHub list containers, drawn and navigated by the shared Menu<T> in the
* stock list style: the selected item gets a rounded outline sized to its
* text, with no fill, and every other item's text is dimmed to 2/15
* brightness. Scrolling animates and the ends bounce, like our own menus, but the
* selection itself moves instantly (no highlight slide), as on stock.
*
* Native-free (the font is passed in) so it can be unit-tested under Node.
*/
import { GrayImage } from "../../graphics/image";
import { Menu } from "../../ui/menu-core";
import type { EvenHubListContainer } from "./containers";
/** The subset of EvenHubFont a list needs. */
export type EvenHubListFont = {
readonly lineHeight: number;
measureLine(text: string): number;
drawText(image: GrayImage, x: number, y: number, text: string, value?: number): void;
};
/** Space between the selection outline and the item text, horizontally and vertically. */
export const LIST_ITEM_PADDING_X = 12;
export const LIST_ITEM_PADDING_Y = 6;
const LIST_SELECT_RADIUS = 8;
const SELECTED_TEXT = 255;
/** 4-bit level 3 (3/15). */
export const DESELECTED_TEXT = 50;
const OUTLINE_FOCUSED = 255;
const OUTLINE_UNFOCUSED = 130;
export function listRowHeight(font: EvenHubListFont): number {
return font.lineHeight + 2 * LIST_ITEM_PADDING_Y;
}
/**
* One Menu per container object, so its scroll motion persists across paints.
* A rebuilt page has new container objects and so starts without motion.
*/
const menus = new WeakMap<EvenHubListContainer, Menu<string>>();
const ELLIPSIS = "...";
/** `text`, or its longest prefix that fits in `maxWidth` with "..." appended. */
export function truncateToWidth(font: EvenHubListFont, text: string, maxWidth: number): string {
if (font.measureLine(text) <= maxWidth) return text;
const chars = Array.from(text);
// Binary search for the longest prefix that fits with the ellipsis.
let low = 0, high = chars.length - 1;
while (low < high) {
const mid = (low + high + 1) >> 1;
if (font.measureLine(chars.slice(0, mid).join("") + ELLIPSIS) <= maxWidth) low = mid;
else high = mid - 1;
}
return chars.slice(0, low).join("") + ELLIPSIS;
}
/** The container's menu, synced to its items and selection (the container is the source of truth). */
function listMenu(list: EvenHubListContainer, font: EvenHubListFont): Menu<string> {
let menu = menus.get(list);
if (!menu) {
const rowHeight = listRowHeight(font);
menu = new Menu<string>({
items: list.itemNames,
selectedIndex: list.selectedIndex,
getHeight: () => rowHeight,
// The draw callback shows the selection, so there is no highlight to slide.
highlight: false,
// No wrap and no exit callbacks: the ends bounce. The session tells the app.
wrap: false,
draw: ({ image, item, x, y, width, height, selected, focused }) => {
// itemWidth 0 is auto: the outline hugs the text. A fixed itemWidth
// sets the outline's width exactly, and text that doesn't fit inside
// its padding is cut short with "...".
const fixedWidth = list.itemWidth > 0 ? Math.min(list.itemWidth, width) : 0;
const text = fixedWidth ? truncateToWidth(font, item, fixedWidth - 2 * LIST_ITEM_PADDING_X) : item;
if (selected && list.selectBorder) {
image.drawRoundedRect(
x,
y,
fixedWidth || Math.min(font.measureLine(text) + 2 * LIST_ITEM_PADDING_X, width),
height - 1,
focused ? OUTLINE_FOCUSED : OUTLINE_UNFOCUSED,
LIST_SELECT_RADIUS,
);
}
font.drawText(image, x + LIST_ITEM_PADDING_X, y + LIST_ITEM_PADDING_Y, text,
selected ? SELECTED_TEXT : DESELECTED_TEXT);
},
});
menus.set(list, menu);
}
if (menu.items !== list.itemNames) menu.setItems(list.itemNames, list.selectedIndex);
else if (menu.selectedIndex !== list.selectedIndex) menu.select(list.selectedIndex);
return menu;
}
/** Paint the list's items inside its border and padding. */
export function paintListItems(
image: GrayImage,
list: EvenHubListContainer,
font: EvenHubListFont,
focused: boolean,
): void {
const inset = list.borderWidth + list.paddingLength;
const rowHeight = listRowHeight(font);
// A row cut by the bottom edge is drawn clipped, as a hint that there is
// more. A container shorter than one row still shows one whole row.
listMenu(list, font).paint(image, {
x: list.x + inset,
y: list.y + inset,
width: Math.max(1, list.width - 2 * inset),
height: Math.max(rowHeight, list.height - 2 * inset),
}, focused);
}
/**
* Step the selection (swipe up = previous). Returns false when it was already
* at that end: the selection stays put and the list bounces.
*/
export function stepListSelection(list: EvenHubListContainer, font: EvenHubListFont, delta: -1 | 1): boolean {
const menu = listMenu(list, font);
const before = list.selectedIndex;
menu.moveSelection(delta);
list.selectedIndex = menu.selectedIndex ?? 0;
return list.selectedIndex !== before;
}
+70 -33
View File
@@ -52,6 +52,7 @@ import {
type EvenHubPage,
} from "./containers";
import { compositePage } from "./compositor";
import { stepListSelection } from "./list-menu";
import { type EvenHubManifest } from "./ehpk";
import { permissionsIncludeMicrophone, permissionsInclude } from "./permissions";
import { evenHubMicRouter, type EvenHubMicClient } from "./mic-router";
@@ -109,30 +110,61 @@ export const EVENHUB_BRIDGE_INJECT_SCRIPT = `
};
})();
(function () {
// Host-driven timers. Chromium heavily throttles a page's own
// setTimeout/setInterval when the phone screen is off, which slows
// timer-driven apps to a crawl. Replace them with a queue fired by
// window.__fcTimerTick(), which the native host calls at ~60Hz regardless of
// Host-driven timers and requestAnimationFrame. Chromium heavily throttles a
// page's own setTimeout/setInterval when the phone screen is off, and pauses
// or throttles a hidden page's rAF, which slows timer-driven apps to a crawl
// and stalls canvas apps that render on a rAF loop. Replace them with queues
// fired by window.__fcTick(), which the native host calls regardless of
// screen state (host-initiated evaluateJavascript escapes the throttle).
if (window.__fcTimerTick) return;
// (The glasses render via BLE, not the phone's display, so vsync alignment
// doesn't matter — a steady frame rate does.)
//
// __fcTick returns how many ms until it next has work (-1: none), and the
// host sleeps until then instead of evaluating JS at 60Hz for an idle page.
// Work added outside a tick that is due before the host's next tick wakes it
// through the bridge.
if (window.__fcTick) return;
var FRAME_MS = 16;
var timers = new Map();
var nextId = 1;
var rafs = new Map();
var nextRafId = 1;
var inTick = false;
// When the host will next call __fcTick; Infinity while it is idle.
var hostNextTickAt = Infinity;
function needTickBy(due) {
if (inTick || due >= hostNextTickAt) return;
hostNextTickAt = Date.now();
var bridge = window.__faceclawEvenHub;
if (bridge && bridge.wakeTimers) bridge.wakeTimers();
}
window.setTimeout = function (cb, delay) {
var args = Array.prototype.slice.call(arguments, 2);
var id = nextId++;
timers.set(id, { cb: cb, args: args, due: Date.now() + (+delay || 0), interval: 0 });
var due = Date.now() + (+delay || 0);
timers.set(id, { cb: cb, args: args, due: due, interval: 0 });
needTickBy(due);
return id;
};
window.setInterval = function (cb, delay) {
var args = Array.prototype.slice.call(arguments, 2);
var id = nextId++;
var d = +delay || 0;
timers.set(id, { cb: cb, args: args, due: Date.now() + d, interval: d });
var due = Date.now() + d;
timers.set(id, { cb: cb, args: args, due: due, interval: d });
needTickBy(due);
return id;
};
window.clearTimeout = function (id) { timers.delete(id); };
window.clearInterval = function (id) { timers.delete(id); };
window.__fcTimerTick = function () {
window.requestAnimationFrame = function (cb) {
var id = nextRafId++;
rafs.set(id, cb);
needTickBy(Date.now() + FRAME_MS);
return id;
};
window.cancelAnimationFrame = function (id) { rafs.delete(id); };
function runTimers() {
var now = Date.now();
var dueIds = [];
timers.forEach(function (entry, id) { if (entry.due <= now) dueIds.push(id); });
@@ -150,24 +182,8 @@ export const EVENHUB_BRIDGE_INJECT_SCRIPT = `
}
try { entry.cb.apply(null, entry.args); } catch (e) { if (window.console) console.error(e); }
}
};
})();
(function () {
// Host-driven requestAnimationFrame, same idea as the timers above: a hidden
// page's rAF is paused/throttled with the screen off, stalling canvas apps
// that render on a rAF loop. Drive it from window.__fcRafTick(), called by the
// native ticker each frame. (The glasses render via BLE, not the phone's
// display, so vsync alignment doesn't matter — a steady frame rate does.)
if (window.__fcRafTick) return;
var rafs = new Map();
var nextRafId = 1;
window.requestAnimationFrame = function (cb) {
var id = nextRafId++;
rafs.set(id, cb);
return id;
};
window.cancelAnimationFrame = function (id) { rafs.delete(id); };
window.__fcRafTick = function () {
}
function runRafs() {
if (rafs.size === 0) return;
var ts = window.performance && performance.now ? performance.now() : Date.now();
// Snapshot and clear: callbacks that re-request during this frame run on
@@ -177,6 +193,32 @@ export const EVENHUB_BRIDGE_INJECT_SCRIPT = `
current.forEach(function (cb) {
try { cb(ts); } catch (e) { if (window.console) console.error(e); }
});
}
function inTickDo(fn) {
inTick = true;
try { fn(); } finally { inTick = false; }
}
// Fixed-rate entry points for hosts that don't use __fcTick's schedule (the
// iOS host calls both every frame).
window.__fcTimerTick = function () { inTickDo(runTimers); };
window.__fcRafTick = function () { inTickDo(runRafs); };
window.__fcTick = function () {
inTick = true;
try {
runTimers();
runRafs();
} finally {
inTick = false;
}
var now = Date.now();
var delay = rafs.size ? FRAME_MS : -1;
timers.forEach(function (entry) {
var d = entry.due - now;
if (delay < 0 || d < delay) delay = d;
});
if (delay >= 0) delay = Math.max(FRAME_MS, Math.ceil(delay));
hostNextTickAt = delay < 0 ? Infinity : now + delay;
return delay;
};
})();
`;
@@ -502,13 +544,8 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
private scrollList(list: EvenHubListContainer, eventType: number): void {
// Swipe up selects the previous item, swipe down the next (stock direction).
const delta = eventType === SCROLL_TOP_EVENT ? -1 : 1;
const next = list.selectedIndex + delta;
if (next < 0 || next >= list.itemNames.length) {
// At a boundary the selection stays put and the app hears about it.
this.emitListEvent(list, eventType);
return;
}
list.selectedIndex = next;
// At a boundary the selection stays put (the list bounces) and the app hears about it.
if (!stepListSelection(list, EvenHubFont.get(), delta)) this.emitListEvent(list, eventType);
this.windowHooks?.requestRender();
}
+6 -12
View File
@@ -54,7 +54,9 @@ function originRule(url: string): string {
export function createEvenHubWebView(session: EvenHubSession): EvenHubWebView {
const activity = Application.android?.foregroundActivity ?? Application.android?.startActivity;
const context = activity ?? Utils.android.getApplicationContext();
const webView = new com.faceclaw.app.FaceclawEvenHubWebView(context);
// A mutable wrapper, so the host can re-point the WebView at a recreated
// activity (see FaceclawEvenHubWebViewHost).
const webView = new com.faceclaw.app.FaceclawEvenHubWebView(new android.content.MutableContextWrapper(context));
const settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
@@ -94,16 +96,7 @@ export function createEvenHubWebView(session: EvenHubSession): EvenHubWebView {
webView.addJavascriptInterface(new com.faceclaw.app.FaceclawEvenHubJsBridge(listener), "__faceclawEvenHub");
// Surface the app's console in logcat (tag FaceclawEvenHubConsole).
const ChromeClient = (android.webkit.WebChromeClient as any).extend({
onConsoleMessage: (message: any): boolean => {
android.util.Log.i(
"FaceclawEvenHubConsole",
`${message.message()} (${message.sourceId()}:${message.lineNumber()})`,
);
return true;
},
});
webView.setWebChromeClient(new ChromeClient());
webView.setWebChromeClient(new com.faceclaw.app.FaceclawEvenHubChromeClient());
const nativeHost = com.faceclaw.app.FaceclawEvenHubWebViewHost.getInstance();
nativeHost.attach(activity, webView);
@@ -125,7 +118,8 @@ export function createEvenHubWebView(session: EvenHubSession): EvenHubWebView {
console.warn(`evenhub webview destroy failed: ${error}`);
}
},
showOnPhone: () => nativeHost.showOnPhone(webView),
showOnPhone: () =>
nativeHost.showOnPhone(Application.android?.foregroundActivity ?? Application.android?.startActivity ?? null, webView),
hideOnPhone: () => nativeHost.hideOnPhone(),
};
}
+18 -4
View File
@@ -2537,6 +2537,19 @@ class DashboardController {
this.pendingShellRenderCauseFrameId = 0;
const frameId = frameTimings.startFrame("render:shell", causeFrameId);
frameTimings.annotateFrame(frameId, shell.describeInputTarget());
// Nothing to send a frame to: stop here, BEFORE painting. This check used
// to run only after the paint, which made a no-display state a
// main-thread busy loop: paint (~55 ms) -> endRenderPass reports stale
// data -> requestShellRender re-queues (shellRenderQueued, since a render
// is in progress) -> the display check discards the work -> the do/while
// in requestShellRender goes straight round again. Measured on a device
// with the glasses not presenting: 40 of 40 frames discarded, ~19 a
// second, enough to starve input and ANR. Leaving early costs nothing and
// breaks the loop, because the re-request lives downstream of this point.
if (!this.display || this.phase === "charging") {
frameTimings.finishFrame(frameId, "discarded: shell render with no display target");
return;
}
const wantFreshData = this.nextShellRenderWantsFreshData;
this.nextShellRenderWantsFreshData = false;
if (wantFreshData) frameTimings.logFrame(frameId, "follow-up repaint that must not use cached data");
@@ -2555,11 +2568,12 @@ class DashboardController {
this.nextShellRenderWantsFreshData = true;
this.requestShellRender(frameId);
}
// The display-target check that used to live here now runs before the
// paint, at the top of this function. Nothing between the two can change
// it -- paintScene is synchronous and there is no await in between -- so
// repeating it here is dead code, and the compiler agrees: the early
// return narrows this.phase, making the "charging" comparison impossible.
const display = this.display;
if (!display || this.phase === "charging") {
frameTimings.finishFrame(frameId, "discarded: shell render with no display target");
return;
}
await frameTimings.spanAsync(frameId, "submit", () => display.submitShellScene(planes, paintMs, frameId));
// Backpressure: the next shell render waits for this one to reach the
// glasses. Timing out here means the loop was blocked for the full timeout
+33 -5
View File
@@ -95,6 +95,34 @@ function inMode15UncertainRange(cp: number): boolean {
return false;
}
/**
* advanceOf's result per (codePoint, nextCodePoint) pair. Pretext's metrics
* are static data, so this never goes stale; it saves wrap/draw three
* getTextWidth calls (each splitting strings and walking the font chain) for
* every character of every repaint.
*/
const kernedAdvances = new Map<number, number>();
function kernedAdvance(codePoint: number, nextCodePoint: number): number {
// Codepoints are < 0x110000, so this key is unique and exact as a double.
const key = codePoint * 0x110000 + nextCodePoint;
let advance = kernedAdvances.get(key);
if (advance === undefined) {
const a = String.fromCodePoint(codePoint);
if (!nextCodePoint) {
advance = getTextWidth(a);
} else {
const b = String.fromCodePoint(nextCodePoint);
advance = getTextWidth(a + b) - getTextWidth(b);
}
// Pairs are bounded by the text actually shown, but CJK-heavy apps could
// still accumulate a lot of them; start over rather than grow forever.
if (kernedAdvances.size >= 65536) kernedAdvances.clear();
kernedAdvances.set(key, advance);
}
return advance;
}
/** The 4bpp level an 8-bit value packs to (BmpUtil's GRAY_TO_NIBBLE). */
const quantNibble = grayToNibble;
@@ -178,15 +206,15 @@ export class EvenHubFont implements FwTextFont {
* exactly: width(a+b) - width(b) isolates a's kerned advance.
*/
advanceOf(codePoint: number, nextCodePoint = 0): number {
const a = String.fromCodePoint(codePoint);
if (!nextCodePoint) return getTextWidth(a);
const b = String.fromCodePoint(nextCodePoint);
return getTextWidth(a + b) - getTextWidth(b);
return kernedAdvance(codePoint, nextCodePoint);
}
/** Single-line pixel width including kerning (pretext-exact). */
measureLine(text: string): number {
return getTextWidth(text);
const cps = Array.from(text, (c) => c.codePointAt(0)!);
let width = 0;
for (let i = 0; i < cps.length; i++) width += kernedAdvance(cps[i]!, cps[i + 1] ?? 0);
return width;
}
/**
+3 -3
View File
@@ -1,5 +1,5 @@
import { nightscoutApiTokenSetting, nightscoutSiteUrlSetting } from "../ui/dashboard-settings";
import { fetchWithUserAgent } from "../util/http";
import { fetchTextWithUserAgent } from "../util/http";
export type NightscoutPoint = {
timestampMs: number;
@@ -305,11 +305,11 @@ export class NightscoutBridge {
}
async function fetchJson<T>(url: string): Promise<T> {
const response = await fetchWithUserAgent(url);
const response = await fetchTextWithUserAgent(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return (await response.json()) as T;
return response.json<T>();
}
function parseTreatments(treatments: NightscoutTreatmentResponse[], nowMs: number): {
+18 -1
View File
@@ -18,6 +18,7 @@ import {
} from "~/assistant/models";
import { isLocalModelReady } from "../native/llama";
import { drawRightValueMenuItem, drawToggleMenuItem, MenuItem, openModalMenu } from "./menu";
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";
@@ -361,11 +362,27 @@ export const autoBrightnessCurveSetting = new ConfigSettingString({
});
const SCREEN_FADE_MS = 280;
export const menuAnimationSetting = new ConfigSettingBoolean({
id: "menu-animation",
label: "Menu animation",
storageKey: MENU_ANIMATION_KEY,
defaultValue: true,
description: "Slide the highlight, scroll, and bounce at the ends in menus, lists, and the launcher and Files icon grids. When off, they move instantly.",
});
export const screenFadeSetting = new ConfigSettingBoolean({
id: "screen-fade",
label: "Screen fade",
storageKey: "display.screenFade",
defaultValue: true,
description: "Fade the display in and out when the screen turns on or off. When off, it switches instantly.",
});
export function getBrightnessPreferences() {
const level = brightnessSettingToLevel(brightnessSetting.get());
return { auto: level === null, level: level ?? 50,
minimum: Number(autoBrightnessMinSetting.get()), maximum: Number(autoBrightnessMaxSetting.get()),
curve: autoBrightnessCurveSetting.getValidValue(), fadeMs: SCREEN_FADE_MS };
curve: autoBrightnessCurveSetting.getValidValue(), fadeMs: screenFadeSetting.get() ? SCREEN_FADE_MS : 0 };
}
export const screenTimeoutSetting = new ConfigSettingEnum<ScreenTimeoutSetting>({
+18
View File
@@ -60,9 +60,11 @@ import {
phoneRotationSetting,
ringConnectionModeSetting,
sonioxApiKeySetting,
screenFadeSetting,
enumSettingMenuItem,
firmwareDebugFlagsSetting,
lockScreenEnabledSetting,
menuAnimationSetting,
saveVoiceRecordingsSetting,
showBleBandwidthSetting,
suspendEvenHubWhenScreenOffSetting,
@@ -114,6 +116,8 @@ function settingsSections(): SettingsSection[] {
enumSettingMenuItem(displayModeSetting),
// Submenu: top-bar battery indicator style plus per-device visibility.
batteryIndicatorsMenuItem(),
// Submenu: toggles for menu/icon-grid motion and the screen on/off fade.
animationsMenuItem(),
// Controls the top-bar clock (24-hour vs 12-hour).
enumSettingMenuItem(timeFormatSetting),
// Opens the modal font picker (face, weight, size) for UI text.
@@ -312,6 +316,20 @@ function batteryIndicatorsMenuItem(): MenuItem {
};
}
/** The Display section's "Animations" row: opens a modal submenu of animation toggles. */
function animationsMenuItem(): MenuItem {
return {
label: "Animations",
description: "Turn off menu and icon-grid motion, or the fade when the screen turns on and off.",
onSelect: (ctx) => {
openSettingsSubMenu(ctx, "Animations", [
toggleSettingMenuItem(menuAnimationSetting),
toggleSettingMenuItem(screenFadeSetting),
]);
},
};
}
const LOCAL_MODEL_GB = `${(LOCAL_MODEL.sizeBytes / 1e9).toFixed(1)}GB`;
// While a download is running, re-render on progress updates so the row's
+18
View File
@@ -0,0 +1,18 @@
/**
* Whether menus and icon grids animate on the glasses (Settings > Display >
* Animations > Menu animation). The motion classes can't read the settings
* store themselves (it is native, and they load under Node in unit tests),
* so ui/menu.ts installs a reader in each isolate that paints menus. Without
* one, menus animate.
*/
export const MENU_ANIMATION_KEY = "display.menuAnimation";
let readMenuAnimation: () => boolean = () => true;
export function menuAnimationEnabled(): boolean {
return readMenuAnimation();
}
export function setMenuAnimationReader(read: () => boolean): void {
readMenuAnimation = read;
}
+3 -1
View File
@@ -1,3 +1,5 @@
import { menuAnimationEnabled } from "./menu-animation-pref";
export const MENU_HIGHLIGHT_DURATION_MS = 240;
export type MenuHighlightAnimation = { dx: number; dy: number; startedAt: number; token: number; durationMs: number };
@@ -30,7 +32,7 @@ export class MenuHighlightMotion {
fromX += this.animation.dx * remaining;
fromY += this.animation.dy * remaining;
}
const eligible = previous && previous.index !== index && this.fromIndex === previous.index &&
const eligible = menuAnimationEnabled() && previous && previous.index !== index && this.fromIndex === previous.index &&
(previous.scroll === scroll || scrolling) && previous.width === width && previous.height === height;
this.animation = eligible ? { dx: Math.round(fromX - x), dy: Math.round(fromY - y), startedAt: now, token: nextAnimationToken(), durationMs: MENU_HIGHLIGHT_DURATION_MS } : undefined;
this.fromIndex = null;
+4 -2
View File
@@ -1,4 +1,5 @@
import { DrawExpression as E, ExprOp } from "../graphics/draw-expression";
import { menuAnimationEnabled } from "./menu-animation-pref";
import { MENU_HIGHLIGHT_DURATION_MS, nextAnimationToken } from "./menu-highlight-motion";
/** Longest scroll, in pixels, that animates; longer jumps snap. */
@@ -72,16 +73,17 @@ export class MenuScrollMotion {
/** Record this paint's settled offset; returns the animation in flight, if any. */
paint(scroll: number, box: Box, now: number): MenuScrollAnimation | undefined {
const previous = this.previous;
const enabled = menuAnimationEnabled();
const sameBox = !!previous && previous.box.x === box.x && previous.box.y === box.y &&
previous.box.width === box.width && previous.box.height === box.height;
if (!previous || !sameBox || previous.scroll !== scroll) {
const from = previous ? this.offsetAt(previous.scroll, now) : scroll;
const eligible = sameBox && this.navigated && from !== scroll && Math.abs(scroll - from) <= MAX_ANIMATED_SCROLL;
const eligible = enabled && sameBox && this.navigated && from !== scroll && Math.abs(scroll - from) <= MAX_ANIMATED_SCROLL;
this.animation = eligible
? { from, to: scroll, startedAt: now, token: nextAnimationToken(), durationMs: MENU_HIGHLIGHT_DURATION_MS }
: undefined;
this.previous = { scroll, box: { ...box } };
} else if (this.bounceBy) {
} else if (this.bounceBy && enabled) {
const from = this.offsetAt(scroll, now);
this.animation = Math.abs(scroll - from) <= MAX_ANIMATED_SCROLL
? { from, peak: scroll + this.bounceBy, to: scroll, startedAt: now, token: nextAnimationToken(), durationMs: MENU_BOUNCE_DURATION_MS }
+7
View File
@@ -1,12 +1,19 @@
import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage, type UiFont } from "../graphics/image";
import { wrapText } from "../graphics/textwrap";
import { getDefaultSmallFont } from "../graphics/ui-fonts";
import { getBooleanSetting } from "../native/settings-store";
import { clamp } from "../util/numeric-util";
import { Layer, LayerContext, PaintBelow } from "./layers";
import { MENU_ANIMATION_KEY, setMenuAnimationReader } from "./menu-animation-pref";
import { Menu, MENU_HIGHLIGHT_FILL, MENU_HIGHLIGHT_STROKE } from "./menu-core";
import { GESTURE_DOUBLE_CLICK, InputEvent } from "./gestures";
import { LIST_ROW_TEXT_INSET, centeredTextY, lineStep, listRowHeight, menuTitleHeight } from "./metrics";
// Menu<T> and IconGrid consult this (through their motion classes) at each
// paint; a SharedPreferences read, so changes apply to the next navigation.
setMenuAnimationReader(() => getBooleanSetting(MENU_ANIMATION_KEY, true));
const DEFAULT_MENU_X = 8;
const DEFAULT_MENU_Y = 8;
const DEFAULT_MENU_WIDTH = 272;
+52
View File
@@ -16,6 +16,58 @@ export function fetchWithUserAgent(url: string, init?: RequestInit): Promise<Res
return fetch(url, { ...init, headers: withUserAgent(init?.headers) });
}
/** The parts of a fetch() Response that fetchTextWithUserAgent provides. */
export interface TextResponse {
ok: boolean;
status: number;
text(): Promise<string>;
json<T = unknown>(): Promise<T>;
}
/**
* fetchWithUserAgent for text/JSON bodies, decoded on the Java side.
* NativeScript's fetch() polyfill reads every body as a blob, and on Android
* that copies it from the Java byte[] into JS one bridge call per byte
* (Uint8Array.from in http-request's toArrayBuffer): ~160ms of main thread
* for one Nightscout refresh. Here the body crosses once, as a string.
*/
export async function fetchTextWithUserAgent(
url: string,
init?: { method?: string; headers?: HeadersInit; body?: string },
): Promise<TextResponse> {
// Required lazily so the Node test harness can load this module (via
// fetchWithUserAgent's users) without mocking @nativescript/core. Only the
// http module: the @nativescript/core barrel would pull the UI classes
// (Frame's FragmentClass etc.) into the app workers that import this file,
// and their duplicate extends break the static binding generator.
const { request } = require("@nativescript/core/http") as typeof import("@nativescript/core/http");
const response = await request({
url,
method: init?.method ?? "GET",
headers: withUserAgent(init?.headers),
content: init?.body,
});
const status = response.statusCode;
let body: string | undefined;
const read = (): string => {
if (body === undefined) {
const content = response.content as any;
if (!content) body = "";
// HttpResponseEncoding.UTF8 is 0, so content.toString() can't ask for
// UTF-8 explicitly on Android; decode the raw ByteArrayOutputStream.
else if (global.isAndroid) body = String(content.raw.toString("UTF-8"));
else body = content.toString();
}
return body!;
};
return {
ok: status >= 200 && status < 300,
status,
text: async () => read(),
json: async () => JSON.parse(read()),
};
}
/** Copies headers into a plain record, adding our User-Agent if absent. */
export function withUserAgent(headers?: HeadersInit): Record<string, string> {
const merged: Record<string, string> = {};
+1 -1
View File
@@ -1,2 +1,2 @@
export const FACECLAW_VERSION = "0.7.2";
export const FACECLAW_VERSION = "0.8.0";
export const USER_AGENT = "Faceclaw/"+FACECLAW_VERSION;
@@ -15,8 +15,18 @@ actual class Sha256Digest actual constructor() {
actual fun currentTimeMillis(): Long = System.currentTimeMillis()
actual fun formatLocalTime(epochMs: Long, pattern: String): String =
SimpleDateFormat(pattern, Locale.US).format(Date(epochMs))
// SimpleDateFormat is costly to build (pattern parse, Calendar, locale data) and not thread-safe,
// so keep one per thread per pattern; the send loop formats a timestamp for every image it logs.
private val localTimeFormats = object : ThreadLocal<HashMap<String, SimpleDateFormat>>() {
override fun initialValue() = HashMap<String, SimpleDateFormat>()
}
actual fun formatLocalTime(epochMs: Long, pattern: String): String {
val format = localTimeFormats.get()!!.getOrPut(pattern) { SimpleDateFormat(pattern, Locale.US) }
// Re-read the default zone each call, as a fresh instance would.
format.timeZone = java.util.TimeZone.getDefault()
return format.format(Date(epochMs))
}
actual object PlatformLog {
actual fun i(tag: String, message: String) {
@@ -275,15 +275,17 @@ class GlassesSessionCore(
internal val desiredTilesLock: ProtocolLock = platform.createLock()
internal var desiredFingerprint = ""
// Headerless packed 4bpp frame (see BmpUtil.pack4bppFromGray8) plus its
// pixel dimensions.
internal var desiredPacked: ByteArray? = ByteArray(0)
// Composited 8bpp frame plus its pixel dimensions. The send loop packs it to
// the headerless 4bpp wire format (BmpUtil.pack4bppFromGray8) when it picks
// the frame up, so frames superseded before sending are never packed and
// the packing stays off the submitting (main) thread.
internal var desiredGray: ByteArray? = ByteArray(0)
internal var desiredWidth = 0
internal var desiredHeight = 0
internal var desiredPaintMs = 0
internal var desiredFrameId = 0
// Screen-space deferred draws (glyphs + images) whose pixels are baked
// into desiredPacked; the resource-cache planner may replay them as
// into desiredGray; the resource-cache planner may replay them as
// on-glasses cached draws.
internal var desiredDraws: Array<SurfaceCompositor.ScreenDraw>? = arrayOf()
// (frame, reason) of the last "waiting to send" line, so a frame that
@@ -962,9 +964,7 @@ class GlassesSessionCore(
val frameId = frameTimings.startFrame(
"compositor:visible $id=$visible")
compositor.setSurfaceVisible(id, visible)
val composite = compositor.composite()
val packed = BmpUtil.pack4bppFromGray8(composite.screenGray, composite.width, composite.height)
storeDesiredComposite(composite, packed, 0, frameId)
storeDesiredComposite(compositor.composite(), 0, frameId)
}
/**
@@ -976,9 +976,7 @@ class GlassesSessionCore(
val frameId = frameTimings.startFrame(
"compositor:" + (if (blanked) "blank" else "unblank"))
compositor.setBlanked(blanked)
val composite = compositor.composite()
val packed = BmpUtil.pack4bppFromGray8(composite.screenGray, composite.width, composite.height)
storeDesiredComposite(composite, packed, 0, frameId)
storeDesiredComposite(compositor.composite(), 0, frameId)
}
/**
@@ -998,7 +996,7 @@ class GlassesSessionCore(
fun submitShellScene(bytes: ByteReader, paintMs: Int, frameId: Int) {
compositor.setShellScene(bytes)
val composite = compositor.composite()
storeDesiredComposite(composite, BmpUtil.pack4bppFromGray8(composite.screenGray, composite.width, composite.height), paintMs, frameId)
storeDesiredComposite(composite, paintMs, frameId)
}
/** Legacy compositor dimming for callers without a shell scene. */
@@ -1035,17 +1033,11 @@ class GlassesSessionCore(
val composite = compositor.applyAndComposite(
surfaceId, pixels8bpp, rectX, rectY, rectWidth, rectHeight, contentFingerprint, glyphs)
frameTimings.spanEnd(frameId, "composite")
// Pack the composited 8bpp buffer down to the headerless 4bpp frame
// format the wire planners consume; BMP framing is added later only for
// the uncompressed fallback.
frameTimings.spanStart(frameId, "pack-4bpp")
val packed = BmpUtil.pack4bppFromGray8(composite.screenGray, composite.width, composite.height)
frameTimings.spanEnd(frameId, "pack-4bpp")
storeDesiredComposite(composite, packed, paintMs, frameId)
storeDesiredComposite(composite, paintMs, frameId)
}
/** Store a composite as the desired frame unless a newer one won the race. */
internal fun storeDesiredComposite(composite: SurfaceCompositor.Composite, packed: ByteArray, paintMs: Int, frameId: Int) {
internal fun storeDesiredComposite(composite: SurfaceCompositor.Composite, paintMs: Int, frameId: Int) {
var supersededFrameId = 0
var stale = false
desiredTilesLock.locked {
@@ -1056,7 +1048,7 @@ class GlassesSessionCore(
} else {
lastStoredCompositeSeq = composite.seq
supersededFrameId = desiredFrameId
desiredPacked = packed
desiredGray = composite.screenGray
desiredWidth = composite.width
desiredHeight = composite.height
desiredFingerprint = composite.fingerprint
@@ -711,7 +711,7 @@ internal fun GlassesSessionCore.enqueueAmbientLightControlLocked(payload: ByteAr
internal fun GlassesSessionCore.enqueueDesiredImageLocked() {
val fingerprint: String
val packedSnapshot: ByteArray?
val graySnapshot: ByteArray?
val width: Int
val height: Int
val paintMs: Int
@@ -720,7 +720,7 @@ internal fun GlassesSessionCore.enqueueDesiredImageLocked() {
val scene: ShellScene
desiredTilesLock.locked {
fingerprint = desiredFingerprint
packedSnapshot = desiredPacked
graySnapshot = desiredGray
width = desiredWidth
height = desiredHeight
paintMs = desiredPaintMs
@@ -729,7 +729,13 @@ internal fun GlassesSessionCore.enqueueDesiredImageLocked() {
scene = desiredShellScene
desiredFrameId = 0
}
val packedFrame: ByteArray = packedSnapshot ?: ByteArray(0)
// Pack here rather than at submit: a frame superseded before the send loop
// gets to it is never packed, and the main thread doesn't pay for it.
frameTimings.spanStart(frameId, "pack-4bpp")
val packedFrame: ByteArray =
if (graySnapshot == null || graySnapshot.isEmpty()) ByteArray(0)
else BmpUtil.pack4bppFromGray8(graySnapshot, width, height)
frameTimings.spanEnd(frameId, "pack-4bpp")
// Visibility belongs to this immutable composite, not the latest UI request.
enqueueBrightnessLocked(!fingerprint.startsWith("blanked:"))
if (customFirmwareDetected && packedFrame.size > 0) {
@@ -298,11 +298,78 @@ class DisplayListRenderer(
}
require(width > 0 && height > 0 && x + width <= source.width && y + height <= source.height)
// Mirrors the firmware's overflow guard before the depth shift.
if (walk.apply && dx in -65536..65536) {
// Snapshot the rectangle so overlapping copies have memmove semantics.
val copy = IntArray(width * height) { source.get(x + it % width, y + it / width) }
for (i in copy.indices) target.put(dx + i % width, dy + i / width, copy[i])
if (!walk.apply || dx !in -65536..65536) return
// Clip the destination to the writable area, in shifted target pixels.
// The source is read unshifted, like Target.get.
val originX = dx + target.shiftX
var left = maxOf(originX, 0)
var right = minOf(originX + width, target.width)
var top = maxOf(dy, 0)
var bottom = minOf(dy.toLong() + height, target.height.toLong()).toInt()
target.clip?.let { clip ->
left = maxOf(left, clip[0]); top = maxOf(top, clip[1])
right = minOf(right, clip[2]); bottom = minOf(bottom, clip[3])
}
if (left >= right || top >= bottom) return
val count = right - left
val rows = bottom - top
var sourceX = x + (left - originX)
var sourceBytes = source.bytes
var sourceStride = source.stride
var sourceRow = source.offset + (y + (top - dy)) * sourceStride
if (sourceBytes === target.bytes) {
// Snapshot the packed source span so overlapping copies have memmove semantics.
val first = sourceX / 2
val span = (sourceX + count - 1) / 2 - first + 1
val snapshot = ByteArray(span * rows)
for (row in 0 until rows) {
val start = sourceRow + row * sourceStride + first
sourceBytes.copyInto(snapshot, row * span, start, start + span)
}
sourceBytes = snapshot
sourceStride = span
sourceRow = 0
sourceX = sourceX and 1
}
for (row in 0 until rows) {
copyPixels(sourceBytes, sourceRow + row * sourceStride, sourceX,
target.bytes, target.offset + (top + row) * target.stride, left, count)
}
}
/** Copy [count] packed 4bpp pixels between rows that must not overlap. */
private fun copyPixels(source: ByteArray, sourceRow: Int, sourceX: Int,
destination: ByteArray, destinationRow: Int, destinationX: Int, count: Int) {
var sx = sourceX
var dx = destinationX
var remaining = count
if (dx and 1 != 0) {
putPixel(destination, destinationRow, dx++, getPixel(source, sourceRow, sx++))
remaining--
}
val pairs = remaining / 2
var si = sourceRow + sx / 2
var di = destinationRow + dx / 2
if (sx and 1 == 0) {
source.copyInto(destination, di, si, si + pairs)
} else {
// Misaligned: each destination byte straddles two source bytes.
repeat(pairs) {
destination[di++] = ((source[si].toInt() shl 4) or ((source[++si].toInt() and 255) ushr 4)).toByte()
}
}
if (remaining and 1 != 0) {
putPixel(destination, destinationRow, dx + pairs * 2, getPixel(source, sourceRow, sx + pairs * 2))
}
}
private fun getPixel(bytes: ByteArray, row: Int, x: Int): Int =
(bytes[row + x / 2].toInt() ushr (if (x and 1 == 0) 4 else 0)) and 15
private fun putPixel(bytes: ByteArray, row: Int, x: Int, value: Int) {
val index = row + x / 2
val old = bytes[index].toInt()
bytes[index] = if (x and 1 == 0) ((old and 15) or (value shl 4)).toByte() else ((old and 240) or value).toByte()
}
private fun drawStockText(reader: DrawReader, target: Target, walk: Walk) {
@@ -2,11 +2,17 @@ package com.faceclaw.app
/** Immutable shell snapshot. Keys identify writable surfaces across repaints, not their pixels. */
class ShellScene(val layers: List<Layer>, val selections: List<RetainedDrawing> = emptyList(), val screenDepth: Int = 0) {
class Layer(val key: Int, val x: Int, val y: Int, val width: Int, val height: Int, val dim: Int, val packed: ByteArray, val selections: List<RetainedDrawing> = emptyList(), val depth: Int = 0)
class Layer(val key: Int, val x: Int, val y: Int, val width: Int, val height: Int, val dim: Int, val packed: ByteArray, val selections: List<RetainedDrawing> = emptyList(), val depth: Int = 0) {
// Layers are reused by every composite until the shell repaints, and hashing packed
// byte-by-byte on each one was a measurable share of the compositor's time.
internal val fingerprint: String by lazy {
"$key,$x,$y,$width,$height,$dim,$depth,${CachedResource(packed).hash},${selections.joinToString { row -> row.fingerprint }}"
}
}
val allSelections = selections + layers.flatMap { it.selections }
val retainedResources = allSelections.flatMap { it.resources }
init { require(retainedResources.size + layers.size < 511 && screenDepth in -128..127) }
val fingerprint: String = layers.joinToString(";") { "${it.key},${it.x},${it.y},${it.width},${it.height},${it.dim},${it.depth},${CachedResource(it.packed).hash},${it.selections.joinToString { row -> row.fingerprint }}" } + selections.joinToString { it.fingerprint } + "|depth:$screenDepth"
val fingerprint: String = layers.joinToString(";") { it.fingerprint } + selections.joinToString { it.fingerprint } + "|depth:$screenDepth"
fun calls(width: Int, height: Int, surfaces: IntArray, selected: IntArray): List<ByteArray> {
val calls = ArrayList<ByteArray>(); var rowId = 0
val now = drawAnimationTimeMs()
@@ -582,7 +582,11 @@ class SurfaceCompositor @JvmOverloads constructor(private val includePreviewInFr
expectedBytes)
)
}
run {
if (rectX == 0 && rectWidth == surface.width) {
// Full-width rect (every current submitter): one bulk read. Per-row reads from a
// direct ByteBuffer each cross into native code, which showed up in profiles.
pixels.get(surface.pixels, rectY * surface.width, expectedBytes)
} else run {
var row: Int = 0
while ((row < rectHeight)) {
var dstOffset: Int = (((rectY + row) * surface.width) + rectX)
+7
View File
@@ -22,6 +22,7 @@ function settingsFixture(store = new Map()) {
if (id.includes('settings-store')) return {
onSettingsStoreChanged() {}, getStringSetting: (k, d) => store.get(k) ?? d,
setStringSetting: (k, v) => store.set(k, v),
getBooleanSetting: (k, d) => store.get(k) ?? d, setBooleanSetting: (k, v) => store.set(k, v),
};
if (id.includes('brightness-curve')) return require('../.test-build/app/g2/brightness-curve.js');
return { Layer: class {}, ASSISTANT_MODEL_CHOICES: [] };
@@ -35,6 +36,12 @@ test('auto minimum defaults to 20 and preserves a saved preference', () => {
assert.equal(settingsFixture().getBrightnessPreferences().minimum, 20);
assert.equal(settingsFixture(new Map([['display.autoBrightnessMin', '25']])).getBrightnessPreferences().minimum, 25);
});
test('the screen fade setting switches the on/off fade between 280 ms and instant', () => {
const api = settingsFixture();
assert.equal(api.getBrightnessPreferences().fadeMs, 280);
api.screenFadeSetting.set(false);
assert.equal(api.getBrightnessPreferences().fadeMs, 0);
});
test('curve drafts preview exactly while brightness keeps the previous valid saved curve', () => {
const store = new Map([['display.autoBrightnessCurve', '0:0,2:50,8:100']]);
let api = settingsFixture(store), curve = api.autoBrightnessCurveSetting;
+1
View File
@@ -27,6 +27,7 @@ const layers = load('app/ui/layers.ts', {
'../native/frame-timings': { spanCurrent: (_name, paint) => paint() },
});
const menu = load('app/ui/menu.ts', {
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), '../native/settings-store': { getBooleanSetting: (_key, fallback) => fallback },
'./menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
'../graphics/image': graphics, '../graphics/ui-fonts': fonts, '../graphics/textwrap': textwrap,
'../util/numeric-util': numeric, './gestures': gestures, './metrics': load('app/ui/metrics.ts'),
+14
View File
@@ -89,3 +89,17 @@ test("an omitted or out-of-range textColor falls back to the device default", ()
assert.equal(page.containers[0].textColor, undefined);
}
});
test("borderWidth is clamped to stock's maximum of 5", () => {
const page = parsePage({
listObject: [{ containerID: 1, containerName: "l", borderWidth: 9 }],
textObject: [{ containerID: 2, containerName: "t", borderWidth: 12 }, { containerID: 3, containerName: "u", borderWidth: 3 }],
});
assert.deepEqual(page.containers.map((c) => c.borderWidth), [5, 5, 3]);
});
test("a list without isItemSelectBorderEn has no selection border (protobuf default 0)", () => {
const page = parsePage({ listObject: [{ containerID: 1, containerName: "l", itemContainer: { itemName: ["a"] } }] });
assert.equal(page.containers[0].selectBorder, false);
assert.equal(page.containers[0].itemWidth, 0);
});
+133
View File
@@ -0,0 +1,133 @@
// EvenHub list containers in the stock style, on the shared Menu: dim
// unselected text, a text-sized outline, animated scrolling and bounce, and a
// selection that moves instantly.
const test = require("node:test");
const assert = require("node:assert/strict");
const {
paintListItems, stepListSelection, listRowHeight, truncateToWidth, DESELECTED_TEXT, LIST_ITEM_PADDING_X, LIST_ITEM_PADDING_Y,
} = require("../.test-build/app/apps/evenhub/list-menu.js");
const { GrayImage } = require("../.test-build/app/graphics/image.js");
const { DrawOp } = require("../.test-build/app/graphics/display-list.js");
/** Each character is a 6x10 block of ink at 10px advance. */
const font = {
lineHeight: 20,
measureLine: (text) => text.length * 10,
drawText: (image, x, y, text, value = 255) => {
for (let i = 0; i < text.length; i++) image.fillRect(x + i * 10, y + 4, 6, 10, value);
},
};
function list(itemNames, height) {
return {
kind: "list", id: 1, name: "list", x: 0, y: 0, width: 200, height,
borderWidth: 0, borderRadius: 0, paddingLength: 0, isEventCapture: true, zOrderIndex: undefined,
preserve: false, itemNames, itemWidth: 0, selectBorder: true, selectedIndex: 0,
};
}
function paint(container, now, focused = true) {
const original = Date.now;
Date.now = () => now;
try {
const image = new GrayImage(200, 200, 0);
paintListItems(image, container, font, focused);
return image;
} finally {
Date.now = original;
}
}
const displayLists = (image) => image.draws.map((draw) => draw.presentation?.displayList).filter(Boolean);
const pixel = (image, x, y) => image.withDrawsBaked().pixels[y * image.width + x];
test("the unfocused outline is dimmer", () => {
const image = paint(list(["ab"], 100), 1000, false);
assert.equal(pixel(image, 0, 16), 130);
});
test("selection within the viewport changes instantly, with no animation", () => {
const container = list(["a", "b", "c", "d", "e", "f"], 128);
paint(container, 1000);
assert.equal(stepListSelection(container, font, 1), true);
assert.equal(container.selectedIndex, 1);
const image = paint(container, 2000);
assert.deepEqual(displayLists(image), []);
});
test("navigation that scrolls animates a strip", () => {
const container = list(["a", "b", "c", "d", "e", "f"], 128);
paint(container, 1000);
for (let i = 0; i < 3; i++) {
stepListSelection(container, font, 1);
paint(container, 1000 + i);
}
assert.equal(container.selectedIndex, 3);
const scrolled = displayLists(paint(container, 5000));
assert.deepEqual(scrolled, [], "settled paints don't animate");
stepListSelection(container, font, 1);
const [strip] = displayLists(paint(container, 6000));
assert.ok(strip?.calls.some((call) => call.op === DrawOp.RECT_COPY), "the scroll animates");
assert.ok(!strip.calls.some((call) => call.op === DrawOp.ROUNDED_RECT), "no separate sliding highlight");
});
test("stepping past an end keeps the selection and bounces", () => {
const container = list(["a", "b", "c", "d", "e", "f"], 128);
paint(container, 1000);
assert.equal(stepListSelection(container, font, -1), false);
assert.equal(container.selectedIndex, 0);
const [bounce] = displayLists(paint(container, 2000));
assert.ok(bounce?.calls.some((call) => call.op === DrawOp.RECT_COPY), "the list bounces");
});
test("a row cut by the bottom edge is drawn clipped", () => {
// 100px fits three 32px rows and the top 4px of the fourth, whose ink
// starts 10px into the row, so a 16px taller box shows its first 10 lines.
const clipped = paint(list(["a", "b", "c", "d"], 100), 1000);
const textTop = 3 * 32 + LIST_ITEM_PADDING_Y + 4;
assert.equal(pixel(clipped, LIST_ITEM_PADDING_X, textTop), 0, "below the edge");
const partial = paint(list(["a", "b", "c", "d"], 3 * 32 + 16), 1000);
assert.equal(pixel(partial, LIST_ITEM_PADDING_X, 3 * 32 + 16), 0, "nothing past the edge");
assert.equal(pixel(partial, LIST_ITEM_PADDING_X, textTop), DESELECTED_TEXT, "the visible part is drawn");
});
test("at the end of a list with a partial row, the top row stays whole", () => {
const container = list(["a", "b", "c", "d", "e"], 3 * 32 + 16);
paint(container, 1000);
for (let i = 0; i < 4; i++) {
stepListSelection(container, font, 1);
paint(container, 1000 + i);
}
const image = paint(container, 9000);
// As in every Menu, the viewport never starts on a partial row: c, d and
// e show whole, leaving 16px empty below e rather than cutting c in half.
assert.equal(pixel(image, LIST_ITEM_PADDING_X, LIST_ITEM_PADDING_Y + 4), DESELECTED_TEXT, "c at the top");
assert.equal(pixel(image, LIST_ITEM_PADDING_X, 64 + LIST_ITEM_PADDING_Y + 4), 255, "e selected, third row");
});
test("with the selection border off, the selected item has no outline", () => {
const container = { ...list(["ab"], 100), selectBorder: false };
const image = paint(container, 1000);
assert.equal(pixel(image, 0, 16), 0, "no outline edge");
assert.equal(pixel(image, LIST_ITEM_PADDING_X, LIST_ITEM_PADDING_Y + 4), 255, "text still selected-bright");
});
test("a fixed itemWidth sets the outline's width exactly", () => {
const container = { ...list(["ab"], 100), itemWidth: 150 };
const image = paint(container, 1000);
assert.equal(pixel(image, 149, 16), 255, "right edge at itemWidth");
assert.equal(pixel(image, 150, 16), 0);
});
test("text wider than a fixed itemWidth is truncated with an ellipsis", () => {
// 10px per char: 100 - 2 * 12 = 76px holds "abcd..." (70px) but not "abcde..." (80px).
assert.equal(truncateToWidth(font, "abcdefghij", 76), "abcd...");
assert.equal(truncateToWidth(font, "abcdefg", 76), "abcdefg", "fits: unchanged");
assert.equal(truncateToWidth(font, "abcdefgh", 20), "...", "room for nothing but the ellipsis");
const drawn = [];
const recording = { ...font, drawText: (image, x, y, text, value) => { drawn.push(text); font.drawText(image, x, y, text, value); } };
const image = new GrayImage(200, 200, 0);
paintListItems(image, { ...list(["abcdefghij", "ab"], 100), itemWidth: 100 }, recording, true);
assert.deepEqual(drawn, ["abcd...", "ab"]);
});
+77
View File
@@ -0,0 +1,77 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const source = fs.readFileSync(path.join(__dirname, '../app/apps/evenhub/session.ts'), 'utf8');
const shim = source.match(/export const EVENHUB_BRIDGE_INJECT_SCRIPT = `([\s\S]*?)`;/)[1];
function page() {
const state = { now: 1000, wakes: 0, log: [] };
const win = {
Date: { now: () => state.now }, console, Map, Array, Math,
__faceclawEvenHub: { postMessage() {}, wakeTimers() { state.wakes++; } },
};
win.window = win;
win.performance = { now: () => state.now };
vm.createContext(win);
vm.runInContext(shim, win);
state.win = win;
state.tick = () => vm.runInContext('__fcTick()', win);
return state;
}
test('an idle page asks for no ticks, and its first timer wakes the host once', () => {
const p = page();
assert.equal(p.tick(), -1);
p.win.setTimeout(() => p.log.push('a'), 100);
p.win.setTimeout(() => p.log.push('b'), 200);
assert.equal(p.wakes, 1);
p.now += 5;
assert.equal(p.tick(), 95);
p.now += 95;
assert.equal(p.tick(), 100);
assert.deepEqual(p.log, ['a']);
p.now += 100;
assert.equal(p.tick(), -1);
assert.deepEqual(p.log, ['a', 'b']);
});
test('work due before the scheduled tick wakes the host; work added during a tick does not', () => {
const p = page();
p.win.setTimeout(() => {}, 500);
p.tick();
const wakes = p.wakes;
p.win.setTimeout(() => { p.win.setTimeout(() => p.log.push('inner'), 0); }, 10);
assert.equal(p.wakes, wakes + 1);
p.now += 10;
assert.equal(p.tick(), 16, 'the inner zero-delay timer runs next frame');
assert.equal(p.wakes, wakes + 1);
p.now += 16;
p.tick();
assert.deepEqual(p.log, ['inner']);
});
test('an animation-frame loop keeps the host at frame rate until it stops', () => {
const p = page();
let frames = 0;
const loop = () => { if (++frames < 3) p.win.requestAnimationFrame(loop); };
p.win.requestAnimationFrame(loop);
p.now += 16; assert.equal(p.tick(), 16);
p.now += 16; assert.equal(p.tick(), 16);
p.now += 16; assert.equal(p.tick(), -1);
assert.equal(frames, 3);
});
test('intervals keep cadence and the fixed-rate entry points still work', () => {
const p = page();
const id = p.win.setInterval(() => p.log.push('iv'), 50);
p.now += 50; assert.equal(p.tick(), 50);
p.now += 50; p.tick();
p.win.clearInterval(id);
assert.equal(p.tick(), -1);
p.win.setTimeout(() => p.log.push('legacy'), 0);
vm.runInContext('__fcTimerTick(); __fcRafTick()', p.win);
assert.deepEqual(p.log, ['iv', 'iv', 'legacy']);
});
+5 -1
View File
@@ -60,7 +60,11 @@ function loadIconGrid({ lastInputWasWatch = false } = {}) {
'./menu-core': build('ui/menu-core'),
'./metrics': metrics,
};
const menu = load('app/ui/menu.ts', { ...common, './layers': {} });
const menu = load('app/ui/menu.ts', {
...common, './layers': {},
'./menu-animation-pref': build('ui/menu-animation-pref'),
'../native/settings-store': { getBooleanSetting: (_key, fallback) => fallback },
});
const grid = load('app/ui/icon-grid.ts', {
...common,
'../graphics/draw-expression': build('graphics/draw-expression'),
@@ -36,6 +36,46 @@ class DisplayListTest {
renderer.render(DrawProtocol.SCREEN, DisplayListRenderer.Target(source,640,480), DisplayListRenderer.Target(destination,640,480))
assertContentEquals(source, destination)
}
@Test fun rectCopyMatchesPerPixelReferenceWithShiftsClipsAndAliasing() {
val random = Random(7)
repeat(4000) { case ->
val width = random.nextInt(1, 20); val height = random.nextInt(1, 6)
val offset = random.nextInt(3); val shift = random.nextInt(-4, 5)
val clip = if (random.nextBoolean()) null else {
val left = random.nextInt(-3, width + 1); val top = random.nextInt(-2, height + 1)
intArrayOf(left, top, left + random.nextInt(0, width + 3), top + random.nextInt(0, height + 2))
}
// Screen as a separate array, the target's own array at another offset, or the target itself.
val mode = random.nextInt(3)
val screenWidth = random.nextInt(1, 20); val screenHeight = random.nextInt(1, 6)
val screenOffset = random.nextInt(3)
val targetSize = offset + (width + 1) / 2 * height
val screenSize = screenOffset + (screenWidth + 1) / 2 * screenHeight
val bytes = random.nextBytes(maxOf(targetSize, if (mode == 1) screenSize else 0) + 2)
val screenBytes = if (mode == 0) random.nextBytes(screenSize + 1) else bytes
val sourceId = if (mode == 2) DrawProtocol.CURRENT else DrawProtocol.SCREEN
val sourceWidth = if (mode == 2) width else screenWidth
val sourceHeight = if (mode == 2) height else screenHeight
val w = random.nextInt(1, sourceWidth + 1); val h = random.nextInt(1, sourceHeight + 1)
val x = random.nextInt(sourceWidth - w + 1); val y = random.nextInt(sourceHeight - h + 1)
val dx = random.nextInt(-w - 5, width + 5); val dy = random.nextInt(-h - 2, height + 2)
val expected = bytes.copyOf()
val expectedScreen = if (mode == 0) screenBytes.copyOf() else expected
val referenceTarget = DisplayListRenderer.Target(expected, width, height, offset, shift, clip)
val referenceSource = if (mode == 2) referenceTarget
else DisplayListRenderer.Target(expectedScreen, screenWidth, screenHeight, screenOffset)
val snapshot = IntArray(w * h) { referenceSource.get(x + it % w, y + it / w) }
for (i in snapshot.indices) referenceTarget.put(dx + i % w, dy + i / w, snapshot[i])
val target = DisplayListRenderer.Target(bytes, width, height, offset, shift, clip)
val screen = if (mode == 2) target else DisplayListRenderer.Target(screenBytes, screenWidth, screenHeight, screenOffset)
DisplayListRenderer(emptyMap()).execute(
DrawProtocol.sequence(listOf(DrawProtocol.rectCopy(sourceId, x, y, w, h, dx, dy))), target, screen)
assertContentEquals(expected, bytes, "case $case")
if (mode == 0) assertContentEquals(expectedScreen, screenBytes, "case $case screen")
}
}
@Test fun invalidGraphDoesNotCopyScreenIntoComposition() {
val screen = hex("12345678"); val composition = hex("9abcdef0")
val resources = mapOf(1 to DrawProtocol.displayList(listOf(byteArrayOf(99,0))))
+1
View File
@@ -19,6 +19,7 @@ const menuCore=load('app/ui/menu-core.ts',{
'../graphics/image':graphics,'./menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
});
const {MenuLayer}=load('app/ui/menu.ts',{
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), '../native/settings-store': { getBooleanSetting: (_key, fallback) => fallback },
'../graphics/image':graphics,'../graphics/textwrap':{},'../graphics/ui-fonts':{getDefaultSmallFont:()=>font},
'../util/numeric-util':{clamp:(n,a,b)=>Math.max(a,Math.min(b,n))},'./gestures':{},
'./menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
+21
View File
@@ -9,6 +9,7 @@ const { DrawExpression: E } = require('../.test-build/app/graphics/draw-expressi
const { menuScrollList, slidingHighlightY } = require('../.test-build/app/graphics/menu-scroll-list.js');
const { MENU_BOUNCE_DURATION_MS, scrollOffsetExpression } = require('../.test-build/app/ui/menu-scroll-motion.js');
const { encodePresentation } = require('../.test-build/app/graphics/presentation-wire.js');
const { setMenuAnimationReader } = require('../.test-build/app/ui/menu-animation-pref.js');
// Also consumed by FrameDisplayListTest.kt.
const SCROLL = '078a000000030002000400020000070000009600000001000200040011223344556677880200020000000000ff250100300102300180f0800180f0161101001732800180f01610300180f0302341403101001102000200010008000000ff280101300100300180f0800180f0161101001732800180f01610300180f030234140310100170100160400020000000103';
@@ -196,6 +197,26 @@ test('a bounce during a scroll starts from the offset on screen', () => {
assert.ok(offsets[0] < offsets[1], 'it starts where the scroll had got to, above its settled offset');
});
test('with menu animation off, scrolls, slides and bounces snap', (t) => {
setMenuAnimationReader(() => false);
t.after(() => setMenuAnimationReader(() => true));
const timed = (image) => image.draws.filter((draw) => draw.presentation?.displayList?.timeline);
const menu = inkMenu();
paint(menu, 1000);
menu.moveSelection(1);
const slid = paint(menu, 2000);
assert.equal(menu.scrollTop, 0);
assert.equal(timed(slid).length, 0, 'the highlight snaps');
menu.moveSelection(1);
const scrolled = paint(menu, 3000);
assert.equal(menu.scrollTop, 20);
assert.equal(timed(scrolled).length, 0, 'the scroll snaps');
menu.select(6);
paint(menu, 4000);
menu.moveSelection(1);
assert.equal(timed(paint(menu, 5000)).length, 0, 'no bounce');
});
test('scroll lists survive the bridge with animated copy coordinates', () => {
const strip = { width: 2, height: 4, pixels: Uint8Array.of(17, 34, 51, 68, 85, 102, 119, 136) };
const timeline = { from: 0, to: 2, startedAt: 1000, token: 7, durationMs: MENU_HIGHLIGHT_DURATION_MS };
+1
View File
@@ -155,6 +155,7 @@ test('Music settings keeps toggles and selection when a new app arrives and supp
'../util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) },
'./menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
'./metrics': load('app/ui/metrics.ts'), './gestures': {},
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), '../native/settings-store': { getBooleanSetting: (_key, fallback) => fallback },
};
deps['./menu-core'] = load('app/ui/menu-core.ts', (name) => deps[name]);
const menu = load('app/ui/menu.ts', (name) => deps[name]);
+2 -2
View File
@@ -206,7 +206,7 @@ test('bridge exposes numeric measurements and treats absent values as unknown',
let pump = { reservoir: '10.5', battery: { voltage: '1.15' } };
const module = load('app/native/nightscout-bridge.ts', {
'../ui/dashboard-settings': { nightscoutSiteUrlSetting: { get: () => 'https://example.test' }, nightscoutApiTokenSetting: { get: () => 'test' } },
'../util/http': { async fetchWithUserAgent(url) {
'../util/http': { async fetchTextWithUserAgent(url) {
const body = url.includes('/entries.') ? [{ date: now, sgv: 100 }] : url.includes('/devicestatus.') ? [{ pump, openaps: { suggested: { mills: now - 60_000 } } }] : url.includes('/status.') ? {} : [];
return { ok: true, json: async () => body };
} },
@@ -231,7 +231,7 @@ test('polling starts once and stops even while the initial HTTP request is pendi
const timers = new Map();
const module = load('app/native/nightscout-bridge.ts', {
'../ui/dashboard-settings': { nightscoutSiteUrlSetting: { get: () => 'https://example.test' }, nightscoutApiTokenSetting: { get: () => 'test' } },
'../util/http': { async fetchWithUserAgent() {
'../util/http': { async fetchTextWithUserAgent() {
calls++;
await pending;
return { ok: true, json: async () => [] };
+1
View File
@@ -86,6 +86,7 @@ function ui(fontSize = 12) {
'../util/render-freshness': { renderPassAllowsStaleData: () => false },
'./menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
'./metrics': load('app/ui/metrics.ts'),
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), '../native/settings-store': { getBooleanSetting: (_key, fallback) => fallback },
'./gestures': {},
};
const requireModule = (name) => {
+1
View File
@@ -22,6 +22,7 @@ const font = BdfFont.parse(fs.readFileSync(path.join(__dirname, '../app/fonts/te
const textwrap = load('app/graphics/textwrap.ts', {});
const fonts = { getDefaultSmallFont: () => font };
const menu = load('app/ui/menu.ts', {
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), '../native/settings-store': { getBooleanSetting: (_key, fallback) => fallback },
'../graphics/image': graphics, '../graphics/textwrap': textwrap, '../graphics/ui-fonts': fonts,
'../util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) }, './gestures': {},
'./metrics': metrics, './menu-core': menuCore,
+1
View File
@@ -45,6 +45,7 @@
"../app/apps/microphones/radar-dots.ts",
"../app/apps/microphones/name-guess.ts",
"../app/apps/evenhub/containers.ts",
"../app/apps/evenhub/list-menu.ts",
"../app/apps/timer/timer-model.ts",
"../app/apps/teleprompter/script-tracker.ts",
"../app/apps/nightscout/nightscout-alerts.ts",