Clean up unused code

Mostly remnants of iOS porting, where some things were temporarily in
typescript but became shared kotlin
This commit is contained in:
James Babcock committed 2026-09-30 13:54:50 -07:00
1 parent 2c088378bd
commit 7d8f03ffe5
18 files changed
+66 -644

No files matched your search

@@ -1,113 +0,0 @@
package com.faceclaw.app
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.Build
import android.telephony.SignalStrength
import android.telephony.TelephonyManager
import android.util.Log
import java.io.ByteArrayOutputStream
import java.lang.reflect.Method
/** Reads Wi-Fi/cell/hotspot state; the icon artwork is the shared StatusIconArt. */
class FaceclawSystemStatusIconProvider private constructor() {
companion object {
private const val TAG = "FaceclawStatusIcons"
@JvmStatic
fun getSystemStatusIconGrays(context: Context?, iconSize: Int): ByteArray {
if (context == null) {
return ByteArray(0)
}
val appContext = context.applicationContext
val size = Math.max(1, Math.min(96, iconSize))
val out = ByteArrayOutputStream(size * size * 3)
val wifiLevel = getWifiLevel(appContext)
if (wifiLevel >= 0) {
append(out, StatusIconArt.scale(StatusIconArt.wifi(wifiLevel), size))
}
val cellLevel = getCellLevel(appContext)
if (cellLevel >= 0) {
append(out, StatusIconArt.scale(StatusIconArt.cell(cellLevel), size))
}
if (isHotspotEnabled(appContext)) {
append(out, StatusIconArt.scale(StatusIconArt.hotspot(), size))
}
return out.toByteArray()
}
private fun getWifiLevel(context: Context): Int {
try {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
val activeNetwork: Network? = if (connectivityManager == null) null else connectivityManager.activeNetwork
val capabilities: NetworkCapabilities? = if (activeNetwork == null) null else connectivityManager!!.getNetworkCapabilities(activeNetwork)
if (capabilities == null || !capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return -1
}
val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?
val info: WifiInfo? = if (wifiManager == null) null else wifiManager.connectionInfo
if (info == null || !isValidRssi(info.rssi)) {
return -1
}
return Math.max(0, Math.min(4, WifiManager.calculateSignalLevel(info.rssi, 5)))
} catch (t: Throwable) {
Log.w(TAG, "failed to read Wi-Fi status", t)
return -1
}
}
private fun getCellLevel(context: Context): Int {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
return -1
}
try {
val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?
val signalStrength: SignalStrength? = if (telephonyManager == null) null else telephonyManager.signalStrength
if (signalStrength == null) {
return -1
}
return Math.max(0, Math.min(4, signalStrength.level))
} catch (e: SecurityException) {
// Most Android versions require READ_PHONE_STATE for this. We skip it
// rather than prompting for a broad phone permission just for an icon.
return -1
} catch (t: Throwable) {
Log.w(TAG, "failed to read cellular status", t)
return -1
}
}
private fun isHotspotEnabled(context: Context): Boolean {
try {
val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?
if (wifiManager == null) {
return false
}
val method: Method = wifiManager.javaClass.getDeclaredMethod("getWifiApState")
method.isAccessible = true
val result: Any? = method.invoke(wifiManager)
val state = if (result is Int) result else -1
return state == 13 || state == 12 // WIFI_AP_STATE_ENABLED / ENABLING
} catch (ignored: Throwable) {
return false
}
}
private fun isValidRssi(rssi: Int): Boolean {
return rssi > -127 && rssi < 0
}
private fun append(out: ByteArrayOutputStream, bytes: ByteArray) {
out.write(bytes, 0, bytes.size)
}
}
}
-80
View File
@@ -1,80 +0,0 @@
import { type RingInput } from "./ring-input";
import { type CompassEvent } from '../native/compass-types'
/** iOS binary bridge to the same Kotlin protocol used by Android. */
import { fromData, toData, nativeArray } from '../native/kotlin-data'
import { OsEventTypeList } from './events'
declare const FaceclawKitIosProtocol: any, FaceclawKitIosMessageReceiver: any
const protocol = FaceclawKitIosProtocol.new()
export const G2_WRITE = '00002760-08c2-11e1-9073-0e8ac72e5401'
export const G2_NOTIFY = '00002760-08c2-11e1-9073-0e8ac72e5402'
export const G2_RENDER_NOTIFY = '00002760-08c2-11e1-9073-0e8ac72e6402'
export const RING_NOTIFY = ['bae80011-4f05-4503-8e65-3af1f7329d1f', 'bae80013-4f05-4503-8e65-3af1f7329d1f']
export const SID = { auth: 0x80, launch: 1, hub: 0xe0, settings: 9, cfw: 0xf0 } as const
export function concat(...parts: Uint8Array[]): Uint8Array {
const output = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
let offset = 0
for (const part of parts) { output.set(part, offset); offset += part.length }
return output
}
export const integer = (field: number, value: number): Uint8Array => fromData(protocol.integerFieldValue(field, value))
export const bytes = (field: number, value: Uint8Array): Uint8Array => fromData(protocol.bytesFieldData(field, toData(value)))
export const authentication = (magic: number) => fromData(protocol.authenticationMagic(magic))
export const prelude = () => fromData(protocol.prelude())
export const heartbeat = (magic: number) => fromData(protocol.heartbeatMagic(magic))
export const audioControl = (magic: number, enabled: boolean) => fromData(protocol.audioControlMagicEnabled(magic, enabled))
export const settingsQuery = (magic: number) => fromData(protocol.settingsQueryMagic(magic))
export const shutdown = (magic: number) => fromData(protocol.shutdownMagic(magic))
export const framebufferLease = (acquire: boolean) => fromData(protocol.framebufferLeaseAcquire(acquire))
export const createLayout = (magic: number) => fromData(protocol.createLayoutMagic(magic))
export const crc16 = (data: Uint8Array): number => protocol.crcData(toData(data))
export function frameMessage(payload: Uint8Array, sid: number, flag: number, sequence: number, maxWrite = 240): Uint8Array[] {
const capacity = Math.min(232, Math.floor(maxWrite) - 8)
if (capacity < 12 || !Number.isFinite(capacity)) throw new Error('Negotiated BLE write size is too small')
if (Math.ceil((payload.length + 2) / capacity) > 255) throw new Error('Protocol message exceeds the fragment limit')
return nativeArray(protocol.frameDataSidFlagSequenceMaxWrite(toData(payload), sid, flag, sequence, Math.floor(maxWrite)), fromData)
}
export type ProtocolMessage = { sid: number; flag: number; payload: Uint8Array; command: number; magic: number; packet?: Uint8Array }
export class MessageReceiver {
private native = FaceclawKitIosMessageReceiver.new()
clear(): void { this.native.clear() }
receive(link: string, data: Uint8Array, now = Date.now()): ProtocolMessage[] {
return nativeArray(this.native.receiveLinkDataNow(link, toData(data), now), (message: any) => ({
sid: message.sid, flag: message.flag, payload: fromData(message.payload), command: message.command,
magic: message.magic, ...(message.packet ? { packet: fromData(message.packet) } : {}),
}))
}
}
export const readInteger = (data: Uint8Array, field: number, fallback = 0): number => protocol.readIntegerDataFieldFallback(toData(data), field, fallback)
export const readBytes = (data: Uint8Array, field: number): Uint8Array | undefined => {
const value = protocol.readBytesDataField(toData(data), field)
return value ? fromData(value) : undefined
}
export const readString = (data: Uint8Array, field: number): string => protocol.readStringDataField(toData(data), field)
export function authenticationSucceeded(message: ProtocolMessage, magic: number): boolean {
return message.sid === SID.auth && message.command === 4 && message.magic === magic && readBytes(message.payload, 3)?.length === 0
}
export type GlassesInput = { ringInput?: RingInput; kind: 'sys-event' | 'list-click' | 'text-click' | 'display-wake' | 'even-ai'; eventType: number; eventSource: number; systemExitReasonCode: number; containerName: string; frameId: number }
function input(event: any): GlassesInput | null {
return event ? { kind: event.kind === 'sys-event' && event.eventType === OsEventTypeList.HEAD_UP_EVENT ? 'display-wake' : event.kind,
eventType: event.eventType, eventSource: event.eventSource, systemExitReasonCode: event.systemExitReasonCode,
ringInput: Number(event.ringTick) >= 0 ? { tick: Number(event.ringTick), type: Number(event.ringType),
aux: Number(event.ringAux), speed: Number(event.ringSpeed) } : undefined,
containerName: event.containerName, frameId: 0 } : null
}
export const decodeGlassesInput = (message: ProtocolMessage): GlassesInput | null => input(protocol.glassesInputDataSidFlag(toData(message.payload), message.sid, message.flag))
export const decodeRingInput = (data: Uint8Array): GlassesInput | null => input(protocol.ringInputData(toData(data)))
export function packGray4(gray: Uint8Array, width: number, height: number): Uint8Array {
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || gray.length !== width * height) throw new Error('Invalid display frame')
return fromData(protocol.packDataWidthHeight(toData(gray), width, height))
}
export const rle4 = (packed: Uint8Array): Uint8Array => fromData(protocol.rleData(toData(packed)))
export function decodeCompassInput(message: ProtocolMessage): CompassEvent | null {
const event = protocol.compassInputDataSidFlag(toData(message.payload), message.sid, message.flag)
return event ? { command: event.command, headingDegrees: event.headingDegrees,
...(event.diagnosticFlags >= 0 ? { diagnostics: {
magneticAccuracy: event.magneticAccuracy, magneticAnomalies: event.magneticAnomalies,
orientationSource: event.orientationSource, flags: event.diagnosticFlags, sampleTimeMs: Number(event.sampleTimeMs),
} } : {}),
} : null
}
-53
View File
@@ -1,53 +0,0 @@
/** Reader for the bundled Source Han Sans serialized LVGL font. Matches
* Android LvglFontFile's metrics/glyph byte format, without a Java dependency. */
export class LvglFont {
readonly metrics: Uint8Array
private readonly view: DataView
private readonly ids = new Map<number, number>()
private readonly bitmaps: number
private readonly descriptors: number
constructor(private readonly bytes: Uint8Array) {
this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
if (bytes.length < 64 || bytes.slice(0, 4).some(v => v !== 90)) throw new Error('Missing LVGL font header')
const height = this.u16(0x38), baseline = height - this.u16(0x3a)
const descriptor = this.pointer(this.u32(0x34))
this.bitmaps = this.pointer(this.u32(descriptor)); this.descriptors = this.pointer(this.u32(descriptor + 4))
const cmaps = this.pointer(this.u32(descriptor + 8)), packed = this.u16(descriptor + 18), count = packed & 0x1ff
if (!height || baseline < 0 || !count || ((packed >>> 9) & 15) !== 4 || (packed >>> 14) !== 3) throw new Error('Unsupported LVGL font')
this.metrics = new Uint8Array([height, baseline])
for (let i = 0; i < count; i++) {
const at = cmaps + i * 20, start = this.u32(at), length = this.u16(at + 4), first = this.u16(at + 6)
const unicodePtr = this.u32(at + 8), offsetsPtr = this.u32(at + 12), listLength = this.u16(at + 16), type = this.u8(at + 18)
if (type === 2 || type === 0) {
const offsets = type === 0 ? this.pointer(offsetsPtr) : 0
for (let n = 0; n < length; n++) {
const offset = type === 0 ? this.u8(offsets + n) : n
if (n && !offset) continue
this.ids.set(start + n, first + offset)
}
} else if (type === 1 || type === 3) {
const unicode = this.pointer(unicodePtr), offsets = offsetsPtr ? this.pointer(offsetsPtr) : -1
for (let n = 0; n < listLength; n++) {
const offset = offsets < 0 ? n : type === 1 ? this.u16(offsets + n * 2) : this.u8(offsets + n)
if (n && !offset) continue
this.ids.set(start + this.u16(unicode + n * 2), first + offset)
}
} else throw new Error('Unsupported LVGL cmap')
}
}
glyph(codePoint: number): Uint8Array {
const id = this.ids.get(codePoint)
if (!id) return new Uint8Array()
const at = this.descriptors + id * 16, bitmap = this.bitmaps + this.u32(at)
const width = this.u16(at + 8), height = this.u16(at + 10), length = width && height ? (Math.floor(width / 2) + 1) * height : 0
this.check(bitmap, length)
const result = new Uint8Array(8 + length)
result.set(this.bytes.subarray(at + 8, at + 16)); result.set(this.bytes.subarray(bitmap, bitmap + length), 8)
return result
}
private check(at: number, size: number): void { if (at < 0 || at + size > this.bytes.length) throw new Error('Truncated LVGL font') }
private pointer(address: number): number { const at = address - 0x80100000; this.check(at, 1); return at }
private u8(at: number): number { this.check(at, 1); return this.bytes[at] }
private u16(at: number): number { return this.view.getUint16(at, true) }
private u32(at: number): number { return this.view.getUint32(at, true) }
}
+5 -2
View File
@@ -1,6 +1,9 @@
import { fromData, toData } from '../native/kotlin-data'
import type { SurfaceConfiguration, SurfaceRect } from './surface-compositor'
export type { SurfaceConfiguration, SurfaceRect } from './surface-compositor'
export type SurfaceRect = { x: number; y: number; width: number; height: number }
export type SurfaceConfiguration = SurfaceRect & {
zOrder: number
transparency: 'opaque' | 'color-key'
}
declare const FaceclawKitIosSurfaceCompositor: any
/** Retained pixels, clipping, layers and composition live in shared Kotlin. */
export class SurfaceCompositor {
-103
View File
@@ -1,103 +0,0 @@
import { presentationRecords, readPresentation, paintPresentation, type Selection } from "./presentation-wire"
/** Platform-independent 8bpp surface composition for the local display. */
export type SurfaceRect = { x: number; y: number; width: number; height: number }
export type SurfaceConfiguration = SurfaceRect & {
zOrder: number
transparency: 'opaque' | 'color-key'
}
type Surface = SurfaceConfiguration & { pixels: Uint8Array; visible: boolean; selections: Selection[] }
export class SurfaceCompositor {
private readonly surfaces = new Map<string, Surface>()
private shellScene: Uint8Array | null = null
private shellReceivedAt = 0
setShellScene(bytes: Uint8Array): void { this.shellScene = new Uint8Array(bytes); this.shellReceivedAt = Date.now() }
private dimBelow = 0
private dimFactor = 1
private blanked = false
constructor(readonly width: number, readonly height: number) {
if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) {
throw new Error('Invalid compositor size')
}
}
configureSurface(id: string, options: SurfaceConfiguration): void {
if (![options.x, options.y, options.width, options.height, options.zOrder].every(Number.isInteger)
|| options.width <= 0 || options.height <= 0) throw new Error('Invalid surface geometry')
const previous = this.surfaces.get(id)
const pixels = previous?.width === options.width && previous.height === options.height
? previous.pixels : new Uint8Array(options.width * options.height)
this.surfaces.set(id, { ...options, pixels, visible: previous?.visible ?? true, selections: previous?.selections ?? [] })
}
removeSurface(id: string): void { this.surfaces.delete(id) }
setSurfaceVisible(id: string, visible: boolean): void {
const surface = this.surfaces.get(id)
if (surface) surface.visible = visible
}
/** Stereo depth only shifts the lenses; this local composite shows the unshifted screen. */
setSurfaceDepth(_id: string, _depth: number): void {}
setUnderlayDim(belowZOrder: number, factor: number): void {
if (!Number.isFinite(factor)) throw new Error('Invalid dim factor')
this.dimBelow = belowZOrder
this.dimFactor = Math.max(0, Math.min(1, factor))
}
setScreenBlanked(blanked: boolean): void { this.blanked = blanked }
submitSurfaceFrame(id: string, pixels: Uint8Array, rect: SurfaceRect, _draws: ArrayBuffer | null = null): void {
const surface = this.surfaces.get(id)
if (!surface) throw new Error(`Unknown surface: ${id}`)
if (![rect.x, rect.y, rect.width, rect.height].every(Number.isInteger)
|| rect.width <= 0 || rect.height <= 0 || pixels.length !== rect.width * rect.height) {
throw new Error('Invalid frame buffer or rectangle')
}
surface.selections = presentationRecords(_draws)
const left = Math.max(0, rect.x), right = Math.min(surface.width, rect.x + rect.width)
const top = Math.max(0, rect.y), bottom = Math.min(surface.height, rect.y + rect.height)
for (let y = top; y < bottom; y++) {
if (right <= left) break
const source = (y - rect.y) * rect.width + left - rect.x
surface.pixels.set(pixels.subarray(source, source + right - left), y * surface.width + left)
}
}
composite(): Uint8Array {
const output = new Uint8Array(this.width * this.height)
if (this.blanked) return output
const surfaces = [...this.surfaces.values()].filter(s => s.visible && !(this.shellScene && s === this.surfaces.get('shell'))).sort((a, b) => a.zOrder - b.zOrder)
for (const surface of surfaces) {
const left = Math.max(0, surface.x), right = Math.min(this.width, surface.x + surface.width)
const top = Math.max(0, surface.y), bottom = Math.min(this.height, surface.y + surface.height)
const dim = !this.shellScene && surface.zOrder < this.dimBelow ? this.dimFactor : 1
for (let y = top; y < bottom; y++) {
let source = (y - surface.y) * surface.width + left - surface.x
let target = y * this.width + left
for (let x = left; x < right; x++, source++, target++) {
const value = surface.pixels[source]
// Test the original value: opaque near-black must still cover the
// window beneath, even when dimming rounds it down to black.
if (surface.transparency === 'color-key' && value === 0) continue
output[target] = Math.round(value * dim)
}
}
}
const screen = output.slice()
if (!surfaces.some(s => s.zOrder > 1) && (this.shellScene || surfaces.some(s => s.selections.length))) {
for(let i=0;i<output.length;i++) output[i]=Math.min(15,(output[i]!+8)>>4)*16
for(const surface of surfaces) for(const row of surface.selections) paintPresentation(output,screen,this.width,this.height,{...row,x:row.x+surface.x,y:row.y+surface.y,occlusions:row.occlusions.map(r=>({...r,x:r.x+surface.x,y:r.y+surface.y}))})
}
if (this.shellScene && !surfaces.some(s => s.zOrder > 1)) {
const quantize = (v: number) => Math.min(15, (v + 8) >> 4)
for (let i=0;i<output.length;i++) output[i]=quantize(output[i])*16
const bytes=this.shellScene, view=new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
let p=2
for(let i=0;i<view.getUint16(0,true);i++) {
const x=view.getInt16(p+2,true), y=view.getInt16(p+4,true), w=view.getUint16(p+6,true), h=view.getUint16(p+8,true), dim=view.getUint16(p+10,true), selections=view.getUint16(p+12,true), shift=Math.floor(view.getInt16(p+14,true)/2)
p+=16
if(dim<256) for(let j=0;j<output.length;j++) output[j]=Math.floor((output[j]/16)*dim/256)*16
for(let yy=0;yy<h;yy++) for(let xx=0;xx<w;xx++) {
if(x+xx+shift>=0 && y+yy>=0 && x+xx+shift<this.width && y+yy<this.height) output[(y+yy)*this.width+x+xx+shift]=quantize(bytes[p+yy*w+xx])*16
}
p+=w*h
for(let j=0;j<selections;j++) { const record=readPresentation(bytes,p);p=record.end;if(record.selection.displayList?.timeline) record.selection.displayList = { ...record.selection.displayList, presentedAt: this.shellReceivedAt, timeline: { ...record.selection.displayList.timeline, startedAt: record.selection.displayList.timeline.startedAt - (Date.now()-this.shellReceivedAt) } };paintPresentation(output,screen,this.width,this.height,record.selection) }
}
}
return output
}
}
-33
View File
@@ -1,33 +0,0 @@
import type { KotlinBridge } from './kotlin-platform';
// Handwritten declarations for the small native surface, checked against the
// compiled API. NativeScript runtime metadata is generated from the AAR.
declare namespace com.faceclaw.shared {
// Used as com.faceclaw.shared.KotlinBridge; oxlint misses qualified references.
// oxlint-disable-next-line no-unused-vars
class KotlinBridge extends java.lang.Object {
constructor();
platform(): string;
threadName(): string;
isMainThread(): boolean;
greet(name: string): string;
roundTrip(message: string, listener: KotlinBridgeListener): string;
}
class KotlinBridgeListener extends java.lang.Object {
constructor(implementation: { transform(message: string): string });
}
}
export function createKotlinBridge(): KotlinBridge {
const bridge = new com.faceclaw.shared.KotlinBridge();
return {
platform: () => bridge.platform(),
threadName: () => bridge.threadName(),
isMainThread: () => bridge.isMainThread(),
greet: name => bridge.greet(name),
roundTrip(message, transform) {
const listener = new com.faceclaw.shared.KotlinBridgeListener({ transform });
return bridge.roundTrip(message, listener);
},
};
}
-11
View File
@@ -1,11 +0,0 @@
/** Exported native API normalized across Java interfaces and Obj-C protocols. */
export interface KotlinBridge {
platform(): string;
threadName(): string;
isMainThread(): boolean;
greet(name: string): string;
/** Synchronous callback; must not throw across the native boundary. */
roundTrip(message: string, transform: (message: string) => string): string;
}
export function createKotlinBridge(): KotlinBridge;
-42
View File
@@ -1,42 +0,0 @@
import type { KotlinBridge } from './kotlin-platform';
// Handwritten declarations matching FaceclawKit's Objective-C header.
declare class FaceclawKitKotlinBridge extends NSObject {
static alloc(): FaceclawKitKotlinBridge;
init(): this;
platform(): string;
threadName(): string;
isMainThread(): boolean;
greetName(name: string): string;
roundTripMessageListener(message: string, listener: FaceclawKitKotlinBridgeListener): string;
}
interface FaceclawKitKotlinBridgeListener {
transformMessage(message: string): string;
}
declare const FaceclawKitKotlinBridgeListener: {
prototype: FaceclawKitKotlinBridgeListener;
};
@NativeClass()
class KotlinCallback extends NSObject implements FaceclawKitKotlinBridgeListener {
static ObjCProtocols = [FaceclawKitKotlinBridgeListener];
transform!: (message: string) => string;
transformMessage(message: string): string { return this.transform(message); }
}
export function createKotlinBridge(): KotlinBridge {
const bridge = FaceclawKitKotlinBridge.alloc().init();
return {
platform: () => bridge.platform(),
threadName: () => bridge.threadName(),
isMainThread: () => bridge.isMainThread(),
greet: name => bridge.greetName(name),
roundTrip(message, transform) {
const listener = KotlinCallback.new() as KotlinCallback;
listener.transform = transform;
// Kotlin uses this listener synchronously and never retains it.
return bridge.roundTripMessageListener(message, listener);
},
};
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { File, knownFolders, path, type ImageSource } from "@nativescript/core";
import { SurfaceCompositor } from "../graphics/surface-compositor";
import { SurfaceCompositor } from "../graphics/surface-compositor.ios";
import { G2_LENS_WIDTH, G2_LENS_HEIGHT } from "../graphics/image";
import { previewPixels } from "./ios-graphics";
import { toData } from "./kotlin-data";
-42
View File
@@ -1,42 +0,0 @@
import { Utils } from "@nativescript/core";
import { GrayImage } from "../graphics/image";
import { spanCurrent } from "./frame-timings";
import { toUint8Array } from "~/util/array-util";
declare const com: any;
const ICON_SIZE = 24;
const ICON_CACHE_MS = 5_000;
let cachedIcons: GrayImage[] = [];
let cachedAtMs = 0;
export function readSystemStatusIcons(): GrayImage[] {
if (!global.isAndroid) return [];
const now = Date.now();
if (now - cachedAtMs < ICON_CACHE_MS) {
return cachedIcons.map(cachedIcon => cachedIcon.clone());
}
const context = Utils.android.getApplicationContext();
if (!context) return [];
const bytes = spanCurrent("fetch-system-status-icons", () =>
toUint8Array(
com.faceclaw.app.FaceclawSystemStatusIconProvider.getSystemStatusIconGrays(context, ICON_SIZE),
),
);
const iconByteLength = ICON_SIZE * ICON_SIZE;
const iconCount = Math.floor(bytes.length / iconByteLength);
const icons: GrayImage[] = [];
for (let index = 0; index < iconCount; index++) {
const icon = new GrayImage(ICON_SIZE, ICON_SIZE, 0);
icon.pixels.set(bytes.subarray(index * iconByteLength, (index + 1) * iconByteLength));
icons.push(icon);
}
cachedIcons = icons;
cachedAtMs = now;
return icons.map(icon => icon.clone());
}
-4
View File
@@ -359,10 +359,6 @@
"java": "com/faceclaw/app/FaceclawSseRequest.java",
"kotlin": "App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawSseRequest.kt"
},
{
"java": "com/faceclaw/app/FaceclawSystemStatusIconProvider.java",
"kotlin": "App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawSystemStatusIconProvider.kt"
},
{
"java": "com/faceclaw/app/FaceclawVoiceController.java",
"kotlin": "App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawVoiceController.kt"
@@ -1,35 +0,0 @@
package com.faceclaw.shared
/** NativeScript implements this Kotlin-owned contract in TypeScript. */
interface KotlinBridgeListener {
fun transform(message: String): String
}
/**
* Portable Kotlin at the same commonMain source path used by ios-port. Calls and callbacks are
* synchronous on the caller's thread. The listener is used only during roundTrip and is never
* retained.
*/
class KotlinBridge {
fun platform(): String = PlatformInfo.name
fun threadName(): String = PlatformInfo.threadName()
fun isMainThread(): Boolean = PlatformInfo.isMainThread()
fun greet(name: String): String = "Hello, $name, from Kotlin"
fun roundTrip(message: String, listener: KotlinBridgeListener): String {
val reply = listener.transform("Kotlin received: $message")
// Consume the TypeScript return value, then return it across the bridge.
return "Kotlin received callback: $reply"
}
}
internal expect object PlatformInfo {
val name: String
fun threadName(): String
fun isMainThread(): Boolean
}
@@ -0,0 +1,9 @@
package com.faceclaw.shared
internal expect object PlatformInfo {
val name: String
fun threadName(): String
fun isMainThread(): Boolean
}
-23
View File
@@ -1,10 +1,8 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs'), vm = require('node:vm');
const { createHash } = require('node:crypto');
const { zstdCompressSync } = require('node:zlib');
const { loader } = require('./helpers/load-typescript.cjs');
const { LvglFont } = require('../.test-build/app/graphics/lvgl-font.js');
function pack(files) {
const key = Buffer.from('EVEN REALITIES');
@@ -17,27 +15,6 @@ function pack(files) {
})]);
}
test('iOS LVGL reader loads the bundled font including CJK and game symbols', () => {
const bytes = new Uint8Array(fs.readFileSync('app/fonts/source-han-sans/SourceHanSansSC-Light-20.lvgl.bin'));
const font = new LvglFont(bytes);
// Metrics and full glyph SHA-256 vectors from production Java LvglFontFile.
assert.deepEqual([...font.metrics], [25, 19]);
const vectors = [
[0x25a6, 'b08ecb603fd059b0a00ba3088f18b79185c421e73049797cd3cb0828e1e5cd04'],
[0x25c6, 'c176d5dcdb5f7e3a7220455528efde3760672c40cee39b422fc3f5ad20df66dd'],
[0x4e2d, '9bde2c8f1ffcf7afc598f4d0350c9ff262484816aa0c9b46d31f0c3c09613003'],
[0xff21, '0074f96299a75b86912282416e47e0823790e091352aec852eff49b89b2e719d'],
];
for (const [cp, hash] of vectors) {
const glyph = font.glyph(cp);
const w = glyph[0] | glyph[1] << 8, h = glyph[2] | glyph[3] << 8;
assert.ok(w > 0 && h > 0); assert.equal(glyph.length, 8 + (Math.floor(w / 2) + 1) * h);
assert.equal(createHash('sha256').update(glyph).digest('hex'), hash);
}
assert.equal(font.glyph(0x10ffff).length, 0);
assert.throws(() => new LvglFont(bytes.subarray(0, 80)), /bounds|Truncated/);
});
test('EHPK entrypoints and extraction paths cannot escape their package directory', () => {
const load = loader({}, { fzstd: require('fzstd') });
const api = load('app/apps/evenhub/ehpk.ts');
+43 -21
View File
@@ -5,7 +5,6 @@ const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
const images = require('../.test-build/app/graphics/image.js');
const { SurfaceCompositor } = require('../.test-build/app/graphics/surface-compositor.js');
const events = require('../.test-build/app/g2/events.js');
function load(file, modules, globals = {}) {
@@ -20,6 +19,7 @@ function load(file, modules, globals = {}) {
}
const planes = load('app/graphics/plane.ts', { './image': images });
const timings = load('app/native/frame-timings.ts', {});
const LAUNCHER_GRAY = 75;
function fixture() {
const observers = new Map(), phoneState = { protectedDataAvailable: true };
@@ -38,7 +38,7 @@ function fixture() {
'../util/render-freshness': { beginRenderPass() {}, endRenderPass: () => false },
'./glance-state': require('../.test-build/app/g2/glance-state.js'),
}, clock);
const launcherPixels = new Uint8Array(640 * 480).fill(75), fullRect = { x: 0, y: 0, width: 640, height: 480 };
const launcherPixels = new Uint8Array(640 * 480).fill(LAUNCHER_GRAY), fullRect = { x: 0, y: 0, width: 640, height: 480 };
const window = { windowId: 'launcher', surfaceId: 'launcher', appId: 'launcher', title: 'Apps',
// The launcher repaints into whichever display target the controller has after a switch.
requestRender() { void controller?.displayReady.then(() => controller.display?.submitSurfaceFrame('launcher', launcherPixels, fullRect, 'launcher')); }, setScreenOn() {} };
@@ -55,21 +55,43 @@ function fixture() {
if (input.type === 'display-wake' || !screenOn && input.type === 'double-click') shell.wake();
},
};
// Both display targets compose with the real (TypeScript reference) compositor so
// the pixel assertions below exercise real layering, blanking and lock surfaces.
// Both display targets share a minimal compositor (z-ordered opaque and
// color-keyed surfaces, visibility, blanking) so the pixel assertions below
// exercise layering, blanking and lock surfaces.
class Display {
compositor = new SurfaceCompositor(640, 480);
surfaces = new Map(); blanked = false; depths = [];
async configureCompositorScreen() {}
async configureSurface(id, options) { this.compositor.configureSurface(id, options); }
async removeSurface(id) { this.compositor.removeSurface(id); this.changed(); }
async setSurfaceVisible(id, visible) { this.compositor.setSurfaceVisible(id, visible); this.changed(); }
depths = [];
async setSurfaceDepth(id, depth) { this.depths.push([id, depth]); this.compositor.setSurfaceDepth(id, depth); }
async setUnderlayDim(below, factor) { this.compositor.setUnderlayDim(below, factor); this.changed(); }
async setScreenBlanked(blanked) { this.compositor.setScreenBlanked(blanked); this.changed(); }
async submitSurfaceFrame(id, pixels, rect, _fingerprint, _paintMs, _frameId, draws = null) { this.compositor.submitSurfaceFrame(id, pixels, rect, draws); this.changed(); }
async submitShellScene(bytes) { this.compositor.setShellScene(bytes); this.changed(); }
getCompositePreview() { return this.compositor.composite(); }
async configureSurface(id, options) {
const previous = this.surfaces.get(id);
const pixels = previous?.width === options.width && previous.height === options.height
? previous.pixels : new Uint8Array(options.width * options.height);
this.surfaces.set(id, { ...options, pixels, visible: previous?.visible ?? true });
}
async removeSurface(id) { this.surfaces.delete(id); this.changed(); }
async setSurfaceVisible(id, visible) { const surface = this.surfaces.get(id); if (surface) surface.visible = visible; this.changed(); }
async setSurfaceDepth(id, depth) { this.depths.push([id, depth]); }
async setUnderlayDim() { this.changed(); }
async setScreenBlanked(blanked) { this.blanked = blanked; this.changed(); }
async submitSurfaceFrame(id, pixels, rect) {
const surface = this.surfaces.get(id);
if (!surface) throw new Error(`Unknown surface: ${id}`);
for (let y = 0; y < rect.height; y++) {
surface.pixels.set(pixels.subarray(y * rect.width, (y + 1) * rect.width), (rect.y + y) * surface.width + rect.x);
}
this.changed();
}
async submitShellScene() { this.changed(); }
getCompositePreview() {
const output = new Uint8Array(640 * 480);
if (this.blanked) return output;
for (const s of [...this.surfaces.values()].filter(s => s.visible).sort((a, b) => a.zOrder - b.zOrder)) {
for (let y = 0; y < s.height; y++) for (let x = 0; x < s.width; x++) {
const value = s.pixels[y * s.width + x];
if (s.transparency !== 'color-key' || value) output[(s.y + y) * 640 + s.x + x] = value;
}
}
return output;
}
changed() {}
}
class PreviewDisplayTarget extends Display {
@@ -93,7 +115,7 @@ function fixture() {
async start() { this.emitState('connected', 'Connected.'); }
async disconnect() { this.emitState('disconnected', 'Disconnected.'); }
waitForFrameFinished() { return Promise.resolve('sent'); }
changed() { if (this.phase === 'connected') sent.push(this.compositor.composite()); }
changed() { if (this.phase === 'connected') sent.push(this.getCompositePreview()); }
}
const provider = {
isEnabled: () => settings.enabled, showOnTap: () => settings.tap,
@@ -221,17 +243,17 @@ test('double-tap and other shell wakes replace Glanceboard without waking it aga
const f = fixture(); await f.connect(); f.shell.sleep();
await f.hardware(9); await f.hardware(3);
assert.equal(f.shell.isScreenOn(), true); assert.equal(f.controller.glance.isVisible(), false);
assert.equal(f.sent.at(-1)[0], 80); assert.equal(f.boardStats.stops, 1);
assert.equal(f.sent.at(-1)[0], LAUNCHER_GRAY); assert.equal(f.boardStats.stops, 1);
f.shell.sleep(); await f.hardware(0); f.shell.wake(); await f.render();
assert.equal(f.controller.glance.isVisible(), false); assert.equal(f.sent.at(-1)[0], 80);
await f.advance(5000); await f.render(); assert.equal(f.sent.at(-1)[0], 80);
assert.equal(f.controller.glance.isVisible(), false); assert.equal(f.sent.at(-1)[0], LAUNCHER_GRAY);
await f.advance(5000); await f.render(); assert.equal(f.sent.at(-1)[0], LAUNCHER_GRAY);
});
test('head tilt uses Glanceboard when enabled and otherwise wakes the regular UI', async () => {
const f = fixture(); await f.connect(); f.shell.sleep();
await f.hardware(12, 1); assertBoard(f.sent.at(-1)); assert.equal(f.shell.isScreenOn(), false);
await f.hardware(3); f.shell.sleep(); f.settings.tilt = false;
await f.hardware(12, 1); assert.equal(f.shell.isScreenOn(), true); assert.equal(f.sent.at(-1)[0], 80);
await f.hardware(12, 1); assert.equal(f.shell.isScreenOn(), true); assert.equal(f.sent.at(-1)[0], LAUNCHER_GRAY);
});
test('disabled triggers and scrolls do not show the board; awake taps still reach the shell', async () => {
@@ -276,7 +298,7 @@ test('iOS lock hides apps and Glanceboard, blocks input, and stays locked when p
await f.hardware(12, 1); assert.ok(f.sent.at(-1).every(p => p === 123));
f.observers.get('unlock')(); await f.render();
assert.equal(f.controller.glassesLocked, false);
assert.equal(f.sent.at(-1)[0], 80);
assert.equal(f.sent.at(-1)[0], LAUNCHER_GRAY);
await f.hardware(0); assert.equal(f.received.length, 1);
});
+8 -30
View File
@@ -7,7 +7,6 @@ const graphics=require('../.test-build/app/graphics/image.js');
const planes=require('../.test-build/app/graphics/plane.js');
const wire=require('../.test-build/app/graphics/presentation-wire.js');
const {encodeShellScene}=require('../.test-build/app/graphics/shell-scene.js');
const {SurfaceCompositor}=require('../.test-build/app/graphics/surface-compositor.js');
function load(file,modules) {
const context={exports:{},require:name=>{assert.ok(name in modules, name);return modules[name];}};
vm.runInNewContext(ts.transpileModule(fs.readFileSync(file,'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2020}}).outputText,context);
@@ -37,27 +36,17 @@ test('menu retains the selected text and rounded highlight on the menu plane',as
assert.ok(row.source.pixels.some(v=>v===255));assert.ok(!image.withDrawsBaked(false).pixels.some(v=>v===255));
const flat=planes.flattenPlanesWithDraws([{image,x:0,y:0}]);
const records=wire.presentationRecords(prepareFrameDraws(flat.draws));assert.equal(records.length,1);
const c=new SurfaceCompositor(80,80);c.configureSurface('app',{x:0,y:0,width:80,height:80,zOrder:0,transparency:'opaque'});
c.submitSurfaceFrame('app',flat.image.pixels,{x:0,y:0,width:80,height:80},prepareFrameDraws(flat.draws));
const screen=flat.image.pixels.slice(),preview=c.composite();
assert.ok(preview.some(v=>v===240));assert.deepEqual(flat.image.pixels,screen);
await m.layer.handleInput({type:'scroll-down'},m.context);
const next=m.paint().draws.find(d=>d.presentation);assert.ok(next.y>row.y);assert.equal(next.presentation.depth,0);
});
test('shell menu selection survives serialization and is not baked into its surface',()=>{
test('shell menu selection survives serialization',()=>{
const image=menu().paint(),bytes=encodeShellScene([{image,x:0,y:0,shellKey:7}]);
assert.equal(new DataView(bytes.buffer).getUint16(14,true),1);
const c=new SurfaceCompositor(80,80);c.setShellScene(bytes);assert.ok(c.composite().some(v=>v===240));
});
test('later opaque planes occlude a replayed selection without erasing its visible part',()=>{
test('later opaque planes add an occlusion to a replayed selection',()=>{
const image=menu().paint(),row=image.draws.find(d=>d.presentation),cover=new graphics.GrayImage(10,8,1);
const flat=planes.flattenPlanesWithDraws([{image,x:0,y:0},{image:cover,x:row.x+10,y:row.y+2}]);
const records=wire.presentationRecords(prepareFrameDraws(flat.draws));assert.ok(records[0].displayList.calls.some(c => c.op === 2 && c.resource === 65535));
const c=new SurfaceCompositor(80,80);c.configureSurface('app',{x:0,y:0,width:80,height:80,zOrder:0,transparency:'opaque'});
c.submitSurfaceFrame('app',flat.image.pixels,{x:0,y:0,width:80,height:80},prepareFrameDraws(flat.draws));
const preview=c.composite();
for(let y=row.y+2;y<row.y+10;y++) for(let x=row.x+10;x<row.x+20;x++) assert.equal(preview[y*80+x],0);
assert.ok(preview.some(v=>v===240));
});
const {LayerStack,noopLayerActions}=load('app/ui/layers.ts',{
@@ -71,24 +60,15 @@ test('context menu surface and selected row both use +4 without changing the app
assert.deepEqual(frame.image.pixels,base.pixels);
const records=wire.presentationRecords(prepareFrameDraws(frame.draws));
assert.deepEqual(records.map(r=>r.depth),[4,4]);assert.equal(records[0].mode,'masked-image');
const c=new SurfaceCompositor(100,90);c.configureSurface('app',{x:0,y:0,width:100,height:90,zOrder:0,transparency:'opaque'});
c.submitSurfaceFrame('app',frame.image.pixels,{x:0,y:0,width:100,height:90},prepareFrameDraws(frame.draws));
const preview=c.composite();
assert.equal(preview[45*100+10],96); // old left edge has no baked menu
assert.equal(preview[45*100+13],0); // shifted opaque black interior
assert.equal(preview[8*100+12],96); // transparent rounded corner
assert.ok(preview.some(v=>v===240));
stack.pop();const closed=planes.flattenPlanesWithDraws(stack.paint());
c.submitSurfaceFrame('app',closed.image.pixels,{x:0,y:0,width:100,height:90},prepareFrameDraws(closed.draws));
assert.deepEqual(c.composite(),base.pixels);
assert.deepEqual(closed.image.pixels,base.pixels);
assert.deepEqual(wire.presentationRecords(prepareFrameDraws(closed.draws)),[]);
});
test('system menu bridge shifts its surface and selected row together by +4',()=>{
const image=menu().paint(),bytes=encodeShellScene([{image,x:8,y:0,shellKey:7,depth:4}]);
const view=new DataView(bytes.buffer),w=view.getUint16(8,true),h=view.getUint16(10,true);
assert.equal(view.getInt16(16,true),4);
assert.equal(wire.readPresentation(bytes,18+w*h).selection.depth,4);
const c=new SurfaceCompositor(100,80);c.setShellScene(bytes);const preview=c.composite();
assert.equal(preview[40*100+8],0);assert.equal(preview[40*100+10],80);
});
test('unselected sidebar icons retain -2 depth through shell cropping, including attention badges',()=>{
const shellScene=require('../.test-build/app/graphics/shell-scene.js');
@@ -106,10 +86,10 @@ test('unselected sidebar icons retain -2 depth through shell cropping, including
chrome.drawSidebar(image,state);
assert.deepEqual(Array.from(image.draws.filter(d=>d.presentation),d=>d.presentation.depth),[-2,-2]);
const crop=shellScene.shellCrop(image,0,0,64,280,1),bytes=encodeShellScene([crop]);
const c=new SurfaceCompositor(640,480);c.setShellScene(bytes);const preview=c.composite();
assert.equal(preview[34*640+30],240); // selected icon stays at its original x
assert.equal(preview[74*640+29],240); // unselected icon moves left by one
assert.equal(preview[74*640+33],0); // no baked copy at the original right edge
const view=new DataView(bytes.buffer),w=view.getUint16(8,true),h=view.getUint16(10,true);
assert.equal(view.getUint16(14,true),2);
const first=wire.readPresentation(bytes,18+w*h),second=wire.readPresentation(bytes,first.end);
assert.deepEqual([first.selection.depth,second.selection.depth],[-2,-2]);
state.selectedIndex=1;const next=new graphics.GrayImage(640,480);chrome.drawSidebar(next,state);
assert.equal(next.draws.filter(d=>d.presentation).length,2);
});
@@ -128,6 +108,4 @@ test('shell modal carries its inner menu highlight animation instead of baking i
const image=paint(),row=image.draws.find(d=>d.presentation);
assert.ok(row.y>before.y);assert.ok(row.presentation.displayList.timeline,'the slide stays a timed display list');
assert.ok(!image.withDrawsBaked(false).pixels.some(v=>v===255),'selected text is not baked into the modal surface');
const c=new SurfaceCompositor(200,200);c.setShellScene(encodeShellScene([{image,x:0,y:0,shellKey:9}]));
assert.ok(c.composite().some(v=>v===240));
});
-49
View File
@@ -1,49 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { SurfaceCompositor } = require('../.test-build/app/graphics/surface-compositor.js');
const rect = (x, y, width, height) => ({ x, y, width, height });
function surface(c, id, box, values, zOrder = 0, transparency = 'opaque') {
c.configureSurface(id, { ...box, zOrder, transparency });
c.submitSurfaceFrame(id, Uint8Array.from(values), rect(0, 0, box.width, box.height));
}
test('shell color key preserves underlying text while opaque black covers it', () => {
const c = new SurfaceCompositor(3, 2);
surface(c, 'app', rect(0, 0, 3, 2), [200, 200, 200, 200, 200, 200]);
surface(c, 'shell', rect(0, 0, 3, 2), [0, 1, 255, 0, 0, 0], 1, 'color-key');
c.setUnderlayDim(1, 0.5);
assert.deepEqual([...c.composite()], [100, 1, 255, 100, 100, 100]);
c.setSurfaceVisible('shell', false);
assert.deepEqual([...c.composite()], [100, 100, 100, 100, 100, 100]);
surface(c, 'opaque', rect(1, 0, 1, 2), [0, 0], 2);
assert.deepEqual([...c.composite()], [100, 0, 100, 100, 0, 100]);
});
test('partial frames clip in surface coordinates, then surfaces clip to the screen', () => {
const c = new SurfaceCompositor(3, 2);
surface(c, 'app', rect(-1, 0, 3, 2), [1, 2, 3, 4, 5, 6]);
const source = Uint8Array.from([99, 10, 20, 99, 30, 40, 99]);
c.submitSurfaceFrame('app', source.subarray(1, 5), rect(1, 1, 2, 2));
source.fill(0);
assert.deepEqual([...c.composite()], [2, 3, 0, 10, 20, 0]);
c.submitSurfaceFrame('app', Uint8Array.from([50, 60, 70, 80]), rect(-1, -1, 2, 2));
// The clipped update changed the offscreen column, leaving visible pixels intact.
assert.deepEqual([...c.composite()], [2, 3, 0, 10, 20, 0]);
});
test('moving a surface retains its frame; resizing clears it; blanking is reversible', () => {
const c = new SurfaceCompositor(3, 1);
surface(c, 'app', rect(0, 0, 2, 1), [7, 9]);
c.configureSurface('app', { ...rect(1, 0, 2, 1), zOrder: 0, transparency: 'opaque' });
assert.deepEqual([...c.composite()], [0, 7, 9]);
c.setScreenBlanked(true); assert.deepEqual([...c.composite()], [0, 0, 0]);
c.setScreenBlanked(false); assert.deepEqual([...c.composite()], [0, 7, 9]);
c.configureSurface('app', { ...rect(0, 0, 3, 1), zOrder: 0, transparency: 'opaque' });
assert.deepEqual([...c.composite()], [0, 0, 0]);
});
test('layer order is independent of creation order; removal reveals lower surfaces', () => {
const c = new SurfaceCompositor(1, 1);
surface(c, 'top', rect(0, 0, 1, 1), [20], 10);
surface(c, 'bottom', rect(0, 0, 1, 1), [80], -1);
assert.equal(c.composite()[0], 20);
c.removeSurface('top'); assert.equal(c.composite()[0], 80);
assert.throws(() => c.submitSurfaceFrame('missing', new Uint8Array(1), rect(0, 0, 1, 1)));
assert.throws(() => c.submitSurfaceFrame('bottom', new Uint8Array(2), rect(0, 0, 1, 1)));
});
-2
View File
@@ -16,11 +16,9 @@
"../app/remote/protocol.ts",
"../app/remote/listeners.ts",
"../app/g2/ancs-client.ts",
"../app/graphics/lvgl-font.ts",
"../app/phone-ui/ble-bandwidth-meter.ts",
"../app/apps/terminal/hub-header.ts",
"../app/g2/ios-peripheral-identity.ts",
"../app/graphics/surface-compositor.ts",
"../app/graphics/image.ts",
"../app/graphics/plane.ts",
"../app/graphics/shell-scene.ts",