forked from Blendman974/faceclaw
Refactor Java to shared kotlin
This commit is contained in:
1 parent
bc8e80c533
commit
68810197a8
173 files changed
+9855
-6252
No files matched your search
@@ -0,0 +1,15 @@
|
||||
import { fromData, toData, nativeArray } from '../native/kotlin-data'
|
||||
declare const FaceclawKitIosProtocol: any
|
||||
const protocol = FaceclawKitIosProtocol.new()
|
||||
export function buildBoundingBoxPayload(previous: Uint8Array | null, next: Uint8Array, width: number, height: number, frameId: number): Uint8Array | null {
|
||||
if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0 ||
|
||||
width % 4 || height % 2 || width / 4 > 255 || height / 2 > 255 ||
|
||||
!previous || previous.length !== width * height / 2 || next.length !== previous.length) return null
|
||||
const result = protocol.boundingBoxPreviousNextWidthHeightFrameId(toData(previous), toData(next), width, height, frameId)
|
||||
return result ? fromData(result) : null
|
||||
}
|
||||
export function buildFullFrameBands(packed: Uint8Array, width: number, height: number, firstId: number): Uint8Array[] {
|
||||
if (width <= 0 || width > 640 || width % 4 || height <= 0 || height > 480 || height % 2 || packed.length !== width * height / 2)
|
||||
throw new Error('Invalid framebuffer dimensions')
|
||||
return nativeArray(protocol.fullFrameBandsDataWidthHeightFirstId(toData(packed), width, height, firstId), fromData)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/** 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 = { kind: 'sys-event' | 'list-click' | 'text-click' | 'display-wake'; 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,
|
||||
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)))
|
||||
@@ -0,0 +1,21 @@
|
||||
import { fromData, toData, nativeArray } from '../native/kotlin-data'
|
||||
declare const FaceclawKitIosCfwTransport: any, FaceclawKitIosProtocol: any
|
||||
export const CFW_MAX_MESSAGE = 65535
|
||||
export type CfwAck = { nack: boolean; streamId: number; messageId: number; lens: number; size: number; checksum: number }
|
||||
/** maxWrite is the ATT value limit; Kotlin owns the persistent zlib stream. */
|
||||
export class CfwTransport {
|
||||
private native = FaceclawKitIosCfwTransport.new()
|
||||
reset(): void { this.native.reset() }
|
||||
encode(message: Uint8Array, streamId: number, lenses: number, maxWrite: number): Uint8Array[] {
|
||||
if (message.length > CFW_MAX_MESSAGE || !Number.isInteger(streamId) || streamId < 0 || streamId > 255 ||
|
||||
![1, 2, 3].includes(lenses) || !Number.isInteger(maxWrite) || maxWrite < 20 || maxWrite > 514)
|
||||
throw new Error('Invalid CFW stream parameters')
|
||||
return nativeArray(this.native.encodeDataStreamIdLensesMaxWrite(toData(message), streamId, lenses, maxWrite), fromData)
|
||||
}
|
||||
}
|
||||
const protocol = FaceclawKitIosProtocol.new()
|
||||
export function parseCfwAcks(packet: Uint8Array): CfwAck[] | null {
|
||||
const acks = protocol.acksData(toData(packet))
|
||||
return acks ? nativeArray(acks, (ack: any) => ({ nack: ack.nack, streamId: ack.streamId, messageId: ack.messageId,
|
||||
lens: ack.lens, size: ack.size, checksum: ack.checksum })) : null
|
||||
}
|
||||
@@ -116,7 +116,7 @@ function prepareFwTextRun(placed: PlacedFwText): boolean {
|
||||
bytes.set(entry.data.nibbles, offset + 10);
|
||||
offset += 10 + entry.data.nibbles.length;
|
||||
}
|
||||
com.faceclaw.app.FwGlyphAtlas.register(buffer);
|
||||
com.faceclaw.app.FwGlyphAtlas.register(new com.faceclaw.app.AndroidByteReader(buffer));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -130,7 +130,7 @@ function imageId(placed: PlacedImage): number | null {
|
||||
let id: number | null = null;
|
||||
if (source.width > 0 && source.width <= 255 && source.height > 0 && source.height <= 255) {
|
||||
const key = `img:${source.width}x${source.height}:${source.contentHash32().toString(16)}`;
|
||||
id = com.faceclaw.app.ImageAtlas.ensure(key, source.width, source.height, source.pixels.buffer);
|
||||
id = com.faceclaw.app.ImageAtlas.ensure(key, source.width, source.height, new com.faceclaw.app.AndroidByteReader(source.pixels.buffer));
|
||||
if (!(typeof id === "number") || id <= 0) id = null;
|
||||
}
|
||||
imageIds.set(source, id);
|
||||
@@ -184,9 +184,9 @@ export function prepareFrameDraws(draws: readonly DeferredDraw[]): ArrayBuffer |
|
||||
}
|
||||
if (registration) {
|
||||
const plainBuffer = buildRegistrationBuffer(registration);
|
||||
if (plainBuffer) com.faceclaw.app.GlyphAtlas.register(plainBuffer);
|
||||
if (plainBuffer) com.faceclaw.app.GlyphAtlas.register(new com.faceclaw.app.AndroidByteReader(plainBuffer));
|
||||
const aaBuffer = buildAaRegistrationBuffer(registration);
|
||||
if (aaBuffer) com.faceclaw.app.GlyphAtlas.registerAa(aaBuffer);
|
||||
if (aaBuffer) com.faceclaw.app.GlyphAtlas.registerAa(new com.faceclaw.app.AndroidByteReader(aaBuffer));
|
||||
}
|
||||
if (bytes === 0) return null;
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { fromData, toData } from '../native/kotlin-data'
|
||||
import type { SurfaceConfiguration, SurfaceRect } from './surface-compositor'
|
||||
export type { SurfaceConfiguration, SurfaceRect } from './surface-compositor'
|
||||
declare const FaceclawKitIosSurfaceCompositor: any
|
||||
/** Retained pixels, clipping, layers and composition live in shared Kotlin. */
|
||||
export class SurfaceCompositor {
|
||||
private native: any
|
||||
constructor(readonly width: number, readonly height: number) {
|
||||
if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) throw new Error('Invalid compositor size')
|
||||
this.native = FaceclawKitIosSurfaceCompositor.alloc().initWithWidthHeight(width, height)
|
||||
}
|
||||
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')
|
||||
this.native.configureIdXYWidthHeightZOrderTransparent(id, options.x, options.y, options.width, options.height, options.zOrder, options.transparency === 'color-key')
|
||||
}
|
||||
removeSurface(id: string): void { this.native.removeId(id) }
|
||||
setSurfaceVisible(id: string, visible: boolean): void { this.native.visibleIdVisible(id, visible) }
|
||||
setUnderlayDim(belowZOrder: number, factor: number): void {
|
||||
if (!Number.isFinite(factor)) throw new Error('Invalid dim factor')
|
||||
this.native.dimBelowFactor(belowZOrder, factor)
|
||||
}
|
||||
setScreenBlanked(blanked: boolean): void { this.native.blankBlanked(blanked) }
|
||||
submitSurfaceFrame(id: string, pixels: Uint8Array, rect: SurfaceRect): void {
|
||||
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')
|
||||
this.native.submitIdDataXYWidthHeight(id, toData(pixels), rect.x, rect.y, rect.width, rect.height)
|
||||
}
|
||||
composite(): Uint8Array { return fromData(this.native.composite()) }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/** Bulk binary bridge; slices are normalized without per-byte native calls. */
|
||||
export function toData(bytes: Uint8Array): NSData {
|
||||
const buffer = bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength
|
||||
? bytes.buffer : bytes.slice().buffer
|
||||
return NSData.dataWithBytesLength(interop.handleof(buffer), bytes.byteLength)
|
||||
}
|
||||
export function fromData(data: NSData): Uint8Array {
|
||||
return new Uint8Array(interop.bufferFromData(data)).slice()
|
||||
}
|
||||
export function nativeArray<T, R>(items: NSArray<T>, convert: (item: T) => R): R[] {
|
||||
return Array.from({ length: items.count }, (_, i) => convert(items.objectAtIndex(i)))
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { runKotlinProtocolSmokeTest } from './kotlin-protocol-smoke';
|
||||
import type { KotlinBridge } from './kotlin-platform';
|
||||
|
||||
// Handwritten declarations for the small native surface, checked against the
|
||||
@@ -17,6 +18,7 @@ declare namespace com.faceclaw.shared {
|
||||
}
|
||||
|
||||
export function createKotlinBridge(): KotlinBridge {
|
||||
runKotlinProtocolSmokeTest();
|
||||
const bridge = new com.faceclaw.shared.KotlinBridge();
|
||||
return {
|
||||
platform: () => bridge.platform(),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { runKotlinProtocolSmokeTest } from './kotlin-protocol-smoke.ios';
|
||||
import type { KotlinBridge } from './kotlin-platform';
|
||||
|
||||
// Handwritten declarations matching FaceclawKit's Objective-C header.
|
||||
@@ -26,6 +27,7 @@ class KotlinCallback extends NSObject implements FaceclawKitKotlinBridgeListener
|
||||
}
|
||||
|
||||
export function createKotlinBridge(): KotlinBridge {
|
||||
runKotlinProtocolSmokeTest();
|
||||
const bridge = FaceclawKitKotlinBridge.alloc().init();
|
||||
return {
|
||||
platform: () => bridge.platform(),
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import * as protocol from '../g2/ble-protocol.ios'
|
||||
import { CfwTransport, parseCfwAcks } from '../g2/cfw-transport.ios'
|
||||
import { SurfaceCompositor } from '../graphics/surface-compositor.ios'
|
||||
import { buildBoundingBoxPayload } from '../g2/ble-image-optimizer.ios'
|
||||
import { lvglMetrics } from './lvgl-font.ios'
|
||||
|
||||
/** Development-only checks of real NativeScript selectors and bulk data crossings. */
|
||||
export function runKotlinProtocolSmokeTest(): void {
|
||||
const hex = (data: Uint8Array) => Array.from(data, byte => byte.toString(16).padStart(2, '0')).join('')
|
||||
const assert = (condition: boolean, what: string) => { if (!condition) throw new Error(`Kotlin protocol bridge: ${what}`) }
|
||||
const auth = protocol.authentication(101)
|
||||
assert(hex(auth) === '080410651a0408011004', 'authentication')
|
||||
assert(protocol.crc16(new Uint8Array([1, 2, 3])) === 0xadad, 'CRC')
|
||||
const receiver = new protocol.MessageReceiver()
|
||||
const frame = protocol.frameMessage(auth, 128, 0, 64)[0]
|
||||
const received = receiver.receive('test', frame)
|
||||
assert(received.length === 1 && received[0].magic === 101 && hex(received[0].payload) === hex(auth), 'reassembly')
|
||||
const payload = protocol.bytes(13, protocol.bytes(3, protocol.concat(protocol.integer(1, 12), protocol.integer(2, 2))))
|
||||
const event = protocol.decodeGlassesInput({ sid: 224, flag: 1, payload, command: 0, magic: 0 })
|
||||
assert(event?.kind === 'display-wake' && event.eventSource === 2, 'event')
|
||||
const transport = new CfwTransport()
|
||||
const packets = transport.encode(new Uint8Array(128).fill(9), 255, 3, 185)
|
||||
assert(packets.length > 0 && packets.every(p => p.length <= 185), 'compression')
|
||||
transport.reset()
|
||||
assert(parseCfwAcks(new Uint8Array()) === null, 'invalid ACK')
|
||||
const c = new SurfaceCompositor(3, 2)
|
||||
c.configureSurface('test', { x: 0, y: 0, width: 3, height: 2, zOrder: 0, transparency: 'opaque' })
|
||||
c.submitSurfaceFrame('test', new Uint8Array([0, 16, 255, 32, 48, 64]), { x: 0, y: 0, width: 3, height: 2 })
|
||||
assert(hex(c.composite()) === '0010ff203040', 'composition')
|
||||
assert(hex(protocol.packGray4(c.composite(), 3, 2)) === '01f02340', 'packing')
|
||||
c.setScreenBlanked(true); assert(c.composite().every(p => p === 0), 'blanking')
|
||||
const changed = new Uint8Array(16); changed[0] = 255
|
||||
assert(buildBoundingBoxPayload(new Uint8Array(16), changed, 8, 4, 1)?.[0] === 3, 'image update')
|
||||
assert(lvglMetrics('/nonexistent/faceclaw-font').length === 0, 'font bridge')
|
||||
console.log('FACECLAW_KOTLIN_PROTOCOL_PASS iOS')
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
declare const com: any
|
||||
|
||||
/** Development-only checks of NativeScript metadata and bulk ByteBuffer crossings. */
|
||||
export function runKotlinProtocolSmokeTest(): void {
|
||||
const native = com.faceclaw.app
|
||||
const hex = (data: any) => Array.from({ length: data.length }, (_, i) => (data[i] & 255).toString(16).padStart(2, '0')).join('')
|
||||
const assert = (condition: boolean, what: string) => { if (!condition) throw new Error(`Kotlin protocol bridge: ${what}`) }
|
||||
const auth = native.BleProtocol.buildAuthenticationRequest(101)
|
||||
assert(hex(auth) === '080410651a0408011004', 'authentication')
|
||||
const compositor = new native.SurfaceCompositor()
|
||||
compositor.configureScreen(3, 2)
|
||||
compositor.configureSurface('test', 0, 0, 3, 2, 0, 0)
|
||||
const pixels = new Uint8Array([0, 16, 255, 32, 48, 64])
|
||||
compositor.submitSurface('test', new native.AndroidByteReader(pixels.buffer), 0, 0, 3, 2, '1')
|
||||
assert(hex(compositor.composite().gray) === '0010ff203040', 'composition/ByteBuffer')
|
||||
assert(hex(native.BmpUtil.pack4bppFromGray8(compositor.composite().gray, 3, 2)) === '01f02340', 'packing')
|
||||
const id = native.ImageAtlas.ensure('kotlin-smoke', 3, 2, new native.AndroidByteReader(pixels.buffer))
|
||||
assert(id > 0 && native.ImageAtlas.get(id).width === 3, 'image atlas/reused buffer')
|
||||
console.log('FACECLAW_KOTLIN_PROTOCOL_PASS Android')
|
||||
}
|
||||
@@ -1,16 +1,5 @@
|
||||
import { LvglFont } from '../graphics/lvgl-font'
|
||||
import { readBinaryFile } from './file-access'
|
||||
const cache = new Map<string, LvglFont>()
|
||||
function load(path: string): LvglFont {
|
||||
let font = cache.get(path)
|
||||
if (!font) {
|
||||
const bytes = readBinaryFile(path)
|
||||
if (!bytes) throw new Error('Cannot read LVGL font')
|
||||
font = new LvglFont(bytes)
|
||||
if (cache.size >= 2) cache.delete(cache.keys().next().value!)
|
||||
cache.set(path, font)
|
||||
}
|
||||
return font
|
||||
}
|
||||
export function lvglMetrics(path: string): Uint8Array { return load(path).metrics }
|
||||
export function lvglGlyph(path: string, codePoint: number): Uint8Array { return load(path).glyph(codePoint) }
|
||||
import { fromData } from './kotlin-data'
|
||||
declare const FaceclawKitIosProtocol: any
|
||||
const protocol = FaceclawKitIosProtocol.new()
|
||||
export function lvglMetrics(path: string): Uint8Array { return fromData(protocol.fontMetricsPath(path)) }
|
||||
export function lvglGlyph(path: string, codePoint: number): Uint8Array { return fromData(protocol.fontGlyphPathCodePoint(path, codePoint)) }
|
||||
Reference in new issue
Block a user