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
+8
-10
@@ -15,15 +15,13 @@ That compiles the pure modules with the project's TypeScript into
|
||||
dependencies are needed — the tests are plain `.test.cjs` files that use
|
||||
`node:test` and `node:assert`.
|
||||
|
||||
Compass diagnostics have focused UI and wire-format checks:
|
||||
The shared Kotlin suite runs separately from the Node tests:
|
||||
|
||||
node --test tests/compass-debug.test.cjs tests/compass-protocol.test.cjs
|
||||
npm run test:kotlin
|
||||
npm run test:kotlin:ios
|
||||
|
||||
The protocol check also compiles the production Java parser, so it needs a
|
||||
JDK (`JAVA_HOME`, or `javac` and `java` on `PATH`). Its golden packet is shared
|
||||
with the firmware encoder test in `g2flash/tests/compass_diagnostics_test.c`.
|
||||
|
||||
R1 battery field-106 decoding (valid zero, charging, unavailable/disconnected,
|
||||
legacy firmware, malformed messages) uses the same C/Java golden packet:
|
||||
|
||||
node --test tests/ring-battery-protocol.test.cjs
|
||||
It includes the migrated compass, R1 battery, gesture and texture Java fixtures,
|
||||
which now call the Kotlin implementation from Android host tests. Common tests
|
||||
also run as native iOS simulator binaries. See [the Kotlin README](../native/kotlin/README.md)
|
||||
for SDK requirements, source layout and coverage. The compass and battery
|
||||
fixtures retain the golden packets shared with firmware tests.
|
||||
@@ -9,28 +9,22 @@ const { crc16, concat, MessageReceiver } = require('../.test-build/app/g2/ble-pr
|
||||
const hex = value => Buffer.from(value).toString('hex');
|
||||
|
||||
test('iOS transport matches Android packets including persistent compression, reset, raw fallback and ATT limits', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-cfw-java-'));
|
||||
const java = name => process.env.JAVA_HOME ? path.join(process.env.JAVA_HOME, 'bin', name) : name;
|
||||
const random = new Uint8Array(65535); let seed = 42;
|
||||
for (let i = 0; i < random.length; i++) { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; random[i] = seed & 255; }
|
||||
const cases = [[100, 3, 185, new Uint8Array([6, 0, 0, 255, 255])],
|
||||
[101, 3, 185, new Uint8Array([6, 0, 0, 255, 255])], [102, 1, 20, new Uint8Array(500).fill(42)],
|
||||
'reset', [255, 3, 514, random], [103, 3, 240, new Uint8Array([11])]];
|
||||
try {
|
||||
execFileSync(java('javac'), ['-d', dir,
|
||||
path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/CfwTransport.java'),
|
||||
path.join(__dirname, 'fixtures/CfwTransportVectors.java')]);
|
||||
const expected = execFileSync(java('java'), ['-cp', dir, 'com.faceclaw.app.CfwTransportVectors',
|
||||
...cases.map(c => c === 'reset' ? c : `${c[0]}:${c[1]}:${c[2]}:${hex(c[3])}`)],
|
||||
{ maxBuffer: 1024 * 1024 }).toString().trim().split('\n');
|
||||
// Captured from the original Java encoder before migration; production now uses Kotlin.
|
||||
const expected = require('./fixtures/cfw-java-golden.json');
|
||||
const hash = value => require('node:crypto').createHash('sha256').update(value).digest('hex');
|
||||
const transport = new CfwTransport(); let index = 0;
|
||||
for (const c of cases) {
|
||||
if (c === 'reset') { transport.reset(); continue; }
|
||||
const [id, lenses, maxWrite, payload] = c, packets = transport.encode(payload, id, lenses, maxWrite);
|
||||
assert.ok(packets.every(p => p.length <= maxWrite));
|
||||
assert.equal(packets.map(hex).join(' '), expected[index++]);
|
||||
assert.equal(hash(packets.map(hex).join(' ')), expected[index++]);
|
||||
}
|
||||
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
|
||||
|
||||
});
|
||||
|
||||
function ackPacket(records, lens = 1, nack = false) {
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
|
||||
test('compass diagnostics decode with legacy and malformed-extension fallback', () => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-compass-java-'));
|
||||
const javaBin = (name) => process.env.JAVA_HOME ? path.join(process.env.JAVA_HOME, 'bin', name) : name;
|
||||
try {
|
||||
execFileSync(javaBin('javac'), ['-d', directory,
|
||||
path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java'),
|
||||
path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app/util/CollectionUtils.java'),
|
||||
path.join(__dirname, 'fixtures/CompassProtocolTest.java')], { stdio: 'pipe' });
|
||||
execFileSync(javaBin('java'), ['-ea', '-cp', directory, 'com.faceclaw.app.CompassProtocolTest'], { stdio: 'pipe' });
|
||||
} finally {
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -151,7 +151,7 @@ test('the background registers once and uses a nine-byte image reference on late
|
||||
const registered = [];
|
||||
const { prepareFrameDraws } = load('app/graphics/glyph-wire.ts', {}, '', {
|
||||
global: { isAndroid: true },
|
||||
com: { faceclaw: { app: { ImageAtlas: { ensure: (...args) => {
|
||||
com: { faceclaw: { app: { AndroidByteReader: class { constructor(buffer) { this.buffer = buffer; } }, ImageAtlas: { ensure: (...args) => {
|
||||
registered.push(args);
|
||||
return 1;
|
||||
} } } } },
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
|
||||
test('CFW idle-gesture events decode to sys-event types and sources; wake and junk do not', () => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-gesture-java-'));
|
||||
const javaBin = (name) => process.env.JAVA_HOME ? path.join(process.env.JAVA_HOME, 'bin', name) : name;
|
||||
try {
|
||||
execFileSync(javaBin('javac'), ['-d', directory,
|
||||
path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java'),
|
||||
path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app/util/CollectionUtils.java'),
|
||||
path.join(__dirname, 'fixtures/FaceclawGestureEventTest.java')], { stdio: 'pipe' });
|
||||
execFileSync(javaBin('java'), ['-ea', '-cp', directory, 'com.faceclaw.app.FaceclawGestureEventTest'], { stdio: 'pipe' });
|
||||
} finally {
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
/** Production Android encoder oracle for the iOS transport parity test. */
|
||||
public final class CfwTransportVectors {
|
||||
public static void main(String[] args) {
|
||||
CfwTransport transport = new CfwTransport();
|
||||
for (String line : args) {
|
||||
String[] fields = line.split(":", -1);
|
||||
if (fields[0].equals("reset")) { transport.reset(); continue; }
|
||||
int id = Integer.parseInt(fields[0]), lenses = Integer.parseInt(fields[1]);
|
||||
int maxWrite = Integer.parseInt(fields[2]);
|
||||
byte[] payload = java.util.HexFormat.of().parseHex(fields[3]);
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (byte[] packet : transport.encode(payload, id, lenses, maxWrite + 3))
|
||||
result.append(java.util.HexFormat.of().formatHex(packet)).append(" ");
|
||||
System.out.println(result.toString().trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
[
|
||||
"d73e76bae77dd09f6af2f9483b8d24b7ebb79dca266ace5f062dea936c181219",
|
||||
"60afd64152c40d6a0b4a70437d3636a36b41f690fe7fa43a44c1fff1accb0845",
|
||||
"8f4ce275c048001ef30da8b9d93e63c15d3fb49bc643d3f5fd6908b0adaf2292",
|
||||
"50a45b6816d4f0669d09958ef2dd32ab3d162b6959b6252a940d3ec1180bd80e",
|
||||
"5e53d5665b33cd46cb868f8063cda22ee6cce4584e5e28123803e41642f5563f"
|
||||
]
|
||||
@@ -0,0 +1,43 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { checkAndroidRuntime } = require('../scripts/kotlin-build.cjs');
|
||||
|
||||
test('Android preparation rejects a stale metadata generator but allows fresh and matching platforms', () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-kotlin-build-'));
|
||||
try {
|
||||
const installed = path.join(root, 'node_modules/@nativescript/android/framework/build-tools/android-metadata-generator.jar');
|
||||
const generated = path.join(root, 'platforms/android/build-tools/android-metadata-generator.jar');
|
||||
fs.mkdirSync(path.dirname(installed), { recursive: true });
|
||||
fs.writeFileSync(installed, 'current metadata generator');
|
||||
assert.doesNotThrow(() => checkAndroidRuntime(root));
|
||||
fs.mkdirSync(path.dirname(generated), { recursive: true });
|
||||
fs.writeFileSync(generated, 'old metadata generator');
|
||||
assert.throws(() => checkAndroidRuntime(root), /ns platform clean android/);
|
||||
fs.copyFileSync(installed, generated);
|
||||
assert.doesNotThrow(() => checkAndroidRuntime(root));
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('every remaining Java source has an explicit Android boundary and every migration has one replacement', () => {
|
||||
const root = path.resolve(__dirname, '..');
|
||||
const java = path.join(root, 'App_Resources/Android/src/main/java');
|
||||
const list = directory => fs.readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
|
||||
const file = path.join(directory, entry.name);
|
||||
return entry.isDirectory() ? list(file) : file.endsWith('.java') ? [path.relative(java, file)] : [];
|
||||
});
|
||||
const boundaries = require('../native/kotlin/android-java-boundaries.json');
|
||||
const retained = boundaries.flatMap(group => { assert.ok(group.reason.length > 20); return group.files; });
|
||||
assert.deepEqual(list(java).sort(), retained.sort());
|
||||
assert.equal(new Set(retained).size, retained.length);
|
||||
const migrated = require('../native/kotlin/migrated-java-sources.json');
|
||||
assert.equal(new Set(migrated.map(entry => entry.java)).size, migrated.length);
|
||||
for (const entry of migrated) {
|
||||
assert.equal(fs.existsSync(path.join(java, entry.java)), false, entry.java);
|
||||
assert.ok(fs.existsSync(path.join(root, 'native/kotlin', entry.kotlin)), entry.kotlin);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||
|
||||
plugins {
|
||||
kotlin("multiplatform") version "2.4.20"
|
||||
id("com.android.kotlin.multiplatform.library") version "8.13.2"
|
||||
}
|
||||
|
||||
// Compile the production sources without building NativeScript or touching BLE.
|
||||
kotlin {
|
||||
android {
|
||||
namespace = "com.faceclaw.protocoltests"
|
||||
compileSdk = 35
|
||||
minSdk = 24
|
||||
withJava()
|
||||
compilerOptions { jvmTarget.set(JvmTarget.JVM_17) }
|
||||
withHostTestBuilder {}.configure {}
|
||||
}
|
||||
iosArm64()
|
||||
iosSimulatorArm64()
|
||||
sourceSets {
|
||||
commonMain { kotlin.srcDir("../../native/kotlin/shared/src/commonMain/kotlin") }
|
||||
androidMain { kotlin.srcDir("../../native/kotlin/shared/src/androidMain/kotlin") }
|
||||
iosMain { kotlin.srcDir("../../native/kotlin/shared/src/iosMain/kotlin") }
|
||||
commonTest.dependencies { implementation(kotlin("test")) }
|
||||
}
|
||||
}
|
||||
|
||||
// The font is already shipped in the app; avoid copying megabytes into test fixtures.
|
||||
val generateFixturePaths = tasks.register("generateFixturePaths") {
|
||||
val output = layout.buildDirectory.file("generated/fixtures/com/faceclaw/app/FixturePaths.kt")
|
||||
outputs.dir(layout.buildDirectory.dir("generated/fixtures"))
|
||||
doLast {
|
||||
val font = file("../../app/fonts/source-han-sans/SourceHanSansSC-Light-20.lvgl.bin").canonicalPath
|
||||
output.get().asFile.apply {
|
||||
parentFile.mkdirs()
|
||||
writeText("package com.faceclaw.app\ninternal const val TEST_FONT_PATH = \"${font.replace("\\", "\\\\").replace("\"", "\\\"")}\"\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
kotlin.sourceSets.commonTest { kotlin.srcDir(generateFixturePaths) }
|
||||
@@ -0,0 +1,3 @@
|
||||
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
|
||||
dependencyResolutionManagement { repositories { google(); mavenCentral() } }
|
||||
rootProject.name = "FaceclawProtocolTests"
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -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)
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
|
||||
test('ring battery decodes valid, unavailable, legacy, and malformed reports', () => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-ring-java-'));
|
||||
const javaBin = (name) => process.env.JAVA_HOME ? path.join(process.env.JAVA_HOME, 'bin', name) : name;
|
||||
try {
|
||||
execFileSync(javaBin('javac'), ['-d', directory,
|
||||
path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java'),
|
||||
path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app/util/CollectionUtils.java'),
|
||||
path.join(__dirname, 'fixtures/RingBatteryProtocolTest.java')], { stdio: 'pipe' });
|
||||
execFileSync(javaBin('java'), ['-ea', '-cp', directory, 'com.faceclaw.app.RingBatteryProtocolTest'], { stdio: 'pipe' });
|
||||
} finally {
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -1,23 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
|
||||
test('256 KiB cache uploads and planner draws preserve wide image and glyph offsets', () => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-texture-java-'));
|
||||
const javaBin = (name) => process.env.JAVA_HOME ? path.join(process.env.JAVA_HOME, 'bin', name) : name;
|
||||
const root = path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app');
|
||||
try {
|
||||
const clock = path.join(directory, 'SystemClock.java');
|
||||
const log = path.join(directory, 'Log.java');
|
||||
fs.writeFileSync(clock, 'package android.os; public class SystemClock { public static long elapsedRealtime() { return 0; } }');
|
||||
fs.writeFileSync(log, 'package android.util; public class Log { public static int i(String tag, String msg) { return 0; } }');
|
||||
const sources = ['GlyphAtlas.java', 'ImageAtlas.java', 'FwGlyphAtlas.java', 'SurfaceCompositor.java',
|
||||
'util/BmpUtil.java', 'util/CollectionUtils.java', 'g2protocol/BleProtocol.java',
|
||||
'g2protocol/BleImageOptimizer.java', 'g2protocol/TextureCacheState.java', 'g2protocol/TexturePlanner.java'];
|
||||
execFileSync(javaBin('javac'), ['-d', directory, ...sources.map(file => path.join(root, file)),
|
||||
clock, log, path.join(__dirname, 'fixtures/TextureCacheProtocolTest.java')], { stdio: 'pipe' });
|
||||
execFileSync(javaBin('java'), ['-ea', '-cp', directory, 'com.faceclaw.app.TextureCacheProtocolTest'], { stdio: 'pipe' });
|
||||
} finally { fs.rmSync(directory, { recursive: true, force: true }); }
|
||||
});
|
||||
Reference in new issue
Block a user