diff --git a/app/app.css b/app/app.css index b59200cd..28d6483c 100644 --- a/app/app.css +++ b/app/app.css @@ -81,12 +81,6 @@ Button.-primary { font-size: 18; } -/* The logo art is black-on-transparent; tint it light in dark mode so it - * doesn't vanish into the dark page background. */ -.ns-dark .onboarding-logo { - tint-color: #e6e6e6; -} - /* License / privacy-policy links in the onboarding disclaimer footer. The * padding widens the tap target beyond the small text. */ .footer-link { diff --git a/app/app.ios.css b/app/app.ios.css index 4245407f..b3b6f08c 100644 --- a/app/app.ios.css +++ b/app/app.ios.css @@ -5,6 +5,7 @@ .body-text { font-size: 18; } .h1 { font-size: 28; font-weight: bold; } .footer-link { color: #285c45; padding: 4 8; text-decoration: underline; } +.ns-dark .footer-link { color: #7bc47f; } Page { background-color: #f5f5f2; diff --git a/app/native/ios-bluetooth.ts b/app/native/ios-bluetooth.ts index 3de713f1..aac0b385 100644 --- a/app/native/ios-bluetooth.ts +++ b/app/native/ios-bluetooth.ts @@ -7,6 +7,8 @@ declare const FaceclawKitIosBleCentral: any, FaceclawKitIosProtocolPlatform: any /** CBManagerState raw values reported by the Kotlin central. */ export const BLE_STATE_UNSUPPORTED = 2, BLE_STATE_UNAUTHORIZED = 3, BLE_STATE_POWERED_OFF = 4, BLE_STATE_POWERED_ON = 5 +/** CBManagerAuthorization.allowedAlways. */ +const BLE_AUTHORIZATION_ALLOWED = 3 export type BluetoothEvent = | { kind: 'state'; state: number; authorization: number } @@ -50,17 +52,21 @@ export class IosBluetooth { } }, }) - this.native.setScanListenerListener(this.scanListener) } onEvent(listener: (event: BluetoothEvent) => void): () => void { this.listeners.add(listener); return () => { this.listeners.delete(listener) } } private emit(event: BluetoothEvent): void { for (const listener of [...this.listeners]) listener(event) } + /** + * Whether the user has allowed Bluetooth. Unlike `state` this is accurate before the + * central exists, and reading it never shows the permission prompt. + */ + isAuthorized(): boolean { return Number(this.native.authorization()) === BLE_AUTHORIZATION_ALLOWED } /** Creates the central (first use shows the Bluetooth permission prompt) without blocking the JS thread. */ private ensureCentral(): void { - // A zero timeout returns immediately after creating the central; the state arrives - // through the scan listener on the main queue. - this.native.waitForPoweredOnTimeoutMs(0) + // Registering the listener creates the central, or has an existing one re-report its + // state; the state arrives through the listener on the main queue. + this.native.setScanListenerListener(this.scanListener) } ensureReady(): Promise { if (this.state === BLE_STATE_POWERED_ON) return Promise.resolve() diff --git a/app/phone-ui/pairing.css b/app/phone-ui/pairing.css index 2ea8ddb9..2fb5ea91 100644 --- a/app/phone-ui/pairing.css +++ b/app/phone-ui/pairing.css @@ -236,3 +236,10 @@ Button.permissions-primary-dimmed { .ns-dark .permissions-check { color: #7bc47f; } + +/* Onboarding splash (phone-ui/onboarding-page). The logo art is + * black-on-transparent; tint it white in dark mode so it doesn't vanish into + * the dark page background. */ +.ns-dark .onboarding-logo { + tint-color: #ffffff; +} diff --git a/app/phone-ui/permissions-view-model.ts b/app/phone-ui/permissions-view-model.ts index f93d4662..f5fcde4e 100644 --- a/app/phone-ui/permissions-view-model.ts +++ b/app/phone-ui/permissions-view-model.ts @@ -107,7 +107,7 @@ const ANDROID_PERMISSIONS: PermissionDefinition[] = [ const PERMISSIONS: PermissionDefinition[] = global.isIOS ? [{ id: "nearby-devices", title: "Nearby Devices", description: "Needed to communicate with your smart glasses over Bluetooth.", optional: false, - isGranted: () => iosBluetooth().state === 5, + isGranted: () => iosBluetooth().isAuthorized(), request: () => iosBluetooth().ensureReady(), }, { id: "calendar", title: "Calendar", @@ -143,6 +143,7 @@ export class PermissionsViewModel extends Observable { private readonly onboarding: boolean; private _cards: PermissionCardItem[] = []; private requesting = false; + private stopWatchingBluetooth: (() => void) | null = null; constructor(options?: { onboarding?: boolean }) { super(); @@ -159,11 +160,20 @@ export class PermissionsViewModel extends Observable { onPageLoaded(): void { Application.on(Application.resumeEvent, this.onAppResume); + // The answer to the Bluetooth prompt can arrive after request() has stopped + // waiting for it, and with no resume to re-check on. + if (global.isIOS) { + this.stopWatchingBluetooth = iosBluetooth().onEvent((event) => { + if (event.kind === "state") this.refresh(); + }); + } this.refresh(); } onPageUnloaded(): void { Application.off(Application.resumeEvent, this.onAppResume); + this.stopWatchingBluetooth?.(); + this.stopWatchingBluetooth = null; } // --- observable properties ------------------------------------------------- @@ -177,7 +187,7 @@ export class PermissionsViewModel extends Observable { } get instructions(): string { - if (global.isIOS) return "Faceclaw uses Bluetooth to communicate with your smart glasses. Calendar and Apple Music access are optional. Tap a card to allow access; a checkmark means it is ready."; + if (global.isIOS) return "Faceclaw uses Bluetooth to communicate with your smart glasses. Calendar and Apple Music access are optional. Tap a card to allow access; a checkmark means access is allowed."; return this.onboarding ? `Faceclaw uses these ${global.isIOS ? "iOS" : "Android"} permissions. Tap a card to grant one; a checkmark means it is already granted. ` + "Optional permissions can also be granted later, from the Permissions item in the main-screen menu." diff --git a/tests/ios-permissions.test.cjs b/tests/ios-permissions.test.cjs new file mode 100644 index 00000000..66f2a6ad --- /dev/null +++ b/tests/ios-permissions.test.cjs @@ -0,0 +1,131 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { loader } = require('./helpers/load-typescript.cjs'); + +const NOT_DETERMINED = 0, DENIED = 2, ALLOWED = 3; +const STATE_UNAUTHORIZED = 3, STATE_POWERED_ON = 5; + +/** + * The Permissions page and the real scan layer over a fake Kotlin central. As in + * IosBleCentral, registering the scan listener is what creates the CBCentralManager, so + * `registrations` counting up from 0 is the moment iOS would show its permission prompt. + */ +function harness({ authorization = NOT_DETERMINED, onboarding = true } = {}) { + const central = { + authorizationValue: authorization, + listener: null, + registrations: 0, + authorization() { return this.authorizationValue; }, + setScanListenerListener(listener) { this.registrations++; this.listener = listener; }, + // CoreBluetooth answering: the state arrives some time after the central is created. + report(state, value) { + this.authorizationValue = value; + this.listener.onBluetoothStateStateAuthorization(state, value); + }, + }; + const alerts = []; + const timers = []; + const appListeners = new Set(); + const load = loader({ + global: { isIOS: true }, + setTimeout: (fn, delay) => { timers.push({ fn, delay }); return timers.length; }, + clearTimeout: id => { timers[id - 1].cleared = true; }, + FaceclawKitIosBleCentral: { alloc: () => ({ initWithPlatform: () => central }) }, + FaceclawKitIosProtocolPlatform: { shared: {} }, + FaceclawKitIosBleScanListener: {}, + }, { + '@nativescript/core': { + Application: { resumeEvent: 'resume', on: (_name, fn) => appListeners.add(fn), off: (_name, fn) => appListeners.delete(fn) }, + ApplicationSettings: { getString: (_key, fallback) => fallback, setString() {}, remove() {} }, + Dialogs: { alert: async options => { alerts.push(options.message); }, confirm: async () => true }, + Frame: { topmost: () => null }, + Observable: class { notifyPropertyChange() {} }, + }, + '../g2/ios-peripheral-identity': {}, + '../util/hex-util': { hexToBytes() {} }, + './kotlin-listener.ios': { kotlinListener: (_protocol, methods) => methods }, + '../g2/android-permissions': {}, + '../native/calendar-permissions': { hasCalendarPermission: () => false, ensureCalendarPermission: async () => false }, + '../native/battery-optimization': {}, + '../native/file-access': {}, + '../native/notification-access': {}, + '../native/media-controller': { mediaControllerBridge: { hasAccess: () => false, requestAccess: async () => false } }, + }); + const { PermissionsViewModel } = load('app/phone-ui/permissions-view-model.ts'); + const model = new PermissionsViewModel({ onboarding }); + const card = () => model.cards.find(item => item.id === 'nearby-devices'); + return { + central, alerts, timers, appListeners, model, card, + checked: () => card().checkVisibility === 'visible', + tap: () => card().onCardTap({ object: { bindingContext: card() } }), + flush: () => new Promise(resolve => setImmediate(resolve)), + }; +} + +test('opening the page does not prompt; tapping the card does, and allowing checks it', async () => { + const page = harness(); + page.model.onPageLoaded(); + assert.equal(page.central.registrations, 0, 'rendering the card must not create the central'); + assert.equal(page.checked(), false); + assert.match(page.model.primaryClass, /dimmed/); + + page.tap(); + assert.equal(page.central.registrations, 1, 'the tap creates the central, which shows the prompt'); + + page.central.report(STATE_POWERED_ON, ALLOWED); + await page.flush(); + assert.equal(page.checked(), true); + assert.equal(page.model.primaryClass, '-primary'); + assert.equal(page.alerts.length, 0); +}); + +test('Bluetooth already allowed is checked on the first render, with no central and no prompt', () => { + // A central's state arrives asynchronously, which is why a card reading it rendered unchecked + // and then had its tap ignored once the state said granted. + const page = harness({ authorization: ALLOWED }); + assert.equal(page.checked(), true); + assert.equal(page.model.primaryClass, '-primary'); + page.tap(); + assert.equal(page.central.registrations, 0); +}); + +test('an answer arriving after the wait timed out still updates the page', async () => { + const page = harness(); + page.model.onPageLoaded(); + page.tap(); + page.timers.find(timer => timer.delay === 30_000).fn(); + await page.flush(); + assert.match(page.alerts[0], /timed out/); + assert.equal(page.checked(), false); + + page.central.report(STATE_POWERED_ON, ALLOWED); + assert.equal(page.checked(), true); + assert.equal(page.model.primaryClass, '-primary'); +}); + +test('denied stays unchecked, and tapping again re-reads the state and explains', async () => { + const page = harness(); + page.model.onPageLoaded(); + page.tap(); + page.central.report(STATE_UNAUTHORIZED, DENIED); + await page.flush(); + assert.equal(page.checked(), false); + assert.match(page.alerts[0], /iPhone Settings/); + + page.tap(); + assert.equal(page.central.registrations, 2, 'an existing central re-reports its state when registered again'); + page.central.report(STATE_UNAUTHORIZED, DENIED); + await page.flush(); + assert.equal(page.alerts.length, 2); +}); + +test('leaving the page stops watching Bluetooth', () => { + const page = harness(); + page.model.onPageLoaded(); + page.tap(); + page.model.onPageUnloaded(); + assert.equal(page.appListeners.size, 0); + const before = page.model.cards; + page.central.report(STATE_POWERED_ON, ALLOWED); + assert.equal(page.model.cards, before, 'no refresh once unloaded'); +});