Custom auto-brightness, and fade in/out effects

This commit is contained in:
James Babcock committed 2026-09-25 00:57:43 -07:00
1 parent f66e0b025f
commit 4f3ad37c20
29 files changed
+589 -93

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { normalizeBrightnessCurve, brightnessCurveError, DEFAULT_BRIGHTNESS_CURVE } = require('../.test-build/app/g2/brightness-curve.js');
test('brightness curve accepts monotone knots and canonicalizes spacing', () => {
assert.equal(normalizeBrightnessCurve(' 0:0, 2.5:20,1000:100 '), '0:0,2.5:20,1000:100');
});
test('invalid brightness drafts survive editing and report an error', () => {
for (const text of ['', '0:0', '1:0,100:100', '0:0,1:80,2:50,3:100', '0:0,0:100', '0:0,NaN:100', '0:0,1:99', '0:0,1e9:100', ':0,1:100']) {
assert.equal(normalizeBrightnessCurve(text), text);
assert.ok(brightnessCurveError(text), text);
}
});
test('only the previous default migrates to the calibrated curve', () => {
assert.equal(normalizeBrightnessCurve('0:0,1:10,10:30,100:65,1000:100'), DEFAULT_BRIGHTNESS_CURVE);
assert.equal(normalizeBrightnessCurve('0:0,3:50,10:100'), '0:0,3:50,10:100');
});
const fs = require('node:fs'), vm = require('node:vm'), ts = require('typescript');
function settingsFixture(store = new Map()) {
const context = { exports: {}, global: { isIOS: false }, require: id => {
if (id.includes('settings-store')) return {
onSettingsStoreChanged() {}, getStringSetting: (k, d) => store.get(k) ?? d,
setStringSetting: (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: [] };
}};
vm.runInNewContext(ts.transpileModule(fs.readFileSync('app/ui/dashboard-settings.ts', 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
return context.exports;
}
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('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;
assert.equal(api.getBrightnessPreferences().minimum, 20);
curve.set('0:0,2:50,8:');
assert.equal(curve.get(), '0:0,2:50,8:');
assert.ok(curve.validationError());
assert.equal(api.getBrightnessPreferences().curve, '0:0,2:50,8:100');
// Restart keeps the draft and the last accepted curve separate.
api = settingsFixture(store); curve = api.autoBrightnessCurveSetting;
assert.equal(curve.get(), '0:0,2:50,8:');
assert.equal(api.getBrightnessPreferences().curve, '0:0,2:50,8:100');
curve.set('0:0,2:50,6:100');
assert.equal(curve.validationError(), null);
assert.equal(api.getBrightnessPreferences().curve, '0:0,2:50,6:100');
});
+2 -2
View File
@@ -66,9 +66,9 @@ test('swipes change the saved level by 10, clamp at both ends, and both tap gest
await f.input('click'); assert.ok(f.stack.isAtBase()); assert.equal(f.closed(), 1);
f.open();
for (let i = 0; i < 12; i++) await f.input('scroll-down');
assert.equal(f.value(), '0'); assert.equal(f.writes(), 17);
assert.equal(f.value(), '2'); assert.equal(f.writes(), 17);
await f.input('double-click'); assert.ok(f.stack.isAtBase()); assert.equal(f.closed(), 2);
assert.equal(f.value(), '0');
assert.equal(f.value(), '2');
});
test('enabling Auto while the picker is open prevents manual changes', async () => {
+17 -2
View File
@@ -229,7 +229,7 @@ test('background glasses input still composites frames; phone resume preserves t
async start() { starts++; this.phase = 'connected'; this.stateListener({ phase: 'connected', status: 'Connected.' }); }
async disconnect() { stops++; this.phase = 'disconnected'; this.stateListener({ phase: 'disconnected', status: 'Disconnected.' }); }
async close() {}
async setBrightness() {} async enableWearDetectionAndRequestState() {}
async configureBrightness() {} async setBrightness() {} async enableWearDetectionAndRequestState() {}
async configureCompositorScreen() {} async configureSurface() {} async setUnderlayDim() {} async setSurfaceVisible() {}
async setScreenBlanked() {} async removeSurface() {}
async submitSurfaceFrame(_id, pixels) { if (this.phase === 'connected') frames.push(pixels); }
@@ -245,7 +245,7 @@ test('background glasses input still composites frames; phone resume preserves t
waitForFrameFinished() { return Promise.resolve('composited'); }
getCompositePreview() { return new Uint8Array([1, 2]); }
}
const settings = { brightnessSetting: { get: () => 'auto' }, brightnessSettingToLevel: () => null, lockScreenEnabledSetting: { get: () => true }, onAnySettingChanged: () => () => {}, previewColorSetting: { get: () => 'white' } };
const settings = { brightnessSetting: { get: () => 'auto' }, brightnessSettingToLevel: () => null, getBrightnessPreferences: () => ({ auto: true, level: 50, minimum: 2, maximum: 100, curve: '0:0,1000:100', fadeMs: 280 }), lockScreenEnabledSetting: { get: () => true }, onAnySettingChanged: () => () => {}, previewColorSetting: { get: () => 'white' } };
const modules = {
"../ui/input-monitor": load("app/ui/input-monitor.ts", {}),
'../remote/service': { startRemoteInput() {} },
@@ -498,3 +498,18 @@ test('iOS keyboard action opens the shared destination session and remains block
host.glassesLocked = true; host.typeIntoApp(); assert.equal(opened, 1);
host.glassesLocked = false; host.active = false; host.typeIntoApp(); assert.equal(opened, 1);
});
test('iOS curve editor retains invalid draft and retries Save with a validation message', async () => {
const prompts = [], errors = [], saved = [];
const answers = [{ result: true, text: '0:0,5:' }, { result: true, text: '0:0,5:100' }];
const { IosPreviewController } = load('app/g2/ios-preview-controller.ts', { require: id => id === '@nativescript/core'
? { Dialogs: { prompt: async options => { prompts.push(options.defaultText); return answers.shift(); }, alert: async options => errors.push(options.message) } }
: {} });
const host = Object.create(IosPreviewController.prototype); host.active = true;
const curve = require('../.test-build/app/g2/brightness-curve.js');
assert.equal(await host.editSetting({ editorTitle: 'Auto light curve', get: () => '0:0,8:100',
set: value => saved.push(value), validationError: curve.brightnessCurveError }), true);
assert.deepEqual(prompts, ['0:0,8:100', '0:0,5:']);
assert.equal(errors.length, 1);
assert.deepEqual(saved, ['0:0,5:100']);
});
+2 -2
View File
@@ -86,7 +86,7 @@ function fixture() {
onWearState(fn) { return this.on('wear', fn); } onBatteryState() { return noop(); } onFirmwareInfo() { return noop(); }
onFrameMetrics() { return noop(); } addCompassListener() { return noop(); } onAncsRelayFrame() { return noop(); }
onAncsAuthorization() { return noop(); } setRequiresAncs() {} rightWriteLimit() { return 20; } onPhoneLockSignal() {}
async writeRawToRight() {} async setBrightness() {} async enableWearDetectionAndRequestState() {} async playBuzzerSequence() {} async close() {}
async writeRawToRight() {} async configureBrightness() {} async setBrightness() {} async enableWearDetectionAndRequestState() {} async playBuzzerSequence() {} async close() {}
emitState(phase, status = phase) { if (phase === 'connected' || phase === 'disconnected') this.phase = phase; this.listeners.state?.({ phase, status }); }
emitRing(input) { this.listeners.ring?.(input); }
emitWear(wearing) { this.listeners.wear?.(wearing); }
@@ -131,7 +131,7 @@ function fixture() {
'../phone-ui/onboarding-state': { isWelcomeSoundPending: () => false },
'../ui/sound-effects': {},
'../ui/shell/worker-window': {}, '../ui/shell/in-process-window': {},
'../ui/dashboard-settings': { brightnessSetting: { get: () => 'auto' }, brightnessSettingToLevel: () => null, lockScreenEnabledSetting: { get: () => settings.lock }, onAnySettingChanged: fn => { settingsChanged = fn; return () => {}; }, previewColorSetting: { get: () => 'white' } },
'../ui/dashboard-settings': { brightnessSetting: { get: () => 'auto' }, brightnessSettingToLevel: () => null, getBrightnessPreferences: () => ({ auto: true, level: 50, minimum: 2, maximum: 100, curve: '0:0,1000:100', fadeMs: 280 }), lockScreenEnabledSetting: { get: () => settings.lock }, onAnySettingChanged: fn => { settingsChanged = fn; return () => {}; }, previewColorSetting: { get: () => 'white' } },
'../native/phone-battery': { readPhoneBatteryState: () => ({ battery: 80, charging: false }) },
'../apps/ios-availability': { iosAppUnavailableReason: () => null },
'../graphics/glyph-wire': { prepareFrameDraws: () => null },
@@ -0,0 +1,108 @@
package com.faceclaw.app
import kotlin.test.*
class BrightnessPolicyTest {
private fun report(lux: Int, reason: Int = 2, flags: Int = 11): ByteArray {
val b = ByteArray(24)
b[0] = 65; b[1] = 76; b[2] = 1; b[3] = reason.toByte(); b[4] = flags.toByte()
val raw = lux * 10
for (i in 0..3) b[6+i] = (raw ushr (8*i)).toByte()
return b
}
@Test fun defaultMatchesMeasuredLightingPreferences() {
val p = BrightnessPolicy()
for ((raw, expected) in listOf(0 to 20, 2 to 26, 15 to 46, 50 to 100, 500 to 100)) {
val b = report(0)
b[6] = raw.toByte(); b[7] = (raw shr 8).toByte()
p.resetSamples(); p.sample(b, 1000)
assertEquals(expected, p.target, "raw ALS=$raw")
}
}
@Test fun curveUsesConfiguredBoundsAndLogInterpolation() {
val p = BrightnessPolicy()
p.configure(true, 50, 10, 90, "0:0,99:100", 280)
p.sample(report(9), 1000)
assertEquals(50, p.target) // log(10) / log(100) = 1/2
p.resetSamples(); p.sample(report(0), 2000); assertEquals(10, p.target)
p.resetSamples(); p.sample(report(10000), 3000); assertEquals(90, p.target)
}
@Test fun onlySuccessfulPassivePollsDriveAuto() {
val p = BrightnessPolicy()
val initial = p.target
for (reason in listOf(0, 1, 3, 4)) assertFalse(p.sample(report(0, reason), 1000))
for (flags in listOf(0, 1, 3, 9, 10)) assertFalse(p.sample(report(0, flags = flags), 1000))
assertFalse(p.sample(byteArrayOf(), 1000))
assertEquals(initial, p.target)
assertTrue(p.sample(report(0), 1000)); assertEquals(20, p.target)
}
@Test fun manualPersistsAcrossSamplesAndModeChangesUseLatestLight() {
val p = BrightnessPolicy()
p.configure(false, 70, 2, 80, "0:0,100:100", 450)
p.sample(report(100), 1000); assertEquals(70, p.target)
p.setMode(true, 50); assertEquals(80, p.target)
p.setMode(false, 0); assertEquals(2, p.target)
assertEquals(450, p.fadeMs)
}
@Test fun brightensFasterThanItDimsAndResetsStaleSamples() {
val up = BrightnessPolicy(); val down = BrightnessPolicy()
for (p in listOf(up, down)) p.configure(true, 50, 2, 100, "0:0,100:100", 280)
up.sample(report(0), 1000); up.sample(report(100), 1500)
down.sample(report(100), 1000); down.sample(report(0), 1500)
assertTrue(up.target - 2 > 100 - down.target)
down.sample(report(0), 20000); assertEquals(2, down.target)
}
@Test fun autoHoldsSmallChangesUntilTheyAccumulateToFivePoints() {
val p = BrightnessPolicy()
p.configure(true, 50, 20, 40, "0:0,1:20,2:25,3:45,4:50,5:100", 280)
var now = 1000L
fun sample(lux: Int, changed: Boolean, target: Int) {
// Space readings beyond the smoothing window to isolate the deadband.
now += 11000
assertEquals(changed, p.sample(report(lux), now), "lux=$lux")
assertEquals(target, p.target, "lux=$lux")
}
sample(0, true, 20)
repeat(5) { sample(1, false, 20) } // Desired 24 stays suppressed.
sample(2, true, 25) // Exact five-point increase is accepted.
sample(3, false, 25) // Desired 29.
sample(4, true, 30)
sample(2, true, 25) // Exact five-point decrease is accepted too.
sample(1, false, 25)
sample(0, true, 20)
}
@Test fun boundsDoNotBypassDeadbandButExplicitChangesDo() {
for ((initial, lux) in listOf(24 to 0, 36 to 5)) {
val p = BrightnessPolicy()
p.configure(false, initial, 20, 40, "0:0,5:100", 280)
p.setMode(true, initial)
assertFalse(p.sample(report(lux), 1000))
assertEquals(initial, p.target)
p.setMode(false, initial + 1)
assertEquals(initial + 1, p.target) // Small manual changes remain exact.
p.setMode(true, initial)
assertEquals(if (lux == 0) 20 else 40, p.target)
}
val p = BrightnessPolicy()
p.sample(report(0), 1000)
p.configure(true, 50, 21, 100, BrightnessPolicy.DEFAULT_CURVE, 280)
assertEquals(21, p.target) // An explicit bounds edit applies immediately.
}
@Test fun invalidCurveDoesNotPartiallyChangeLivePolicy() {
val p = BrightnessPolicy()
for (curve in listOf("", "0:0", "1:0,100:100", "0:0,1:80,2:50,3:100", "0:0,0:100", "0:0,NaN:100", "0:0,1:99")) {
assertFailsWith<IllegalArgumentException> { p.configure(false, 90, 20, 80, curve, 0) }
assertTrue(p.automatic); assertEquals(280, p.fadeMs)
}
p.configure(true, 50, 80, 20, "0:0,100:100", 0)
p.sample(report(0), 1000); assertEquals(80, p.target)
}
}
@@ -262,6 +262,42 @@ private class Session {
}
class GlassesSessionCoreTest {
@Test fun brightnessConfigPrecedesFirstFrameAndSleepWakeFollowsComposites() {
val s = Session()
s.core.configureBrightness(false, 70, 2, 100, "0:0,1000:100", 280)
s.core.configureCompositorScreen(640, 480)
s.core.configureSurface("s", 0, 0, 64, 32, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
s.startAndAwaitLayout()
s.core.monitor.withLock { s.core.customFirmwareDetected = true }
try {
s.submitFrame(1, 0x70, 1)
assertTrue(waitUntil(5000) { s.displayedMatchesDesired() })
fun outputs() = s.link.writes.filter { it.address == LEFT && it.kind == "brightness-output" }
assertTrue(waitUntil(5000) { outputs().isNotEmpty() })
val first = outputs().first().message!!
assertContentEquals(byteArrayOf(30, 1, 70, 1, 24, 1), first)
val writes = s.link.writes.filter { it.address == LEFT }
assertTrue(writes.indexOfFirst { it.kind == "als-control" } < writes.indexOfFirst { it.kind == "brightness-output" })
assertTrue(writes.indexOfFirst { it.kind == "brightness-output" } < writes.indexOfFirst { it.message?.firstOrNull() == 28.toByte() })
s.core.setScreenBlanked(true)
assertTrue(waitUntil(5000) { s.displayedMatchesDesired() && outputs().last().message!![3] == 0.toByte() })
s.core.setScreenBlanked(false)
assertTrue(waitUntil(5000) { s.displayedMatchesDesired() && outputs().last().message!![3] == 1.toByte() })
// The ordered CFW window may replay accepted commands; those must
// retain the same brightness and visibility, without an extra toggle.
val visibility = outputs().map { it.message!![3].toInt() }
val transitions = visibility.filterIndexed { i, v -> i == 0 || visibility[i-1] != v }
assertEquals(listOf(1, 0, 1), transitions)
assertTrue(outputs().all { it.message!![2] == 70.toByte() })
// The demo cannot restore the stock adjuster while Faceclaw owns brightness.
s.core.setAmbientLightPolling(false, 250, 0, 1000, true)
s.platform.offsetMs += 3000
s.core.interruptibleSleep.interrupt()
assertTrue(waitUntil(5000) { s.link.writes.count { it.address == LEFT && it.kind == "als-control" } >= 2 })
assertTrue(s.link.writes.filter { it.kind == "als-control" }.all { it.message!![1] == 1.toByte() })
} finally { s.core.close() }
}
@Test
fun connectsAuthenticatesPreludesAndCreatesTheLayout() {
val s = Session()
+2 -2
View File
@@ -46,9 +46,9 @@ test('shared brightness controls snap manual levels and restore the manual value
h.model.onBrightnessAutoChange({ value: false });
assert.equal(h.brightness(), '80');
h.model.onBrightnessChange({ value: -10 });
assert.equal(h.brightness(), '0');
assert.equal(h.brightness(), '2');
h.model.onBrightnessChange({ value: NaN });
assert.equal(h.brightness(), '0');
assert.equal(h.brightness(), '2');
});
test('shared screen-size picker preserves cancellation and applies the selected mode', async () => {
+2 -1
View File
@@ -46,6 +46,7 @@
"../app/apps/evenhub/containers.ts",
"../app/apps/timer/timer-model.ts",
"../app/apps/teleprompter/script-tracker.ts",
"../app/apps/nightscout/nightscout-alerts.ts"
"../app/apps/nightscout/nightscout-alerts.ts",
"../app/g2/brightness-curve.ts"
]
}