Refactor a bunch of Java to Kotlin, making it usable in an iOS port

This commit is contained in:
James Babcock committed 2026-09-18 22:46:08 -07:00
1 parent c0f8f7e9c2
commit 410fd5840b
162 files changed
+9650 -6224

No files matched your search

@@ -0,0 +1,52 @@
package com.faceclaw.app;
import java.util.Arrays;
public class CompassProtocolTest {
private static byte[] hex(String value) {
byte[] bytes = new byte[value.length() / 2];
for (int i = 0; i < bytes.length; i++) bytes[i] = (byte)Integer.parseInt(value.substring(i * 2, i * 2 + 2), 16);
return bytes;
}
private static BleProtocol.CompassEvent parse(byte[] payload) {
return parse(payload, BleProtocol.FLAG_NOTIFY);
}
private static BleProtocol.CompassEvent parse(byte[] payload, int flag) {
byte[] frame = BleProtocol.framePb(payload, 8, flag, 15).get(0);
return BleProtocol.parseCompassEvent(BleProtocol.parseFrame(frame));
}
public static void main(String[] args) {
// Golden packet also checked against the real C encoder in g2flash's host test.
byte[] packet = hex("080f1000520308e702a2060c434d010302038c0098badcfe");
BleProtocol.CompassEvent event = parse(packet);
assert event.headingDegrees == 359 && event.command == 15;
assert event.magneticAccuracy == 3 && event.magneticAnomalies == 2;
assert event.orientationSource == 3 && event.diagnosticFlags == 0x8c;
assert event.sampleTimeMs == 0xfedcba98L; // unsigned 32-bit timestamp through Java long
assert parse(packet, BleProtocol.FLAG_NOTIFY_ALT).headingDegrees == 359;
assert parse(packet, BleProtocol.FLAG_REQUEST) == null;
assert parse(packet, 0) == null;
byte[] legacy = Arrays.copyOf(packet, 9);
event = parse(legacy);
assert event.headingDegrees == 359 && event.diagnosticFlags == -1;
for (int n = 9; n < packet.length; ++n) {
event = parse(Arrays.copyOf(packet, n));
assert event.headingDegrees == 359 && event.diagnosticFlags == -1;
}
for (int offset : new int[] {12, 13, 14, 15, 16, 17, 19}) {
byte[] invalid = packet.clone(); invalid[offset] = 99;
event = parse(invalid);
assert event.headingDegrees == 359 && event.diagnosticFlags == -1;
}
packet[15] = packet[16] = (byte)255; packet[17] = 0; packet[18] = 0;
event = parse(packet);
assert event.magneticAccuracy == -1 && event.magneticAnomalies == -1;
assert event.orientationSource == 0 && event.diagnosticFlags == 0;
event = parse(hex("08101000"));
assert event.command == 16 && event.headingDegrees == -1 && event.diagnosticFlags == -1;
event = parse(hex("08111000"));
assert event.command == 17 && event.diagnosticFlags == -1;
assert parse(hex("080f1000520308e802")) == null; // 360 isn't a heading
assert BleProtocol.parseCompassEvent(null) == null;
System.out.println("Compass protocol checks passed");
}
}
@@ -0,0 +1,67 @@
package com.faceclaw.app;
import java.util.Arrays;
public class FaceclawGestureEventTest {
private static byte[] hex(String value) {
byte[] result = new byte[value.length() / 2];
for (int i = 0; i < result.length; ++i)
result[i] = (byte)Integer.parseInt(value.substring(i * 2, i * 2 + 2), 16);
return result;
}
private static byte[] pb(byte[] payload) {
byte[] frame = BleProtocol.framePb(payload, 9, BleProtocol.FLAG_NOTIFY, 15).get(0);
return BleProtocol.parseFrame(frame).pb;
}
/** G2SettingPackage{commandId=3, magic=0, field102=['F','C',1,event,source,0]}: the CFW's wire shape. */
private static byte[] packet(int event, int source) {
byte[] p = hex("08031000b20606464301000000");
p[10] = (byte)event; p[11] = (byte)source;
return p;
}
public static void main(String[] args) {
// Event codes map to the sys-events a live page would produce.
int[][] events = {
{2, BleProtocol.EVENT_CLICK},
{3, BleProtocol.EVENT_RING_LONG_PRESS},
{4, BleProtocol.EVENT_RING_LONG_PRESS_RELEASE},
};
int[][] sources = {
{0, BleProtocol.EVENT_SOURCE_GLASSES_L},
{1, BleProtocol.EVENT_SOURCE_GLASSES_R},
{4, BleProtocol.EVENT_SOURCE_RING},
{7, 0},
};
for (int[] e : events) for (int[] s : sources) {
BleProtocol.FaceclawGestureEvent g = BleProtocol.parseFaceclawGestureEvent(pb(packet(e[0], s[0])));
assert g != null && g.eventType == e[1] && g.eventSource == s[1] : e[0] + "/" + s[0];
}
// The double-tap wake event (1) and unknown codes are not gestures, and the
// wake parser does not mistake a gesture for a wake.
byte[] wake = packet(1, 0x34); wake[12] = 0x12;
assert BleProtocol.parseFaceclawGestureEvent(pb(wake)) == null;
assert BleProtocol.parseFaceclawWakeEvent(pb(wake)) == 0x1234;
assert BleProtocol.parseFaceclawWakeEventCode(pb(wake)) == 1;
// The head-up wake (5) shares the nonce handshake but keeps its own code.
byte[] headUp = packet(5, 0x34); headUp[12] = 0x12;
assert BleProtocol.parseFaceclawGestureEvent(pb(headUp)) == null;
assert BleProtocol.parseFaceclawWakeEvent(pb(headUp)) == 0x1234;
assert BleProtocol.parseFaceclawWakeEventCode(pb(headUp)) == BleProtocol.FACECLAW_WAKE_EVENT_HEAD_UP;
for (int code : new int[] {2, 3, 4, 6}) {
assert BleProtocol.parseFaceclawWakeEvent(pb(packet(code, 1))) == -1;
assert BleProtocol.parseFaceclawWakeEventCode(pb(packet(code, 1))) == -1;
}
for (int code : new int[] {0, 5, 6, 255})
assert BleProtocol.parseFaceclawGestureEvent(pb(packet(code, 1))) == null;
// Wrong protocol version, wrong magic letters, truncated payloads, plain settings.
byte[] bad = packet(2, 1); bad[9] = 2;
assert BleProtocol.parseFaceclawGestureEvent(pb(bad)) == null;
bad = packet(2, 1); bad[7] = 'X';
assert BleProtocol.parseFaceclawGestureEvent(pb(bad)) == null;
byte[] full = packet(2, 1);
for (int n = 0; n < full.length; ++n)
assert BleProtocol.parseFaceclawGestureEvent(pb(Arrays.copyOf(full, n))) == null : n;
assert BleProtocol.parseFaceclawGestureEvent(pb(hex("08031000"))) == null;
assert BleProtocol.parseFaceclawGestureEvent(null) == null;
System.out.println("FaceclawGestureEventTest ok");
}
}
@@ -0,0 +1,50 @@
package com.faceclaw.app;
import java.util.Arrays;
public class RingBatteryProtocolTest {
private static byte[] hex(String value) {
byte[] result = new byte[value.length() / 2];
for (int i = 0; i < result.length; ++i)
result[i] = (byte)Integer.parseInt(value.substring(i * 2, i * 2 + 2), 16);
return result;
}
private static BleProtocol.RingBatterySnapshot parse(byte[] payload) {
byte[] frame = BleProtocol.framePb(payload, 9, BleProtocol.FLAG_NOTIFY, 15).get(0);
return BleProtocol.parseRingBattery(BleProtocol.parseFrame(frame).pb);
}
public static void main(String[] args) {
// Same golden payload as g2flash/tests/ring_battery_test.c.
byte[] packet = hex("08031000d206055242010752");
BleProtocol.RingBatterySnapshot result = parse(packet);
assert result.battery == 82 && result.charging == 1;
packet[10] = 3;
for (int level = 0; level <= 100; ++level) {
packet[11] = (byte)level;
result = parse(packet);
assert result.battery == level && result.charging == 0;
}
for (int flags : new int[] {0, 1}) {
packet[10] = (byte)flags; packet[11] = (byte)255;
result = parse(packet);
assert result.battery == -1 && result.charging == -1;
}
packet = hex("08031000d206055242010752");
for (int n = 0; n < packet.length; ++n)
assert parse(Arrays.copyOf(packet, n)) == null;
for (int offset : new int[] {7, 8, 9, 10, 11}) {
byte previous = packet[offset]; packet[offset] = (byte)255;
assert parse(packet) == null;
packet[offset] = previous;
}
assert parse(hex("08031000")) == null; // older firmware
assert parse(hex("d206055242010252")) == null; // valid without connected
assert parse(hex("d206055242010352")).battery == 82;
assert parse(hex("d2060552420100ff")).battery == -1;
// Invalid unknown value and charging-without-valid must be rejected.
assert parse(hex("d206055242010052")) == null;
assert parse(hex("d2060552420105ff")) == null;
assert parse(hex("d206055242010364")).battery == 100;
assert parse(hex("d206055242010365")) == null;
assert BleProtocol.parseRingBattery(null) == null;
}
}
@@ -0,0 +1,58 @@
package com.faceclaw.app;
import java.lang.reflect.*;
import java.util.*;
public class TextureCacheProtocolTest {
static int u16(byte[] b, int p) { return (b[p]&255) | (b[p+1]&255)<<8; }
static int u32(byte[] b, int p) { return u16(b,p) | u16(b,p+2)<<16; }
public static void main(String[] args) throws Exception {
TextureCacheState cache = new TextureCacheState();
byte[] pixels = new byte[255*255];
for (int i=0;i<pixels.length;i++) pixels[i]=(byte)(i%15+1);
ImageAtlas.Entry big = new ImageAtlas.Entry(255,255,pixels);
for (int i=0;i<3;i++) assert cache.ensureImage(i,big)>=0;
ImageAtlas.Entry tiny = new ImageAtlas.Entry(1,1,new byte[]{15});
int imageOffset = cache.ensureImage(100,tiny);
assert imageOffset>65535;
GlyphAtlas.Glyph glyph = new GlyphAtlas.Glyph(1,1,0,1,0,null,new byte[]{15});
int glyphOffset = cache.ensureGlyph(42,'A',glyph);
int table = cache.fontTableOffset(42);
assert table>65535 && glyphOffset==table+96*4;
byte[] memory = new byte[262144];
for (byte[] upload: cache.drainUploadPayloads(3600)) {
assert upload[0]==18;
int pos=1;
while (pos<upload.length) {
int offset=u32(upload,pos), n=u16(upload,pos+4);
System.arraycopy(upload,pos+6,memory,offset,n); pos+=6+n;
}
assert pos==upload.length;
}
assert memory[imageOffset]==1 && memory[imageOffset+2]==0x1f;
assert u32(memory,table+('A'-32)*4)==glyphOffset;
assert !cache.hasPendingUploads();
// Exercise the production planner encoders with offsets above 64 KiB.
Class<?> selected=Class.forName("com.faceclaw.app.TexturePlanner$Selected");
Constructor<?> ctor=selected.getDeclaredConstructors()[0]; ctor.setAccessible(true);
Object image=ctor.newInstance(SurfaceCompositor.ScreenDraw.image(100,321,123),null,tiny,321,15);
Method encode=TexturePlanner.class.getDeclaredMethod("encodeImageDraw",TextureCacheState.class,selected);
encode.setAccessible(true);
byte[] draw=(byte[])encode.invoke(null,cache,image);
assert draw.length==10 && draw[0]==19 && u32(draw,1)==imageOffset;
assert u16(draw,5)==321 && u16(draw,7)==123 && draw[9]==31;
Object letter=ctor.newInstance(SurfaceCompositor.ScreenDraw.glyph(42,'A',321,123,255),glyph,null,321,15);
Method runs=TexturePlanner.class.getDeclaredMethod("buildRuns",TextureCacheState.class,List.class,List.class);
runs.setAccessible(true); List<byte[]> out=new ArrayList<>();
runs.invoke(null,cache,Collections.singletonList(letter),out);
byte[] run=out.get(0);
assert run.length==12 && run[0]==20 && u32(run,1)==table;
assert u16(run,5)==321 && u16(run,7)==123 && run[9]==31 && run[10]==1 && run[11]=='A';
int id=200;
while (cache.ensureImage(id++,big)>=0) {}
int before=cache.usedBytes();
assert cache.ensureImage(id,big)==-1 && cache.usedBytes()==before;
cache.reset(); assert cache.usedBytes()==0 && !cache.hasPendingUploads();
assert cache.ensureImage(id,tiny)==0;
}
}
@@ -0,0 +1,117 @@
package com.faceclaw.app
import java.io.ByteArrayOutputStream
import java.util.Collections
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.zip.Inflater
import kotlin.test.*
// Host tests have no Android clock; all other services use the production adapter.
internal actual fun testPlatform(): ProtocolPlatform =
object : ProtocolPlatform by AndroidProtocolPlatform {
override fun elapsedRealtimeMs() = System.nanoTime() / 1_000_000
}
internal actual fun inflateRecords(records: List<ByteArray>): List<ByteArray> {
val inflater = Inflater()
try {
return records.map { record ->
if (record[0].toInt() and CfwTransport.RESET_CONTEXT != 0) inflater.reset()
val body = record.copyOfRange(5, record.size)
if (record[0].toInt() and CfwTransport.COMPRESSED == 0) body
else {
inflater.setInput(body)
val out = ByteArrayOutputStream()
val buffer = ByteArray(4096)
do {
val count = inflater.inflate(buffer)
out.write(buffer, 0, count)
} while (!inflater.needsInput())
out.toByteArray()
}
}
} finally {
inflater.end()
}
}
class AndroidProtocolTest {
@Test
fun javaGoldenCorpus() {
// SHA-256 of packets emitted by the pre-migration Java implementation.
val raw = java.security.MessageDigest.getInstance("SHA-256")
val compressed = java.security.MessageDigest.getInstance("SHA-256")
val transport = CfwTransport(testPlatform())
var state = 123456789
try {
repeat(120) { i ->
val size = intArrayOf(0, 1, 4, 247, 248, 252, 4095, 4096, 8192, 65535)[i % 10]
val data =
ByteArray(size) {
state = state xor (state shl 13)
state = state xor (state ushr 17)
state = state xor (state shl 5)
state.toByte()
}
if (i % 3 == 0) data.fill((i % 7).toByte())
val id = (i * 37) and 255
val lenses = 1 + (i / 7) % 3
val mtu = intArrayOf(23, 247, 512, 517)[i % 4]
if (i % 13 == 0) transport.reset()
CfwTransport.frame(data, id, lenses, mtu).forEach { raw.update(it) }
transport.encode(data, id, lenses, mtu).forEach { compressed.update(it) }
}
assertEquals(
"d0efdb99ac71763dd29b70fbd0021b80e1cfe514dfc8a60e2a8424892b16c9f5",
raw.digest().toHexString(),
)
assertEquals(
"eb5ce0cc6e41b8e84f0d9455f98f3f666b20be0643c3756c5f7aa9d9a66085e2",
compressed.digest().toHexString(),
)
} finally {
transport.close()
}
}
@Test
fun writeModeMapping() {
assertEquals(
android.bluetooth.BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT,
AndroidProtocolPlatform.writeType(GattWriteMode.WITH_RESPONSE),
)
assertEquals(
android.bluetooth.BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE,
AndroidProtocolPlatform.writeType(ConnectionOptions.WRITE_MODE),
)
}
@Test
fun concurrentAllocationNeverDuplicatesAnInUseId() {
val pool = BleMagicPool(testPlatform())
val inUse = Collections.synchronizedSet(mutableSetOf<Int>())
val executor = Executors.newFixedThreadPool(8)
try {
val jobs =
List(8) {
executor.submit {
repeat(2000) {
val id = pool.allocate()
assertTrue(inUse.add(id))
Thread.yield()
assertTrue(inUse.remove(id))
pool.release(1, id, null, null)
}
}
}
jobs.forEach { it.get(30, TimeUnit.SECONDS) }
assertEquals(156, List(156) { pool.allocate() }.toSet().size)
} finally {
executor.shutdownNow()
}
}
}
internal actual fun digest(bytes: ByteArray): String =
BinaryEncoding.bytesToHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes))
@@ -0,0 +1,27 @@
package com.faceclaw.app
import kotlin.test.Test
/** Existing wire fixtures also verify the Java API retained by the Kotlin port. */
class JavaCompatibilityTest {
@Test fun compass() = CompassProtocolTest.main(emptyArray())
@Test fun ringBattery() = RingBatteryProtocolTest.main(emptyArray())
@Test fun gestures() = FaceclawGestureEventTest.main(emptyArray())
@Test fun textureCache() = TextureCacheProtocolTest.main(emptyArray())
}
class AndroidByteReaderTest {
@Test fun repeatedBridgeCrossingsHaveIndependentCursors() {
val buffer = java.nio.ByteBuffer.wrap(byteArrayOf(10, 20, 30))
val first = AndroidByteReader(buffer)
kotlin.test.assertEquals(10, first.get().toInt())
kotlin.test.assertEquals(0, buffer.position())
val second = AndroidByteReader(buffer)
kotlin.test.assertEquals(3, second.remaining())
kotlin.test.assertEquals(10, second.get().toInt())
kotlin.test.assertEquals(20, first.get().toInt())
}
}
@@ -0,0 +1,44 @@
package com.faceclaw.app
import kotlin.test.*
internal expect fun digest(bytes: ByteArray): String
class AudioRecordingTest {
@Test
fun javaNoiseSuppressionGoldenAcrossChunksAndReset() {
val suppressor = FaceclawNoiseSuppressor(16000)
val output = ByteSink()
for (round in 0 until 80) {
val input = ByteArray(if (round % 7 == 0) 514 else 640)
for (i in 0 until input.size / 2) {
val value = ((round * 317 + i * 773) % 48000) - 24000
input[i * 2] = value.toByte()
input[i * 2 + 1] = (value shr 8).toByte()
}
if (round == 41) suppressor.reset()
output.write(assertNotNull(suppressor.process(input)))
}
// SHA-256 from the original Java DSP, including warmup and irregular chunks.
assertEquals(
"4a7e86b70d61d683b17c7051dbd6666f5ea62427fdd7fdb1d4c9a1772a1eb8ef",
digest(output.toByteArray()),
)
}
@Test
fun javaGifGoldenIncludingDedupAndLzwCodeGrowth() {
val recorder = SharedGifScreenRecorder()
assertTrue(recorder.encode().isEmpty())
for (round in 0 until 7) {
val pixels = ByteArray(33 * 17) { ((it * 73 + round * 117) % 256).toByte() }
recorder.addFrame(pixels, 33, 17, round * 133L)
recorder.addFrame(pixels, 33, 17, round * 133L + 10)
}
assertFalse(recorder.isOverflowed())
assertEquals(
"8c5dcb98fa03653972f7f7d5ddaaacff323dd633578905bc252ebe21f9d82780",
digest(recorder.encode()),
)
}
}
@@ -0,0 +1,22 @@
package com.faceclaw.app
import kotlin.test.*
class FontTest {
@Test
fun bundledFontMatchesJavaMetricsAndGlyphs() {
assertContentEquals(byteArrayOf(25, 19), LvglFontFile.getMetrics(TEST_FONT_PATH))
val vectors =
mapOf(
0x25a6 to "b08ecb603fd059b0a00ba3088f18b79185c421e73049797cd3cb0828e1e5cd04",
0x25c6 to "c176d5dcdb5f7e3a7220455528efde3760672c40cee39b422fc3f5ad20df66dd",
0x4e2d to "9bde2c8f1ffcf7afc598f4d0350c9ff262484816aa0c9b46d31f0c3c09613003",
0xff21 to "0074f96299a75b86912282416e47e0823790e091352aec852eff49b89b2e719d",
)
vectors.forEach { (codePoint, expected) ->
assertEquals(expected, digest(LvglFontFile.getGlyph(TEST_FONT_PATH, codePoint)))
}
assertTrue(LvglFontFile.getGlyph(TEST_FONT_PATH, 0x10ffff).isEmpty())
assertTrue(LvglFontFile.getMetrics("/nonexistent/faceclaw-font").isEmpty())
}
}
@@ -0,0 +1,283 @@
package com.faceclaw.app
import kotlin.random.Random
import kotlin.test.*
internal expect fun testPlatform(): ProtocolPlatform
internal expect fun inflateRecords(records: List<ByteArray>): List<ByteArray>
internal fun record(packets: List<ByteArray>): ByteArray =
packets.flatMap { it.slice(9 until it.size - 2) }.toByteArray()
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private fun u16(bytes: ByteArray, offset: Int) =
(bytes[offset].toInt() and 255) or ((bytes[offset + 1].toInt() and 255) shl 8)
class ProtocolTest {
@Test
fun javaGoldenPacketsAndCrc() {
assertEquals(0x29b1, CfwTransport.crc("123456789".encodeToByteArray()))
assertEquals(0xffff, CfwTransport.crc(byteArrayOf()))
// Captured from the Java implementation before migration, including sequence wrap.
val expected =
listOf(
"aa21ff0c0101f000830b0f0078c331323334862b",
"aa21000c0101f000033536373839616263648c7b",
"aa2101050101f000436566de70",
)
val actual = CfwTransport.frame("123456789abcdef".encodeToByteArray(), 255, 3, 23)
assertEquals(expected.size, actual.size)
expected.zip(actual).forEach { (a, b) -> assertContentEquals(hex(a), b) }
}
@Test
fun framingBoundariesAndValidation() {
for (size in listOf(0, 1, 247, 252, 253, 65535)) {
val data = ByteArray(size) { it.toByte() }
for (mtu in listOf(23, 247, 512, 517)) {
val packets = CfwTransport.frame(data, 255, 2, mtu)
packets.forEachIndexed { i, packet ->
assertTrue(packet.size <= mtu - 3)
assertEquals((255 + i) and 255, packet[2].toInt() and 255)
assertEquals(packet.size - 8, packet[3].toInt() and 255)
assertEquals(
2 or (if (i == 0) 128 else 0) or (if (i == packets.lastIndex) 64 else 0),
packet[8].toInt() and 255,
)
assertEquals(
CfwTransport.crc(packet.copyOfRange(8, packet.size - 2)),
u16(packet, packet.size - 2),
)
}
val stream = record(packets)
assertEquals(size, u16(stream, 1))
assertEquals(CfwTransport.crc(data), u16(stream, 3))
assertContentEquals(data, stream.copyOfRange(5, stream.size))
}
}
for (invalid in listOf<ByteArray?>(null, ByteArray(65536))) assertFailsWith<
IllegalArgumentException
> {
CfwTransport.frame(invalid, 0, 3, 23)
}
for (stream in listOf(-1, 256)) assertFailsWith<IllegalArgumentException> {
CfwTransport.frame(byteArrayOf(), stream, 3, 23)
}
for (lens in listOf(0, 4)) assertFailsWith<IllegalArgumentException> {
CfwTransport.frame(byteArrayOf(), 0, lens, 23)
}
for (mtu in listOf(22, 518)) assertFailsWith<IllegalArgumentException> {
CfwTransport.frame(byteArrayOf(), 0, 3, mtu)
}
}
@Test
fun streamingCompressionRoundTripsAndResets() {
val transport = CfwTransport(testPlatform())
try {
val text = "shared history 👓 ".repeat(300).encodeToByteArray()
val inputs = listOf(text, text, byteArrayOf(), byteArrayOf(), text, text)
val records = inputs.mapIndexed { i, data ->
if (i == 5) transport.reset()
record(transport.encode(data, i, if (i < 4) 3 else 1, 247))
}
assertTrue(records[1].size < records[0].size)
assertTrue(records[0][0].toInt() and CfwTransport.RESET_CONTEXT != 0)
assertEquals(0, records[1][0].toInt() and CfwTransport.RESET_CONTEXT)
assertTrue(records[4][0].toInt() and CfwTransport.RESET_CONTEXT != 0)
assertTrue(records[5][0].toInt() and CfwTransport.RESET_CONTEXT != 0)
inputs.zip(inflateRecords(records)).forEach { (a, b) -> assertContentEquals(a, b) }
transport.close()
transport.close()
val reopened = record(transport.encode(text, 10, 1, 512))
assertTrue(reopened[0].toInt() and CfwTransport.RESET_CONTEXT != 0)
assertContentEquals(text, inflateRecords(listOf(reopened)).single())
} finally {
transport.close()
}
}
@Test
fun incompressibleMaximumFallsBackWithoutPoisoningHistory() {
val transport = CfwTransport(testPlatform())
try {
val data = Random(42).nextBytes(65535)
val raw = record(transport.encode(data, 255, 3, 517))
assertEquals(3 or CfwTransport.RESET_CONTEXT, raw[0].toInt())
val next = record(transport.encode(data.copyOf(1000), 0, 3, 517))
assertTrue(next[0].toInt() and CfwTransport.RESET_CONTEXT != 0)
val decoded = inflateRecords(listOf(raw, next))
assertContentEquals(data, decoded[0])
assertContentEquals(data.copyOf(1000), decoded[1])
} finally {
transport.close()
}
}
@Test
fun ackBatchesAndMalformedPackets() {
for (count in 1..4) {
val packet = ackPacket(count)
val acks = assertNotNull(CfwTransport.parseAcks(packet))
assertEquals(count, acks.size)
acks.forEachIndexed { i, ack ->
assertFalse(ack.nack)
assertEquals(255 - i, ack.streamId)
assertEquals(0x1234 + i, ack.messageId)
assertEquals(2, ack.lens)
assertEquals(0x4567 + i, ack.size)
assertEquals(0xabcd + i, ack.checksum)
}
assertEquals(255, assertNotNull(CfwTransport.parseAck(packet)).streamId)
// Every bit of the payload (including ACK trailers and CRC) is protected.
for (i in 8 until packet.size) {
val corrupt = packet.copyOf()
corrupt[i] = (corrupt[i].toInt() xor 1).toByte()
assertNull(CfwTransport.parseAcks(corrupt))
}
}
assertTrue(assertNotNull(CfwTransport.parseAck(ackPacket(1, 3))).nack)
assertNull(CfwTransport.parseAcks(ackPacket(2, 3)))
assertNull(CfwTransport.parseAcks(ackPacket(5)))
assertNull(CfwTransport.parseAcks(ackPacket(1, 2)))
for (index in listOf(0, 1, 3, 4, 5, 6, 7)) {
val corrupt = ackPacket(1)
corrupt[index] = (corrupt[index].toInt() xor 1).toByte()
assertNull(CfwTransport.parseAcks(corrupt))
}
val wrongLens = ackPacket(1)
wrongLens[12] = 3
sealAck(wrongLens)
assertNull(CfwTransport.parseAcks(wrongLens))
for (size in 0..18) assertNull(CfwTransport.parseAcks(ByteArray(size)))
assertNull(CfwTransport.parseAcks(null))
}
@Test
fun ackMatchingAndReplay() {
val input = byteArrayOf(1, 2, 3)
val message = message(input = input)
input[0] = 99
assertContentEquals(byteArrayOf(1, 2, 3), message.message)
fun ack(
lens: Int,
stream: Int = 100,
nack: Boolean = false,
size: Int = 3,
checksum: Int = message.cfwChecksum,
id: Int = 0,
) = CfwTransport.Ack(nack, stream, id, lens, size, checksum)
assertFalse(message.acceptCfwAck(null))
assertFalse(message.acceptCfwAck(ack(1, stream = 99)))
assertFalse(message.acceptCfwAck(ack(1, size = 4)))
assertFalse(message.acceptCfwAck(ack(1, checksum = 0)))
assertFalse(message.acceptCfwAck(ack(3)))
assertFalse(message.acceptCfwAck(ack(1, id = 1)))
assertEquals(0, message.cfwAckLenses)
assertFalse(message.acceptCfwAck(ack(1)))
assertFalse(message.acceptCfwAck(ack(1)))
assertTrue(message.acceptCfwAck(ack(2)))
assertFalse(message.acceptCfwAck(ack(1, nack = true, size = 0, checksum = 0)))
assertFalse(message.acceptCfwAck(ack(2)))
message.ackDeadlineAtMs = 500
message.ackPayload = byteArrayOf(1)
message.prepareCfwReplay(101)
assertEquals(1, message.cfwRetries)
assertFalse(message.cfwRetryPending)
assertEquals(0, message.cfwAckLenses)
assertEquals(0L, message.ackDeadlineAtMs)
assertTrue(message.ackPayload.isEmpty())
assertFalse(message.acceptCfwAck(ack(1)))
assertFalse(message.acceptCfwAck(ack(1, stream = 101)))
assertTrue(message.acceptCfwAck(ack(2, stream = 101)))
var callbacks = 0
message.onAck = MessageCallback { callbacks++ }
message.onAck!!.run()
assertEquals(1, callbacks)
}
@Test
fun orderedCompletionAndWholeWindowRecovery() {
val head = message()
val tail = message()
val stock = message(sid = 1)
val window = listOf(stock, head, tail)
tail.cfwAckLenses = 3
assertNull(CfwMessageWindow.acknowledgedHead(window))
assertTrue(CfwMessageWindow.replayWindow(window, 100).isEmpty())
head.ackDeadlineAtMs = 100
assertTrue(CfwMessageWindow.replayWindow(window, 99).isEmpty())
assertEquals(listOf(head, tail), CfwMessageWindow.replayWindow(window, 100))
head.cfwAckLenses = 3
assertSame(head, CfwMessageWindow.acknowledgedHead(window))
assertTrue(CfwMessageWindow.replayWindow(window, 100).isEmpty())
tail.cfwRetryPending = true
assertEquals(listOf(head, tail), CfwMessageWindow.replayWindow(window, 100))
head.cfwRetryPending = true
assertNull(CfwMessageWindow.acknowledgedHead(window))
}
@Test
fun magicPoolExhaustionLruAndReleaseRecords() {
var now = 123L
val platform =
object : ProtocolPlatform by testPlatform() {
override fun elapsedRealtimeMs() = now
}
val pool = BleMagicPool(platform)
assertEquals((100..255).toList(), List(156) { pool.allocate() })
assertFailsWith<IllegalStateException> { pool.allocate() }
pool.release(1, 101, "first", "ack")
pool.release(1, 100, null, null)
now = 456
pool.release(2, 101, "other", "timeout") // duplicate release must not allocate twice
assertEquals(101, pool.allocate())
assertEquals(100, pool.allocate())
assertFailsWith<IllegalStateException> { pool.allocate() }
val first = assertNotNull(pool.getReleaseRecord(1, 101))
assertEquals(123L, first.releasedAtMs)
assertEquals("first", first.label)
assertEquals(456L, assertNotNull(pool.getReleaseRecord(2, 101)).releasedAtMs)
assertEquals("", assertNotNull(pool.getReleaseRecord(1, 100)).reason)
for (invalid in listOf(-1, 99, 256)) {
pool.release(1, invalid, "bad", "bad")
assertNull(pool.getReleaseRecord(1, invalid))
}
}
}
private fun message(sid: Int = CfwTransport.SID, input: ByteArray = byteArrayOf(1, 2, 3)) =
OutboundMessage("test", "test", sid, 0, 100, input, 500, 0, false)
private fun ackPacket(count: Int, kind: Int = 1): ByteArray {
val packet = ByteArray(19 + (count - 1) * 7)
packet[0] = 0xaa.toByte()
packet[1] = 0x12
packet[3] = (packet.size - 8).toByte()
packet[4] = 1
packet[5] = 1
packet[6] = 0xf0.toByte()
packet[8] = kind.toByte()
packet[12] = 2
fun put16(offset: Int, value: Int) {
packet[offset] = value.toByte()
packet[offset + 1] = (value ushr 8).toByte()
}
for (i in 0 until count) {
val offset = if (i == 0) 9 else 17 + (i - 1) * 7
packet[offset] = (255 - i).toByte()
put16(offset + 1, 0x1234 + i)
put16(offset + (if (i == 0) 4 else 3), 0x4567 + i)
put16(offset + (if (i == 0) 6 else 5), 0xabcd + i)
}
sealAck(packet)
return packet
}
private fun sealAck(packet: ByteArray) {
val crc = CfwTransport.crc(packet.copyOfRange(8, packet.size - 2))
packet[packet.size - 2] = crc.toByte()
packet[packet.size - 1] = (crc ushr 8).toByte()
}
@@ -0,0 +1,136 @@
package com.faceclaw.app
import kotlin.test.*
class SharedGraphicsTest {
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
@Test
fun androidWireVectorsAndGrayQuantization() {
val vectors =
listOf(
BleProtocol.buildAuthenticationRequest(101) to "080410651a0408011004",
BleProtocol.PRELUDE_F5872_PAYLOAD to "0802109c01220a1a081206120408001000",
BleProtocol.buildCreateInputPage(102) to
"080010661a2308011a1c0800100018c00420a0024801520964617368626f617264580162012028904e",
BleProtocol.buildHeartbeat(103) to "080c106772020800",
BleProtocol.buildSettingsQuery(104) to "0802106822020801",
BleProtocol.buildShutdown(105, 1) to "080910695a020801",
BleProtocol.buildFaceclawWakeControl(5, 0) to "08011000aa0606464301050000",
)
vectors.forEach { (actual, expected) -> assertContentEquals(hex(expected), actual) }
val packed =
BmpUtil.pack4bppFromGray8(
byteArrayOf(0, 1, 7, 8, 15, 16, 23, 24, 127, -128, -9, -1),
3,
4,
)
assertContentEquals(hex("0000111012808ff0"), packed)
assertContentEquals(hex("40311011121810182f10"), BleImageOptimizer.rleEncode(packed))
assertContentEquals(
hex("aa21400c01018000080410651a04080110041024"),
BleProtocol.framePb(vectors.first().first, 128, 0, 64).single(),
)
}
@Test
fun splitStreamsExpiryAndCorruption() {
val payload =
BleProtocol.encodeVarintField(1, 3) +
BleProtocol.encodeVarintField(2, 110) +
BleProtocol.encodeBytesField(8, ByteArray(3900) { 55 })
val frames = BleProtocol.framePb(payload, 224, 32, 17, 185)
assertTrue(frames.all { it.size <= 185 })
val stream = frames.reduce { a, b -> a + b }
val receiver = MessageReceiver()
assertTrue(receiver.receive("L", stream.copyOf(7), 0).isEmpty())
val message = receiver.receive("L", stream.copyOfRange(7, stream.size), 1).single()
assertContentEquals(payload, message.payload)
assertEquals(3, message.command)
assertEquals(110, message.magic)
stream[stream.lastIndex] = (stream.last().toInt() xor 1).toByte()
assertTrue(receiver.receive("L", stream, 2).isEmpty())
receiver.receive("L", frames.first(), 10)
assertTrue(receiver.receive("R", frames.drop(1).reduce { a, b -> a + b }, 11).isEmpty())
assertTrue(receiver.receive("L", frames.drop(1).reduce { a, b -> a + b }, 5011).isEmpty())
assertFailsWith<IllegalArgumentException> { BleProtocol.framePb(payload, 1, 0, 1, 10) }
assertFailsWith<IllegalArgumentException> { BleProtocol.framePb(ByteArray(60000), 1, 0, 1) }
val invalid = BleProtocol.framePb(byteArrayOf(0x1a, 0x7f), 224, 0, 2).single()
assertTrue(receiver.receive("L", invalid, 6000).isEmpty())
}
@Test
fun eventDecodeAcceptsValidatedPayloadWithoutStrippingAgain() {
val event = BleProtocol.encodeVarintField(1, 12) + BleProtocol.encodeVarintField(2, 2)
val payload = BleProtocol.encodeBytesField(13, BleProtocol.encodeBytesField(3, event))
val received =
MessageReceiver()
.receive("L", BleProtocol.framePb(payload, 224, 1, 1).single(), 0)
.single()
val decoded = assertNotNull(G2Event.decodePayload(received.sid, received.payload))
assertEquals("sys-event", decoded.kind)
assertEquals(12, decoded.eventType)
assertEquals(2, decoded.eventSource)
}
@Test
fun retainedCompositionClippingDimmingAndBlanking() {
val c = SurfaceCompositor()
c.configureScreen(3, 2)
c.configureSurface("app", 0, 0, 3, 2, 0, 0)
c.submitSurface("app", ArrayByteReader(ByteArray(6) { 200.toByte() }), 0, 0, 3, 2, "1")
c.configureSurface("shell", 0, 0, 3, 2, 1, 1)
c.submitSurface("shell", ArrayByteReader(byteArrayOf(0, 1, -1, 0, 0, 0)), 0, 0, 3, 2, "2")
c.setUnderlayDim(1, 128)
assertContentEquals(byteArrayOf(100, 1, -1, 100, 100, 100), c.composite().gray)
c.setSurfaceVisible("shell", false)
assertContentEquals(ByteArray(6) { 100 }, c.composite().gray)
c.configureSurface("opaque", 1, 0, 1, 2, 2, 0)
c.submitSurface("opaque", ArrayByteReader(byteArrayOf(0, 0)), 0, 0, 1, 2, "3")
assertContentEquals(byteArrayOf(100, 0, 100, 100, 0, 100), c.composite().gray)
c.setBlanked(true)
assertContentEquals(ByteArray(6), c.composite().gray)
c.setBlanked(false)
c.removeSurface("opaque")
c.configureSurface("app", -1, 0, 3, 2, 0, 0)
c.setUnderlayDim(0, 256)
assertContentEquals(byteArrayOf(-56, -56, 0, -56, -56, 0), c.composite().gray)
}
@Test
fun pngChunksAndPixels() {
val png = SharedScreenshots.encode4BitGrayPng(byteArrayOf(0, 16, -1, 32, 48, 64), 3, 2)
assertContentEquals(hex("89504e470d0a1a0a"), png.copyOf(8))
fun intAt(offset: Int): Int =
(0..3).fold(0) { n, i -> (n shl 8) or (png[offset + i].toInt() and 255) }
var offset = 8
val types = mutableListOf<String>()
var compressed = ByteArray(0)
while (offset < png.size) {
val size = intAt(offset)
val type = png.copyOfRange(offset + 4, offset + 8).decodeToString()
types.add(type)
if (type == "IHDR") {
assertEquals(3, intAt(offset + 8))
assertEquals(2, intAt(offset + 12))
assertEquals(4, png[offset + 16].toInt())
assertEquals(0, png[offset + 17].toInt())
}
if (type == "IDAT") compressed += png.copyOfRange(offset + 8, offset + 8 + size)
offset += size + 12
}
assertEquals(listOf("IHDR", "IDAT", "IEND"), types)
assertContentEquals(hex("0001f0002340"), inflateData(compressed, 6))
}
@Test
fun wavHeaderAndHex() {
assertEquals("007f80ff", BinaryEncoding.bytesToHex(byteArrayOf(0, 127, -128, -1)))
assertContentEquals(
hex(
"524946462804000057415645666d74201000000001000100803e0000007d0000020010006461746104040000"
),
BinaryEncoding.wavHeader(1028, 16000, 1),
)
}
}
@@ -0,0 +1,38 @@
package com.faceclaw.app
import kotlin.test.*
class IosNativeApiTest {
@Test
fun binaryFacadeRoundTripsAndSlices() {
val bytes = byteArrayOf(0, -1, 2, -128)
assertContentEquals(bytes, bytes.data().byteArray())
assertTrue(byteArrayOf().data().byteArray().isEmpty())
val reader = IosByteReader(bytes.data())
assertEquals(0, reader.get().toInt())
val target = ByteArray(5)
reader.get(target, 1, 3)
assertContentEquals(byteArrayOf(0, -1, 2, -128, 0), target)
assertEquals(0, reader.remaining())
val protocol = IosProtocol()
val auth = protocol.authentication(101)
val frames = protocol.frame(auth, 128, 0, 64, 185)
val result = IosMessageReceiver().receive("L", frames.single(), 0).single()
assertEquals(101, result.magic)
assertContentEquals(auth.byteArray(), result.payload.byteArray())
}
@Test
fun nativeCompositorClipsPartialUpdatesBeforeCoalescing() {
val compositor = IosSurfaceCompositor(3, 2)
compositor.configure("app", 0, 0, 3, 2, 0, false)
compositor.submit("app", byteArrayOf(10, 20, 30, 40, 50, 60).data(), -1, 0, 3, 2)
assertContentEquals(byteArrayOf(20, 30, 0, 50, 60, 0), compositor.composite().byteArray())
compositor.submit("app", byteArrayOf(99).data(), 2, 1, 1, 1)
assertContentEquals(byteArrayOf(20, 30, 0, 50, 60, 99), compositor.composite().byteArray())
compositor.blank(true)
assertContentEquals(ByteArray(6), compositor.composite().byteArray())
compositor.blank(false)
assertEquals(99, compositor.composite().byteArray().last().toInt())
}
}
@@ -0,0 +1,81 @@
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package com.faceclaw.app
import kotlin.test.*
import kotlinx.cinterop.*
import platform.CoreBluetooth.*
import platform.posix.memset
import platform.zlib.*
internal actual fun testPlatform(): ProtocolPlatform = IosProtocolPlatform
internal actual fun inflateRecords(records: List<ByteArray>): List<ByteArray> = memScoped {
val stream = alloc<z_stream>()
memset(stream.ptr, 0, sizeOf<z_stream>().convert())
check(inflateInit(stream.ptr) == Z_OK)
try {
records.map { record ->
if (record[0].toInt() and CfwTransport.RESET_CONTEXT != 0)
check(inflateReset(stream.ptr) == Z_OK)
val body = record.copyOfRange(5, record.size)
if (record[0].toInt() and CfwTransport.COMPRESSED == 0) body
else {
val output = mutableListOf<Byte>()
val buffer = ByteArray(4096)
body.usePinned { input ->
stream.next_in = input.addressOf(0).reinterpret()
stream.avail_in = body.size.toUInt()
buffer.usePinned { destination ->
do {
stream.next_out = destination.addressOf(0).reinterpret()
stream.avail_out = buffer.size.toUInt()
val status = inflate(stream.ptr, Z_SYNC_FLUSH)
check(status == Z_OK || status == Z_BUF_ERROR)
output.addAll(buffer.take(buffer.size - stream.avail_out.toInt()))
} while (stream.avail_in > 0u || stream.avail_out == 0u)
}
}
stream.next_in = null
stream.next_out = null
output.toByteArray()
}
}
} finally {
inflateEnd(stream.ptr)
}
}
class IosProtocolTest {
@Test
fun platformClockAndWriteModes() {
val before = IosProtocolPlatform.elapsedRealtimeMs()
assertTrue(before > 0)
assertTrue(IosProtocolPlatform.elapsedRealtimeMs() >= before)
assertEquals(
CBCharacteristicWriteWithResponse,
IosProtocolPlatform.writeType(GattWriteMode.WITH_RESPONSE),
)
assertEquals(
CBCharacteristicWriteWithoutResponse,
IosProtocolPlatform.writeType(ConnectionOptions.WRITE_MODE),
)
}
}
internal actual fun digest(bytes: ByteArray): String {
val result = ByteArray(32)
result.usePinned { output ->
if (bytes.isEmpty())
platform.CoreCrypto.CC_SHA256(null, 0u, output.addressOf(0).reinterpret())
else
bytes.usePinned { input ->
platform.CoreCrypto.CC_SHA256(
input.addressOf(0),
bytes.size.toUInt(),
output.addressOf(0).reinterpret(),
)
}
}
return BinaryEncoding.bytesToHex(result)
}