()
+ val detector = GestureDetector(clock::schedule, clock::cancel, { 650L }, {
+ history += it to clock.now
+ actions += config.action(it)
+ }).apply { wantsLong = config.action(Gesture.LONG) != SnapAction.NoAction }
+ val edges = OplusKeyEdges(
+ { seenEdges++; detector.down() },
+ { seenEdges++; detector.up() },
+ )
+ private var nextHandle = 0L
+
+ fun begin() {
+ detector.reset()
+ tracking.begin(config.logKeyCode, edges)
+ edges.reset()
+ session = TeachingSession(TeachingAccess(false, true, false))
+ delivery.advance(TeachingHandle(++nextHandle))
+ }
+
+ fun handsOff() {
+ delivery.discardPending()
+ edges.reset()
+ tracking.reset()
+ }
+
+ fun queue(time: Long, sample: KeySample.Log): () -> Unit {
+ clock.advanceTo(time)
+ val receipt = delivery.stamp
+ return {
+ tracking.deliver(delivery, receipt, timestamp(time), sample, config.keyBinding(), edges) {
+ deliveredSamples++
+ val current = session
+ if (current != null) current.observe(sample, time)
+ else if (KeyMatching.matches(config.keyBinding(), sample) &&
+ isKnownOplusKeyLine(sample.uid, sample.tag, sample.message)) edges.accept(timestamp(time))
+ }
+ }
+ }
+
+ fun line(time: Long, tid: String, tag: String, message: String) {
+ queue(time, context.sample(1, delivery.stamp.epoch, "1000", tid, tag, message))()
+ }
+
+ fun raw(time: Long, code: String, down: Boolean) = line(time, "raw", RAW_TAG, rawMessage(code, down))
+ fun edge(time: Long) = line(time, "edge", TAG, MESSAGE)
+
+ fun candidateHeld() {
+ begin()
+ handsOff()
+ for (time in POSITIVES) {
+ raw(time, SNAP, true)
+ edge(time + 1)
+ edge(time + 2)
+ if (time != POSITIVES.last()) {
+ raw(time + 100, SNAP, false)
+ edge(time + 101)
+ edge(time + 102)
+ }
+ }
+ session!!.capture(BASELINE, TAPS, HOLD)
+ delivery.advance(delivery.stamp.handle)
+ val candidate = (session!!.state as TeachingState.Candidate).result as LearnResult.LogLineFound
+ assertEquals(SNAP, candidate.logKeyCode)
+ assertNull(candidate.inputKey)
+ }
+
+ fun beginCheck(time: Long) {
+ delivery.advance(delivery.stamp.handle)
+ session!!.beginCheck(time)
+ }
+
+ fun readyHeld() {
+ candidateHeld()
+ beginCheck(23000)
+ raw(24000, VOLUME, true)
+ line(24001, "raw", TAG, MESSAGE)
+ raw(24100, VOLUME, false)
+ line(24101, "raw", TAG, MESSAGE)
+ clock.advanceTo(CHECK_END)
+ session!!.finishCheck(CHECK_END)
+ assertTrue(session!!.state is TeachingState.Ready)
+ assertTrue(history.isEmpty())
+ }
+
+ fun exit() {
+ detector.reset()
+ session = null
+ delivery.advance(null)
+ tracking.restore(config.logKeyCode, edges)
+ tracking.reset()
+ }
+
+ fun cancel() {
+ session!!.cancel()
+ exit()
+ }
+ }
+
+ @Test
+ fun teachingUpQueuedBehindConfirmedSaveOrCancelLeavesTheNextPressAndHoldTimingsIntact() {
+ for (save in listOf(false, true)) for (enableLong in listOf(false, true)) {
+ val h = Harness(enableLong)
+ h.readyHeld()
+ val old = h.config
+ val closed = h.session!!
+ lateinit var queuedUp: () -> Unit
+ if (save) {
+ assertTrue(closed.save { patch ->
+ queuedUp = h.queue(29000, snap())
+ h.config = patch.applyTo(h.config)
+ true
+ })
+ h.exit()
+ assertEquals(SNAP, h.config.logKeyCode)
+ } else {
+ queuedUp = h.queue(29000, snap())
+ h.cancel()
+ assertEquals(old, h.config)
+ }
+ val delivered = h.deliveredSamples
+ h.clock.advanceTo(30000)
+ queuedUp()
+ queuedUp()
+ assertEquals(delivered, h.deliveredSamples)
+ assertEquals(TeachingState.Closed, closed.state)
+ assertEquals(0, h.seenEdges)
+ assertTrue(h.history.isEmpty())
+ assertTrue(h.actions.isEmpty())
+
+ h.edge(31000)
+ assertEquals(if (enableLong) emptyList() else listOf(Gesture.SINGLE to 31000L), h.history)
+ h.edge(31100)
+ val firstAt = if (enableLong) 31100L else 31000L
+ h.clock.advanceTo(32000)
+ assertEquals(listOf(Gesture.SINGLE to firstAt), h.history)
+ assertEquals(listOf(SnapAction.Device(DeviceAction.FLASHLIGHT)), h.actions)
+ if (enableLong) {
+ h.edge(33000)
+ h.clock.advanceTo(33649)
+ assertEquals(1, h.history.size)
+ h.clock.advanceTo(33650)
+ assertEquals(listOf(Gesture.SINGLE to firstAt, Gesture.LONG to 33650L), h.history)
+ h.edge(34000)
+ h.clock.advanceTo(35000)
+ assertEquals(2, h.history.size)
+ }
+ }
+ }
+
+ @Test
+ fun staleRuntimeObservationUsesTheWholeBindingAndCannotSeedSnapFromIdentifiedVolume() {
+ val rejected = listOf(
+ snap().copy(threadKey = VOLUME),
+ snap().copy(uid = "2000"),
+ snap().copy(tag = "Other_OplusKeyEventUtil"),
+ snap().copy(message = "another restrict listen mode message"),
+ )
+ for (sample in rejected) {
+ val h = Harness()
+ h.begin()
+ h.handsOff()
+ val queued = h.queue(100, sample)
+ h.cancel()
+ queued()
+ assertEquals(0, h.seenEdges)
+ assertTrue(h.history.isEmpty())
+ h.edge(1000)
+ assertEquals(listOf(Gesture.SINGLE to 1000L), h.history)
+ h.edge(1100)
+ h.clock.advanceTo(2000)
+ assertEquals(1, h.history.size)
+ }
+ }
+
+ @Test
+ fun staleReleaseDuringAnotherAttemptUpdatesOnlyItsPhysicalPhase() {
+ val h = Harness()
+ h.readyHeld()
+ val release = h.queue(29000, snap())
+ h.cancel()
+ h.begin()
+ val retry = h.session!!
+ val delivered = h.deliveredSamples
+ release()
+ assertEquals(delivered, h.deliveredSamples)
+ assertEquals(TeachingState.Capturing, retry.state)
+ retry.capture(BASELINE, TAPS, HOLD)
+ assertEquals(TeachingState.Failed(TeachingFailure.NOT_FOUND), retry.state)
+ assertFalse(retry.save { error("Retry must not inherit proof") })
+ h.cancel()
+ h.edge(31000)
+ assertEquals(listOf(Gesture.SINGLE to 31000L), h.history)
+ h.edge(31100)
+ h.clock.advanceTo(32000)
+ assertEquals(1, h.history.size)
+ }
+
+ @Test
+ fun staleCaptureCannotTeachTheRetryAndStaleCheckSamplesCannotWitnessOrCollide() {
+ val h = Harness()
+ h.begin()
+ val queued = POSITIVES.map { h.queue(it, snap()) }
+ h.cancel()
+ h.begin()
+ val delivered = h.deliveredSamples
+ queued.forEach { it() }
+ h.session!!.capture(BASELINE, TAPS, HOLD)
+ assertEquals(TeachingState.Failed(TeachingFailure.NOT_FOUND), h.session!!.state)
+ assertEquals(delivered, h.deliveredSamples)
+
+ val checking = Harness()
+ checking.candidateHeld()
+ val volumeDown = checking.queue(24000, KeySample.Log("1000", RAW_TAG, rawMessage(VOLUME, true), VOLUME, "raw"))
+ val volumeUp = checking.queue(24000, KeySample.Log("1000", RAW_TAG, rawMessage(VOLUME, false), VOLUME, "raw"))
+ val collision = checking.queue(24000, snap())
+ checking.beginCheck(24000)
+ val samples = checking.deliveredSamples
+ volumeDown()
+ volumeUp()
+ collision()
+ assertEquals(samples, checking.deliveredSamples)
+ assertTrue(checking.session!!.state is TeachingState.Checking)
+ checking.session!!.finishCheck(24000 + TeachingSession.CHECK_MS + TeachingSession.SETTLE_MS)
+ assertEquals(TeachingState.Failed(TeachingFailure.NO_DIFFERENT_KEY), checking.session!!.state)
+ assertTrue(checking.history.isEmpty())
+ assertTrue(checking.actions.isEmpty())
+ checking.cancel()
+ checking.edge(31000)
+ checking.edge(31100)
+ checking.clock.advanceTo(32000)
+ assertEquals(listOf(Gesture.SINGLE to 31000L), checking.history)
+ }
+
+ @Test
+ fun preHandsOffDownOrUpCannotInvertTheAuthoritativeReleasedBaseline() {
+ for (up in listOf(false, true)) {
+ val h = Harness(enableLong = true)
+ h.begin()
+ if (up) h.edge(0)
+ val oldEdge = h.queue(100, snap())
+ h.handsOff()
+ val delivered = h.deliveredSamples
+ oldEdge()
+ assertEquals(delivered, h.deliveredSamples)
+ h.cancel()
+ h.edge(1000)
+ h.edge(1100)
+ h.clock.advanceTo(2000)
+ assertEquals(listOf(Gesture.SINGLE to 1100L), h.history)
+ }
+ }
+
+ companion object {
+ private const val TAG = "KEYLOG_OplusKeyEventUtil"
+ private const val MESSAGE = "should not notify undefined keys in restrict listen mode"
+ private const val RAW_TAG = "KEYLOG_PhoneWindowManagerExtImpl"
+ private const val SNAP = "KEYCODE_ACTION_BUTTON_CLICK"
+ private const val VOLUME = "KEYCODE_VOLUME_DOWN"
+ private val BASELINE = 0L..5000L
+ private val TAPS = listOf(6000L..9000L, 10000L..13000L, 14000L..17000L)
+ private val HOLD = 18000L..21500L
+ private val POSITIVES = listOf(7000L, 11000L, 15000L, 18200L)
+ private const val CHECK_END = 23000 + TeachingSession.CHECK_MS + TeachingSession.SETTLE_MS
+
+ private fun snap() = KeySample.Log("1000", TAG, MESSAGE, null)
+ private fun rawMessage(code: String, down: Boolean) =
+ "overrideInterceptKeyBeforeQueueing:KeyEvent { action=${if (down) "ACTION_DOWN" else "ACTION_UP"}, keyCode=$code, scanCode=0 }"
+ private fun timestamp(time: Long) = "10-18 11:00:%02d.%03d".format(time / 1000, time % 1000)
+ }
+}
diff --git a/app/src/test/java/com/heykay/snapkeymap/TeachingSessionTest.kt b/app/src/test/java/com/heykay/snapkeymap/TeachingSessionTest.kt
new file mode 100644
index 0000000..ce861a3
--- /dev/null
+++ b/app/src/test/java/com/heykay/snapkeymap/TeachingSessionTest.kt
@@ -0,0 +1,474 @@
+package com.heykay.snapkeymap
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class TeachingSessionTest {
+ private val fullAccess = TeachingAccess(accessibility = true, fullLogs = true, inputLive = true)
+ private val baseline = 0L..5000L
+ private val taps = listOf(6000L..9000L, 10000L..13000L, 14000L..17000L)
+ private val hold = 18000L..21500L
+ private val positiveTimes = listOf(7000L, 11000L, 15000L, 18200L)
+ private val checkStart = 23000L
+ private val checkEnd = checkStart + TeachingSession.CHECK_MS + TeachingSession.SETTLE_MS
+ private val stylusTag = "StylusModule"
+ private val reportedSignature = "StylusModule.onUpdateToolType():# Update tool type = #"
+ private val oplusTag = "KEYLOG_OplusKeyEventUtil"
+ private val oplusMessage = "should not notify undefined keys in restrict listen mode"
+ private val snapCode = "KEYCODE_ACTION_BUTTON_CLICK"
+ private val inputCode = "BTN_TRIGGER_HAPPY32"
+
+ @Test
+ fun reportedF12PositiveF11NegativeStylusSignatureIsRejectedWithoutSaving() {
+ val saved = SavedConfig()
+ val old = saved.value
+ val session = logged()
+ val result = (session.state as TeachingState.Candidate).result as LearnResult.LogLineFound
+ assertEquals(KeySignature(stylusTag, reportedSignature, "424242"), result.signature)
+ assertFalse(saved.save(session))
+ session.beginCheck(checkStart)
+ differentAccessibility(session, code = 141)
+ session.observe(stylus("9876", "54"), 24500)
+ failed(session, TeachingFailure.COLLISION)
+ assertFalse(saved.save(session))
+ assertEquals(old, saved.value)
+ assertEquals(0, saved.writes)
+ }
+
+ @Test
+ fun livePreciseInputCannotHideABroadLogFallbackDuringValidation() {
+ val session = logged(withInput = true)
+ assertEquals(InputKey(inputCode), ((session.state as TeachingState.Candidate).result as LearnResult.LogLineFound).inputKey)
+ session.beginCheck(checkStart)
+ session.observe(input("KEY_F11", true), 24000)
+ session.observe(input("KEY_F11", false), 24100)
+ session.observe(stylus("9876", "54"), 24500)
+ failed(session, TeachingFailure.COLLISION)
+ }
+
+ @Test
+ fun colorOsVolumeRawDownUpAndFilteredSameThreadOplusEdgesPass() {
+ for (volume in listOf("KEYCODE_VOLUME_UP", "KEYCODE_VOLUME_DOWN", "24", "25", "164")) {
+ val session = logged(oplus = true)
+ session.beginCheck(checkStart)
+ val context = LoggedKeyContext()
+ val down = context.sample(1, 1, "system", "42", "KEYLOG_PhoneWindowManagerExtImpl", rawKey(volume, true))
+ session.observe(down, 24000)
+ session.observe(context.sample(1, 1, "1000", "42", oplusTag, oplusMessage), 24001)
+ session.observe(context.sample(1, 1, "1000", "42", "KEYLOG_PhoneWindowManagerExtImpl", rawKey(volume, false)), 24100)
+ session.observe(context.sample(1, 1, "1000", "42", oplusTag, oplusMessage), 24101)
+ session.finishCheck(checkEnd)
+ assertTrue("Expected a complete filtered $volume check", session.state is TeachingState.Ready)
+ assertTrue(session.save { true })
+ }
+ }
+
+ @Test
+ fun equalOrMissingColorOsContextCollidesAndAnotherThreadCannotProvideAFilter() {
+ for (contextCode in listOf(snapCode, null)) {
+ val session = logged(oplus = true)
+ session.beginCheck(checkStart)
+ differentAccessibility(session)
+ session.observe(KeySample.Log("1000", oplusTag, oplusMessage, contextCode), 24500)
+ failed(session, TeachingFailure.COLLISION)
+ }
+ val session = logged(oplus = true)
+ session.beginCheck(checkStart)
+ differentAccessibility(session)
+ val context = LoggedKeyContext()
+ context.sample(1, 1, "1000", "other", "KEYLOG_PhoneWindowManagerExtImpl", rawKey("KEYCODE_VOLUME_DOWN", true))
+ session.observe(context.sample(1, 1, "1000", "snap", oplusTag, oplusMessage), 24500)
+ failed(session, TeachingFailure.COLLISION)
+ }
+
+ @Test
+ fun directKnownCodeStillCollidesWithADifferentScanAndUpAloneCollides() {
+ for (down in listOf(true, false)) {
+ val session = direct()
+ session.beginCheck(checkStart)
+ differentAccessibility(session)
+ session.observe(KeySample.Accessibility(142, 999, down), 24500)
+ failed(session, TeachingFailure.COLLISION)
+ }
+ }
+
+ @Test
+ fun unknownCodeRequiresTheSameScanToCollideAndDifferentScanCanWitness() {
+ val valid = direct(code = 0, scan = 88)
+ valid.beginCheck(checkStart)
+ differentAccessibility(valid, code = 0, scan = 99)
+ valid.finishCheck(checkEnd)
+ assertTrue(valid.state is TeachingState.Ready)
+ val collision = direct(code = 0, scan = 88)
+ collision.beginCheck(checkStart)
+ collision.observe(KeySample.Accessibility(0, 88, false), 24000)
+ failed(collision, TeachingFailure.COLLISION)
+ }
+
+ @Test
+ fun exactInputReleaseCollidesAndDifferentExactInputCanWitnessALoggedCheck() {
+ val collision = logged(withInput = true)
+ collision.beginCheck(checkStart)
+ collision.observe(input(inputCode, false), 24000)
+ failed(collision, TeachingFailure.COLLISION)
+ val valid = logged(withInput = true)
+ valid.beginCheck(checkStart)
+ valid.observe(input("KEY_VOLUMEDOWN", true), 24000)
+ valid.observe(input("KEY_VOLUMEDOWN", false), 24100)
+ valid.finishCheck(checkEnd)
+ assertTrue(valid.state is TeachingState.Ready)
+ }
+
+ @Test
+ fun volumeIsExcludedFromCaptureButReachesValidationAsACompleteWitness() {
+ val session = TeachingSession(fullAccess)
+ positiveTimes.forEach { session.observe(KeySample.Accessibility(25, 114, true), it) }
+ session.capture(baseline, taps, hold)
+ failed(session, TeachingFailure.NOT_FOUND)
+ val candidate = direct()
+ candidate.beginCheck(checkStart)
+ differentAccessibility(candidate, code = 25)
+ candidate.finishCheck(checkEnd)
+ assertTrue(candidate.state is TeachingState.Ready)
+ }
+
+ @Test
+ fun silenceAmbientLogsReleaseOnlyAndUnreleasedPressCannotPass() {
+ val cases: List<(TeachingSession) -> Unit> = listOf(
+ {},
+ { it.observe(KeySample.Log("2000", "Ambient", "some log", null), 24000) },
+ { it.observe(KeySample.Accessibility(25, 114, false), 24000) },
+ { it.observe(KeySample.Accessibility(25, 114, true), 24000) },
+ {
+ it.observe(input("BTN_TOUCH", true), 24000)
+ it.observe(input("BTN_TOUCH", false), 24100)
+ },
+ {
+ differentAccessibility(it)
+ it.observe(KeySample.Accessibility(24, 115, true), 24500)
+ },
+ {
+ it.observe(KeySample.Accessibility(25, 114, true, repeat = 2), 24000)
+ it.observe(KeySample.Accessibility(25, 114, false), 24100)
+ },
+ )
+ cases.forEach { observe ->
+ val session = logged()
+ session.beginCheck(checkStart)
+ observe(session)
+ session.finishCheck(checkEnd)
+ failed(session, TeachingFailure.NO_DIFFERENT_KEY)
+ }
+ }
+
+ @Test
+ fun directRequiresAccessibilityWitnessNotInputOrRawLogs() {
+ val session = direct()
+ session.beginCheck(checkStart)
+ session.observe(input("KEY_VOLUMEDOWN", true), 24000)
+ session.observe(input("KEY_VOLUMEDOWN", false), 24100)
+ session.observe(KeySample.Log("1000", "KEYLOG_PhoneWindowManagerExtImpl", rawKey("25", true), "25"), 24200)
+ session.observe(KeySample.Log("1000", "KEYLOG_PhoneWindowManagerExtImpl", rawKey("25", false), "25"), 24300)
+ session.finishCheck(checkEnd)
+ failed(session, TeachingFailure.NO_DIFFERENT_KEY)
+ }
+
+ @Test
+ fun rawVolumeEvidenceRequiresSystemWriterReleaseAndSameThread() {
+ for (differentThread in listOf(false, true)) {
+ val session = logged()
+ session.beginCheck(checkStart)
+ session.observe(KeySample.Log(if (differentThread) "1000" else "2000", "KEYLOG_PhoneWindowManagerExtImpl",
+ rawKey("25", true), "25", "one"), 24000)
+ session.observe(KeySample.Log(if (differentThread) "1000" else "2000", "KEYLOG_PhoneWindowManagerExtImpl",
+ rawKey("25", false), "25", "two"), 24100)
+ session.finishCheck(checkEnd)
+ failed(session, TeachingFailure.NO_DIFFERENT_KEY)
+ }
+ }
+
+ @Test
+ fun fiveSecondsNeedsSettlingAndLateReleaseCanCompleteButLateDownCannotWitness() {
+ val valid = direct()
+ valid.beginCheck(checkStart)
+ valid.observe(KeySample.Accessibility(25, 114, true), checkStart + 4900)
+ valid.finishCheck(checkStart + TeachingSession.CHECK_MS)
+ assertTrue(valid.state is TeachingState.Checking)
+ valid.observe(KeySample.Accessibility(25, 114, false), checkStart + 5200)
+ valid.finishCheck(checkEnd)
+ assertTrue(valid.state is TeachingState.Ready)
+
+ val late = direct()
+ late.beginCheck(checkStart)
+ late.observe(KeySample.Accessibility(25, 114, true), checkStart + 5100)
+ late.observe(KeySample.Accessibility(25, 114, false), checkStart + 5200)
+ late.finishCheck(checkEnd)
+ failed(late, TeachingFailure.NO_DIFFERENT_KEY)
+
+ val lateRelease = direct()
+ lateRelease.beginCheck(checkStart)
+ lateRelease.observe(KeySample.Accessibility(25, 114, true), checkStart + 4900)
+ lateRelease.observe(KeySample.Accessibility(25, 114, false), checkEnd + 100)
+ lateRelease.finishCheck(checkEnd + 200)
+ failed(lateRelease, TeachingFailure.NO_DIFFERENT_KEY)
+ }
+
+ @Test
+ fun collisionDuringSettlingOrReadyInvalidatesProofBeforeSave() {
+ for (ready in listOf(false, true)) {
+ val session = logged()
+ session.beginCheck(checkStart)
+ differentAccessibility(session)
+ if (ready) session.finishCheck(checkEnd)
+ session.observe(stylus("9900", "22"), if (ready) checkEnd + 100 else checkStart + 5200)
+ failed(session, TeachingFailure.COLLISION)
+ }
+ }
+
+ @Test
+ fun requiredAccessMustBePresentAtStartAndLossCannotHealWithoutRetry() {
+ val startCases = listOf(
+ direct(access = fullAccess.copy(accessibility = false)),
+ direct(withInput = true, access = fullAccess.copy(accessibility = false)),
+ logged(access = fullAccess.copy(fullLogs = false)),
+ logged(withInput = true, access = fullAccess.copy(inputLive = false)),
+ )
+ startCases.forEach {
+ it.beginCheck(checkStart)
+ failed(it, TeachingFailure.ACCESS_LOST)
+ it.accessChanged(fullAccess)
+ it.beginCheck(checkStart + 1)
+ failed(it, TeachingFailure.ACCESS_LOST)
+ }
+ for (ready in listOf(false, true)) {
+ val sessions = listOf(
+ direct() to fullAccess.copy(accessibility = false),
+ direct(withInput = true) to fullAccess.copy(accessibility = false),
+ logged() to fullAccess.copy(fullLogs = false),
+ logged(withInput = true) to fullAccess.copy(inputLive = false),
+ )
+ sessions.forEach { (session, lost) ->
+ session.beginCheck(checkStart)
+ differentAccessibility(session)
+ if (ready) session.finishCheck(checkEnd)
+ session.accessChanged(lost)
+ session.accessChanged(fullAccess)
+ session.finishCheck(checkEnd)
+ failed(session, TeachingFailure.ACCESS_LOST)
+ }
+ }
+ }
+
+ @Test
+ fun offLimitedAndWaitingLogsAllInvalidateEvenWhenPreciseInputStaysLive() {
+ for (logs in listOf(LogAccess.OFF, LogAccess.LIMITED, LogAccess.WAITING)) {
+ val session = logged(withInput = true)
+ session.beginCheck(checkStart)
+ differentAccessibility(session)
+ session.finishCheck(checkEnd)
+ assertTrue(session.state is TeachingState.Ready)
+ session.accessChanged(TeachingAccess(true, logs, true))
+ session.accessChanged(TeachingAccess(true, LogAccess.FULL, true))
+ failed(session, TeachingFailure.ACCESS_LOST)
+ }
+ }
+
+ @Test
+ fun onlyRequiredSourcesAreMandatoryAndSourceReplacementInvalidatesUntilRetry() {
+ val direct = direct(access = TeachingAccess(true, false, false))
+ direct.beginCheck(checkStart)
+ differentAccessibility(direct)
+ direct.finishCheck(checkEnd)
+ assertTrue(direct.state is TeachingState.Ready)
+
+ val logged = logged(access = TeachingAccess(false, true, false))
+ logged.beginCheck(checkStart)
+ logged.observe(KeySample.Log("1000", "KEYLOG_PhoneWindowManagerExtImpl", rawKey("25", true), "25"), 24000)
+ logged.observe(KeySample.Log("1000", "KEYLOG_PhoneWindowManagerExtImpl", rawKey("25", false), "25"), 24100)
+ logged.finishCheck(checkEnd)
+ assertTrue(logged.state is TeachingState.Ready)
+
+ for (ready in listOf(false, true)) {
+ val session = logged(withInput = true)
+ session.beginCheck(checkStart)
+ differentAccessibility(session)
+ if (ready) session.finishCheck(checkEnd)
+ session.sourceRestarted(logs = true)
+ session.accessChanged(fullAccess)
+ failed(session, TeachingFailure.ACCESS_LOST)
+ val inputRestart = logged(withInput = true)
+ inputRestart.beginCheck(checkStart)
+ inputRestart.sourceRestarted(logs = false, input = true)
+ failed(inputRestart, TeachingFailure.ACCESS_LOST)
+ }
+ }
+
+ @Test
+ fun directInputMetadataDoesNotRequireAnUnusedRuntimeSource() {
+ for (ready in listOf(false, true)) {
+ val session = direct(withInput = true, access = TeachingAccess(true, false, false))
+ session.beginCheck(checkStart)
+ differentAccessibility(session)
+ if (ready) session.finishCheck(checkEnd)
+ session.sourceRestarted(logs = true, input = true)
+ session.accessChanged(fullAccess)
+ session.accessChanged(TeachingAccess(true, false, false))
+ session.finishCheck(checkEnd)
+ assertTrue(session.state is TeachingState.Ready)
+ assertTrue(session.save { patch ->
+ val config = patch.applyTo(Config())
+ assertEquals(LearnedKey(142, 88), config.keyEvent)
+ assertEquals(InputKey(inputCode), config.inputKey)
+ true
+ })
+ }
+ }
+
+ @Test
+ fun captureCandidateCheckingFailureAndCancelNeverWriteAndClosedCannotRevive() {
+ val saved = SavedConfig()
+ val old = saved.value
+ val capturing = TeachingSession(fullAccess)
+ assertFalse(saved.save(capturing))
+ capturing.cancel()
+ capturing.capture(baseline, taps, hold)
+ capturing.beginCheck(checkStart)
+ assertEquals(TeachingState.Closed, capturing.state)
+ assertFalse(saved.save(capturing))
+ val candidate = direct()
+ assertFalse(saved.save(candidate))
+ candidate.beginCheck(checkStart)
+ assertFalse(saved.save(candidate))
+ candidate.cancel()
+ differentAccessibility(candidate)
+ candidate.finishCheck(checkEnd)
+ assertFalse(saved.save(candidate))
+ val failed = direct()
+ failed.beginCheck(checkStart)
+ failed.finishCheck(checkEnd)
+ assertFalse(saved.save(failed))
+ assertEquals(old, saved.value)
+ assertEquals(0, saved.writes)
+ }
+
+ @Test
+ fun staleDeliveryCannotSupplyReleaseForRetryOrWriteAfterCancel() {
+ val gate = TeachingDelivery()
+ val saved = SavedConfig()
+ gate.advance(TeachingHandle(1))
+ val first = direct()
+ first.beginCheck(checkStart)
+ val oldStamp = gate.stamp
+ first.cancel()
+ gate.advance(TeachingHandle(2))
+ val retry = direct()
+ retry.beginCheck(checkStart)
+ retry.observe(KeySample.Accessibility(25, 114, true), 24000)
+ gate.deliver(oldStamp) { retry.observe(KeySample.Accessibility(25, 114, false), 24100) }
+ retry.finishCheck(checkEnd)
+ failed(retry, TeachingFailure.NO_DIFFERENT_KEY)
+ assertFalse(saved.save(first))
+ assertFalse(saved.save(retry))
+ assertEquals(0, saved.writes)
+ }
+
+ @Test
+ fun explicitSaveWritesOnceAndAppliesOnlyLearnedFieldsToCurrentConfig() {
+ val saved = SavedConfig()
+ val session = direct()
+ session.beginCheck(checkStart)
+ differentAccessibility(session)
+ session.finishCheck(checkEnd)
+ assertEquals(0, saved.writes)
+ val current = saved.value.copy(enabled = false, theme = ThemeMode.DARK, pausedApps = setOf("current.app"),
+ holdMs = 900, actions = mapOf(Gesture.SINGLE to SnapAction.NoAction))
+ saved.value = current
+ assertTrue(saved.save(session))
+ assertEquals(current.copy(keyEvent = LearnedKey(142, 88), logSignature = null, logKeyCode = null, inputKey = null), saved.value)
+ assertFalse(saved.save(session))
+ session.cancel()
+ assertFalse(saved.save(session))
+ assertEquals(1, saved.writes)
+ }
+
+ @Test
+ fun loggedSaveRetainsCalibrationAndClearsOldDirectBinding() {
+ val session = logged(oplus = true, withInput = true)
+ val learned = (session.state as TeachingState.Candidate).result as LearnResult.LogLineFound
+ session.beginCheck(checkStart)
+ differentAccessibility(session)
+ session.finishCheck(checkEnd)
+ val current = Config(keyEvent = LearnedKey(141, 87), theme = ThemeMode.DARK, releaseGapMs = 400)
+ assertTrue(session.save { patch ->
+ val changed = patch.applyTo(current)
+ assertNull(changed.keyEvent)
+ assertEquals(learned.signature, changed.logSignature)
+ assertEquals(learned.logKeyCode, changed.logKeyCode)
+ assertEquals(learned.inputKey, changed.inputKey)
+ assertEquals(learned.holdRepeats, changed.holdRepeats)
+ assertEquals(learned.releaseGapMs, changed.releaseGapMs)
+ assertEquals(ThemeMode.DARK, changed.theme)
+ assertTrue(runCatching { patch.applyTo(current) }.isFailure)
+ true
+ })
+ assertFalse(session.save { true })
+ }
+
+ private fun direct(
+ code: Int = 142, scan: Int = 88, withInput: Boolean = false, access: TeachingAccess = fullAccess,
+ ): TeachingSession =
+ TeachingSession(access).apply {
+ positiveTimes.forEach {
+ observe(KeySample.Accessibility(code, scan, true), it)
+ if (withInput) observe(input(inputCode, true), it)
+ }
+ capture(baseline, taps, hold)
+ assertEquals(LearnResult.KeyEventFound(LearnedKey(code, scan), if (withInput) InputKey(inputCode) else null),
+ (state as TeachingState.Candidate).result)
+ }
+
+ private fun logged(oplus: Boolean = false, withInput: Boolean = false, access: TeachingAccess = fullAccess): TeachingSession =
+ TeachingSession(access).apply {
+ positiveTimes.forEachIndexed { index, time ->
+ if (oplus) {
+ observe(KeySample.Log("1000", "KEYLOG_PhoneWindowManagerExtImpl", rawKey(snapCode, true), snapCode), time)
+ observe(KeySample.Log("1000", oplusTag, oplusMessage, snapCode), time + 1)
+ } else observe(stylus("${900 + index}", "${10 + index}"), time)
+ if (withInput) observe(input(inputCode, true), time)
+ }
+ capture(baseline, taps, hold)
+ assertTrue(state is TeachingState.Candidate)
+ assertTrue((state as TeachingState.Candidate).result is LearnResult.LogLineFound)
+ }
+
+ private fun differentAccessibility(session: TeachingSession, code: Int = 25, scan: Int = 114) {
+ session.observe(KeySample.Accessibility(code, scan, true), 24000)
+ session.observe(KeySample.Accessibility(code, scan, false), 24100)
+ }
+
+ private fun stylus(counter: String, type: String) = KeySample.Log("424242", stylusTag,
+ "StylusModule.onUpdateToolType():$counter Update tool type = $type", null)
+
+ private fun rawKey(code: String, down: Boolean) =
+ "overrideInterceptKeyBeforeQueueing:KeyEvent { action=${if (down) "ACTION_DOWN" else "ACTION_UP"}, keyCode=$code, scanCode=0 }"
+
+ private fun input(code: String, down: Boolean) = KeySample.Input(InputKeyEvent(InputKey(code), down))
+
+ private fun failed(session: TeachingSession, reason: TeachingFailure) {
+ assertEquals(TeachingState.Failed(reason), session.state)
+ assertFalse(session.save { true })
+ }
+
+ private class SavedConfig {
+ var value = Config(keyEvent = LearnedKey(141, 87), theme = ThemeMode.LIGHT)
+ var writes = 0
+ fun save(session: TeachingSession): Boolean = session.save { patch ->
+ value = patch.applyTo(value)
+ writes++
+ true
+ }
+ }
+}
diff --git a/app/src/test/java/com/heykay/snapkeymap/TileStateTest.kt b/app/src/test/java/com/heykay/snapkeymap/TileStateTest.kt
new file mode 100644
index 0000000..b895864
--- /dev/null
+++ b/app/src/test/java/com/heykay/snapkeymap/TileStateTest.kt
@@ -0,0 +1,41 @@
+package com.heykay.snapkeymap
+
+import android.service.quicksettings.Tile
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class TileStateTest {
+ @Test
+ fun untaughtKeyIsUnavailableRegardlessOfPermissionOrEnabled() {
+ for (config in listOf(Config(), Config(logSignature = KeySignature("tag", "message")))) {
+ for (permission in listOf(false, true)) {
+ for (enabled in listOf(false, true)) {
+ assertEquals(
+ "config=$config permission=$permission enabled=$enabled",
+ Tile.STATE_UNAVAILABLE,
+ tileState(config.copy(enabled = enabled), permission),
+ )
+ }
+ }
+ }
+ }
+
+ @Test
+ fun taughtLogKeyRequiresPermissionEvenWhenDisabled() {
+ val config = Config(logSignature = KeySignature("tag", "message", "1000"))
+ for (enabled in listOf(false, true)) {
+ assertEquals(Tile.STATE_UNAVAILABLE, tileState(config.copy(enabled = enabled), false))
+ }
+ assertEquals(Tile.STATE_ACTIVE, tileState(config.copy(enabled = true), true))
+ assertEquals(Tile.STATE_INACTIVE, tileState(config.copy(enabled = false), true))
+ }
+
+ @Test
+ fun taughtKeyEventMirrorsEnabledWithoutLogPermission() {
+ val config = Config(keyEvent = LearnedKey(100, 0))
+ for (permission in listOf(false, true)) {
+ assertEquals(Tile.STATE_ACTIVE, tileState(config.copy(enabled = true), permission))
+ assertEquals(Tile.STATE_INACTIVE, tileState(config.copy(enabled = false), permission))
+ }
+ }
+}
diff --git a/docs/privacy.md b/docs/privacy.md
index a357e4a..c1ed980 100644
--- a/docs/privacy.md
+++ b/docs/privacy.md
@@ -6,7 +6,9 @@ With Shizuku allowed, the app runs `logcat` and also reads raw key input events
Circle to Search uses Shizuku when available, then tries the system service directly if necessary. It opens Google's search interface over the current screen. Google handles that search under its own privacy policy. SnapKey Map does not capture or store the screen for this action. Other mapped actions do not use Shizuku. Apps and websites you open through an action have their own privacy policies.
-The accessibility service checks window-event package and class names to identify app activities, ignoring non-activity windows such as keyboards and status indicators. It keeps only the latest activity's package name in memory and uses it only to pause in the apps you choose. It cannot read screen content. Your chosen paused-app package names are saved in settings.
+The accessibility service can receive hardware key events from other apps when Android delivers them. The app acts only on the key you taught it and passes other keys on unchanged. While you teach the key, it keeps key codes, scan codes, and arrival times from eligible key-down events in memory. On success, it saves only the learned key identity, not those observations. The service also checks window-event package and class names to identify app activities, ignoring non-activity windows such as keyboards and status indicators. It keeps a cache of up to 64 package-and-class resolution results and the latest resolved activity package name in memory. Both are cleared when the service disconnects. It uses the latest package name only to pause in the apps you choose. It cannot read screen content. Your chosen paused-app package names are saved in settings.
+
+**Copy report** and **Report a bug**, under **Details** on the status card, build a report on the phone. It lists the app, phone, ColorOS and Android versions, the setup method, the learned key, timing, the kind of each gesture's action, and the last 20 detections, which are kept only in memory. It never includes contact numbers, links, app names or log lines. The app does not send it anywhere. Copy report puts it on the clipboard, and Report a bug opens the GitHub form in your browser so you can review it before you submit.
Keep these limits in mind:
@@ -16,5 +18,5 @@ Keep these limits in mind:
- The shortcut picker lists apps that provide `ACTION_CREATE_SHORTCUT`. It cannot list every pinned shortcut. A deep link may work instead.
- Calls are not placed directly, because the app has no calling permission. Call a contact opens the dialer, and direct-dial shortcuts show a message instead.
- With Shizuku running and allowed on Android 15 or later, ringer presets use true Silent without turning on Do Not Disturb. On older Android versions, without Shizuku, or if the shell command fails, Silent uses the public Android API, needs Do Not Disturb access, and may turn on Do Not Disturb. Without that access, the fallback skips Silent and shows a reminder. The Do Not Disturb toggle always needs notification policy access; the app asks when you assign it, or when assigning Silent without Shizuku.
-- Mappings and the learned key are not included in Android backups.
+- Backups are written only to a file you choose and can contain contact numbers, links and app names; Android cloud backup stays off.
- The app cannot bypass the lock screen or control every function in every app.
diff --git a/fastlane/metadata/android/en-US/changelogs/10200.txt b/fastlane/metadata/android/en-US/changelogs/10200.txt
new file mode 100644
index 0000000..69ef929
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/10200.txt
@@ -0,0 +1 @@
+Try each gesture's action from Home with the ▶ button. Turn the mapping on or off from the Snap Key Quick Settings tile. Back up settings, including the learned key, to a file you choose and restore them later. Copy a privacy-safe bug report, or open a prefilled bug form, from Details on the status card. Teaching now asks you to press a different key before saving, so other keys can't trigger your actions. The accessibility description now lists what the service receives.
\ No newline at end of file
diff --git a/fastlane/metadata/android/en-US/full_description.txt b/fastlane/metadata/android/en-US/full_description.txt
index 617617b..aea719c 100644
--- a/fastlane/metadata/android/en-US/full_description.txt
+++ b/fastlane/metadata/android/en-US/full_description.txt
@@ -12,7 +12,7 @@
How it works
ColorOS does not pass the Snap Key to apps. SnapKey Map detects it from the system log, so it needs the READ_LOGS permission once. You grant it with Shizuku on the phone, or with ADB from a computer. A setup wizard walks you through each step and then teaches the app your key.
With Shizuku running, the app reads the log and raw key events through Shizuku. This gives more precise press and release detection, and lets ringer presets use Oppo's own Silent mode on Android 15 or later.
-The accessibility service runs actions such as screenshot and lock, and opens apps from the background. It cannot read screen content.
+The accessibility service runs actions such as screenshot and lock, and opens apps from the background. It can receive hardware key events from other apps when Android delivers them. It acts only on the key you taught it. It checks package and class names in window events to identify app activities and pause in apps you choose. It cannot read screen content.
Privacy
The app has no internet permission, no ads, and no tracking. Log lines are checked in memory and discarded, never saved or uploaded.