diff --git a/README.md b/README.md index 9eb2e5f..c1e23b3 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,8 @@ Tap the lock next to a gesture to run it only when your phone is unlocked. On the home screen you can pause the key in chosen apps, such as the camera, and hide confirmation pop-ups. Errors still show. +Tap ▶ next to a gesture to try its action without pressing the key. Turn the mapping on or off from the **Snap Key** Quick Settings tile. Back up your settings, including the learned key, to a file and restore them after a reinstall. **Details** on the status card can copy a bug report or open a prefilled bug form. + The app follows Material 3 with dynamic colour and a System, Light, or Dark theme. It declares no internet permission. # Requirements diff --git a/ROADMAP.md b/ROADMAP.md index 02680a5..dfa33a6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -13,6 +13,17 @@ The F-Droid submission will request the same developer-signed APK as GitHub Rele - [x] **Release v1.0.15 with release notes.** The first release built for F-Droid. Each release since then passes the reproducibility check. - [ ] **Submit to F-Droid.** Open a merge request in [fdroiddata](https://gitlab.com/fdroid/fdroiddata) with the build recipe. Review can take days or weeks. +## Delivered in v1.2.0 + +Quality-of-life additions for everyday use. Behaviour on other firmware may differ. + +- [x] **Try a gesture.** Tap ▶ next to an assigned gesture on Home to run its action at once. Try always shows its confirmation, even with Show confirmations off. +- [x] **Quick Settings tile.** Add the **Snap Key** tile to turn the mapping on or off without opening the app. Long-press the tile to open the app. +- [x] **Back up and restore.** Save gesture actions, ringer presets, paused apps, timing, theme and the learned key to a file you choose, and restore them later. A gesture mapped to an app that is no longer installed shows "App not installed". +- [x] **Bug reports.** **Details** on the status card can copy a report with your versions, setup and last 20 detections, or open the bug form with its fields filled in. Reports name only the kind of each action, never contact numbers, links or app names. +- [x] **Safer teaching.** After teaching, press a different key, such as volume. The app keeps the learned key only if that press doesn't match it, and saves it only when you tap Save. Cancelling or a failed check keeps your previous settings. +- [x] **Clearer accessibility disclosure.** The service description, store listing and privacy page say that Android passes every hardware key press to the service and tells it which app is in front. The app acts only on the key you taught it. + ## Delivered in v1.1.0 This release replaces v1.0.18 and includes its changes. It combines a review against Android's Compose, lifecycle and accessibility guidance with feedback from the [launch post](https://www.reddit.com/r/Oppo/comments/1xaze1m/i_built_an_app_to_remap_the_oppo_find_x9s_snap_key/). It was tested manually on a Find X9 running ColorOS 17. Behaviour on other firmware may differ. diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 0de9c21..9892d86 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -16,8 +16,8 @@ android { minSdk = 29 targetSdk = 36 // F-Droid reads both as literals from this file. - versionCode = 10100 - versionName = "1.1.0" + versionCode = 10200 + versionName = "1.2.0" } // F-Droid can't inspect the dependency list that Google encrypts into the signing block. diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 84bd4a4..20fdd18 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -61,8 +61,26 @@ + + + + + + + + + + + Unit @@ -70,8 +71,8 @@ object ActionRunner { context, Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Uri.encode(action.number))), ) - is SnapAction.Device -> runDevice(context, action.action) - is SnapAction.Ringer -> cycleRinger(context, action) + is SnapAction.Device -> runDevice(context, action.action, alwaysConfirm) + is SnapAction.Ringer -> cycleRinger(context, action, alwaysConfirm) } } catch (e: ActivityNotFoundException) { toast(context, "No app can do that: ${action.label}") @@ -80,10 +81,10 @@ object ActionRunner { } } - private fun runDevice(context: Context, action: DeviceAction) { + private fun runDevice(context: Context, action: DeviceAction, alwaysConfirm: Boolean) { when (action) { - DeviceAction.FLASHLIGHT -> toggleTorch(context) - DeviceAction.DO_NOT_DISTURB -> toggleDoNotDisturb(context) + DeviceAction.FLASHLIGHT -> toggleTorch(context, alwaysConfirm) + DeviceAction.DO_NOT_DISTURB -> toggleDoNotDisturb(context, alwaysConfirm) DeviceAction.SCREENSHOT -> global(context, AccessibilityService.GLOBAL_ACTION_TAKE_SCREENSHOT) DeviceAction.CIRCLE_TO_SEARCH -> if (!CircleToSearch.start()) { toast(context, "Circle to Search isn't available. Set Google as your digital assistant app.") @@ -158,9 +159,9 @@ object ActionRunner { if (cameraId != torchCameraId) return torchUnavailable = false torchOn = enabled - if (pendingTorchToggle) { - pendingTorchToggle = false - run(app, SnapAction.Device(DeviceAction.FLASHLIGHT)) + pendingTorchToggle?.let { alwaysConfirm -> + pendingTorchToggle = null + run(app, SnapAction.Device(DeviceAction.FLASHLIGHT), alwaysConfirm) } } @@ -168,8 +169,8 @@ object ActionRunner { if (cameraId != torchCameraId) return torchUnavailable = true torchOn = null - if (pendingTorchToggle) toast(app, "Flashlight isn't available while the camera is in use") - pendingTorchToggle = false + if (pendingTorchToggle != null) toast(app, "Flashlight isn't available while the camera is in use") + pendingTorchToggle = null } }, Handler(Looper.getMainLooper())) torchWatched = true @@ -177,7 +178,7 @@ object ActionRunner { return id } - private fun toggleTorch(context: Context) { + private fun toggleTorch(context: Context, alwaysConfirm: Boolean) { val id = watchTorch(context) if (id == null) { toast(context, "This phone has no flashlight") @@ -190,19 +191,20 @@ object ActionRunner { val current = torchOn if (current == null) { // Registration delivers the real initial state asynchronously, including Quick Settings changes. - pendingTorchToggle = !pendingTorchToggle + pendingTorchToggle = if (pendingTorchToggle == null) alwaysConfirm else null return } context.getSystemService(CameraManager::class.java).setTorchMode(id, !current) torchOn = !current + if (alwaysConfirm) confirm(context, if (current) "Flashlight off" else "Flashlight on", alwaysConfirm) } - private fun cycleRinger(context: Context, action: SnapAction.Ringer) { + private fun cycleRinger(context: Context, action: SnapAction.Ringer, alwaysConfirm: Boolean) { val app = context.applicationContext scope.launch { ringerMutex.withLock { try { - changeRinger(app, action) + changeRinger(app, action, alwaysConfirm) } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -212,7 +214,7 @@ object ActionRunner { } } - private suspend fun changeRinger(context: Context, action: SnapAction.Ringer) { + private suspend fun changeRinger(context: Context, action: SnapAction.Ringer, alwaysConfirm: Boolean) { val audio = context.getSystemService(AudioManager::class.java) val externalMode = audio.ringerMode // Before Android 15, `cmd audio` has no set-ringer-mode yet still exits 0, so success can't be trusted. @@ -231,7 +233,7 @@ object ActionRunner { } if (result?.exitCode == 0) { vibrateRinger(context, next) - confirm(context, next.label) + confirm(context, next.label, alwaysConfirm) return } } @@ -242,7 +244,7 @@ object ActionRunner { audio.ringerMode = next.audioMode vibrateRinger(context, next) if (skippedSilent) toast(context, "Allow Do Not Disturb access to use Silent") - else confirm(context, next.label) + else confirm(context, next.label, alwaysConfirm) } private fun ringerMode(mode: Int): RingerMode? = when (mode) { @@ -272,7 +274,7 @@ object ActionRunner { RingerMode.SILENT -> AudioManager.RINGER_MODE_SILENT } - private fun toggleDoNotDisturb(context: Context) { + private fun toggleDoNotDisturb(context: Context, alwaysConfirm: Boolean) { val notifications = context.getSystemService(NotificationManager::class.java) if (!notifications.isNotificationPolicyAccessGranted) { toast(context, "Allow SnapKey Map to change Do Not Disturb") @@ -283,11 +285,11 @@ object ActionRunner { notifications.setInterruptionFilter( if (turnOn) NotificationManager.INTERRUPTION_FILTER_PRIORITY else NotificationManager.INTERRUPTION_FILTER_ALL, ) - confirm(context, if (turnOn) "Do Not Disturb on" else "Do Not Disturb off") + confirm(context, if (turnOn) "Do Not Disturb on" else "Do Not Disturb off", alwaysConfirm) } - private fun confirm(context: Context, text: String) { - if (SnapEngine.store.config.value.showConfirmations) toast(context, text) + private fun confirm(context: Context, text: String, alwaysConfirm: Boolean) { + if (alwaysConfirm || SnapEngine.store.config.value.showConfirmations) toast(context, text) } private fun toast(context: Context, text: String) { diff --git a/app/src/main/java/com/heykay/snapkeymap/BugReport.kt b/app/src/main/java/com/heykay/snapkeymap/BugReport.kt new file mode 100644 index 0000000..48599ee --- /dev/null +++ b/app/src/main/java/com/heykay/snapkeymap/BugReport.kt @@ -0,0 +1,134 @@ +package com.heykay.snapkeymap + +import android.content.Context +import android.os.Build +import java.net.URLEncoder +import rikka.shizuku.Shizuku + +data class ReportInfo( + val versionName: String, + val versionCode: Long, + val phoneModel: String, + val colorOsVersion: String, + val androidRelease: String, + val sdk: Int, + val shizukuState: String, + val detectionMode: String, + val hasLogPermission: Boolean, +) + +fun gatherReportInfo(context: Context, config: Config, precise: Boolean): ReportInfo { + val version = context.packageManager.getPackageInfo(context.packageName, 0) + val colorOs = runCatching { + Class.forName("android.os.SystemProperties") + .getMethod("get", String::class.java) + .invoke(null, "ro.build.version.oplusrom") as String + }.getOrNull()?.takeIf { it.isNotBlank() } ?: "unknown" + val shizuku = runCatching { + when { + !Shizuku.pingBinder() -> "Not running" + canUseShizuku() -> "Running and allowed" + else -> "Running, not allowed" + } + }.getOrDefault("Unavailable") + return ReportInfo( + versionName = version.versionName ?: "unknown", + versionCode = version.longVersionCode, + phoneModel = Build.MODEL, + colorOsVersion = colorOs, + androidRelease = Build.VERSION.RELEASE, + sdk = Build.VERSION.SDK_INT, + shizukuState = shizuku, + detectionMode = when { + !config.needsLogAccess -> "Accessibility key events" + precise -> "Precise input via Shizuku" + else -> "System logs" + }, + hasLogPermission = SnapEngine.hasLogPermission(), + ) +} + +internal fun learnedKeySummary(config: Config): String = listOf( + config.keyEvent?.let { "keyEvent: code=${it.keyCode}, scan=${it.scanCode}" } ?: "keyEvent: not set", + config.inputKey?.let { "inputKey: ${it.code}" } ?: "inputKey: not set", + config.logSignature?.let { "logSignature: tag=${it.tag}" } ?: "logSignature: not set", + config.logKeyCode?.let { "logKeyCode: $it" } ?: "logKeyCode: not set", +).joinToString("\n") + +private fun actionKind(action: SnapAction): String = when (action) { + SnapAction.NoAction -> "Do nothing" + is SnapAction.OpenApp -> "Open an app" + is SnapAction.OpenShortcut -> "Open a shortcut" + is SnapAction.OpenLink -> "Open a link" + is SnapAction.CallContact -> "Call a contact" + is SnapAction.Device -> action.action.label + is SnapAction.Ringer -> "Ringer: ${action.modes.joinToString(" → ") { it.label }}" +} + +private fun actionsSummary(config: Config): String = Gesture.entries.joinToString("\n") { gesture -> + "${gesture.title}: ${actionKind(config.action(gesture))}; unlocked-only: ${if (gesture in config.unlockedOnly) "on" else "off"}" +} + +private fun detectionText(detected: SnapEngine.Detected, timeFormat: (Long) -> String): String = + "${detected.gesture.title} at ${timeFormat(detected.atMs)} [${detected.source}]" + +fun buildReport( + info: ReportInfo, + config: Config, + detections: List, + timeFormat: (Long) -> String, +): String = buildString { + appendLine("SnapKey Map ${info.versionName} (${info.versionCode})") + appendLine("Phone: ${info.phoneModel}") + appendLine("ColorOS: ${info.colorOsVersion}") + appendLine("Android: ${info.androidRelease} (SDK ${info.sdk})") + appendLine("Grant method: ${grantMethodText(config.grantMethod)}") + appendLine("Log permission: ${if (info.hasLogPermission) "granted" else "not granted"}") + appendLine("Shizuku: ${info.shizukuState}") + appendLine("Detection mode: ${info.detectionMode}") + appendLine(learnedKeySummary(config)) + appendLine("Double-press window: ${config.doublePressWindowMs} ms") + appendLine("Hold threshold: ${config.holdMs} ms") + appendLine() + appendLine(actionsSummary(config)) + appendLine() + appendLine("Last $DETECTION_HISTORY_SIZE detections:") + if (detections.isEmpty()) appendLine("None yet") + else detections.takeLast(DETECTION_HISTORY_SIZE).forEach { appendLine(detectionText(it, timeFormat)) } +}.trimEnd() + +private fun grantMethodText(method: GrantMethod?): String = when (method) { + GrantMethod.SHIZUKU -> "Shizuku" + GrantMethod.ADB -> "Computer (ADB)" + null -> "Not granted yet" +} + +fun bugReportUrl( + info: ReportInfo, + config: Config, + last: SnapEngine.Detected?, + timeFormat: (Long) -> String, +): String { + val logAccess = if (config.needsLogAccess && !info.hasLogPermission) "Not granted yet" + else grantMethodText(config.grantMethod) + val fields = listOf( + "app-version" to encodeReportField("${info.versionName} (${info.versionCode})", 100), + "device" to encodeReportField("${info.phoneModel}, ColorOS ${info.colorOsVersion}, Android ${info.androidRelease} (SDK ${info.sdk})", 300), + "log-access" to encodeReportField(logAccess, 100), + "teach" to encodeReportField(learnedKeySummary(config), 400), + "actions" to encodeReportField(actionsSummary(config) + "\nLast: " + + (last?.let { detectionText(it, timeFormat) } ?: "None yet"), 700), + ) + return "https://github.com/heykay-47/SnapKeyMap/issues/new?template=bug_report.yml&" + + fields.joinToString("&") { (key, value) -> "$key=$value" } +} + +private fun encodeReportField(value: String, maxLength: Int): String { + var text = value.take(maxLength) + var encoded = URLEncoder.encode(text, "UTF-8").replace("+", "%20") + while (encoded.length > maxLength) { + text = text.dropLast(1) + encoded = URLEncoder.encode(text, "UTF-8").replace("+", "%20") + } + return encoded +} diff --git a/app/src/main/java/com/heykay/snapkeymap/ConfigStore.kt b/app/src/main/java/com/heykay/snapkeymap/ConfigStore.kt index 50b803f..a106c00 100644 --- a/app/src/main/java/com/heykay/snapkeymap/ConfigStore.kt +++ b/app/src/main/java/com/heykay/snapkeymap/ConfigStore.kt @@ -2,6 +2,7 @@ package com.heykay.snapkeymap import android.Manifest import android.content.Context +import android.content.SharedPreferences import android.content.pm.PackageManager import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -74,23 +75,60 @@ internal fun Config.editRingerPreset(oldModes: List, newModes: List< ) } -class ConfigStore(private val context: Context) { - private val prefs = context.getSharedPreferences("snapkey", Context.MODE_PRIVATE) +class ConfigStore internal constructor( + private val prefs: SharedPreferences, + private val hasLogPermission: () -> Boolean, +) { + constructor(context: Context) : this( + context.getSharedPreferences("snapkey", Context.MODE_PRIVATE), + { context.checkSelfPermission(Manifest.permission.READ_LOGS) == PackageManager.PERMISSION_GRANTED }, + ) + private val state = MutableStateFlow(load()) val config: StateFlow = state.asStateFlow() @Synchronized fun update(change: (Config) -> Config) { state.update { current -> - val changed = change(current) - changed.copy( - doublePressWindowMs = changed.doublePressWindowMs.coerceIn(200L, 600L), - holdMs = changed.holdMs.coerceIn(300L, 1200L), - ) + bounded(change(current)) } save(state.value) } + @Synchronized + internal fun updateConfirmed(change: (Config) -> Config): Boolean { + val changed = bounded(change(state.value)) + val previous = prefs.all.mapValues { (_, value) -> if (value is Set<*>) value.toSet() else value } + val saved = runCatching { edit(changed).commit() }.getOrDefault(false) + if (!saved) { + // commit can change SharedPreferences memory even when its disk write fails. + runCatching { + prefs.edit().apply { + clear() + previous.forEach { (key, value) -> + when (value) { + is Boolean -> putBoolean(key, value) + is Int -> putInt(key, value) + is Long -> putLong(key, value) + is Float -> putFloat(key, value) + is String -> putString(key, value) + is Set<*> -> putStringSet(key, value.filterIsInstance().toSet()) + else -> Unit + } + } + }.commit() + } + return false + } + state.value = changed + return true + } + + private fun bounded(config: Config) = config.copy( + doublePressWindowMs = config.doublePressWindowMs.coerceIn(200L, 600L), + holdMs = config.holdMs.coerceIn(300L, 1200L), + ) + private fun load(): Config { val defaults = Config() val actions = Gesture.entries.associateWith { gesture -> @@ -135,8 +173,7 @@ class ConfigStore(private val context: Context) { ) if (!prefs.contains("setup_complete")) { val migrated = config.copy( - setupComplete = config.isTaught && - context.checkSelfPermission(Manifest.permission.READ_LOGS) == PackageManager.PERMISSION_GRANTED, + setupComplete = config.isTaught && hasLogPermission(), ) save(migrated) return migrated @@ -145,6 +182,10 @@ class ConfigStore(private val context: Context) { } private fun save(config: Config) { + edit(config).apply() + } + + private fun edit(config: Config): SharedPreferences.Editor = prefs.edit().apply { putBoolean("enabled", config.enabled) putBoolean("show_confirmations", config.showConfirmations) @@ -175,6 +216,5 @@ class ConfigStore(private val context: Context) { putLong("release_gap", config.releaseGapMs) putLong("double_press_window", config.doublePressWindowMs) putLong("hold_ms", config.holdMs) - }.apply() - } + } } diff --git a/app/src/main/java/com/heykay/snapkeymap/InputKeyDelivery.kt b/app/src/main/java/com/heykay/snapkeymap/InputKeyDelivery.kt new file mode 100644 index 0000000..2f965b5 --- /dev/null +++ b/app/src/main/java/com/heykay/snapkeymap/InputKeyDelivery.kt @@ -0,0 +1,29 @@ +package com.heykay.snapkeymap + +internal class InputKeyDelivery(private val teaching: TeachingDelivery) { + private val held = mutableSetOf() + private var suppressed: InputKey? = null + + fun deliver(event: InputKeyEvent, stamp: TeachingDelivery.Stamp, action: (Boolean) -> Unit) { + val ignore = event.key == suppressed + if (event.down) held += event.key else { + held -= event.key + if (ignore) suppressed = null + } + teaching.deliver(stamp) { action(ignore) } + } + + fun suppressUntilUp(key: InputKey?) { + suppressed = key + } + + fun suppressHeld(key: InputKey?): Boolean { + suppressed = key?.takeIf { it in held } + return suppressed != null + } + + fun readerLost() { + held.clear() + suppressed = null + } +} diff --git a/app/src/main/java/com/heykay/snapkeymap/InputReader.kt b/app/src/main/java/com/heykay/snapkeymap/InputReader.kt index 474adf2..8efdac4 100644 --- a/app/src/main/java/com/heykay/snapkeymap/InputReader.kt +++ b/app/src/main/java/com/heykay/snapkeymap/InputReader.kt @@ -22,10 +22,11 @@ internal fun copyInputKeyEvents(input: InputStream, output: OutputStream) { } /** Shell-only input stream. A failed reader leaves log detection running. */ -class InputReader( +internal class InputReader( private val context: Context, - private val onEvent: (InputKeyEvent, Long) -> Unit, + private val onEvent: (InputKeyEvent, Long, TeachingDelivery.Stamp) -> Unit, private val onLive: (Boolean) -> Unit, + private val receipt: () -> TeachingDelivery.Stamp, private val dispatch: (() -> Unit) -> Unit, ) { @Volatile private var session: Session? = null @@ -68,6 +69,7 @@ class InputReader( val line = reader.readLine() ?: break val event = parseInputKeyEvent(line) ?: continue val time = SystemClock.elapsedRealtime() + val stamp = receipt() dispatch { if (session === this && active) { // Opening a pipe alone does not prove getevent can read devices. @@ -75,7 +77,7 @@ class InputReader( live = true onLive(true) } - onEvent(event, time) + onEvent(event, time, stamp) } } } diff --git a/app/src/main/java/com/heykay/snapkeymap/KeyMatching.kt b/app/src/main/java/com/heykay/snapkeymap/KeyMatching.kt new file mode 100644 index 0000000..2d45983 --- /dev/null +++ b/app/src/main/java/com/heykay/snapkeymap/KeyMatching.kt @@ -0,0 +1,50 @@ +package com.heykay.snapkeymap + +internal sealed interface KeyBinding { + data class Direct(val key: LearnedKey) : KeyBinding + data class Logged( + val signature: KeySignature?, + val logKeyCode: String?, + val inputKey: InputKey?, + ) : KeyBinding +} + +internal fun Config.keyBinding(): KeyBinding = keyEvent?.let { KeyBinding.Direct(it) } + ?: KeyBinding.Logged(logSignature, logKeyCode, inputKey) + +internal sealed interface KeySample { + data class Accessibility(val code: Int, val scan: Int, val down: Boolean, val repeat: Int = 0) : KeySample + data class Input(val event: InputKeyEvent) : KeySample + data class Log( + val uid: String, val tag: String, val message: String, val threadKey: String?, val threadId: String = "", + ) : KeySample +} + +internal object KeyMatching { + fun matches(binding: KeyBinding, sample: KeySample): Boolean = when { + binding is KeyBinding.Direct && sample is KeySample.Accessibility -> + sample.code == binding.key.keyCode && (sample.code != 0 || sample.scan == binding.key.scanCode) + binding is KeyBinding.Logged && sample is KeySample.Input -> + binding.inputKey != null && sample.event.key == binding.inputKey + binding is KeyBinding.Logged && sample is KeySample.Log -> + acceptsKeyLog(binding.signature, sample.uid, sample.tag, sample.message) && + (!isKnownOplusKeyLine(sample.uid, sample.tag, sample.message) || + acceptsLoggedKey(binding.logKeyCode, sample.threadKey)) + else -> false + } +} + +internal class LoggedKeyContext { + private val keys = mutableMapOf() + private var boundary: Pair? = null + + fun sample(generation: Int, epoch: Long, uid: String, tid: String, tag: String, message: String): KeySample.Log { + val next = generation to epoch + if (boundary != next) { + keys.clear() + boundary = next + } + loggedKeyCode(uid, tag, message)?.let { keys[tid] = it } + return KeySample.Log(uid, tag, message, keys[tid], tid) + } +} diff --git a/app/src/main/java/com/heykay/snapkeymap/LogReader.kt b/app/src/main/java/com/heykay/snapkeymap/LogReader.kt index 21717c2..9075ce4 100644 --- a/app/src/main/java/com/heykay/snapkeymap/LogReader.kt +++ b/app/src/main/java/com/heykay/snapkeymap/LogReader.kt @@ -30,6 +30,7 @@ class LogReader( private val onSource: (LogSource) -> Unit, private val dispatchAccess: (() -> Unit) -> Unit = { it() }, private val shouldParse: () -> Boolean = { true }, + private val onStart: () -> Unit = {}, ) { @Volatile private var session: Session? = null @Volatile private var tryLocal = false @@ -46,6 +47,7 @@ class LogReader( if (preferShizuku) tryLocal = false val next = Session() session = next + onStart() worker.execute { next.run() } } diff --git a/app/src/main/java/com/heykay/snapkeymap/OplusKeyEdges.kt b/app/src/main/java/com/heykay/snapkeymap/OplusKeyEdges.kt index f964f0f..a90ed0b 100644 --- a/app/src/main/java/com/heykay/snapkeymap/OplusKeyEdges.kt +++ b/app/src/main/java/com/heykay/snapkeymap/OplusKeyEdges.kt @@ -36,6 +36,11 @@ class OplusKeyEdges(private val onDown: () -> Unit, private val onUp: () -> Unit this.pressed = pressed } + internal fun resetFrom(other: OplusKeyEdges) { + lastEdgeMs = other.lastEdgeMs + pressed = other.pressed + } + private companion object { const val DUPLICATE_WINDOW_MS = 3L const val DAY_MS = 24 * 60 * 60 * 1000L @@ -47,6 +52,62 @@ class OplusKeyEdges(private val onDown: () -> Unit, private val onUp: () -> Unit } } +internal class TeachingLogEdges { + private val byCode = mutableMapOf() + private val contextFree = OplusKeyEdges({}, {}) + + fun deliver( + delivery: TeachingDelivery, + receipt: TeachingDelivery.Stamp, + timestamp: String, + sample: KeySample.Log, + runtimeBinding: KeyBinding, + runtimeEdges: OplusKeyEdges, + action: () -> Unit, + ) { + val explicitEdges = isKnownOplusKeyLine(sample.uid, sample.tag, sample.message) + delivery.deliver(receipt, onStale = { + if (explicitEdges) { + if (delivery.stamp.handle != null) observe(timestamp, sample) + else if (KeyMatching.matches(runtimeBinding, sample)) runtimeEdges.observe(timestamp) + } + }) { + if (receipt.handle != null && explicitEdges) observe(timestamp, sample) + action() + } + } + + fun begin(code: String?, source: OplusKeyEdges) { + byCode.clear() + contextFree.reset() + byCode[null] = OplusKeyEdges({}, {}).apply { resetFrom(source) } + if (code != null) byCode[code] = OplusKeyEdges({}, {}).apply { resetFrom(source) } + } + + fun observe(timestamp: String, sample: KeySample.Log) { + byCode.getOrPut(null) { OplusKeyEdges({}, {}) } + sample.threadKey?.let { + byCode.getOrPut(it) { OplusKeyEdges({}, {}).apply { resetFrom(contextFree) } } + } + if (sample.threadKey == null && KeyMatching.matches(KeyBinding.Logged(null, null, null), sample)) { + contextFree.observe(timestamp) + } + byCode.forEach { (code, edges) -> + if (KeyMatching.matches(KeyBinding.Logged(null, code, null), sample)) edges.observe(timestamp) + } + } + + fun reset() { + contextFree.reset() + byCode.values.forEach { it.reset() } + } + + fun restore(code: String?, target: OplusKeyEdges) { + val source = byCode[code] ?: contextFree + target.resetFrom(source) + } +} + private val LOG_TIME = Regex("""^\d\d-\d\d\s+(\d\d):(\d\d):(\d\d)(?:\.(\d+))?$""") /** Reads the time of day from a logcat "MM-DD HH:MM:SS.mmm" timestamp, in milliseconds. */ diff --git a/app/src/main/java/com/heykay/snapkeymap/SettingsBackup.kt b/app/src/main/java/com/heykay/snapkeymap/SettingsBackup.kt new file mode 100644 index 0000000..5c9866b --- /dev/null +++ b/app/src/main/java/com/heykay/snapkeymap/SettingsBackup.kt @@ -0,0 +1,164 @@ +package com.heykay.snapkeymap + +import org.json.JSONArray +import org.json.JSONException +import org.json.JSONObject +import org.json.JSONTokener + +const val BACKUP_FORMAT = 1 + +data class SettingsBackup( + val actions: Map, + val ringerPresets: List>, + val unlockedOnly: Set, + val pausedApps: Set, + val doublePressWindowMs: Long, + val holdMs: Long, + val theme: ThemeMode, + val showConfirmations: Boolean, + val keyEvent: LearnedKey?, + val inputKey: InputKey?, + val logSignature: KeySignature?, + val logKeyCode: String?, + val holdRepeats: Boolean, + val releaseGapMs: Long, +) { + fun applyTo(current: Config): Config = current.copy( + actions = actions, + ringerPresets = ringerPresets, + unlockedOnly = unlockedOnly, + pausedApps = pausedApps, + doublePressWindowMs = doublePressWindowMs, + holdMs = holdMs, + theme = theme, + showConfirmations = showConfirmations, + keyEvent = keyEvent, + inputKey = inputKey, + logSignature = logSignature, + logKeyCode = logKeyCode, + holdRepeats = holdRepeats, + releaseGapMs = releaseGapMs, + ) +} + +sealed interface BackupResult { + data class Ok(val backup: SettingsBackup) : BackupResult + data class Error(val message: String) : BackupResult +} + +fun backupToJson(config: Config): String = JSONObject().apply { + put("format", BACKUP_FORMAT) + put("actions", JSONObject().apply { + config.actions.forEach { (gesture, action) -> put(gesture.name, JSONObject(action.toJson())) } + }) + put("ringerPresets", JSONArray(ringerPresetsToJson(config.ringerPresets))) + put("unlockedOnly", JSONArray(config.unlockedOnly.map { it.name })) + put("pausedApps", JSONArray(config.pausedApps.toList())) + put("doublePressWindowMs", config.doublePressWindowMs) + put("holdMs", config.holdMs) + put("theme", config.theme.name) + put("showConfirmations", config.showConfirmations) + put("key", JSONObject().apply { + put("keyEvent", config.keyEvent?.let { + JSONObject().put("keyCode", it.keyCode).put("scanCode", it.scanCode) + } ?: JSONObject.NULL) + put("inputKey", config.inputKey?.code ?: JSONObject.NULL) + put("logSignature", config.logSignature?.let { + JSONObject().put("tag", it.tag).put("message", it.message) + .put("uid", it.uid?.let(::normalizeLogUid) ?: JSONObject.NULL) + } ?: JSONObject.NULL) + put("logKeyCode", config.logKeyCode ?: JSONObject.NULL) + put("holdRepeats", config.holdRepeats) + put("releaseGapMs", config.releaseGapMs) + }) +}.toString(2) + +fun parseBackup(text: String): BackupResult = try { + val tokener = JSONTokener(text) + val json = JSONObject(tokener) + require(tokener.nextClean() == '\u0000') { "The backup has unexpected text after the JSON." } + val format = json.opt("format") + require(format is Int || format is Long) { "The backup must have an integer format version." } + val version = (format as Number).toLong() + require(version <= BACKUP_FORMAT) { "This backup is from a newer SnapKey Map. Update the app first." } + require(version == BACKUP_FORMAT.toLong()) { "This backup format is not supported." } + + val actionJson = json.getJSONObject("actions") + val actions = actionJson.keys().asSequence().associate { name -> + val gesture = backupEnum(name, "gesture") + val action = actionJson.getJSONObject(name) + gesture to requireNotNull(SnapAction.fromJson(action.toString())) { "Invalid action for $name." } + } + val presetsJson = json.getJSONArray("ringerPresets") + val presets = List(presetsJson.length()) { backupRingerModes(presetsJson.getJSONArray(it)) } + val key = json.getJSONObject("key") + val keyEvent = key.backupNullableObject("keyEvent")?.let { + LearnedKey(it.backupInt("keyCode"), it.backupInt("scanCode")) + } + val signature = key.backupNullableObject("logSignature")?.let { + KeySignature( + it.backupString("tag"), + it.backupString("message"), + it.backupNullableString("uid")?.let(::normalizeLogUid), + ) + } + BackupResult.Ok(SettingsBackup( + actions = actions, + ringerPresets = loadRingerPresets(ringerPresetsToJson(presets), actions.values), + unlockedOnly = json.getJSONArray("unlockedOnly").backupStrings().map { backupEnum(it, "gesture") }.toSet(), + pausedApps = json.getJSONArray("pausedApps").backupStrings().toSet(), + doublePressWindowMs = json.backupLong("doublePressWindowMs"), + holdMs = json.backupLong("holdMs"), + theme = backupEnum(json.backupString("theme"), "theme"), + showConfirmations = json.backupBoolean("showConfirmations"), + keyEvent = keyEvent, + inputKey = key.backupNullableString("inputKey")?.let(::InputKey), + logSignature = signature, + logKeyCode = key.backupNullableString("logKeyCode"), + holdRepeats = key.backupBoolean("holdRepeats"), + releaseGapMs = key.backupLong("releaseGapMs"), + )) +} catch (_: JSONException) { + BackupResult.Error("This file isn't a valid SnapKey Map backup. A required field is missing or malformed.") +} catch (error: IllegalArgumentException) { + BackupResult.Error(error.message ?: "This file isn't a valid SnapKey Map backup.") +} + +private inline fun > backupEnum(name: String, field: String): T = + enumValues().firstOrNull { it.name == name } + ?: throw IllegalArgumentException("Unknown $field: $name.") + +private fun backupRingerModes(array: JSONArray): List { + val modes = array.backupStrings().map { backupEnum(it, "ringer mode") } + return requireNotNull(runCatching { SnapAction.Ringer(modes) }.getOrNull()) { + "A ringer preset must contain two or three different ringer modes." + }.modes +} + +private fun JSONArray.backupStrings(): List = List(length()) { + requireNotNull(get(it) as? String) { "The backup contains a list entry that is not text." } +} + +private fun JSONObject.backupString(name: String): String = + requireNotNull(get(name) as? String) { "The backup field $name must be text." } + +private fun JSONObject.backupNullableString(name: String): String? = + if (get(name) == JSONObject.NULL) null else backupString(name) + +private fun JSONObject.backupNullableObject(name: String): JSONObject? = + if (get(name) == JSONObject.NULL) null else getJSONObject(name) + +private fun JSONObject.backupBoolean(name: String): Boolean = + requireNotNull(get(name) as? Boolean) { "The backup field $name must be true or false." } + +private fun JSONObject.backupLong(name: String): Long { + val value = get(name) + require(value is Int || value is Long) { "The backup field $name must be an integer." } + return (value as Number).toLong() +} + +private fun JSONObject.backupInt(name: String): Int { + val value = backupLong(name) + require(value in Int.MIN_VALUE.toLong()..Int.MAX_VALUE.toLong()) { "The backup field $name is out of range." } + return value.toInt() +} diff --git a/app/src/main/java/com/heykay/snapkeymap/SnapEngine.kt b/app/src/main/java/com/heykay/snapkeymap/SnapEngine.kt index 6b59aae..36dadd2 100644 --- a/app/src/main/java/com/heykay/snapkeymap/SnapEngine.kt +++ b/app/src/main/java/com/heykay/snapkeymap/SnapEngine.kt @@ -24,6 +24,13 @@ import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import rikka.shizuku.Shizuku +enum class DetectionSource { KEY_EVENT, PRECISE_INPUT, SYSTEM_LOG } + +internal const val DETECTION_HISTORY_SIZE = 20 + +internal fun appendDetection(history: List, d: SnapEngine.Detected): List = + (history + d).takeLast(DETECTION_HISTORY_SIZE) + internal class LogRetryBackoff { private var healthySinceMs: Long? = null private var delayMs = 1000L @@ -44,7 +51,7 @@ internal class LogRetryBackoff { /** Connects the two ways of noticing the Snap Key (key events and the system log) to the actions. */ object SnapEngine { - data class Detected(val gesture: Gesture, val atMs: Long) + data class Detected(val gesture: Gesture, val atMs: Long, val source: DetectionSource) lateinit var store: ConfigStore private set @@ -65,6 +72,7 @@ object SnapEngine { onDown = { markKeySeen(); logGestures.down() }, onUp = { markKeySeen(); logGestures.up() }, ) + private val teachingLogEdges = TeachingLogEdges() private val accessState = MutableStateFlow(LogAccess.OFF) val logAccess: StateFlow = accessState.asStateFlow() @@ -73,6 +81,8 @@ object SnapEngine { private val lastDetected = MutableStateFlow(null) val lastGesture: StateFlow = lastDetected.asStateFlow() + private val historyState = MutableStateFlow>(emptyList()) + val detections: StateFlow> = historyState.asStateFlow() private val lastKeySeenState = MutableStateFlow(null) val lastKeySeenAt: StateFlow = lastKeySeenState.asStateFlow() @@ -84,10 +94,16 @@ object SnapEngine { private val resumeCount = MutableStateFlow(0) val uiResumes: StateFlow = resumeCount.asStateFlow() - @Volatile private var learning: MutableList? = null + private var teachingSession: TeachingSession? = null + private val teachingState = MutableStateFlow(null) + internal val teaching: StateFlow = teachingState.asStateFlow() + private val delivery = TeachingDelivery() + private val inputDelivery = InputKeyDelivery(delivery) + private var nextTeachingId = 0L + private var teachingLogDemand = false private var inputLearningBoundary = Long.MIN_VALUE private var inputPressed = false - private var ignoreInputUntilUp = false + private var logResumeAfterMs = Long.MIN_VALUE private var mainUiVisible = false private var foregroundApp: String? = null private var consentVisible = false @@ -109,15 +125,14 @@ object SnapEngine { main.post { connectShizukuIfNeeded() } } @Volatile private var logGeneration = 0 - private val loggedKeysByThread = mutableMapOf() - private var loggedKeysGeneration = -1 + private val loggedKeys = LoggedKeyContext() private val logRetry = LogRetryBackoff() private var inputRetryDelayMs = 1000L private val reconnectInput = Runnable { - if (wantsLog && store.config.value.enabled && canUseShizuku()) inputReader.start() + if (wantsLog && readersDemanded() && canUseShizuku()) inputReader.start() } private val reconnect = Runnable { - if (wantsLog && store.config.value.enabled && hasLogPermission()) { + if (wantsLog && readersDemanded() && hasLogPermission()) { if (uiVisible || !reader.needsForegroundConsent()) reader.start() else startBackgroundLogs() } @@ -136,14 +151,22 @@ object SnapEngine { context = app, onLine = ::onLogLine, onAccess = ::onAccessChanged, - onSource = { sourceState.value = it }, + onSource = { + if (sourceState.value != it) invalidateTeachingSource(logs = true) + sourceState.value = it + }, dispatchAccess = { task -> main.post { task() }; Unit }, - shouldParse = { !preciseState.value || learning != null }, + shouldParse = { !preciseState.value || delivery.stamp.handle != null }, + onStart = { + logGeneration++ + teachingLogEdges.reset() + invalidateTeachingSource(logs = true) + }, ) - keyGestures = gestureDetector() - logGestures = gestureDetector() - inputGestures = gestureDetector() - inputReader = InputReader(app, ::onInputEvent, ::onInputLiveChanged) { task -> + keyGestures = gestureDetector(DetectionSource.KEY_EVENT) + logGestures = gestureDetector(DetectionSource.SYSTEM_LOG) + inputGestures = gestureDetector(DetectionSource.PRECISE_INPUT) + inputReader = InputReader(app, ::onInputEvent, ::onInputLiveChanged, { delivery.stamp }) { task -> main.post { task() }; Unit } Notifications.createChannel(app) @@ -153,7 +176,7 @@ object SnapEngine { scope.launch { store.config.map { Triple(it.enabled, it.needsLogAccess, it.isTaught) } .distinctUntilChanged().collect { (enabled, needsLog, _) -> - if (!enabled || !needsLog) { + if ((!enabled || !needsLog) && !teachingLogDemand) { consentAttempted = false stop() } else if (uiVisible && accessState.value == LogAccess.OFF) connect() @@ -165,12 +188,12 @@ object SnapEngine { fun now(): Long = SystemClock.elapsedRealtime() - private fun gestureDetector() = GestureDetector( + private fun gestureDetector(source: DetectionSource) = GestureDetector( schedule = { task, delay -> main.postDelayed(task, delay); Unit }, cancel = { task -> main.removeCallbacks(task) }, holdMs = { store.config.value.holdMs }, doublePressWindowMs = { store.config.value.doublePressWindowMs }, - onGesture = ::onGesture, + onGesture = { onGesture(it, source) }, ) fun hasLogPermission(): Boolean = @@ -178,7 +201,7 @@ object SnapEngine { /** Local readers need our screen on top; shell readers do not need foreground consent. */ fun connect(preferShizuku: Boolean = false) { - if (!store.config.value.enabled || !hasLogPermission()) return + if (!readersDemanded() || !hasLogPermission()) return wantLogs() main.removeCallbacks(reconnect) reader.start(preferShizuku) @@ -195,7 +218,19 @@ object SnapEngine { } } + internal fun prepareTeachingLogs() { + teachingLogDemand = true + connect() + } + + internal fun releaseTeachingLogs() { + if (teachingSession != null) return + teachingLogDemand = false + if (!readersDemanded()) stop() + } + fun stop() { + invalidateTeachingSource(logs = true, input = true) wantsLog = false if (watchingShizuku) { watchingShizuku = false @@ -215,6 +250,8 @@ object SnapEngine { private fun connectShizukuIfNeeded() { if (wantsLog && canUseShizuku()) inputReader.start() if (wantsLog && (accessState.value != LogAccess.FULL || sourceState.value == LogSource.LOCAL) && canUseShizuku()) { + invalidateTeachingSource(logs = true) + logGeneration++ reader.stop() connect(preferShizuku = true) } @@ -267,12 +304,15 @@ object SnapEngine { } fun onServiceConnected() { + invalidateTeachingSource(logs = false, accessibility = true) + refreshTeachingAccess() updateListeningSince() startBackgroundLogs() if (!uiVisible) notifyIfPaused() } fun onServiceDisconnected() { + refreshTeachingAccess() foregroundApp = null keyGestures.reset() updateListeningSince() @@ -294,11 +334,13 @@ object SnapEngine { } private fun onInputLiveChanged(live: Boolean) { + if (!live) inputDelivery.readerLost() inputLiveState.value = live + refreshTeachingAccess() updateInputSource() main.removeCallbacks(reconnectInput) if (live) inputRetryDelayMs = 1000L - else if (wantsLog && store.config.value.enabled && canUseShizuku()) { + else if (wantsLog && readersDemanded() && canUseShizuku()) { main.postDelayed(reconnectInput, inputRetryDelayMs) inputRetryDelayMs = (inputRetryDelayMs * 2).coerceAtMost(60_000L) } @@ -308,31 +350,35 @@ object SnapEngine { val config = store.config.value val precise = config.enabled && config.needsLogAccess && config.inputKey != null && inputLiveState.value if (precise != preciseState.value) { + invalidateTeachingSource(logs = true) + teachingLogEdges.reset() val alreadyHandled = precise && logGestures.hasHandledPress val releasedAfterSwitch = !precise && inputPressed logGeneration++ resetGestures() oplusEdges.reset(pressed = releasedAfterSwitch) inputPressed = releasedAfterSwitch - ignoreInputUntilUp = alreadyHandled + inputDelivery.suppressUntilUp(config.inputKey.takeIf { alreadyHandled }) preciseState.value = precise } updateListeningSince() } - private fun onInputEvent(event: InputKeyEvent, time: Long) { + private fun onInputEvent(event: InputKeyEvent, time: Long, stamp: TeachingDelivery.Stamp) { + if (preciseState.value && event.key == store.config.value.inputKey) inputPressed = event.down + inputDelivery.deliver(event, stamp) { ignored -> onCurrentInputEvent(event, time, ignored) } + } + + private fun onCurrentInputEvent(event: InputKeyEvent, time: Long, ignored: Boolean) { if (time <= inputLearningBoundary) return - learning?.let { list -> - if (event.down) synchronized(list) { list += Observation(time, KeyLearning.inputKey(event.key.code)) } + teachingSession?.let { session -> + session.observe(KeySample.Input(event), time) + publishTeaching() return } val config = store.config.value - if (!preciseState.value || event.key != config.inputKey) return - inputPressed = event.down - if (ignoreInputUntilUp) { - if (!event.down) ignoreInputUntilUp = false - return - } + if (!preciseState.value || !KeyMatching.matches(config.keyBinding(), KeySample.Input(event))) return + if (ignored) return inputGestures.wantsDouble = config.action(Gesture.DOUBLE) != SnapAction.NoAction inputGestures.wantsLong = config.action(Gesture.LONG) != SnapAction.NoAction inputGestures.wantsTapHold = config.action(Gesture.TAP_HOLD) != SnapAction.NoAction @@ -341,8 +387,14 @@ object SnapEngine { } private fun onAccessChanged(access: LogAccess) { + if (accessState.value == LogAccess.FULL && access != LogAccess.FULL) { + logGeneration++ + invalidateTeachingSource(logs = true) + } + if (access == LogAccess.WAITING) invalidateTeachingSource(logs = true) logRetry.onAccess(access, now()) accessState.value = access + refreshTeachingAccess() updateListeningSince() if (access == LogAccess.FULL) { consentAttempted = false @@ -356,7 +408,7 @@ object SnapEngine { if (!uiVisible) notifyIfPaused() } main.removeCallbacks(reconnect) - if (access == LogAccess.OFF && wantsLog && store.config.value.enabled && hasLogPermission()) { + if (access == LogAccess.OFF && wantsLog && readersDemanded() && hasLogPermission()) { main.postDelayed(reconnect, logRetry.nextDelayMs()) } } @@ -370,39 +422,28 @@ object SnapEngine { // Called on the logcat thread for every line from another process. private fun onLogLine(timestamp: String, uid: String, tid: String, tag: String, message: String) { - if (preciseState.value && learning == null) return + val stamp = delivery.stamp + val time = now() + if (preciseState.value && stamp.handle == null) return val generation = logGeneration - if (loggedKeysGeneration != generation) { - loggedKeysByThread.clear() - loggedKeysGeneration = generation - } - val keyCode = loggedKeyCode(uid, tag, message) - if (keyCode != null) loggedKeysByThread[tid] = keyCode - val lineKey = loggedKeysByThread[tid] + val sample = loggedKeys.sample(generation, stamp.epoch, uid, tid, tag, message) val explicitEdges = isKnownOplusKeyLine(uid, tag, message) - learning?.let { list -> - synchronized(list) { - if (learning === list) { - val time = now() - list += Observation(time, KeyLearning.logKey(uid, tag, message)) - if (keyCode != null) list += Observation(time, KeyLearning.loggedKey(keyCode)) + if (stamp.handle == null && !KeyMatching.matches(store.config.value.keyBinding(), sample)) return + main.post { + if (generation != logGeneration) return@post + teachingLogEdges.deliver(delivery, stamp, timestamp, sample, store.config.value.keyBinding(), oplusEdges) { + val session = teachingSession + if (stamp.handle != null) { + if (session == null) return@deliver + session.observe(sample, time) + publishTeaching() + return@deliver + } + val config = store.config.value + if (!config.enabled || preciseState.value || !config.needsLogAccess) return@deliver + if (KeyMatching.matches(config.keyBinding(), sample)) { + onLogKeyLine(timestamp, explicitEdges) } - } - if (explicitEdges) main.post { - if (generation == logGeneration) oplusEdges.observe(timestamp) - } - return - } - val config = store.config.value - if (preciseState.value) return - if (explicitEdges && !acceptsLoggedKey(config.logKeyCode, lineKey)) return - val isSnapKey = config.enabled && config.needsLogAccess && acceptsKeyLog(config.logSignature, uid, tag, message) - if (explicitEdges || isSnapKey) main.post { - if (generation != logGeneration || !store.config.value.enabled || preciseState.value) return@post - if (learning != null) { - if (explicitEdges) oplusEdges.observe(timestamp) - } else if (isSnapKey) { - onLogKeyLine(timestamp, explicitEdges) } } } @@ -418,6 +459,10 @@ object SnapEngine { oplusEdges.accept(timestamp) return } + if (now() < logResumeAfterMs) { + logResumeAfterMs = now() + config.releaseGapMs + return + } if (!logKeyDown) { logKeyDown = true markKeySeen() @@ -429,16 +474,15 @@ object SnapEngine { /** Called by the accessibility service. Returns true to stop the key from reaching other apps. */ fun onKeyEvent(event: KeyEvent): Boolean { - learning?.let { list -> - if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0 && event.keyCode !in IGNORED_KEYS) { - synchronized(list) { list += Observation(now(), KeyLearning.keyEventKey(event.keyCode, event.scanCode)) } - } + if (event.action != KeyEvent.ACTION_DOWN && event.action != KeyEvent.ACTION_UP) return false + val sample = KeySample.Accessibility(event.keyCode, event.scanCode, event.action == KeyEvent.ACTION_DOWN, event.repeatCount) + teachingSession?.let { session -> + session.observe(sample, now()) + publishTeaching() return false } val config = store.config.value - val key = config.keyEvent ?: return false - if (!config.enabled || event.keyCode != key.keyCode) return false - if (key.keyCode == KeyEvent.KEYCODE_UNKNOWN && event.scanCode != key.scanCode) return false + if (!config.enabled || !KeyMatching.matches(config.keyBinding(), sample)) return false keyGestures.wantsDouble = config.action(Gesture.DOUBLE) != SnapAction.NoAction keyGestures.wantsLong = config.action(Gesture.LONG) != SnapAction.NoAction keyGestures.wantsTapHold = config.action(Gesture.TAP_HOLD) != SnapAction.NoAction @@ -459,9 +503,12 @@ object SnapEngine { foregroundApp = packageName } - private fun onGesture(gesture: Gesture) { + private fun onGesture(gesture: Gesture, source: DetectionSource) { + if (teachingSession != null) return markKeySeen() - lastDetected.value = Detected(gesture, now()) + val detected = Detected(gesture, now(), source) + historyState.value = appendDetection(historyState.value, detected) + lastDetected.value = detected val config = store.config.value if (foregroundApp in config.pausedApps) return if (gesture in config.unlockedOnly && app.getSystemService(KeyguardManager::class.java).isKeyguardLocked) return @@ -476,70 +523,115 @@ object SnapEngine { vibrator.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK)) } - fun startLearning() { + internal fun beginTeaching(): TeachingHandle { + if (teachingSession != null) { + teachingLogEdges.restore(store.config.value.logKeyCode, oplusEdges) + teachingSession?.cancel() + } + val handle = TeachingHandle(++nextTeachingId) inputLearningBoundary = now() resetGestures() - learning = mutableListOf() + teachingLogEdges.begin(store.config.value.logKeyCode, oplusEdges) + oplusEdges.reset() + teachingSession = TeachingSession(teachingAccess()) + delivery.advance(handle) + teachingLogDemand = true + publishTeaching() + connect() + return handle } /** Called after the hands-off step: the key is released and lines from earlier presses have been handled. */ - fun markKeyReleased() { + internal fun markKeyReleased(handle: TeachingHandle) { + if (delivery.stamp.handle != handle || teachingSession?.state != TeachingState.Capturing) return + delivery.discardPending() oplusEdges.reset() + teachingLogEdges.reset() } private fun resetGestures() { main.removeCallbacks(logKeyUp) logKeyDown = false inputPressed = false - ignoreInputUntilUp = false + inputDelivery.suppressUntilUp(null) keyGestures.reset() logGestures.reset() inputGestures.reset() } - fun cancelLearning() { - if (learning == null) return - inputLearningBoundary = now() - resetGestures() - learning = null + internal fun cancelTeaching(handle: TeachingHandle) { + if (delivery.stamp.handle != handle) return + teachingSession?.cancel() + endTeaching() + } + + internal fun captureTeaching(handle: TeachingHandle, baseline: LongRange, taps: List, hold: LongRange) { + if (delivery.stamp.handle != handle || teachingSession?.state != TeachingState.Capturing) return + teachingSession?.capture(baseline, taps, hold) + delivery.advance(handle) + publishTeaching() + } + + internal fun checkDifferentKey(handle: TeachingHandle) { + if (delivery.stamp.handle != handle || teachingSession?.state !is TeachingState.Candidate) return + refreshTeachingAccess() + delivery.advance(handle) + teachingSession?.beginCheck(now()) + publishTeaching() + } + + internal fun finishDifferentKeyCheck(handle: TeachingHandle) { + if (delivery.stamp.handle != handle) return + refreshTeachingAccess() + teachingSession?.finishCheck(now()) + publishTeaching() + } + + internal fun saveTeaching(handle: TeachingHandle): Boolean { + if (delivery.stamp.handle != handle) return false + refreshTeachingAccess() + val saved = teachingSession?.save { patch -> store.updateConfirmed(patch::applyTo) } == true + publishTeaching() + if (!saved) return false + endTeaching() + return true } - fun finishLearning(baseline: LongRange, taps: List, hold: LongRange): LearnResult { - val list = learning ?: return LearnResult.NothingFound + private fun endTeaching() { inputLearningBoundary = now() resetGestures() - val observations = synchronized(list) { - learning = null - list.toList() - } - val result = KeyLearning.analyze(observations, baseline, taps, hold) - when (result) { - is LearnResult.KeyEventFound -> store.update { - it.copy(keyEvent = result.key, logSignature = null, inputKey = result.inputKey, logKeyCode = null) - } - is LearnResult.LogLineFound -> store.update { - it.copy( - keyEvent = null, - logSignature = result.signature, - inputKey = result.inputKey, - logKeyCode = result.logKeyCode, - holdRepeats = result.holdRepeats, - releaseGapMs = result.releaseGapMs, - ) - } - LearnResult.NothingFound -> Unit - } + teachingSession = null + delivery.advance(null) + teachingState.value = null + teachingLogDemand = false + val config = store.config.value + if (!config.enabled || !config.needsLogAccess) stop() + else if (hasLogPermission() && accessState.value == LogAccess.OFF) connect() updateInputSource() - return result + teachingLogEdges.restore(store.config.value.logKeyCode, oplusEdges) + teachingLogEdges.reset() + inputPressed = inputDelivery.suppressHeld(store.config.value.inputKey) + logResumeAfterMs = now() + store.config.value.releaseGapMs } - private val IGNORED_KEYS = setOf( - KeyEvent.KEYCODE_VOLUME_UP, - KeyEvent.KEYCODE_VOLUME_DOWN, - KeyEvent.KEYCODE_VOLUME_MUTE, - KeyEvent.KEYCODE_POWER, - KeyEvent.KEYCODE_BACK, - KeyEvent.KEYCODE_HOME, - KeyEvent.KEYCODE_APP_SWITCH, + private fun readersDemanded(): Boolean = teachingLogDemand || + (store.config.value.enabled && store.config.value.needsLogAccess) + + private fun teachingAccess() = TeachingAccess( + SnapAccessibilityService.running.value, accessState.value, inputLiveState.value, ) + + private fun refreshTeachingAccess() { + teachingSession?.accessChanged(teachingAccess()) + publishTeaching() + } + + private fun invalidateTeachingSource(logs: Boolean, input: Boolean = false, accessibility: Boolean = false) { + teachingSession?.sourceRestarted(logs, input, accessibility) + publishTeaching() + } + + private fun publishTeaching() { + teachingState.value = teachingSession?.state + } } diff --git a/app/src/main/java/com/heykay/snapkeymap/SnapTileService.kt b/app/src/main/java/com/heykay/snapkeymap/SnapTileService.kt new file mode 100644 index 0000000..5648f85 --- /dev/null +++ b/app/src/main/java/com/heykay/snapkeymap/SnapTileService.kt @@ -0,0 +1,83 @@ +package com.heykay.snapkeymap + +import android.app.PendingIntent +import android.content.Intent +import android.os.Build +import android.service.quicksettings.Tile +import android.service.quicksettings.TileService +import com.heykay.snapkeymap.ui.MainActivity +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.launch + +internal fun tileState(config: Config, hasLogPermission: Boolean): Int = when { + !config.isTaught || (config.needsLogAccess && !hasLogPermission) -> Tile.STATE_UNAVAILABLE + config.enabled -> Tile.STATE_ACTIVE + else -> Tile.STATE_INACTIVE +} + +class SnapTileService : TileService() { + private var listeningScope: CoroutineScope? = null + + override fun onStartListening() { + super.onStartListening() + listeningScope?.cancel() + render(SnapEngine.store.config.value) + listeningScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate).also { scope -> + scope.launch { + SnapEngine.store.config.collect { render(it) } + } + } + } + + override fun onStopListening() { + listeningScope?.cancel() + listeningScope = null + super.onStopListening() + } + + override fun onDestroy() { + listeningScope?.cancel() + super.onDestroy() + } + + override fun onClick() { + super.onClick() + if (isLocked) unlockAndRun { handleClick() } + else handleClick() + } + + private fun handleClick() { + val config = SnapEngine.store.config.value + if (tileState(config, SnapEngine.hasLogPermission()) == Tile.STATE_UNAVAILABLE) { + openApp() + } else { + SnapEngine.store.update { it.copy(enabled = !it.enabled) } + render(SnapEngine.store.config.value) + } + } + + private fun render(config: Config) { + val tile = qsTile ?: return + tile.state = tileState(config, SnapEngine.hasLogPermission()) + tile.label = getString(R.string.snap_tile_label) + tile.subtitle = getString(when (tile.state) { + Tile.STATE_ACTIVE -> R.string.snap_tile_on + Tile.STATE_INACTIVE -> R.string.snap_tile_off + else -> R.string.snap_tile_setup + }) + tile.updateTile() + } + + @Suppress("DEPRECATION") + private fun openApp() { + val intent = Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + if (Build.VERSION.SDK_INT >= 34) { + startActivityAndCollapse(PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)) + } else { + startActivityAndCollapse(intent) + } + } +} diff --git a/app/src/main/java/com/heykay/snapkeymap/TeachingDelivery.kt b/app/src/main/java/com/heykay/snapkeymap/TeachingDelivery.kt new file mode 100644 index 0000000..b4e6273 --- /dev/null +++ b/app/src/main/java/com/heykay/snapkeymap/TeachingDelivery.kt @@ -0,0 +1,25 @@ +package com.heykay.snapkeymap + +internal data class TeachingHandle(val id: Long) + +internal class TeachingDelivery { + data class Stamp(val epoch: Long, val handle: TeachingHandle?) + + @Volatile var stamp = Stamp(0, null) + private set + private var observeFromEpoch = 0L + + fun advance(handle: TeachingHandle?) { + stamp = Stamp(stamp.epoch + 1, handle) + } + + fun discardPending() { + advance(stamp.handle) + observeFromEpoch = stamp.epoch + } + + fun deliver(receipt: Stamp, onStale: () -> Unit = {}, action: () -> Unit) { + if (receipt == stamp) action() + else if (receipt.epoch >= observeFromEpoch) onStale() + } +} diff --git a/app/src/main/java/com/heykay/snapkeymap/TeachingSession.kt b/app/src/main/java/com/heykay/snapkeymap/TeachingSession.kt new file mode 100644 index 0000000..1de2116 --- /dev/null +++ b/app/src/main/java/com/heykay/snapkeymap/TeachingSession.kt @@ -0,0 +1,209 @@ +package com.heykay.snapkeymap + +internal data class TeachingAccess(val accessibility: Boolean, val fullLogs: Boolean, val inputLive: Boolean) { + constructor(accessibility: Boolean, logs: LogAccess, inputLive: Boolean) : + this(accessibility, logs == LogAccess.FULL, inputLive) +} + +internal enum class TeachingFailure { NOT_FOUND, COLLISION, NO_DIFFERENT_KEY, ACCESS_LOST } + +internal sealed interface TeachingState { + data object Capturing : TeachingState + data class Candidate(val result: LearnResult) : TeachingState + data class Checking(val result: LearnResult, val startedAtMs: Long) : TeachingState + data class Ready(val result: LearnResult) : TeachingState + data class SaveFailed(val result: LearnResult) : TeachingState + data class Failed(val reason: TeachingFailure) : TeachingState + data object Closed : TeachingState +} + +internal class TeachingSession(private var access: TeachingAccess) { + var state: TeachingState = TeachingState.Capturing + private set + private val observations = mutableListOf() + private sealed interface WitnessKey { + data class Accessibility(val key: LearnedKey) : WitnessKey + data class Input(val key: InputKey) : WitnessKey + data class LoggedVolume(val threadId: String, val code: String) : WitnessKey + } + private val pressed = mutableSetOf() + private var completedPress = false + + fun observe(sample: KeySample, atMs: Long) { + when (val current = state) { + TeachingState.Capturing -> captureSample(sample, atMs) + is TeachingState.Checking -> { + if (atMs < current.startedAtMs) return + if (KeyMatching.matches(current.result.binding(), sample)) { + fail(TeachingFailure.COLLISION) + return + } + if (atMs <= current.startedAtMs + CHECK_MS + SETTLE_MS) { + witness(current.result, sample, atMs <= current.startedAtMs + CHECK_MS) + } + } + else -> { + val result = validatedResult() ?: return + if (KeyMatching.matches(result.binding(), sample)) fail(TeachingFailure.COLLISION) + } + } + } + + fun capture(baseline: LongRange, taps: List, hold: LongRange) { + if (state != TeachingState.Capturing) return + val result = KeyLearning.analyze(observations, baseline, taps, hold) + observations.clear() + state = if (result == LearnResult.NothingFound) TeachingState.Failed(TeachingFailure.NOT_FOUND) + else TeachingState.Candidate(result) + } + + fun beginCheck(atMs: Long) { + val candidate = state as? TeachingState.Candidate ?: return + if (!requiredAccess(candidate.result)) { + fail(TeachingFailure.ACCESS_LOST) + return + } + pressed.clear() + completedPress = false + state = TeachingState.Checking(candidate.result, atMs) + } + + fun finishCheck(atMs: Long) { + val current = state as? TeachingState.Checking ?: return + if (atMs < current.startedAtMs + CHECK_MS + SETTLE_MS) return + state = when { + !requiredAccess(current.result) -> TeachingState.Failed(TeachingFailure.ACCESS_LOST) + !completedPress || pressed.isNotEmpty() -> TeachingState.Failed(TeachingFailure.NO_DIFFERENT_KEY) + else -> TeachingState.Ready(current.result) + } + } + + fun accessChanged(next: TeachingAccess) { + access = next + val result = when (val current = state) { + is TeachingState.Checking -> current.result + else -> validatedResult() ?: return + } + if (!requiredAccess(result)) fail(TeachingFailure.ACCESS_LOST) + } + + fun sourceRestarted(logs: Boolean, input: Boolean = false, accessibility: Boolean = false) { + val result = when (val current = state) { + is TeachingState.Checking -> current.result + else -> validatedResult() ?: return + } + if ((result is LearnResult.KeyEventFound && accessibility) || + (result is LearnResult.LogLineFound && (logs || (input && result.inputKey != null)))) { + fail(TeachingFailure.ACCESS_LOST) + } + } + + fun save(write: (LearnedKeyPatch) -> Boolean): Boolean { + val result = validatedResult() ?: return false + if (!requiredAccess(result)) { + fail(TeachingFailure.ACCESS_LOST) + return false + } + val saved = runCatching { write(LearnedKeyPatch(result)) }.getOrDefault(false) + state = if (saved) TeachingState.Closed else TeachingState.SaveFailed(result) + return saved + } + + private fun validatedResult(): LearnResult? = when (val current = state) { + is TeachingState.Ready -> current.result + is TeachingState.SaveFailed -> current.result + else -> null + } + + fun cancel() { + observations.clear() + pressed.clear() + state = TeachingState.Closed + } + + private fun requiredAccess(result: LearnResult): Boolean = when (result) { + is LearnResult.KeyEventFound -> access.accessibility + is LearnResult.LogLineFound -> access.fullLogs && (result.inputKey == null || access.inputLive) + LearnResult.NothingFound -> false + } + + private fun fail(reason: TeachingFailure) { + pressed.clear() + state = TeachingState.Failed(reason) + } + + private fun captureSample(sample: KeySample, atMs: Long) { + when (sample) { + is KeySample.Accessibility -> if (sample.down && sample.repeat == 0 && sample.code !in IGNORED_CAPTURE_KEYS) { + observations += Observation(atMs, KeyLearning.keyEventKey(sample.code, sample.scan)) + } + is KeySample.Input -> if (sample.event.down) { + observations += Observation(atMs, KeyLearning.inputKey(sample.event.key.code)) + } + is KeySample.Log -> { + observations += Observation(atMs, KeyLearning.logKey(sample.uid, sample.tag, sample.message)) + loggedKeyCode(sample.uid, sample.tag, sample.message)?.let { + observations += Observation(atMs, KeyLearning.loggedKey(it)) + } + } + } + } + + private fun witness(result: LearnResult, sample: KeySample, allowDown: Boolean) { + val edge: Pair = when (sample) { + is KeySample.Accessibility -> { + if (sample.repeat != 0) return + WitnessKey.Accessibility(LearnedKey(sample.code, if (sample.code == 0) sample.scan else 0)) to sample.down + } + is KeySample.Input -> { + if (result !is LearnResult.LogLineFound) return + val code = sample.event.key.code + if (code == "BTN_TOUCH" || code.startsWith("BTN_TOOL_") || code.startsWith("BTN_STYLUS")) return + WitnessKey.Input(sample.event.key) to sample.event.down + } + is KeySample.Log -> { + if (result !is LearnResult.LogLineFound) return + val code = loggedKeyCode(sample.uid, sample.tag, sample.message) ?: return + if (code !in VOLUME_CODES || code == result.logKeyCode) return + val action = LOG_ACTION.find(sample.message)?.groupValues?.get(1) ?: return + WitnessKey.LoggedVolume(sample.threadId, code) to (action == "ACTION_DOWN" || action == "0") + } + } + if (edge.second) { + if (allowDown) pressed += edge.first + } else if (pressed.remove(edge.first)) completedPress = true + } + + private fun LearnResult.binding(): KeyBinding = when (this) { + is LearnResult.KeyEventFound -> KeyBinding.Direct(key) + is LearnResult.LogLineFound -> KeyBinding.Logged(signature, logKeyCode, inputKey) + LearnResult.NothingFound -> error("No candidate") + } + + internal class LearnedKeyPatch(private val result: LearnResult) { + private var used = false + + fun applyTo(current: Config): Config { + check(!used) { "Teaching patch already used" } + used = true + return when (result) { + is LearnResult.KeyEventFound -> current.copy( + keyEvent = result.key, logSignature = null, logKeyCode = null, inputKey = result.inputKey, + ) + is LearnResult.LogLineFound -> current.copy( + keyEvent = null, logSignature = result.signature, logKeyCode = result.logKeyCode, + inputKey = result.inputKey, holdRepeats = result.holdRepeats, releaseGapMs = result.releaseGapMs, + ) + LearnResult.NothingFound -> error("No candidate") + } + } + } + + companion object { + const val CHECK_MS = 5000L + const val SETTLE_MS = 750L + private val IGNORED_CAPTURE_KEYS = setOf(24, 25, 164, 26, 4, 3, 187) + private val VOLUME_CODES = setOf("KEYCODE_VOLUME_UP", "KEYCODE_VOLUME_DOWN", "KEYCODE_VOLUME_MUTE", "24", "25", "164") + private val LOG_ACTION = Regex("""\baction=(ACTION_DOWN|ACTION_UP|0|1)(?=[,\s}])""") + } +} diff --git a/app/src/main/java/com/heykay/snapkeymap/ui/HelpScreen.kt b/app/src/main/java/com/heykay/snapkeymap/ui/HelpScreen.kt index c56a559..c3fc8f2 100644 --- a/app/src/main/java/com/heykay/snapkeymap/ui/HelpScreen.kt +++ b/app/src/main/java/com/heykay/snapkeymap/ui/HelpScreen.kt @@ -59,7 +59,7 @@ fun HelpScreen(onDone: () -> Unit, onRunSetup: () -> Unit) { "3. Enable accessibility to run actions and open apps from the background. It cannot read screen content.\n\n" + "4. Optionally allow background operation to reduce ColorOS interruptions.\n\n" + "5. Optionally allow notifications for detection paused alerts.\n\n" + - "6. Set Oppo's Snap Key action to None. Teach the key: press three times, then hold once.\n\n" + + "6. Set Oppo's Snap Key action to None. Teach the key: press three times, hold once, then check a different key and save.\n\n" + "7. Choose Press, Double press, Press & hold and Tap, then hold actions, then tap Finish. Test them and check Last:.\n\n" + "Tap the lock next to a gesture to run it only when your phone is unlocked.", ) diff --git a/app/src/main/java/com/heykay/snapkeymap/ui/HomeScreen.kt b/app/src/main/java/com/heykay/snapkeymap/ui/HomeScreen.kt index 1af76f7..7141012 100644 --- a/app/src/main/java/com/heykay/snapkeymap/ui/HomeScreen.kt +++ b/app/src/main/java/com/heykay/snapkeymap/ui/HomeScreen.kt @@ -1,12 +1,19 @@ package com.heykay.snapkeymap.ui import android.annotation.SuppressLint +import android.content.ActivityNotFoundException +import android.content.ClipData +import android.content.ClipboardManager import android.content.Intent import android.content.pm.PackageManager import android.net.Uri +import android.os.Build import android.os.PowerManager import android.provider.Settings import android.text.format.DateFormat +import android.widget.Toast +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement @@ -19,6 +26,7 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.calculateEndPadding import androidx.compose.foundation.layout.calculateStartPadding @@ -35,9 +43,12 @@ import androidx.compose.material.icons.rounded.Info import androidx.compose.material.icons.rounded.Lock import androidx.compose.material.icons.rounded.LockOpen import androidx.compose.material.icons.rounded.Notifications +import androidx.compose.material.icons.rounded.PlayArrow import androidx.compose.material.icons.rounded.Settings import androidx.compose.material.icons.rounded.AvTimer import androidx.compose.material.icons.rounded.Apps +import androidx.compose.material.icons.rounded.Save +import androidx.compose.material.icons.rounded.Restore import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Card @@ -65,6 +76,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -85,7 +97,10 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.text.style.TextOverflow import androidx.core.app.NotificationManagerCompat import com.heykay.snapkeymap.Gesture +import com.heykay.snapkeymap.ActionRunner import com.heykay.snapkeymap.Config +import com.heykay.snapkeymap.BackupResult +import com.heykay.snapkeymap.SettingsBackup import com.heykay.snapkeymap.LogAccess import com.heykay.snapkeymap.LogSource import com.heykay.snapkeymap.R @@ -93,14 +108,22 @@ import com.heykay.snapkeymap.SnapAccessibilityService import com.heykay.snapkeymap.SnapAction import com.heykay.snapkeymap.SnapEngine import com.heykay.snapkeymap.ThemeMode +import com.heykay.snapkeymap.buildReport +import com.heykay.snapkeymap.bugReportUrl +import com.heykay.snapkeymap.gatherReportInfo +import com.heykay.snapkeymap.backupToJson +import com.heykay.snapkeymap.parseBackup +import java.time.LocalDate import java.util.Date import kotlin.math.roundToInt import kotlinx.coroutines.delay import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import rikka.shizuku.Shizuku private const val SHIZUKU_LOG_REQUEST = 2 +private const val MAX_BACKUP_BYTES = 1024 * 1024 private data class HomeChecks( val hasLogPermission: Boolean = false, @@ -135,6 +158,57 @@ fun HomeScreen( var showTiming by rememberSaveable { mutableStateOf(false) } var showPausedApps by rememberSaveable { mutableStateOf(false) } var showUnlockHint by rememberSaveable { mutableStateOf(false) } + var showBackupWarning by rememberSaveable { mutableStateOf(false) } + var pendingRestore by remember { mutableStateOf(null) } + val scope = rememberCoroutineScope() + val backupFile = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/json")) { uri -> + if (uri == null) return@rememberLauncherForActivityResult + val snapshot = SnapEngine.store.config.value + scope.launch { + val result = withContext(Dispatchers.IO) { + runCatching { + val text = backupToJson(snapshot) + val output = checkNotNull(context.contentResolver.openOutputStream(uri, "wt")) + output.bufferedWriter(Charsets.UTF_8).use { it.write(text) } + } + } + Toast.makeText(context, if (result.isSuccess) "Settings backed up" else "Couldn't write the backup file.", Toast.LENGTH_SHORT).show() + } + } + val restoreFile = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri == null) return@rememberLauncherForActivityResult + scope.launch { + val result = withContext(Dispatchers.IO) { + runCatching { + val input = checkNotNull(context.contentResolver.openInputStream(uri)) + val text = input.use { stream -> + val bytes = ByteArray(MAX_BACKUP_BYTES + 1) + var size = 0 + while (size < bytes.size) { + val count = stream.read(bytes, size, bytes.size - size) + if (count < 0) break + size += count + } + require(size <= MAX_BACKUP_BYTES) { "The backup file is too large. Choose a file smaller than 1 MB." } + String(bytes, 0, size, Charsets.UTF_8) + } + parseBackup(text) + } + } + result.fold( + onSuccess = { parsed -> + when (parsed) { + is BackupResult.Ok -> pendingRestore = parsed.backup + is BackupResult.Error -> Toast.makeText(context, parsed.message, Toast.LENGTH_LONG).show() + } + }, + onFailure = { error -> + val message = if (error is IllegalArgumentException) error.message else "Couldn't read the backup file." + Toast.makeText(context, message, Toast.LENGTH_LONG).show() + }, + ) + } + } val pausedSummary by produceState("None", config.pausedApps, resumes, lifecycle) { lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { value = withContext(Dispatchers.Default) { @@ -272,6 +346,13 @@ fun HomeScreen( if (on && !config.unlockHintShown) showUnlockHint = true }, onClick = { onPick(gesture) }, + onTry = { + ActionRunner.run( + SnapAccessibilityService.instance ?: context, + config.action(gesture), + alwaysConfirm = true, + ) + }, ) } } @@ -320,6 +401,35 @@ fun HomeScreen( ) } } + item { SectionHeader("Backup") } + item { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow), + ) { + ListItem( + modifier = Modifier.clickable { showBackupWarning = true }, + colors = ListItemDefaults.colors(containerColor = Color.Transparent), + headlineContent = { Text("Back up settings") }, + leadingContent = { Icon(Icons.Rounded.Save, contentDescription = null) }, + trailingContent = { Icon(Icons.AutoMirrored.Rounded.KeyboardArrowRight, contentDescription = null) }, + ) + HorizontalDivider() + ListItem( + modifier = Modifier.clickable { + try { + restoreFile.launch(arrayOf("application/json", "text/plain", "application/octet-stream")) + } catch (_: ActivityNotFoundException) { + Toast.makeText(context, "No file picker available", Toast.LENGTH_SHORT).show() + } + }, + colors = ListItemDefaults.colors(containerColor = Color.Transparent), + headlineContent = { Text("Restore settings") }, + leadingContent = { Icon(Icons.Rounded.Restore, contentDescription = null) }, + trailingContent = { Icon(Icons.AutoMirrored.Rounded.KeyboardArrowRight, contentDescription = null) }, + ) + } + } item { SectionHeader("Tips") } item { NoteCard( @@ -361,6 +471,39 @@ fun HomeScreen( } if (showTiming) TimingDialog(config = config, onDismiss = { showTiming = false }) if (showPausedApps) PausedAppsSheet(onDismiss = { showPausedApps = false }) + if (showBackupWarning) { + AlertDialog( + onDismissRequest = { showBackupWarning = false }, + title = { Text("Back up settings") }, + text = { Text("The file can contain contact numbers, links and app names. It is saved only where you choose.") }, + confirmButton = { + TextButton(onClick = { + showBackupWarning = false + try { + backupFile.launch("snapkeymap-backup-${LocalDate.now()}.json") + } catch (_: ActivityNotFoundException) { + Toast.makeText(context, "No file picker available", Toast.LENGTH_SHORT).show() + } + }) { Text("Continue") } + }, + dismissButton = { TextButton(onClick = { showBackupWarning = false }) { Text("Cancel") } }, + ) + } + pendingRestore?.let { backup -> + AlertDialog( + onDismissRequest = { pendingRestore = null }, + title = { Text("Restore settings?") }, + text = { Text("This replaces your gesture actions, ringer presets, paused apps, timing, theme, confirmations and the learned key.") }, + confirmButton = { + TextButton(onClick = { + SnapEngine.store.update { backup.applyTo(it) } + pendingRestore = null + Toast.makeText(context, "Settings restored", Toast.LENGTH_SHORT).show() + }) { Text("Restore") } + }, + dismissButton = { TextButton(onClick = { pendingRestore = null }) { Text("Cancel") } }, + ) + } if (showUnlockHint) UnlockHintDialog(onDismiss = { SnapEngine.store.update { it.copy(unlockHintShown = true) } showUnlockHint = false @@ -439,7 +582,8 @@ private fun StatusCard( now: Long, canAskShizuku: Boolean, ) { - val timeFormat = DateFormat.getTimeFormat(LocalContext.current) + val context = LocalContext.current + val timeFormat = DateFormat.getTimeFormat(context) var showDetails by rememberSaveable { mutableStateOf(false) } val colors = MaterialTheme.colorScheme val ready = warning == null && enabled && listening @@ -510,6 +654,31 @@ private fun StatusCard( color = colors.onSurfaceVariant, ) } + Row(Modifier.offset(x = (-12).dp)) { + TextButton(onClick = { + val info = gatherReportInfo(context, config, precise) + val wallOffset = System.currentTimeMillis() - SnapEngine.now() + val secondsFormat = java.text.DateFormat.getTimeInstance(java.text.DateFormat.MEDIUM) + val report = buildReport(info, config, SnapEngine.detections.value) { + secondsFormat.format(Date(wallOffset + it)) + } + context.getSystemService(ClipboardManager::class.java) + .setPrimaryClip(ClipData.newPlainText("SnapKey Map bug report", report)) + if (Build.VERSION.SDK_INT < 33) Toast.makeText(context, "Report copied", Toast.LENGTH_SHORT).show() + }) { Text("Copy report") } + TextButton(onClick = { + val info = gatherReportInfo(context, config, precise) + val wallOffset = System.currentTimeMillis() - SnapEngine.now() + val url = bugReportUrl(info, config, SnapEngine.lastGesture.value) { + timeFormat.format(Date(wallOffset + it)) + } + try { + context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) + } catch (_: ActivityNotFoundException) { + Toast.makeText(context, "No browser available to open the bug form", Toast.LENGTH_SHORT).show() + } + }) { Text("Report a bug") } + } } if (warning != null) { Button(onClick = onFix) { Text("Fix") } @@ -538,7 +707,14 @@ internal fun GestureRow( unlockedOnly: Boolean, onUnlockedOnlyChange: (Boolean) -> Unit, onClick: () -> Unit, + onTry: (() -> Unit)? = null, ) { + val context = LocalContext.current + val resumes by SnapEngine.uiResumes.collectAsStateWithLifecycle() + val packageName = (action as? SnapAction.OpenApp)?.packageName + val missingApp = remember(packageName, resumes) { + packageName != null && context.packageManager.getLaunchIntentForPackage(packageName) == null + } ListItem( modifier = Modifier.clickable(enabled = available, onClick = onClick), colors = ListItemDefaults.colors(containerColor = Color.Transparent), @@ -548,7 +724,7 @@ internal fun GestureRow( if (available) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { Icon(actionIcon(action), contentDescription = null, modifier = Modifier.size(16.dp)) - Text(action.label, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(if (missingApp) "App not installed" else action.label, maxLines = 1, overflow = TextOverflow.Ellipsis) } } else { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { @@ -561,6 +737,11 @@ internal fun GestureRow( if (available) { Row(verticalAlignment = Alignment.CenterVertically) { if (action != SnapAction.NoAction) { + if (onTry != null) { + IconButton(onClick = onTry) { + Icon(Icons.Rounded.PlayArrow, contentDescription = "Try ${gesture.title}") + } + } IconToggleButton(checked = unlockedOnly, onCheckedChange = onUnlockedOnlyChange) { Icon( if (unlockedOnly) Icons.Rounded.Lock else Icons.Rounded.LockOpen, diff --git a/app/src/main/java/com/heykay/snapkeymap/ui/LearnScreen.kt b/app/src/main/java/com/heykay/snapkeymap/ui/LearnScreen.kt index c9faa49..edaaab3 100644 --- a/app/src/main/java/com/heykay/snapkeymap/ui/LearnScreen.kt +++ b/app/src/main/java/com/heykay/snapkeymap/ui/LearnScreen.kt @@ -1,5 +1,6 @@ package com.heykay.snapkeymap.ui +import androidx.activity.compose.BackHandler import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize @@ -25,8 +26,6 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue @@ -36,57 +35,100 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.heykay.snapkeymap.LearnResult import com.heykay.snapkeymap.LogAccess import com.heykay.snapkeymap.SnapAccessibilityService import com.heykay.snapkeymap.SnapEngine +import com.heykay.snapkeymap.TeachingFailure +import com.heykay.snapkeymap.TeachingHandle +import com.heykay.snapkeymap.TeachingSession +import com.heykay.snapkeymap.TeachingState import kotlinx.coroutines.delay -private sealed interface LearnState { - data object Intro : LearnState - data class Running(val prompt: String, val detail: String, val progress: Float) : LearnState - data class Finished(val result: LearnResult) : LearnState -} +private data class LearnPrompt(val prompt: String, val detail: String, val progress: Float) @Composable fun LearnScreen(onDone: () -> Unit) { - var state by remember { mutableStateOf(LearnState.Intro) } - var runs by remember { mutableIntStateOf(0) } - var finishedAt by remember { mutableLongStateOf(Long.MAX_VALUE) } + var handle by remember { mutableStateOf(null) } + var prompt by remember { mutableStateOf(LearnPrompt("Hands off", "Don't touch the phone for a moment…", 0f)) } + val teaching by SnapEngine.teaching.collectAsStateWithLifecycle() + val lifecycle = LocalLifecycleOwner.current.lifecycle + val cancel = { + handle?.let(SnapEngine::cancelTeaching) + handle = null + } + val leave = { + cancel() + SnapEngine.releaseTeachingLogs() + onDone() + } + val retry = { + prompt = LearnPrompt("Hands off", "Don't touch the phone for a moment…", 0f) + handle = SnapEngine.beginTeaching() + } - LaunchedEffect(runs) { - if (runs == 0) return@LaunchedEffect - SnapEngine.startLearning() + LaunchedEffect(handle) { + val owner = handle ?: return@LaunchedEffect - suspend fun phase(prompt: String, detail: String, millis: Long): LongRange { + suspend fun phase(title: String, detail: String, millis: Long): LongRange { val start = SnapEngine.now() while (true) { val elapsed = SnapEngine.now() - start if (elapsed >= millis) break - state = LearnState.Running(prompt, detail, elapsed / millis.toFloat()) + prompt = LearnPrompt(title, detail, elapsed / millis.toFloat()) delay(50) } return start..SnapEngine.now() } val baseline = phase("Hands off", "Don't touch the phone for a moment…", 5000) - SnapEngine.markKeyReleased() + SnapEngine.markKeyReleased(owner) val taps = (1..3).map { round -> val window = phase("Press the Snap Key once", "Press $round of 3", 3000) phase("Let go", "Get ready for the next one…", 1000) window } val hold = phase("Now press and hold it", "Keep holding until the bar is full", 3500) - val result = SnapEngine.finishLearning(baseline, taps, hold) - finishedAt = SnapEngine.now() - state = LearnState.Finished(result) + SnapEngine.captureTeaching(owner, baseline, taps, hold) + } + val checking = teaching as? TeachingState.Checking + LaunchedEffect(handle, checking?.startedAtMs) { + val owner = handle ?: return@LaunchedEffect + val start = checking?.startedAtMs ?: return@LaunchedEffect + val duration = TeachingSession.CHECK_MS + TeachingSession.SETTLE_MS + while (SnapEngine.now() - start < duration) { + val elapsed = SnapEngine.now() - start + prompt = LearnPrompt( + if (elapsed < TeachingSession.CHECK_MS) "Press a different key once, then release it" else "Hands off", + if (elapsed < TeachingSession.CHECK_MS) "A volume key is recommended. Do not touch the Snap Key." + else "Checking the last events…", + (elapsed / duration.toFloat()).coerceIn(0f, 1f), + ) + delay(50) + } + SnapEngine.finishDifferentKeyCheck(owner) } - DisposableEffect(Unit) { - onDispose { SnapEngine.cancelLearning() } + DisposableEffect(lifecycle) { + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_STOP) { + cancel() + SnapEngine.releaseTeachingLogs() + } + } + lifecycle.addObserver(observer) + onDispose { + cancel() + SnapEngine.releaseTeachingLogs() + lifecycle.removeObserver(observer) + } } + BackHandler(onBack = leave) - SnapScaffold(title = "Teach your Snap Key", onBack = onDone) { padding -> + SnapScaffold(title = "Teach your Snap Key", onBack = leave) { padding -> Column( modifier = Modifier .fillMaxSize() @@ -95,18 +137,21 @@ fun LearnScreen(onDone: () -> Unit) { .padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp), ) { - when (val current = state) { - LearnState.Intro -> Intro(onStart = { runs++ }) - is LearnState.Running -> Running(current, onCancel = { - runs = 0 - SnapEngine.cancelLearning() - state = LearnState.Intro - }) - is LearnState.Finished -> Finished( - result = current.result, - finishedAt = finishedAt, - onRetry = { runs++ }, - onDone = onDone, + when (val current = teaching.takeIf { handle != null }) { + null, TeachingState.Closed -> Intro(onStart = retry) + TeachingState.Capturing, is TeachingState.Checking -> Running(prompt, onCancel = leave) + else -> TeachingResult( + state = current, + onCheck = { + prompt = LearnPrompt( + "Press a different key once, then release it", + "A volume key is recommended. Do not touch the Snap Key.", 0f, + ) + handle?.let(SnapEngine::checkDifferentKey) + }, + onSave = { handle?.let { if (SnapEngine.saveTeaching(it)) onDone() } }, + onRetry = retry, + onBack = leave, ) } } @@ -124,7 +169,7 @@ private fun Intro(onStart: () -> Unit) { val logReady = !hasLogPermission || access == LogAccess.FULL Text( - "You'll press the key 3 times, then hold it once. It takes about 20 seconds.", + "You'll press the key 3 times, hold it once, then check a different key before saving. It takes about 30 seconds.", style = MaterialTheme.typography.bodyLarge, ) NoteCard( @@ -163,7 +208,7 @@ private fun Intro(onStart: () -> Unit) { }, ) { if (access != LogAccess.WAITING) { - CardTextButton("Connect") { SnapEngine.connect() } + CardTextButton("Connect") { SnapEngine.prepareTeachingLogs() } } } } @@ -175,7 +220,7 @@ private fun Intro(onStart: () -> Unit) { } @Composable -private fun Running(state: LearnState.Running, onCancel: () -> Unit) { +private fun Running(state: LearnPrompt, onCancel: () -> Unit) { Column( modifier = Modifier.fillMaxWidth().padding(top = 48.dp), horizontalAlignment = Alignment.CenterHorizontally, @@ -194,24 +239,53 @@ private fun Running(state: LearnState.Running, onCancel: () -> Unit) { } @Composable -private fun Finished(result: LearnResult, finishedAt: Long, onRetry: () -> Unit, onDone: () -> Unit) { - val last by SnapEngine.lastGesture.collectAsStateWithLifecycle() - - if (result == LearnResult.NothingFound) { +private fun TeachingResult( + state: TeachingState, + onCheck: () -> Unit, + onSave: () -> Unit, + onRetry: () -> Unit, + onBack: () -> Unit, +) { + if (state is TeachingState.SaveFailed) { NoteCard( icon = Icons.Rounded.Warning, - title = "Couldn't find your Snap Key", - body = "• If you use log access, make sure it's connected before you start.\n" + - "• In Settings › Snap Key, pick a different option, then try again. Some options " + - "keep the key hidden.\n" + - "• Press the key once each time you're asked, and hold it at the end.", + title = "Couldn't save your key", + body = "The save was not confirmed. Your previous key is unchanged. Try saving again or cancel.", + container = MaterialTheme.colorScheme.errorContainer, + ) + Button(onClick = onSave, modifier = Modifier.fillMaxWidth()) { Text("Retry save") } + OutlinedButton(onClick = onBack, modifier = Modifier.fillMaxWidth()) { Text("Cancel") } + return + } + if (state is TeachingState.Failed) { + val title = when (state.reason) { + TeachingFailure.NOT_FOUND -> "Couldn't find your Snap Key" + TeachingFailure.COLLISION -> "Another key matched" + TeachingFailure.NO_DIFFERENT_KEY -> "Couldn't observe a different key" + TeachingFailure.ACCESS_LOST -> "The check was interrupted" + } + val guidance = when (state.reason) { + TeachingFailure.NOT_FOUND -> "Make sure access is connected. Press the Snap Key only when asked, then hold it at the end." + TeachingFailure.COLLISION -> "This candidate also matched during the different-key check. Try teaching again." + TeachingFailure.NO_DIFFERENT_KEY -> "Try again and press and release a volume key during the check. A complete press and release must be observable." + TeachingFailure.ACCESS_LOST -> "Restore the service, full system logs and any required Shizuku input, then try again. Reconnecting alone cannot complete this check." + } + NoteCard( + icon = Icons.Rounded.Warning, + title = title, + body = "Nothing was saved. Your previous key is unchanged.\n\n$guidance", container = MaterialTheme.colorScheme.errorContainer, ) Button(onClick = onRetry, modifier = Modifier.fillMaxWidth()) { Text("Try again") } - OutlinedButton(onClick = onDone, modifier = Modifier.fillMaxWidth()) { Text("Back") } + OutlinedButton(onClick = onBack, modifier = Modifier.fillMaxWidth()) { Text("Back") } return } + val result = when (state) { + is TeachingState.Candidate -> state.result + is TeachingState.Ready -> state.result + else -> return + } val body = when (result) { is LearnResult.KeyEventFound -> "Your Snap Key talks to apps directly, so no log access is needed." is LearnResult.LogLineFound -> if (result.inputKey != null) { @@ -226,15 +300,14 @@ private fun Finished(result: LearnResult, finishedAt: Long, onRetry: () -> Unit, } NoteCard( icon = Icons.Rounded.CheckCircle, - title = "Got it!", - body = body, + title = if (state is TeachingState.Ready) "Different-key check passed" else "Key found. Not saved yet.", + body = body + if (state is TeachingState.Ready) { + "\n\nThis check covers the key you pressed, not every possible key. Save this key?" + } else { + "\n\nCheck a different key before saving. Your previous key is still unchanged." + }, container = MaterialTheme.colorScheme.primaryContainer, ) - val tried = last?.takeIf { it.atMs > finishedAt } - Text( - if (tried == null) "Try it now: press the Snap Key." else "Detected: ${tried.gesture.title} ✓", - style = MaterialTheme.typography.titleLarge, - ) if (result is LearnResult.LogLineFound) { result.inputKey?.let { key -> Text("Matched input key: ${key.code}", style = MaterialTheme.typography.bodySmall) @@ -246,6 +319,11 @@ private fun Finished(result: LearnResult, finishedAt: Long, onRetry: () -> Unit, color = MaterialTheme.colorScheme.onSurfaceVariant, ) } - Button(onClick = onDone, modifier = Modifier.fillMaxWidth()) { Text("Done") } + if (state is TeachingState.Ready) { + Button(onClick = onSave, modifier = Modifier.fillMaxWidth()) { Text("Save key") } + } else { + Button(onClick = onCheck, modifier = Modifier.fillMaxWidth()) { Text("Check a different key") } + } TextButton(onClick = onRetry, modifier = Modifier.fillMaxWidth()) { Text("Teach it again") } + OutlinedButton(onClick = onBack, modifier = Modifier.fillMaxWidth()) { Text("Cancel") } } diff --git a/app/src/main/java/com/heykay/snapkeymap/ui/SetupScreen.kt b/app/src/main/java/com/heykay/snapkeymap/ui/SetupScreen.kt index 843f4a3..bd44219 100644 --- a/app/src/main/java/com/heykay/snapkeymap/ui/SetupScreen.kt +++ b/app/src/main/java/com/heykay/snapkeymap/ui/SetupScreen.kt @@ -253,7 +253,7 @@ fun SetupScreen( } SetupPage.TEACH -> { Text("First set Settings › Snap Key › Oppo's own action to None, so both actions don't run. " + - "Then teach SnapKey Map: press three times and hold once when asked. It takes about 20 seconds.") + "Then teach SnapKey Map: press three times, hold once, and check a different key before saving. It takes about 30 seconds.") OutlinedButton(onClick = { context.openPhoneSettings() }) { Text("Open phone settings") } Button(onClick = onLearn) { Text(if (config.isTaught) "Teach again" else "Teach the Snap Key") } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 1ca98a2..9689a9e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,6 +1,10 @@ SnapKey Map + Snap Key + On + Off + Set up in app About Back By Krithik (heykay-47) @@ -17,5 +21,5 @@ https://github.com/heykay-47 https://buymeatea.in/heykay47 https://github.com/sponsors/heykay-47 - Lets SnapKey Map notice when you press the Snap Key and run the action you picked: open an app, take a screenshot, go home, and so on. It does not read what is on your screen. + Lets SnapKey Map notice when you press the Snap Key and run the action you picked: open an app, take a screenshot, go home, and so on. It can receive hardware key events from other apps when Android delivers them. It acts only on the key you taught it and lets other keys through unchanged. It checks package and class names in window events to identify app activities and pause in apps you choose. It does not read what is on your screen. diff --git a/app/src/test/java/com/heykay/snapkeymap/BugReportTest.kt b/app/src/test/java/com/heykay/snapkeymap/BugReportTest.kt new file mode 100644 index 0000000..123b2b4 --- /dev/null +++ b/app/src/test/java/com/heykay/snapkeymap/BugReportTest.kt @@ -0,0 +1,141 @@ +package com.heykay.snapkeymap + +import java.net.URI +import java.net.URLDecoder +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class BugReportTest { + private val info = ReportInfo( + versionName = "1.2.0", + versionCode = 10200, + phoneModel = "Find X9", + colorOsVersion = "16.0", + androidRelease = "16", + sdk = 36, + shizukuState = "Running and allowed", + detectionMode = "Precise input via Shizuku", + hasLogPermission = true, + ) + private val timeFormat: (Long) -> String = { "time-$it" } + + @Test + fun reportAndUrlIncludeActionKindsWithoutPrivateTargetsOrLogMessages() { + val config = Config( + actions = mapOf( + Gesture.SINGLE to SnapAction.CallContact("+15551234567", "Mum"), + Gesture.DOUBLE to SnapAction.OpenLink("https://secret.example/x"), + Gesture.LONG to SnapAction.OpenApp("com.whatsapp", "WhatsApp"), + Gesture.TAP_HOLD to SnapAction.OpenShortcut("intent:#Intent;component=a/b;end", "Route"), + ), + logSignature = KeySignature("KeyTag", "private raw log message", "1000"), + pausedApps = setOf("com.private.app"), + unlockedOnly = setOf(Gesture.SINGLE), + ) + val last = SnapEngine.Detected(Gesture.SINGLE, 123L, DetectionSource.PRECISE_INPUT) + val report = buildReport(info, config, listOf(last), timeFormat) + val url = bugReportUrl(info, config, last, timeFormat) + val decodedUrl = URLDecoder.decode(url, "UTF-8") + + listOf(report, url, decodedUrl).forEach { text -> + listOf("+15551234567", "https://secret.example/x", "secret.example", "com.whatsapp", "WhatsApp", + "intent:", "Route", "Mum", "private raw log message", "com.private.app").forEach { secret -> + assertFalse("Leaked $secret", text.contains(secret)) + } + } + listOf(report, decodedUrl).forEach { text -> + listOf("Call a contact", "Open a link", "Open an app", "Open a shortcut", "unlocked-only: on", + "tag=KeyTag", "time-123", "PRECISE_INPUT").forEach { expected -> + assertTrue("Missing $expected", text.contains(expected)) + } + } + assertTrue(decodedUrl.contains("Last: Press")) + } + + @Test + fun historyKeepsExactlyTheLastTwentyDetectionsInOrder() { + val detections = (0L until 25L).map { + SnapEngine.Detected(Gesture.SINGLE, it, DetectionSource.KEY_EVENT) + } + val history = detections.fold(emptyList(), ::appendDetection) + + assertEquals(20, history.size) + assertEquals(detections.takeLast(20), history) + } + + @Test + fun reportIncludesEnvironmentTimingLearnedKeysLocksAndBoundedHistory() { + val config = Config( + grantMethod = GrantMethod.SHIZUKU, + keyEvent = LearnedKey(42, 24), + inputKey = InputKey("02ab"), + logKeyCode = "999", + actions = mapOf( + Gesture.SINGLE to SnapAction.Device(DeviceAction.SCREENSHOT), + Gesture.DOUBLE to SnapAction.Ringer(listOf(RingerMode.RING, RingerMode.VIBRATE)), + ), + ) + val detections = (0L until 25L).map { + SnapEngine.Detected(Gesture.SINGLE, it, DetectionSource.SYSTEM_LOG) + } + val report = buildReport(info, config, detections, timeFormat) + + listOf("1.2.0 (10200)", "Find X9", "ColorOS: 16.0", "Android: 16 (SDK 36)", + "Grant method: Shizuku", "Running and allowed", "Precise input via Shizuku", + "keyEvent: code=42, scan=24", "inputKey: 02ab", "logSignature: not set", "logKeyCode: 999", + "Double-press window: 350 ms", "Hold threshold: 650 ms", "Take a screenshot", + "Ringer: Ring → Vibrate", "Do nothing", "unlocked-only: off", "time-24 [SYSTEM_LOG]").forEach { + assertTrue("Missing $it", report.contains(it)) + } + assertEquals(20, report.lines().count { it.contains("[SYSTEM_LOG]") }) + assertFalse(report.contains("time-4 [SYSTEM_LOG]")) + } + + @Test + fun logAccessMatchesTheFormOptionsForEveryGrantAndPermissionState() { + val options = setOf("Shizuku", "Computer (ADB)", "Not granted yet") + (GrantMethod.entries + null).forEach { method -> + listOf(false, true).forEach { permission -> + listOf(false, true).forEach { needsLog -> + val config = Config(grantMethod = method, keyEvent = if (needsLog) null else LearnedKey(42, 0)) + val url = bugReportUrl(info.copy(hasLogPermission = permission), config, null, timeFormat) + val access = queryFields(url).getValue("log-access") + + assertTrue(access in options) + assertEquals(when { + needsLog && !permission -> "Not granted yet" + method == GrantMethod.SHIZUKU -> "Shizuku" + method == GrantMethod.ADB -> "Computer (ADB)" + else -> "Not granted yet" + }, access) + assertTrue(url.length < 2000) + assertFalse(url.contains("+")) + assertEquals(setOf("template", "app-version", "device", "log-access", "teach", "actions"), + queryFields(url).keys) + } + } + } + } + + @Test + fun urlStaysBoundedWithLongUnicodeEnvironmentAndLearnedFields() { + val longText = "手機 &?".repeat(1000) + val url = bugReportUrl( + info.copy(versionName = longText, phoneModel = longText, colorOsVersion = longText), + Config(inputKey = InputKey(longText), logSignature = KeySignature(longText, "never include me")), + SnapEngine.Detected(Gesture.LONG, 123L, DetectionSource.SYSTEM_LOG), + { longText }, + ) + + assertTrue(url.length < 1800) + assertEquals("bug_report.yml", queryFields(url)["template"]) + assertFalse(url.contains("never")) + } + + private fun queryFields(url: String): Map = URI(url).rawQuery.split("&").associate { field -> + val (key, value) = field.split("=", limit = 2) + key to URLDecoder.decode(value, "UTF-8") + } +} diff --git a/app/src/test/java/com/heykay/snapkeymap/ConfigStoreTeachingTest.kt b/app/src/test/java/com/heykay/snapkeymap/ConfigStoreTeachingTest.kt new file mode 100644 index 0000000..53faaf9 --- /dev/null +++ b/app/src/test/java/com/heykay/snapkeymap/ConfigStoreTeachingTest.kt @@ -0,0 +1,179 @@ +package com.heykay.snapkeymap + +import android.content.SharedPreferences +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ConfigStoreTeachingTest { + @Test + fun falseAndThrowingCommitRestorePreferenceMemoryAndKeepCandidateForExplicitRetry() { + for (failure in listOf(Outcome.FALSE, Outcome.THROW)) { + val prefs = FakePreferences() + val store = ConfigStore(prefs) { false } + val session = readySession() + val old = store.config.value + val snapshot = prefs.getAll() + val publishedDuringCommit = mutableListOf() + val stateDuringCommit = mutableListOf() + prefs.outcomes.addAll(listOf(failure, Outcome.FALSE)) + prefs.duringCommit = { + publishedDuringCommit += store.config.value + stateDuringCommit += session.state + } + assertFalse(session.save { store.updateConfirmed(it::applyTo) }) + assertTrue(session.state is TeachingState.SaveFailed) + assertEquals(old, store.config.value) + assertEquals(snapshot, prefs.getAll()) + assertEquals(old, ConfigStore(prefs) { false }.config.value) + assertEquals(listOf(old, old), publishedDuringCommit) + assertTrue(stateDuringCommit.all { it is TeachingState.Ready }) + assertEquals(0, prefs.applies) + assertEquals(2, prefs.commits) + + prefs.duringCommit = null + store.update { it.copy(theme = ThemeMode.DARK, pausedApps = setOf("current.app"), holdMs = 900) } + val current = store.config.value + prefs.duringCommit = { + publishedDuringCommit += store.config.value + stateDuringCommit += session.state + } + assertTrue(session.save { store.updateConfirmed(it::applyTo) }) + assertEquals(TeachingState.Closed, session.state) + assertEquals(current.copy(keyEvent = LearnedKey(142, 88)), store.config.value) + assertEquals(store.config.value, ConfigStore(prefs) { false }.config.value) + assertEquals(prefs.getAll(), prefs.disk) + assertEquals(listOf(old, old, current), publishedDuringCommit) + assertTrue(stateDuringCommit.last() is TeachingState.SaveFailed) + assertFalse(session.save { store.updateConfirmed(it::applyTo) }) + assertEquals(3, prefs.commits) + assertEquals(1, prefs.applies) + } + } + + @Test + fun cancelAfterFailedProductionSaveKeepsOldConfigAndCannotRetry() { + val prefs = FakePreferences() + val store = ConfigStore(prefs) { false } + val old = store.config.value + val snapshot = prefs.getAll() + val session = readySession() + prefs.outcomes += Outcome.FALSE + assertFalse(session.save { store.updateConfirmed(it::applyTo) }) + session.cancel() + assertFalse(session.save { store.updateConfirmed(it::applyTo) }) + assertEquals(TeachingState.Closed, session.state) + assertEquals(old, store.config.value) + assertEquals(snapshot, prefs.getAll()) + assertEquals(2, prefs.commits) + } + + @Test + fun failedProductionSaveKeepsMatchingAndRequiredAccessChecksActive() { + for (collision in listOf(false, true)) { + val prefs = FakePreferences() + val store = ConfigStore(prefs) { false } + val old = store.config.value + val session = readySession() + prefs.outcomes += Outcome.THROW + assertFalse(session.save { store.updateConfirmed(it::applyTo) }) + if (collision) session.observe(KeySample.Accessibility(142, 88, false), 30000) + else session.accessChanged(TeachingAccess(false, true, true)) + assertEquals(TeachingState.Failed(if (collision) TeachingFailure.COLLISION else TeachingFailure.ACCESS_LOST), session.state) + assertFalse(session.save { store.updateConfirmed(it::applyTo) }) + assertEquals(old, store.config.value) + assertEquals(2, prefs.commits) + } + } + + @Test + fun ordinaryUpdateStillPublishesAndUsesApplyWithoutAConfirmedCommit() { + val prefs = FakePreferences() + val store = ConfigStore(prefs) { false } + store.update { it.copy(theme = ThemeMode.DARK, holdMs = 5000) } + assertEquals(ThemeMode.DARK, store.config.value.theme) + assertEquals(1200L, store.config.value.holdMs) + assertEquals("DARK", prefs.getString("theme", null)) + assertEquals(1, prefs.applies) + assertEquals(0, prefs.commits) + } + + private fun readySession() = TeachingSession(TeachingAccess(true, false, false)).apply { + listOf(7000L, 11000L, 15000L, 18200L).forEach { + observe(KeySample.Accessibility(142, 88, true), it) + } + capture(0L..5000L, listOf(6000L..9000L, 10000L..13000L, 14000L..17000L), 18000L..21500L) + beginCheck(23000) + observe(KeySample.Accessibility(25, 114, true), 24000) + observe(KeySample.Accessibility(25, 114, false), 24100) + finishCheck(23000 + TeachingSession.CHECK_MS + TeachingSession.SETTLE_MS) + assertTrue(state is TeachingState.Ready) + } + + private enum class Outcome { TRUE, FALSE, THROW } + + private class FakePreferences : SharedPreferences { + private val memory = mutableMapOf( + "setup_complete" to true, "key_code" to 141, "scan_code" to 87, "theme" to "LIGHT", + "other_boolean" to false, "other_int" to 12, "other_long" to 13L, + "other_float" to 1.5f, "other_string" to "retained", "other_set" to setOf("retained"), + ) + var disk: Map = memory.toMap() + private set + val outcomes = ArrayDeque() + var duringCommit: (() -> Unit)? = null + var commits = 0 + private set + var applies = 0 + private set + + override fun getAll(): MutableMap = memory.toMutableMap() + override fun contains(key: String): Boolean = key in memory + override fun getString(key: String, defValue: String?): String? = memory[key] as? String ?: defValue + override fun getStringSet(key: String, defValues: MutableSet?): MutableSet? = + (memory[key] as? Set<*>)?.filterIsInstance()?.toMutableSet() ?: defValues + override fun getInt(key: String, defValue: Int): Int = memory[key] as? Int ?: defValue + override fun getLong(key: String, defValue: Long): Long = memory[key] as? Long ?: defValue + override fun getFloat(key: String, defValue: Float): Float = memory[key] as? Float ?: defValue + override fun getBoolean(key: String, defValue: Boolean): Boolean = memory[key] as? Boolean ?: defValue + override fun registerOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) = Unit + override fun unregisterOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) = Unit + + override fun edit(): SharedPreferences.Editor = object : SharedPreferences.Editor { + private val changes = mutableMapOf() + private var clear = false + + override fun putString(key: String, value: String?): SharedPreferences.Editor = apply { changes[key] = value } + override fun putStringSet(key: String, values: MutableSet?): SharedPreferences.Editor = + apply { changes[key] = values?.toSet() } + override fun putInt(key: String, value: Int): SharedPreferences.Editor = apply { changes[key] = value } + override fun putLong(key: String, value: Long): SharedPreferences.Editor = apply { changes[key] = value } + override fun putFloat(key: String, value: Float): SharedPreferences.Editor = apply { changes[key] = value } + override fun putBoolean(key: String, value: Boolean): SharedPreferences.Editor = apply { changes[key] = value } + override fun remove(key: String): SharedPreferences.Editor = apply { changes[key] = null } + override fun clear(): SharedPreferences.Editor = apply { clear = true } + + private fun publishMemory() { + if (clear) memory.clear() + changes.forEach { (key, value) -> if (value == null) memory.remove(key) else memory[key] = value } + } + + override fun commit(): Boolean { + commits++ + publishMemory() + duringCommit?.invoke() + return when (outcomes.removeFirstOrNull() ?: Outcome.TRUE) { + Outcome.TRUE -> { disk = memory.toMap(); true } + Outcome.FALSE -> false + Outcome.THROW -> throw IllegalStateException("Injected write failure after memory changed") + } + } + + override fun apply() { + applies++ + publishMemory() + } + } + } +} diff --git a/app/src/test/java/com/heykay/snapkeymap/InputKeyDeliveryTest.kt b/app/src/test/java/com/heykay/snapkeymap/InputKeyDeliveryTest.kt new file mode 100644 index 0000000..f436d9e --- /dev/null +++ b/app/src/test/java/com/heykay/snapkeymap/InputKeyDeliveryTest.kt @@ -0,0 +1,71 @@ +package com.heykay.snapkeymap + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class InputKeyDeliveryTest { + private val key = InputKey("BTN_TRIGGER_HAPPY32") + + @Test + fun queuedReleaseAfterCancelClearsSuppressionWithoutRuntimeOrRetryDelivery() { + for (retry in listOf(false, true)) { + val teaching = TeachingDelivery() + val input = InputKeyDelivery(teaching) + teaching.advance(TeachingHandle(1)) + var teachingSamples = 0 + input.deliver(InputKeyEvent(key, true), teaching.stamp) { teachingSamples++ } + val queuedUp = teaching.stamp + teaching.advance(null) + assertTrue(input.suppressHeld(key)) + if (retry) teaching.advance(TeachingHandle(2)) + input.deliver(InputKeyEvent(key, false), queuedUp) { error("Stale release was delivered") } + assertEquals(1, teachingSamples) + teaching.advance(null) + if (retry) assertFalse(input.suppressHeld(key)) + val edges = mutableListOf() + input.deliver(InputKeyEvent(key, true), teaching.stamp) { ignored -> if (!ignored) edges += true } + input.deliver(InputKeyEvent(key, false), teaching.stamp) { ignored -> if (!ignored) edges += false } + assertEquals(listOf(true, false), edges) + } + } + + @Test + fun releaseBeforeTeachingTimeBoundaryStillClearsHeldState() { + val teaching = TeachingDelivery() + val input = InputKeyDelivery(teaching) + input.deliver(InputKeyEvent(key, true), teaching.stamp) { } + teaching.advance(TeachingHandle(1)) + input.deliver(InputKeyEvent(key, false), teaching.stamp) { } + teaching.advance(null) + assertFalse(input.suppressHeld(key)) + } + + @Test + fun readerLossDiscardsHeldSuppressionAndReplacementCanStartWithACompletePress() { + val teaching = TeachingDelivery() + val input = InputKeyDelivery(teaching) + input.deliver(InputKeyEvent(key, true), teaching.stamp) { } + assertTrue(input.suppressHeld(key)) + input.readerLost() + assertFalse(input.suppressHeld(key)) + val edges = mutableListOf() + input.deliver(InputKeyEvent(key, true), teaching.stamp) { if (!it) edges += true } + input.deliver(InputKeyEvent(key, false), teaching.stamp) { if (!it) edges += false } + assertEquals(listOf(true, false), edges) + } + + @Test + fun releaseOfHeldKeyIsSuppressedButTheNextPressIsDelivered() { + val teaching = TeachingDelivery() + val input = InputKeyDelivery(teaching) + input.deliver(InputKeyEvent(key, true), teaching.stamp) { } + assertTrue(input.suppressHeld(key)) + val edges = mutableListOf() + input.deliver(InputKeyEvent(key, false), teaching.stamp) { if (!it) edges += false } + input.deliver(InputKeyEvent(key, true), teaching.stamp) { if (!it) edges += true } + input.deliver(InputKeyEvent(key, false), teaching.stamp) { if (!it) edges += false } + assertEquals(listOf(true, false), edges) + } +} diff --git a/app/src/test/java/com/heykay/snapkeymap/KeyLearningReplayTest.kt b/app/src/test/java/com/heykay/snapkeymap/KeyLearningReplayTest.kt index a70c022..99bb881 100644 --- a/app/src/test/java/com/heykay/snapkeymap/KeyLearningReplayTest.kt +++ b/app/src/test/java/com/heykay/snapkeymap/KeyLearningReplayTest.kt @@ -70,8 +70,8 @@ class KeyLearningReplayTest { } fun edge(time: Long, tid: String) { clock.advanceTo(time) - if (!acceptsKeyLog(result.signature, "1000", oplusTag, oplusMessage) || - !acceptsLoggedKey(result.logKeyCode, keysByThread[tid])) return + if (!KeyMatching.matches(KeyBinding.Logged(result.signature, result.logKeyCode, result.inputKey), + KeySample.Log("1000", oplusTag, oplusMessage, keysByThread[tid]))) return repeat(3) { edges.accept("10-23 20:15:%02d.%03d".format(time / 1000, time % 1000)) } } @@ -115,7 +115,8 @@ class KeyLearningReplayTest { fun line(time: Long, timestamp: String, tag: String, message: String) { clock.advanceTo(time) // These recorded system lines predate capturing logcat's UID column. - if (!acceptsKeyLog(result.signature, "1000", tag, message)) return + if (!KeyMatching.matches(KeyBinding.Logged(result.signature, result.logKeyCode, result.inputKey), + KeySample.Log("1000", tag, message, null))) return if (isKnownOplusKeyLine("1000", tag, message)) { knownAccepted++ edges.accept(timestamp) @@ -169,7 +170,8 @@ class KeyLearningReplayTest { fun line(time: Long, code: String, value: String) { clock.advanceTo(time) val event = parseInputKeyEvent("[ 42.000000] /dev/input/event0: EV_KEY $code $value") ?: return - if (event.key != result.inputKey) return + if (!KeyMatching.matches(KeyBinding.Logged(result.signature, result.logKeyCode, result.inputKey), + KeySample.Input(event))) return if (event.down) detector.down() else detector.up() } line(0, "BTN_TRIGGER_HAPPY32", "DOWN") diff --git a/app/src/test/java/com/heykay/snapkeymap/KeyMatchingTest.kt b/app/src/test/java/com/heykay/snapkeymap/KeyMatchingTest.kt new file mode 100644 index 0000000..f6298b1 --- /dev/null +++ b/app/src/test/java/com/heykay/snapkeymap/KeyMatchingTest.kt @@ -0,0 +1,77 @@ +package com.heykay.snapkeymap + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class KeyMatchingTest { + private val tag = "KEYLOG_OplusKeyEventUtil" + private val message = "should not notify undefined keys in restrict listen mode" + private val snap = "KEYCODE_ACTION_BUTTON_CLICK" + private val oplus = KeyBinding.Logged(KeySignature(tag, message, "1000"), snap, InputKey("BTN_TRIGGER_HAPPY32")) + + @Test + fun knownAndroidKeyUsesCodeAndUnknownUsesCodeAndScan() { + assertTrue(KeyMatching.matches(KeyBinding.Direct(LearnedKey(142, 88)), key(142, 99))) + assertFalse(KeyMatching.matches(KeyBinding.Direct(LearnedKey(142, 88)), key(141, 88))) + assertTrue(KeyMatching.matches(KeyBinding.Direct(LearnedKey(0, 88)), key(0, 88))) + assertFalse(KeyMatching.matches(KeyBinding.Direct(LearnedKey(0, 88)), key(0, 99))) + assertFalse(KeyMatching.matches(KeyBinding.Direct(LearnedKey(0, 88)), key(142, 88))) + } + + @Test + fun inputIdentityIsExactAndIsNotAnOperationalRouteForDirectKeys() { + assertTrue(KeyMatching.matches(oplus, input("BTN_TRIGGER_HAPPY32"))) + assertFalse(KeyMatching.matches(oplus, input("BTN_TRIGGER_HAPPY3"))) + assertFalse(KeyMatching.matches(oplus.copy(inputKey = null), input("BTN_TRIGGER_HAPPY32"))) + assertFalse(KeyMatching.matches(KeyBinding.Direct(LearnedKey(142, 88)), input("BTN_TRIGGER_HAPPY32"))) + assertFalse(KeyMatching.matches(oplus, key(142, 88))) + } + + @Test + fun logIdentityPreservesUidTagNormalizationAndUsableSignatureRules() { + val signature = KeySignature("StylusModule", "StylusModule.onUpdateToolType():# Update tool type = #", "system") + val binding = KeyBinding.Logged(signature, null, null) + val sample = KeySample.Log("1000", "StylusModule", " StylusModule.onUpdateToolType():9876 Update tool type = 54 ", null) + assertTrue(KeyMatching.matches(binding, sample)) + assertFalse(KeyMatching.matches(binding, sample.copy(uid = "2000"))) + assertFalse(KeyMatching.matches(binding, sample.copy(tag = "OtherStylusModule"))) + assertFalse(KeyMatching.matches(binding, sample.copy(message = "other 9876"))) + assertFalse(KeyMatching.matches(binding.copy(signature = signature.copy(uid = null)), sample)) + val longMessage = "x".repeat(170) + assertTrue(KeyMatching.matches(binding.copy(signature = KeySignature("Long", normalizeLogMessage(longMessage), "1000")), + sample.copy(tag = "Long", message = longMessage + "suffix"))) + } + + @Test + fun oplusFilteringUsesSameThreadContextAndAcceptsMissingContextLikeRuntime() { + val context = LoggedKeyContext() + fun raw(thread: String, code: String) = context.sample(1, 1, "system", thread, "KEYLOG_PhoneWindowManagerExtImpl", + "overrideInterceptKeyBeforeQueueing:KeyEvent { action=ACTION_DOWN, keyCode=$code, scanCode=0 }") + fun edge(thread: String) = context.sample(1, 1, "1000", thread, tag, message) + raw("snap", snap) + raw("volume", "KEYCODE_VOLUME_DOWN") + assertTrue(KeyMatching.matches(oplus, edge("snap"))) + assertFalse(KeyMatching.matches(oplus, edge("volume"))) + assertTrue(KeyMatching.matches(oplus, edge("missing"))) + raw("snap", "KEYCODE_VOLUME_DOWN") + assertFalse(KeyMatching.matches(oplus, edge("snap"))) + assertEquals(null, context.sample(2, 1, "1000", "volume", tag, message).threadKey) + raw("volume", "KEYCODE_VOLUME_DOWN") + assertEquals(null, context.sample(1, 2, "1000", "volume", tag, message).threadKey) + } + + @Test + fun legacyNullSignatureStillAcceptsOnlyKnownSystemOplusLines() { + val legacy = KeyBinding.Logged(null, null, null) + assertTrue(KeyMatching.matches(legacy, KeySample.Log("system", tag, message, null))) + assertFalse(KeyMatching.matches(legacy, KeySample.Log("2000", tag, message, null))) + assertFalse(KeyMatching.matches(legacy, KeySample.Log("1000", "Other", "pressed", null))) + assertFalse(KeyMatching.matches(oplus, KeySample.Log("1000", tag, message, "KEYCODE_VOLUME_DOWN"))) + assertTrue(KeyMatching.matches(oplus.copy(logKeyCode = null), KeySample.Log("1000", tag, message, "KEYCODE_VOLUME_DOWN"))) + } + + private fun key(code: Int, scan: Int) = KeySample.Accessibility(code, scan, true) + private fun input(code: String) = KeySample.Input(InputKeyEvent(InputKey(code), true)) +} diff --git a/app/src/test/java/com/heykay/snapkeymap/OplusKeyEdgesTest.kt b/app/src/test/java/com/heykay/snapkeymap/OplusKeyEdgesTest.kt index 9a40420..3e9240a 100644 --- a/app/src/test/java/com/heykay/snapkeymap/OplusKeyEdgesTest.kt +++ b/app/src/test/java/com/heykay/snapkeymap/OplusKeyEdgesTest.kt @@ -1,6 +1,8 @@ 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 @@ -287,4 +289,307 @@ class OplusKeyEdgesTest { ) assertTrue(result.canDetectHold) } + + @Test + fun teachingRestoresHeldSnapReleaseWithoutAnActionAndKeepsTimestampDedupe() { + val tracking = TeachingLogEdges() + val snap = KeySample.Log("1000", "KEYLOG_OplusKeyEventUtil", + "should not notify undefined keys in restrict listen mode", "KEYCODE_ACTION_BUTTON_CLICK") + tracking.observe(stamp(0), snap) + tracking.observe(stamp(1), snap) + val h = Harness(enableHold = false) + tracking.restore("KEYCODE_ACTION_BUTTON_CLICK", h.edges) + h.duplicatedLine(1) + h.duplicatedLine(100) + h.clock.advanceTo(1000) + assertTrue(h.gestures.isEmpty()) + h.duplicatedLine(2000) + h.duplicatedLine(2100) + h.clock.advanceTo(3000) + assertEquals(listOf(Gesture.SINGLE), h.gestures) + } + + @Test + fun heldVolumeKeyDuringTeachingDoesNotChangeFilteredSnapPhaseOnExit() { + val tracking = TeachingLogEdges() + val snap = KeySample.Log("system", "KEYLOG_OplusKeyEventUtil", + "should not notify undefined keys in restrict listen mode", "KEYCODE_ACTION_BUTTON_CLICK") + tracking.observe(stamp(0), snap) + tracking.observe(stamp(100), snap) + tracking.observe(stamp(200), snap.copy(threadKey = "KEYCODE_VOLUME_DOWN")) + val h = Harness(enableHold = false) + tracking.restore("KEYCODE_ACTION_BUTTON_CLICK", h.edges) + h.duplicatedLine(1000) + h.duplicatedLine(1100) + h.clock.advanceTo(2000) + assertEquals(listOf(Gesture.SINGLE), h.gestures) + } + + @Test + fun missingContextRetainsRuntimeAcceptanceAndResetDiscardsOldTeachingEdges() { + val tracking = TeachingLogEdges() + tracking.begin("KEYCODE_ACTION_BUTTON_CLICK", OplusKeyEdges({}, {})) + val sample = KeySample.Log("1000", "KEYLOG_OplusKeyEventUtil", + "should not notify undefined keys in restrict listen mode", null) + tracking.observe(stamp(0), sample) + val h = Harness(enableHold = false) + tracking.restore("KEYCODE_ACTION_BUTTON_CLICK", h.edges) + h.duplicatedLine(100) + h.clock.advanceTo(1000) + assertTrue(h.gestures.isEmpty()) + tracking.reset() + tracking.restore("KEYCODE_ACTION_BUTTON_CLICK", h.edges) + h.duplicatedLine(2000) + h.duplicatedLine(2100) + h.clock.advanceTo(3000) + assertEquals(listOf(Gesture.SINGLE), h.gestures) + } + + @Test + fun cancellingDuringHandsOffWithTheOldKeyHeldDoesNotInvertItsNextPress() { + val h = Harness(enableHold = false) + h.duplicatedLine(0) + h.detector.reset() + val tracking = TeachingLogEdges() + tracking.begin("KEYCODE_ACTION_BUTTON_CLICK", h.edges) + h.edges.reset() + val sample = KeySample.Log("1000", "KEYLOG_OplusKeyEventUtil", + "should not notify undefined keys in restrict listen mode", "KEYCODE_ACTION_BUTTON_CLICK") + tracking.observe(stamp(100), sample) + tracking.restore("KEYCODE_ACTION_BUTTON_CLICK", h.edges) + h.duplicatedLine(1000) + h.duplicatedLine(1100) + h.clock.advanceTo(2000) + assertEquals(listOf(Gesture.SINGLE), h.gestures) + } + + @Test + fun resetKeepsConfiguredSnapRegistrationBeforeMissingContextDownAndIdentifiedUp() { + val h = Harness(enableHold = false) + val tracking = TeachingLogEdges() + val code = "KEYCODE_ACTION_BUTTON_CLICK" + tracking.begin(code, h.edges) + tracking.reset() + val sample = KeySample.Log("1000", "KEYLOG_OplusKeyEventUtil", + "should not notify undefined keys in restrict listen mode", null) + tracking.observe(stamp(0), sample) + tracking.observe(stamp(100), sample.copy(threadKey = code)) + tracking.restore(code, h.edges) + h.duplicatedLine(1000) + h.duplicatedLine(1100) + h.clock.advanceTo(2000) + assertEquals(listOf(Gesture.SINGLE), h.gestures) + } + + @Test + fun heldVolumeWithoutAnySnapSampleCannotSeedConfiguredSnapPhaseOnCancel() { + val h = Harness(enableHold = false) + val tracking = TeachingLogEdges() + val code = "KEYCODE_ACTION_BUTTON_CLICK" + tracking.begin(code, h.edges) + tracking.reset() + tracking.observe(stamp(0), KeySample.Log("1000", "KEYLOG_OplusKeyEventUtil", + "should not notify undefined keys in restrict listen mode", "KEYCODE_VOLUME_DOWN")) + tracking.restore(code, h.edges) + h.duplicatedLine(1000) + h.duplicatedLine(1100) + h.clock.advanceTo(2000) + assertEquals(listOf(Gesture.SINGLE), h.gestures) + } + + @Test + fun newCrossThreadCandidateHeldThroughVolumeCheckAndSaveIgnoresReleaseThenFiresOneSingle() { + for (oldCode in listOf(null, "KEYCODE_F12")) { + val h = Harness(enableHold = false) + h.detector.wantsDouble = false + var config = Config(logKeyCode = oldCode) + val oldConfig = config + val session = TeachingSession(TeachingAccess(false, true, false)) + val context = LoggedKeyContext() + val tracking = TeachingLogEdges() + tracking.begin(oldCode, h.edges) + h.edges.reset() + tracking.reset() + var epoch = 1L + val snapCode = "KEYCODE_ACTION_BUTTON_CLICK" + val tag = "KEYLOG_OplusKeyEventUtil" + val message = "should not notify undefined keys in restrict listen mode" + + fun log(time: Long, thread: String, lineTag: String, lineMessage: String): KeySample.Log { + h.clock.advanceTo(time) + val sample = context.sample(1, epoch, "1000", thread, lineTag, lineMessage) + session.observe(sample, time) + if (isKnownOplusKeyLine(sample.uid, sample.tag, sample.message)) tracking.observe(stamp(time), sample) + return sample + } + + fun raw(time: Long, thread: String, code: String, down: Boolean) = log(time, thread, + "KEYLOG_PhoneWindowManagerExtImpl", + "overrideInterceptKeyBeforeQueueing:KeyEvent { action=${if (down) "ACTION_DOWN" else "ACTION_UP"}, keyCode=$code, scanCode=0 }") + + for (time in listOf(7000L, 11000L, 15000L, 18200L)) { + raw(time, "raw-snap", snapCode, true) + assertNull(log(time + 1, "edge-snap", tag, message).threadKey) + log(time + 2, "edge-snap", tag, message) + if (time != 18200L) { + raw(time + 100, "raw-snap", snapCode, false) + log(time + 101, "edge-snap", tag, message) + log(time + 102, "edge-snap", tag, message) + } + } + session.capture(0L..5000L, listOf(6000L..9000L, 10000L..13000L, 14000L..17000L), 18000L..21500L) + epoch++ + val learned = (session.state as TeachingState.Candidate).result as LearnResult.LogLineFound + assertEquals(snapCode, learned.logKeyCode) + assertEquals(KeySignature(tag, message, "1000"), learned.signature) + var writes = 0 + assertFalse(session.save { writes++; true }) + assertEquals(0, writes) + session.beginCheck(23000) + epoch++ + raw(24000, "volume", "KEYCODE_VOLUME_DOWN", true) + assertEquals("KEYCODE_VOLUME_DOWN", log(24001, "volume", tag, message).threadKey) + log(24002, "volume", tag, message) + raw(24100, "volume", "KEYCODE_VOLUME_DOWN", false) + log(24101, "volume", tag, message) + log(24102, "volume", tag, message) + val checkEnd = 23000 + TeachingSession.CHECK_MS + TeachingSession.SETTLE_MS + h.clock.advanceTo(checkEnd) + session.finishCheck(checkEnd) + assertTrue(session.state is TeachingState.Ready) + assertEquals(oldConfig, config) + assertTrue(h.gestures.isEmpty()) + + assertTrue(session.save { patch -> + config = patch.applyTo(config) + writes++ + true + }) + assertEquals(1, writes) + assertEquals(TeachingState.Closed, session.state) + assertEquals(snapCode, config.logKeyCode) + h.detector.reset() + epoch++ + tracking.restore(config.logKeyCode, h.edges) + tracking.reset() + + fun runtimeEdge(time: Long) { + h.clock.advanceTo(time) + repeat(2) { copy -> + val sample = context.sample(1, epoch, "1000", "edge-snap", tag, message) + assertNull(sample.threadKey) + assertTrue(KeyMatching.matches(config.keyBinding(), sample)) + h.edges.accept(stamp(time + copy)) + } + } + + runtimeEdge(29000) + h.clock.advanceTo(30000) + assertTrue(h.gestures.isEmpty()) + runtimeEdge(31000) + runtimeEdge(31100) + h.clock.advanceTo(32000) + assertEquals(listOf(Gesture.SINGLE), h.gestures) + assertEquals(listOf(SnapAction.Device(DeviceAction.FLASHLIGHT)), h.gestures.map(config::action)) + } + } + + @Test + fun newCandidateIdentifiedUpCompletesItsEarlierMissingContextDownWithoutVolumeContamination() { + val h = Harness(enableHold = false) + val tracking = TeachingLogEdges() + tracking.begin("KEYCODE_F12", h.edges) + tracking.reset() + val sample = KeySample.Log("1000", "KEYLOG_OplusKeyEventUtil", + "should not notify undefined keys in restrict listen mode", null) + tracking.observe(stamp(0), sample.copy(threadKey = "KEYCODE_VOLUME_DOWN")) + tracking.observe(stamp(100), sample) + tracking.observe(stamp(101), sample) + tracking.observe(stamp(200), sample.copy(threadKey = "KEYCODE_ACTION_BUTTON_CLICK")) + tracking.observe(stamp(201), sample.copy(threadKey = "KEYCODE_ACTION_BUTTON_CLICK")) + tracking.restore("KEYCODE_ACTION_BUTTON_CLICK", h.edges) + h.duplicatedLine(1000) + h.duplicatedLine(1100) + h.clock.advanceTo(2000) + assertEquals(listOf(Gesture.SINGLE), h.gestures) + } + + @Test + fun unrelatedIdentifiedVolumeCannotSeedAnUnregisteredCandidateOrItsFirstIdentifiedDown() { + for (identifiedDown in listOf(false, true)) { + val h = Harness(enableHold = false) + val tracking = TeachingLogEdges() + tracking.begin("KEYCODE_F12", h.edges) + tracking.reset() + val sample = KeySample.Log("1000", "KEYLOG_OplusKeyEventUtil", + "should not notify undefined keys in restrict listen mode", "KEYCODE_VOLUME_DOWN") + tracking.observe(stamp(0), sample) + if (identifiedDown) tracking.observe(stamp(100), sample.copy(threadKey = "KEYCODE_ACTION_BUTTON_CLICK")) + tracking.restore("KEYCODE_ACTION_BUTTON_CLICK", h.edges) + if (identifiedDown) { + h.duplicatedLine(200) + h.clock.advanceTo(500) + assertTrue(h.gestures.isEmpty()) + } + h.duplicatedLine(1000) + h.duplicatedLine(1100) + h.clock.advanceTo(2000) + assertEquals(listOf(Gesture.SINGLE), h.gestures) + } + } + + @Test + fun unregisteredCandidateInheritsMissingContextTimestampDedupeAsWellAsHeldPhase() { + val tracking = TeachingLogEdges() + val sample = KeySample.Log("1000", "KEYLOG_OplusKeyEventUtil", + "should not notify undefined keys in restrict listen mode", null) + tracking.observe(stamp(0), sample) + val h = Harness(enableHold = false) + tracking.restore("KEYCODE_ACTION_BUTTON_CLICK", h.edges) + h.duplicatedLine(1) + h.duplicatedLine(100) + h.clock.advanceTo(1000) + assertTrue(h.gestures.isEmpty()) + h.duplicatedLine(2000) + h.duplicatedLine(2100) + h.clock.advanceTo(3000) + assertEquals(listOf(Gesture.SINGLE), h.gestures) + } + + @Test + fun handsOffOrSourceResetAndNewTeachingDiscardContextFreePhaseAndDedupe() { + for (newTeaching in listOf(false, true)) { + val tracking = TeachingLogEdges() + val sample = KeySample.Log("1000", "KEYLOG_OplusKeyEventUtil", + "should not notify undefined keys in restrict listen mode", null) + tracking.observe(stamp(0), sample) + if (newTeaching) { + val oldKey = OplusKeyEdges({}, {}).apply { reset(pressed = true) } + tracking.begin("KEYCODE_F12", oldKey) + } else tracking.reset() + val h = Harness(enableHold = false) + tracking.restore("KEYCODE_ACTION_BUTTON_CLICK", h.edges) + h.duplicatedLine(0) + h.duplicatedLine(100) + h.clock.advanceTo(1000) + assertEquals(listOf(Gesture.SINGLE), h.gestures) + } + } + + @Test + fun nullCodeStillRestoresTheUnfilteredIdentifiedVolumeAggregate() { + val tracking = TeachingLogEdges() + tracking.begin(null, OplusKeyEdges({}, {})) + tracking.observe(stamp(0), KeySample.Log("1000", "KEYLOG_OplusKeyEventUtil", + "should not notify undefined keys in restrict listen mode", "KEYCODE_VOLUME_DOWN")) + val h = Harness(enableHold = false) + tracking.restore(null, h.edges) + h.duplicatedLine(100) + h.clock.advanceTo(1000) + assertTrue(h.gestures.isEmpty()) + h.duplicatedLine(2000) + h.duplicatedLine(2100) + h.clock.advanceTo(3000) + assertEquals(listOf(Gesture.SINGLE), h.gestures) + } } diff --git a/app/src/test/java/com/heykay/snapkeymap/SettingsBackupTest.kt b/app/src/test/java/com/heykay/snapkeymap/SettingsBackupTest.kt new file mode 100644 index 0000000..94e7f9c --- /dev/null +++ b/app/src/test/java/com/heykay/snapkeymap/SettingsBackupTest.kt @@ -0,0 +1,185 @@ +package com.heykay.snapkeymap + +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class SettingsBackupTest { + private val ringSilent = listOf(RingerMode.RING, RingerMode.SILENT) + private val vibrateRing = listOf(RingerMode.VIBRATE, RingerMode.RING) + private val source = Config( + enabled = false, + showConfirmations = false, + pausedApps = setOf("com.example.paused", "com.example.other"), + unlockedOnly = setOf(Gesture.DOUBLE, Gesture.TAP_HOLD), + unlockHintShown = true, + actions = mapOf( + Gesture.SINGLE to SnapAction.OpenApp("com.example.app", "Example app"), + Gesture.DOUBLE to SnapAction.CallContact("+123456789", "Example contact"), + Gesture.LONG to SnapAction.Ringer(ringSilent), + Gesture.TAP_HOLD to SnapAction.OpenLink("https://example.com/path?q=backup"), + ), + ringerPresets = listOf(vibrateRing, ringSilent), + keyEvent = LearnedKey(317, 759), + inputKey = InputKey("KEY_F24"), + logSignature = KeySignature("ExampleKey", "keyCode=# down", "1000"), + logKeyCode = "317", + holdRepeats = false, + releaseGapMs = 420L, + doublePressWindowMs = 500L, + holdMs = 900L, + theme = ThemeMode.DARK, + setupComplete = true, + introSeen = true, + grantMethod = GrantMethod.SHIZUKU, + setupSkipped = setOf(SetupPage.BATTERY, SetupPage.NOTIFICATIONS), + ) + + @Test + fun roundTripRestoresAllBackedUpFieldsAndPreservesCurrentSetupState() { + val current = Config( + enabled = false, + setupComplete = true, + introSeen = true, + grantMethod = GrantMethod.ADB, + setupSkipped = setOf(SetupPage.NOTIFICATIONS), + unlockHintShown = true, + ) + val actionKinds = listOf( + SnapAction.NoAction, + SnapAction.OpenApp("com.example.missing", "Missing app"), + SnapAction.OpenShortcut("intent:#Intent;action=example;end", "Example shortcut"), + SnapAction.OpenLink("https://example.com"), + SnapAction.CallContact("+987654321", "Another contact"), + SnapAction.Device(DeviceAction.SCREENSHOT), + SnapAction.Ringer(vibrateRing), + ) + actionKinds.forEach { action -> + val original = source.copy(actions = source.actions + (Gesture.SINGLE to action)) + val backup = parsed(backupToJson(original)) + listOf(Config(), current).forEach { destination -> + assertEquals(original.copy( + enabled = destination.enabled, + setupComplete = destination.setupComplete, + introSeen = destination.introSeen, + grantMethod = destination.grantMethod, + setupSkipped = destination.setupSkipped, + unlockHintShown = destination.unlockHintShown, + ), backup.applyTo(destination)) + } + } + } + + @Test + fun nullLearnedKeyFieldsAndSparseActionsRoundTrip() { + val defaults = Config() + assertEquals(defaults, parsed(backupToJson(defaults)).applyTo(source).copy( + enabled = defaults.enabled, + setupComplete = defaults.setupComplete, + introSeen = defaults.introSeen, + grantMethod = defaults.grantMethod, + setupSkipped = defaults.setupSkipped, + unlockHintShown = defaults.unlockHintShown, + )) + } + + @Test + fun newerVersionHasAnActionableError() { + assertEquals( + BackupResult.Error("This backup is from a newer SnapKey Map. Update the app first."), + parseBackup("""{"format":2}"""), + ) + } + + @Test + fun rejectsMalformedTextAndMissingOrNonIntegerFormat() { + listOf("not json", "", "[]", "{}", "{\"format\":", backupToJson(source) + " trailing").forEach(::assertRejected) + listOf("1", 1.5, true, JSONObject.NULL).forEach { format -> + assertRejected(json().put("format", format).toString()) + } + assertRejected(json().put("format", 0).toString()) + assertRejected(json().apply { remove("format") }.toString()) + } + + @Test + fun rejectsUnknownGesturesEnumsAndActionKinds() { + assertRejected(json().apply { + getJSONObject("actions").put("TRIPLE", JSONObject(SnapAction.NoAction.toJson())) + }.toString()) + assertRejected(json().put("unlockedOnly", JSONArray(listOf("TRIPLE"))).toString()) + assertRejected(json().put("theme", "UNKNOWN").toString()) + assertRejected(json().apply { + getJSONObject("actions").put("SINGLE", JSONObject().put("type", "unknown")) + }.toString()) + assertRejected(json().apply { + getJSONObject("actions").put("SINGLE", JSONObject().put("type", "device").put("action", "UNKNOWN")) + }.toString()) + } + + @Test + fun rejectsInvalidRingerPresetsAndActionsWithoutApplyingAnything() { + listOf( + listOf("RING", "UNKNOWN"), + listOf("RING", "RING"), + listOf("RING"), + emptyList(), + ).forEach { modes -> + assertRejected(json().put("ringerPresets", JSONArray().put(JSONArray(modes))).toString()) + assertRejected(json().apply { + getJSONObject("actions").put("LONG", JSONObject().put("type", "ringer").put("modes", JSONArray(modes))) + }.toString()) + } + } + + @Test + fun rejectsWrongFieldTypesInsteadOfCoercingThem() { + assertRejected(json().put("showConfirmations", "false").toString()) + assertRejected(json().put("holdMs", "900").toString()) + assertRejected(json().put("pausedApps", JSONArray(listOf(42))).toString()) + assertRejected(json().apply { getJSONObject("key").getJSONObject("keyEvent").put("keyCode", 2147483648L) }.toString()) + assertRejected(json().apply { getJSONObject("key").remove("inputKey") }.toString()) + assertRejected(json().apply { getJSONObject("actions").getJSONObject("DOUBLE").put("number", 123) }.toString()) + } + + @Test + fun presetsIncludeAssignedModesWithoutDuplicates() { + val backup = parsed(json().put("ringerPresets", JSONArray(ringerPresetsToJson(listOf(vibrateRing, vibrateRing)))).toString()) + assertEquals(listOf(vibrateRing, ringSilent), backup.applyTo(Config()).ringerPresets) + val empty = parsed(json().put("ringerPresets", JSONArray()).toString()) + assertEquals(DEFAULT_RINGER_PRESETS + listOf(ringSilent), empty.applyTo(Config()).ringerPresets) + } + + @Test + fun logUidUsesTheExistingNormalization() { + val backup = parsed(json().apply { getJSONObject("key").getJSONObject("logSignature").put("uid", "system") }.toString()) + assertEquals("1000", backup.applyTo(Config()).logSignature?.uid) + } + + @Test + fun jsonUsesNestedObjectsAndExcludesSetupAndPermissionState() { + val json = json() + assertTrue(json.getJSONObject("actions").get("SINGLE") is JSONObject) + assertTrue(json.get("ringerPresets") is JSONArray) + listOf("enabled", "setupComplete", "introSeen", "grantMethod", "setupSkipped", "unlockHintShown").forEach { + assertFalse("Backup must not contain $it", json.has(it)) + assertFalse("Key must not contain $it", json.getJSONObject("key").has(it)) + } + } + + private fun json(): JSONObject = JSONObject(backupToJson(source)) + + private fun parsed(text: String): SettingsBackup { + val result = parseBackup(text) + assertTrue("Expected a valid backup, got $result", result is BackupResult.Ok) + return (result as BackupResult.Ok).backup + } + + private fun assertRejected(text: String) { + val result = parseBackup(text) + assertTrue("Expected a rejected backup, got $result", result is BackupResult.Error) + assertTrue((result as BackupResult.Error).message.isNotBlank()) + } +} diff --git a/app/src/test/java/com/heykay/snapkeymap/TeachingDeliveryTest.kt b/app/src/test/java/com/heykay/snapkeymap/TeachingDeliveryTest.kt new file mode 100644 index 0000000..a99ee62 --- /dev/null +++ b/app/src/test/java/com/heykay/snapkeymap/TeachingDeliveryTest.kt @@ -0,0 +1,62 @@ +package com.heykay.snapkeymap + +import org.junit.Assert.assertEquals +import org.junit.Test + +class TeachingDeliveryTest { + @Test + fun queuedRuntimeCallbacksCannotCrossEntryAndExitEvenWhenBothRecipientsAreRuntime() { + val gate = TeachingDelivery() + var actions = 0 + val before = gate.stamp + gate.advance(TeachingHandle(1)) + gate.deliver(before) { actions++ } + gate.advance(null) + gate.deliver(before) { actions++ } + assertEquals(0, actions) + gate.deliver(gate.stamp) { actions++ } + assertEquals(1, actions) + } + + @Test + fun cancelledTeachingCallbackNeverFallsThroughToRuntimeAndRetryCannotInheritIt() { + val gate = TeachingDelivery() + gate.advance(TeachingHandle(1)) + val oldLog = gate.stamp + val oldInput = gate.stamp + var teachingSamples = 0 + var runtimeActions = 0 + fun deliver(receipt: TeachingDelivery.Stamp) = gate.deliver(receipt) { + if (gate.stamp.handle == null) runtimeActions++ else teachingSamples++ + } + gate.advance(null) + deliver(oldLog) + deliver(oldInput) + gate.advance(TeachingHandle(2)) + deliver(oldLog) + deliver(oldInput) + assertEquals(0, runtimeActions) + assertEquals(0, teachingSamples) + deliver(gate.stamp) + assertEquals(1, teachingSamples) + } + + @Test + fun phaseBoundaryRejectsLateCaptureButSettlingAndReadyKeepCheckingTheSameReceipt() { + val gate = TeachingDelivery() + val owner = TeachingHandle(7) + gate.advance(owner) + val capture = gate.stamp + gate.advance(owner) + val candidate = gate.stamp + gate.advance(owner) + val checking = gate.stamp + var samples = 0 + gate.deliver(capture) { samples++ } + gate.deliver(candidate) { samples++ } + gate.deliver(checking) { samples++ } + assertEquals(1, samples) + gate.deliver(checking) { samples++ } + assertEquals(2, samples) + } +} diff --git a/app/src/test/java/com/heykay/snapkeymap/TeachingFalsePositiveTest.kt b/app/src/test/java/com/heykay/snapkeymap/TeachingFalsePositiveTest.kt new file mode 100644 index 0000000..eb5ef35 --- /dev/null +++ b/app/src/test/java/com/heykay/snapkeymap/TeachingFalsePositiveTest.kt @@ -0,0 +1,55 @@ +package com.heykay.snapkeymap + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class TeachingFalsePositiveTest { + @Test + fun positiveOnlyF12TeachingAcceptsGenericStylusLogFromUnseenF11() { + val baseline = 0L..5000L + val taps = listOf(6000L..9000L, 10000L..13000L, 14000L..17000L) + val hold = 18000L..21500L + val syntheticWriterUid = "424242" + val tag = "StylusModule" + val reportedSignature = "StylusModule.onUpdateToolType():# Update tool type = #" + + // Only the normalized signature was reported. UID, numbers, and times are synthetic. + // F12 (142) and F11 (141) describe the scenario, not metadata carried by this log. + val f12TeachingLogs = listOf(7000L, 11000L, 15000L, 18200L).mapIndexed { index, time -> + Observation(time, KeyLearning.logKey( + syntheticWriterUid, tag, "StylusModule.onUpdateToolType():${900 + index} Update tool type = ${10 + index}", + )) + } + val baselineNoise = Observation(1000L, KeyLearning.logKey( + syntheticWriterUid, "SyntheticBackground", "idle sample 1", + )) + val observations = listOf(baselineNoise) + f12TeachingLogs + val genericLog = KeyLearning.logKey(syntheticWriterUid, tag, reportedSignature) + assertFalse(observations.any { it.timeMs in baseline && it.key == genericLog }) + + val result = KeyLearning.analyze(observations, baseline, taps, hold) as LearnResult.LogLineFound + + assertEquals(KeySignature(tag, reportedSignature, syntheticWriterUid), result.signature) + assertEquals(null, result.inputKey) + assertEquals(null, result.logKeyCode) + val config = Config( + enabled = true, + logSignature = result.signature, + logKeyCode = result.logKeyCode, + holdRepeats = result.holdRepeats, + releaseGapMs = result.releaseGapMs, + ) + assertTrue(config.isTaught) + + // This negative challenge is withheld from analyze, as in positive-only teaching. + val unseenF11Message = "StylusModule.onUpdateToolType():9876 Update tool type = 54" + assertEquals(reportedSignature, normalizeLogMessage(unseenF11Message)) + val acceptedByFullLogFallback = KeyMatching.matches(config.keyBinding(), + KeySample.Log(syntheticWriterUid, tag, unseenF11Message, null)) + + assertTrue("The unseen F11 log incorrectly passes the learned F12 runtime filter", acceptedByFullLogFallback) + println("REPRO synthetic positive-only F12 teaching learned StylusModule; unseen F11 passed full non-Oplus log acceptance") + } +} diff --git a/app/src/test/java/com/heykay/snapkeymap/TeachingLogDeliveryTest.kt b/app/src/test/java/com/heykay/snapkeymap/TeachingLogDeliveryTest.kt new file mode 100644 index 0000000..29bea88 --- /dev/null +++ b/app/src/test/java/com/heykay/snapkeymap/TeachingLogDeliveryTest.kt @@ -0,0 +1,309 @@ +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 TeachingLogDeliveryTest { + private class Clock { + var now = 0L + private val tasks = mutableMapOf() + + fun schedule(task: Runnable, delay: Long) { tasks[task] = now + delay } + fun cancel(task: Runnable) { tasks.remove(task) } + fun advanceTo(time: Long) { + while (true) { + val next = tasks.entries.minByOrNull { it.value } ?: break + if (next.value > time) break + now = next.value + tasks.remove(next.key) + next.key.run() + } + now = time + } + } + + private class Harness(enableLong: Boolean = false) { + val clock = Clock() + val delivery = TeachingDelivery() + val tracking = TeachingLogEdges() + val context = LoggedKeyContext() + var config = Config(logSignature = KeySignature(TAG, MESSAGE, "1000"), logKeyCode = "KEYCODE_F12").let { + if (enableLong) it.copy(actions = it.actions + (Gesture.LONG to SnapAction.Device(DeviceAction.FLASHLIGHT))) else it + } + var session: TeachingSession? = null + var deliveredSamples = 0 + var seenEdges = 0 + val history = mutableListOf>() + val actions = mutableListOf() + 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.