Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

fix(ball): switch Night Light off around the screenshots the user takes (#78)

Durganshuba8568123265
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 3f32267..2f98173 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -55,6 +55,11 @@
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
+ <!-- Never granted at install: the user runs `adb shell pm grant` once so Gotcha can
+ switch Night Light off around the screenshots they take (#78). -->
+ <uses-permission
+ android:name="android.permission.WRITE_SECURE_SETTINGS"
+ tools:ignore="ProtectedPermissions" />
<!-- Tier 3: component-based / device-wide special access -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
diff --git a/app/src/main/assets/app/about-gotcha.md b/app/src/main/assets/app/about-gotcha.md
index ab28d2b..0596d56 100644
--- a/app/src/main/assets/app/about-gotcha.md
+++ b/app/src/main/assets/app/about-gotcha.md
@@ -73,7 +73,7 @@ Everything below is reached from **Settings** in the navigation drawer.
| Termux (Linux shell) | Guided setup for the Linux shell used by `run_termux_command` and audio conversion |
| Skills / Plugins | Built-in skills, importing community skills by URL, allowed community skill hosts |
| Proactive Assistance | Master switch for proactive offers, OTP/code detection, auto-copy OTP, and what may be scanned (screen content, notifications, clipboard) |
-| Assistive Ball and Wake Word | The floating ball over other apps, hands-free voice calls, the "Hey Gotcha" wake word, when it listens, and detection sensitivity |
+| Assistive Ball and Wake Word | The floating ball over other apps, hands-free voice calls, turning Night Light off for screenshots, the "Hey Gotcha" wake word, when it listens, and detection sensitivity |
| Appearance | Theme |
| Notifications | Reply chime and vibration; the task-finished notification and its reply preview; Gotcha notifications (reminders about unfinished chats, routines that are due and quiet spells, the daily tip, quiet hours, a daily cap, whether chats may be named, clearing the history); and server messages. The bell on the chat screen opens the list of recent notifications, and a chat's ⋮ menu keeps that chat out of notifications |
| About | Samosa AI, other products, legal, contact |
@@ -115,6 +115,7 @@ missing, where to turn it on, and offer to try again afterwards.
| Notification access | Reading and dismissing notifications, media control, now playing | Settings > Permissions |
| Device admin | Lock screen, disable camera, password policy | Settings > Permissions |
| Root | Root commands and secure-settings writes | A rooted device; `check_root` reports the truth |
+| The secure-settings grant (or root) | Turning Night Light off for ball and Screen Lens screenshots, so they come out without its tint | Once, from a computer: `adb shell pm grant com.gotcha android.permission.WRITE_SECURE_SETTINGS`; Settings > Assistive Ball and Wake Word shows the command |
| Termux | Termux commands, audio conversion, pulling files out of Termux | Install Termux from F-Droid, then Settings > Termux (Linux shell) |
| Health Connect | Health summaries and records | Settings > Permissions > Health |
| Display over other apps | The overlay tools and the Assistive Ball | Settings > Permissions |
diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
index f4dcf12..b950d51 100644
--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt
+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
@@ -181,6 +181,12 @@ data class Settings(
val wakeWordEnabled: Boolean = false,
val wakeWordSensitivity: Float = 0.75f,
val wakeWordListeningMode: WakeWordListeningMode = WakeWordListeningMode.ALWAYS,
+ /**
+ * Switch Night Light off for screenshots the user takes from the ball or Screen
+ * Lens, then back on (#78). Off by default: the screen visibly loses its tint
+ * for a few seconds, and it only works with the secure-settings grant or root.
+ */
+ val pauseNightLightForScreenshots: Boolean = false,
/** Server-driven notifications from `<SAMOSA_API_URL>/v1/gotcha/notifications`. */
val serverMessagesEnabled: Boolean = true,
/** Epoch millis of the last successful server-messages fetch. 0 = never. */
@@ -586,6 +592,7 @@ class SettingsRepository(context: Context) : SettingsStore {
wakeWordListeningMode = runCatching {
WakeWordListeningMode.valueOf(string(KEY_WAKE_WORD_LISTENING_MODE, "ALWAYS"))
}.getOrDefault(WakeWordListeningMode.ALWAYS),
+ pauseNightLightForScreenshots = prefs.getBoolean(KEY_PAUSE_NIGHT_LIGHT, false),
serverMessagesEnabled = prefs.getBoolean(KEY_SERVER_MESSAGES_ENABLED, true),
serverMessagesLastFetchedAt = prefs.getLong(KEY_SERVER_MESSAGES_LAST_FETCHED, 0L),
serverMessagesEtag = string(KEY_SERVER_MESSAGES_ETAG),
@@ -673,6 +680,7 @@ class SettingsRepository(context: Context) : SettingsStore {
.putBoolean(KEY_WAKE_WORD_ENABLED, settings.wakeWordEnabled)
.putFloat(KEY_WAKE_WORD_SENSITIVITY, settings.wakeWordSensitivity)
.putString(KEY_WAKE_WORD_LISTENING_MODE, settings.wakeWordListeningMode.name)
+ .putBoolean(KEY_PAUSE_NIGHT_LIGHT, settings.pauseNightLightForScreenshots)
.putBoolean(KEY_SERVER_MESSAGES_ENABLED, settings.serverMessagesEnabled)
.putLong(KEY_SERVER_MESSAGES_LAST_FETCHED, settings.serverMessagesLastFetchedAt)
.putString(KEY_SERVER_MESSAGES_ETAG, settings.serverMessagesEtag)
@@ -800,6 +808,7 @@ class SettingsRepository(context: Context) : SettingsStore {
const val KEY_WAKE_WORD_ENABLED = "wake_word_enabled"
const val KEY_WAKE_WORD_SENSITIVITY = "wake_word_sensitivity"
const val KEY_WAKE_WORD_LISTENING_MODE = "wake_word_listening_mode"
+ const val KEY_PAUSE_NIGHT_LIGHT = "pause_night_light_for_screenshots"
const val KEY_SERVER_MESSAGES_ENABLED = "server_messages_enabled"
const val KEY_SERVER_MESSAGES_LAST_FETCHED = "server_messages_last_fetched"
const val KEY_SERVER_MESSAGES_ETAG = "server_messages_etag"
diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
index dd13945..ffaccfe 100644
--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
@@ -320,10 +320,12 @@ class AssistiveBallService : Service() {
// capture returns null and the prompt is left to the chat flow.
val compressed = if (attachScreenshot) {
showingActivity(com.gotcha.ui.BallActivity.ACTING) {
- com.gotcha.tools.ScreenPerception.compressScreenshot(
- maxDimension = 1024,
- quality = 85
- )
+ DisplayTintGuard.get(applicationContext).withTintSuspended {
+ com.gotcha.tools.ScreenPerception.compressScreenshot(
+ maxDimension = 1024,
+ quality = 85
+ )
+ }
}
} else {
null
@@ -1046,11 +1048,12 @@ class AssistiveBallService : Service() {
chatWindow.setVisibleForCapture(false)
screenCompanionPanel.setVisibleForCapture(false)
}
- delay(250L)
- var bitmap = service.takeScreenshotBitmap()
- if (bitmap == null) {
- delay(800L)
- bitmap = service.takeScreenshotBitmap()
+ val bitmap = DisplayTintGuard.get(applicationContext).withTintSuspended {
+ delay(250L)
+ service.takeScreenshotBitmap() ?: run {
+ delay(800L)
+ service.takeScreenshotBitmap()
+ }
}
withContext(Dispatchers.Main) {
overlay.showChromeAfterCapture()
diff --git a/app/src/main/java/com/gotcha/service/DisplayTintGuard.kt b/app/src/main/java/com/gotcha/service/DisplayTintGuard.kt
new file mode 100644
index 0000000..5c15f2b
--- /dev/null
+++ b/app/src/main/java/com/gotcha/service/DisplayTintGuard.kt
@@ -0,0 +1,163 @@
+package com.gotcha.service
+
+import android.Manifest
+import android.content.Context
+import android.content.pm.PackageManager
+import android.provider.Settings
+import com.gotcha.data.SettingsRepository
+import com.gotcha.tools.RootTool
+import kotlinx.coroutines.NonCancellable
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withContext
+
+/**
+ * Keeps Night Light out of the screenshots the user asks for (#78).
+ *
+ * On some phones the Night Light tint is baked into what the screenshot API
+ * returns, so a ball screenshot or a Screen Lens crop comes out yellow and the
+ * model reads colours wrong. The only way around it is to switch Night Light off
+ * for the capture and back on after, which is what [withTintSuspended] does.
+ *
+ * Switching it is a `Settings.Secure` write, so it needs `WRITE_SECURE_SETTINGS`
+ * (a one-time `adb pm grant`) or root; without either, and whenever the setting
+ * is off or Night Light already is, the capture runs untouched. Only captures the
+ * user triggers go through here — a background poll would make the screen blink.
+ *
+ * Night Light fades rather than switching, so the capture waits [settleMillis]
+ * for the fade to finish. A capture that overlaps another shares its suspension
+ * and the last one out restores the tint. Before switching Night Light off the
+ * guard leaves a [PendingRestore] marker; if the process dies before restoring,
+ * [recoverIfInterrupted] turns it back on at the next service start instead of
+ * leaving the user's screen blue for good.
+ */
+class DisplayTintGuard(
+ private val access: SecureSettingAccess,
+ private val pending: PendingRestore,
+ private val isEnabled: () -> Boolean,
+ private val settleMillis: Long = SETTLE_MILLIS
+) {
+ /** Reads and writes one `Settings.Secure` integer; false/null when it can't. */
+ interface SecureSettingAccess {
+ fun read(key: String): Int?
+ fun write(key: String, value: Int): Boolean
+ }
+
+ /** Durable "Night Light was switched off by us and not yet restored" flag. */
+ interface PendingRestore {
+ var isPending: Boolean
+ }
+
+ private val mutex = Mutex()
+ private var holders = 0
+
+ /** Runs [block] with Night Light off when the guard applies, restoring it after. */
+ suspend fun <T> withTintSuspended(block: suspend () -> T): T {
+ val suspended = acquire()
+ try {
+ return block()
+ } finally {
+ if (suspended) withContext(NonCancellable) { release() }
+ }
+ }
+
+ /** Restores Night Light if a previous process switched it off and died. */
+ suspend fun recoverIfInterrupted() {
+ mutex.withLock {
+ if (holders == 0 && pending.isPending && access.write(NIGHT_DISPLAY_ACTIVATED, 1)) {
+ pending.isPending = false
+ }
+ }
+ }
+
+ private suspend fun acquire(): Boolean = mutex.withLock {
+ if (holders > 0) {
+ holders++
+ return@withLock true
+ }
+ if (!isEnabled() || access.read(NIGHT_DISPLAY_ACTIVATED) != 1) return@withLock false
+ pending.isPending = true
+ if (!access.write(NIGHT_DISPLAY_ACTIVATED, 0)) {
+ pending.isPending = false
+ return@withLock false
+ }
+ holders = 1
+ // Held under the lock so an overlapping capture can't start mid-fade.
+ delay(settleMillis)
+ true
+ }
+
+ private suspend fun release() {
+ mutex.withLock {
+ holders--
+ // A failed restore keeps the marker, so the next start retries it.
+ if (holders == 0 && access.write(NIGHT_DISPLAY_ACTIVATED, 1)) {
+ pending.isPending = false
+ }
+ }
+ }
+
+ companion object {
+ const val NIGHT_DISPLAY_ACTIVATED = "night_display_activated"
+
+ /**
+ * AOSP fades Night Light over 3 s (ColorDisplayService's transition
+ * duration). OEM builds may differ; tune on a device that shows the tint.
+ */
+ const val SETTLE_MILLIS = 3_000L
+
+ const val GRANT_COMMAND =
+ "adb shell pm grant com.gotcha android.permission.WRITE_SECURE_SETTINGS"
+
+ private const val PREFS = "display_tint_guard"
+ private const val KEY_PENDING = "night_light_restore_pending"
+
+ @Volatile private var shared: DisplayTintGuard? = null
+
+ /** The process-wide guard; one instance so overlapping captures share it. */
+ fun get(context: Context): DisplayTintGuard =
+ shared ?: synchronized(this) {
+ shared ?: create(context.applicationContext).also { shared = it }
+ }
+
+ /** True when Gotcha may write secure settings without root. */
+ fun hasSecureSettingsGrant(context: Context): Boolean =
+ context.checkSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS) ==
+ PackageManager.PERMISSION_GRANTED
+
+ private fun create(context: Context): DisplayTintGuard {
+ val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
+ // commit, not apply: the marker has to be on disk before the write it
+ // guards, or a kill in between leaves nothing to recover from.
+ val pending = object : PendingRestore {
+ override var isPending: Boolean
+ get() = prefs.getBoolean(KEY_PENDING, false)
+ set(value) { prefs.edit().putBoolean(KEY_PENDING, value).commit() }
+ }
+ return DisplayTintGuard(
+ access = AndroidSecureSettings(context),
+ pending = pending,
+ isEnabled = { SettingsRepository(context).load().pauseNightLightForScreenshots }
+ )
+ }
+ }
+}
+
+/** Direct `Settings.Secure` access with the ADB grant, root as the fallback. */
+private class AndroidSecureSettings(private val context: Context) : DisplayTintGuard.SecureSettingAccess {
+ private val rootTool by lazy { RootTool() }
+
+ override fun read(key: String): Int? =
+ runCatching { Settings.Secure.getInt(context.contentResolver, key) }.getOrNull()
+ ?: rootTool.readSecureSetting("secure", key)?.toIntOrNull()
+
+ override fun write(key: String, value: Int): Boolean {
+ if (DisplayTintGuard.hasSecureSettingsGrant(context) &&
+ runCatching { Settings.Secure.putInt(context.contentResolver, key, value) }.getOrDefault(false)
+ ) {
+ return true
+ }
+ return rootTool.writeSecureSetting("secure", key, value.toString()).success
+ }
+}
diff --git a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
index 0375611..f9ca326 100644
--- a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
+++ b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
@@ -11,6 +11,9 @@ import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import androidx.annotation.RequiresApi
import com.gotcha.util.GotchaLog
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
@@ -36,6 +39,10 @@ class GotchaAccessibilityService : AccessibilityService() {
super.onServiceConnected()
instance = this
initClipboardListener()
+ // Every capture runs through this service, and the system rebinds it after
+ // the process dies, so a capture killed with Night Light off is undone here.
+ val guard = DisplayTintGuard.get(this)
+ CoroutineScope(Dispatchers.IO).launch { guard.recoverIfInterrupted() }
}
// Passive: we drive the UI on demand from tools rather than reacting to events,
diff --git a/app/src/main/java/com/gotcha/service/ScreenLensController.kt b/app/src/main/java/com/gotcha/service/ScreenLensController.kt
index 5e51920..95b7d25 100644
--- a/app/src/main/java/com/gotcha/service/ScreenLensController.kt
+++ b/app/src/main/java/com/gotcha/service/ScreenLensController.kt
@@ -176,11 +176,12 @@ class ScreenLensController(
overlay?.setCaptureMode(true)
onCaptureChrome(true)
}
- kotlinx.coroutines.delay(250L)
- var full = service.takeScreenshotBitmap()
- if (full == null) {
- kotlinx.coroutines.delay(600L)
- full = service.takeScreenshotBitmap()
+ val full = DisplayTintGuard.get(appContext).withTintSuspended {
+ kotlinx.coroutines.delay(250L)
+ service.takeScreenshotBitmap() ?: run {
+ kotlinx.coroutines.delay(600L)
+ service.takeScreenshotBitmap()
+ }
}
withContext(Dispatchers.Main) {
onCaptureChrome(false)
diff --git a/app/src/main/java/com/gotcha/tools/RootTool.kt b/app/src/main/java/com/gotcha/tools/RootTool.kt
index c834cab..492d4a7 100644
--- a/app/src/main/java/com/gotcha/tools/RootTool.kt
+++ b/app/src/main/java/com/gotcha/tools/RootTool.kt
@@ -88,6 +88,18 @@ class RootTool(
}
}
+ /**
+ * Read a setting via `settings get`, for keys an app can't read itself. Null when
+ * there is no root, the key is unset, or the arguments are unsafe.
+ */
+ fun readSecureSetting(namespace: String, key: String): String? {
+ val ns = namespace.trim().lowercase()
+ if (ns !in setOf("system", "secure", "global") || key.isBlank() || unsafeArg(key)) return null
+ val result = exec("settings get $ns $key") ?: return null
+ val value = result.output.trim()
+ return if (result.exit == 0 && value.isNotEmpty() && value != "null") value else null
+ }
+
private fun unsafeArg(s: String): Boolean =
s.any { it in "\n\r;&|`$()<>\"'\\ " }
diff --git a/app/src/main/java/com/gotcha/ui/AssistiveBallScreen.kt b/app/src/main/java/com/gotcha/ui/AssistiveBallScreen.kt
index 9f890e3..a484b8d 100644
--- a/app/src/main/java/com/gotcha/ui/AssistiveBallScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/AssistiveBallScreen.kt
@@ -1,5 +1,7 @@
package com.gotcha.ui
+import android.content.ClipData
+import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
@@ -30,9 +32,11 @@ import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import com.gotcha.data.Settings
import com.gotcha.data.WakeWordListeningMode
+import com.gotcha.service.DisplayTintGuard
import android.provider.Settings as AndroidSettings
/**
@@ -62,6 +66,7 @@ fun AssistiveBallScreen(
var wakeWordEnabled by remember { mutableStateOf(initial.wakeWordEnabled) }
var wakeWordSensitivity by remember { mutableStateOf(initial.wakeWordSensitivity) }
var wakeWordListeningMode by remember { mutableStateOf(initial.wakeWordListeningMode) }
+ var pauseNightLight by remember { mutableStateOf(initial.pauseNightLightForScreenshots) }
// The wake word runs inside the ball service, so it cannot be on while the
// ball is off. When the ball is switched off here (or this screen is opened
@@ -95,6 +100,21 @@ fun AssistiveBallScreen(
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
+ SettingsToggleRow(
+ label = "Night Light off for screenshots",
+ checked = pauseNightLight,
+ onCheckedChange = {
+ pauseNightLight = it
+ onSave { settings -> settings.copy(pauseNightLightForScreenshots = it) }
+ },
+ switchTestTag = "settings_pause_night_light",
+ switchContentDescription = if (pauseNightLight) {
+ "Stop turning Night Light off for screenshots"
+ } else {
+ "Turn Night Light off for screenshots"
+ }
+ )
+ NightLightGrantHint()
SettingsToggleRow(
label = "Wake word: Hey Gotcha",
checked = wakeWordEnabled,
@@ -211,6 +231,51 @@ fun AssistiveBallScreen(
}
}
+/**
+ * What "Night Light off for screenshots" does, and how to let it. The grant is
+ * an adb command because no Settings screen can hand out WRITE_SECURE_SETTINGS;
+ * tapping the command copies it. Root works too, so the switch is never locked.
+ */
+@Composable
+private fun NightLightGrantHint() {
+ val context = LocalContext.current
+ val granted = remember(context) { DisplayTintGuard.hasSecureSettingsGrant(context) }
+ Text(
+ "Some phones keep the Night Light tint in screenshots. With this on, a " +
+ "screenshot or Screen Lens capture from the ball turns Night Light off, " +
+ "waits a few seconds for the colours to settle, captures, and turns it " +
+ "back on. The screen shows its normal colours meanwhile.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ if (granted) {
+ Text(
+ "Gotcha has permission to switch Night Light.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ } else {
+ Text(
+ "Needs a one-time grant from a computer (or root). Connect with adb and " +
+ "run this — tap to copy:",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ Text(
+ DisplayTintGuard.GRANT_COMMAND,
+ style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable {
+ context.getSystemService(ClipboardManager::class.java)
+ ?.setPrimaryClip(ClipData.newPlainText("adb command", DisplayTintGuard.GRANT_COMMAND))
+ }
+ .padding(vertical = 4.dp)
+ .testTag("settings_pause_night_light_command")
+ )
+ }
+}
+
// Labels mirror the model card's three recommended thresholds (0.65 / 0.50 /
// 0.35). Split points on the slider are the inverse of
// `threshold = 0.70 - 0.27 * sensitivity`:
diff --git a/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt b/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt
index 64aefdd..a9faf32 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt
@@ -200,6 +200,11 @@ private fun entryFor(page: SettingsPage): SettingsSearchEntry = when (page) {
words("overlay, hands free, hands-free"),
listOf(
field("settings_assistive_ball", "Show assistive ball", "floating ball, bubble"),
+ field(
+ "settings_pause_night_light",
+ "Night Light off for screenshots",
+ "night mode, blue light, yellow tint, eye comfort, screenshot colours, screenshot colors"
+ ),
field("settings_wake_word", "Wake word: Hey Gotcha", "always listening"),
field("settings_wake_word_sensitivity", "Wake word sensitivity", "sensitivity")
)
diff --git a/app/src/test/java/com/gotcha/data/SettingsTest.kt b/app/src/test/java/com/gotcha/data/SettingsTest.kt
index 23a6544..e9af67f 100644
--- a/app/src/test/java/com/gotcha/data/SettingsTest.kt
+++ b/app/src/test/java/com/gotcha/data/SettingsTest.kt
@@ -319,6 +319,11 @@ class SettingsTest {
assertEquals(0.75f, defaults.wakeWordSensitivity, 0.001f)
}
+ @Test
+ fun `Night Light is left alone for screenshots unless the user opts in`() {
+ assertEquals(false, Settings().pauseNightLightForScreenshots)
+ }
+
@Test
fun `wake word settings are independent fields on copy`() {
val defaults = Settings()
diff --git a/app/src/test/java/com/gotcha/service/DisplayTintGuardTest.kt b/app/src/test/java/com/gotcha/service/DisplayTintGuardTest.kt
new file mode 100644
index 0000000..2cd6aea
--- /dev/null
+++ b/app/src/test/java/com/gotcha/service/DisplayTintGuardTest.kt
@@ -0,0 +1,151 @@
+package com.gotcha.service
+
+import com.gotcha.service.DisplayTintGuard.Companion.NIGHT_DISPLAY_ACTIVATED
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.async
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.test.advanceUntilIdle
+import kotlinx.coroutines.test.runTest
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Assert.fail
+import org.junit.Test
+
+class DisplayTintGuardTest {
+
+ /** Night Light as the fake settings store sees it, with a log of every write. */
+ private class FakeSettings(var nightLight: Int?, var writable: Boolean = true) :
+ DisplayTintGuard.SecureSettingAccess {
+ val writes = mutableListOf<Int>()
+ override fun read(key: String): Int? = if (key == NIGHT_DISPLAY_ACTIVATED) nightLight else null
+ override fun write(key: String, value: Int): Boolean {
+ if (!writable) return false
+ writes += value
+ nightLight = value
+ return true
+ }
+ }
+
+ private class FakePending : DisplayTintGuard.PendingRestore {
+ override var isPending: Boolean = false
+ }
+
+ private fun guard(settings: FakeSettings, pending: FakePending = FakePending(), enabled: Boolean = true) =
+ DisplayTintGuard(settings, pending, isEnabled = { enabled }, settleMillis = 3_000L)
+
+ @Test
+ fun `turns Night Light off for the capture and back on after`() = runTest {
+ val settings = FakeSettings(nightLight = 1)
+ val pending = FakePending()
+ val seen = guard(settings, pending).withTintSuspended {
+ assertTrue("marker set while suspended", pending.isPending)
+ settings.nightLight
+ }
+ assertEquals(0, seen)
+ assertEquals(listOf(0, 1), settings.writes)
+ assertFalse(pending.isPending)
+ }
+
+ @Test
+ fun `waits for the fade before capturing`() = runTest {
+ val start = testScheduler.currentTime
+ guard(FakeSettings(nightLight = 1)).withTintSuspended {
+ assertEquals(3_000L, testScheduler.currentTime - start)
+ }
+ }
+
+ @Test
+ fun `leaves everything alone when Night Light is already off`() = runTest {
+ val settings = FakeSettings(nightLight = 0)
+ val start = testScheduler.currentTime
+ guard(settings).withTintSuspended { }
+ assertTrue(settings.writes.isEmpty())
+ assertEquals("no settle delay", start, testScheduler.currentTime)
+ }
+
+ @Test
+ fun `leaves everything alone when the setting is off`() = runTest {
+ val settings = FakeSettings(nightLight = 1)
+ guard(settings, enabled = false).withTintSuspended { }
+ assertTrue(settings.writes.isEmpty())
+ }
+
+ @Test
+ fun `captures as before when it may not write secure settings`() = runTest {
+ val settings = FakeSettings(nightLight = 1, writable = false)
+ val pending = FakePending()
+ val result = guard(settings, pending).withTintSuspended { "captured" }
+ assertEquals("captured", result)
+ assertEquals(1, settings.nightLight)
+ assertFalse(pending.isPending)
+ }
+
+ @Test
+ fun `restores Night Light when the capture throws`() = runTest {
+ val settings = FakeSettings(nightLight = 1)
+ try {
+ guard(settings).withTintSuspended { error("capture failed") }
+ fail("expected the capture's exception")
+ } catch (_: IllegalStateException) {
+ }
+ assertEquals(1, settings.nightLight)
+ }
+
+ @Test
+ fun `restores Night Light when the capture is cancelled`() = runTest {
+ val settings = FakeSettings(nightLight = 1)
+ val started = CompletableDeferred<Unit>()
+ val job = launch {
+ guard(settings).withTintSuspended {
+ started.complete(Unit)
+ CompletableDeferred<Unit>().await()
+ }
+ }
+ started.await()
+ job.cancel(CancellationException("user left"))
+ job.join()
+ assertEquals(1, settings.nightLight)
+ }
+
+ @Test
+ fun `overlapping captures restore once, after the last`() = runTest {
+ val settings = FakeSettings(nightLight = 1)
+ val g = guard(settings)
+ val releaseFirst = CompletableDeferred<Unit>()
+ val first = async { g.withTintSuspended { releaseFirst.await() } }
+ advanceUntilIdle()
+ val second = async { g.withTintSuspended { settings.nightLight } }
+ assertEquals("second capture also sees Night Light off", 0, second.await())
+ assertEquals("still off while the first is running", 0, settings.nightLight)
+ releaseFirst.complete(Unit)
+ first.await()
+ assertEquals(listOf(0, 1), settings.writes)
+ }
+
+ @Test
+ fun `a restore interrupted by a process death is finished on the next start`() = runTest {
+ // What a kill mid-capture leaves behind: Night Light off, marker set.
+ val settings = FakeSettings(nightLight = 0)
+ val pending = FakePending().apply { isPending = true }
+ guard(settings, pending).recoverIfInterrupted()
+ assertEquals(1, settings.nightLight)
+ assertFalse(pending.isPending)
+ }
+
+ @Test
+ fun `recovery does nothing without a marker`() = runTest {
+ val settings = FakeSettings(nightLight = 0)
+ guard(settings).recoverIfInterrupted()
+ assertTrue(settings.writes.isEmpty())
+ }
+
+ @Test
+ fun `a failed restore keeps the marker for the next start`() = runTest {
+ val settings = FakeSettings(nightLight = 1)
+ val pending = FakePending()
+ guard(settings, pending).withTintSuspended { settings.writable = false }
+ assertTrue(pending.isPending)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/ui/SettingsSearchEntryTest.kt b/app/src/test/java/com/gotcha/ui/SettingsSearchEntryTest.kt
index 9562fab..ba44aba 100644
--- a/app/src/test/java/com/gotcha/ui/SettingsSearchEntryTest.kt
+++ b/app/src/test/java/com/gotcha/ui/SettingsSearchEntryTest.kt
@@ -23,6 +23,14 @@ class SettingsSearchEntryTest {
assertTrue(SettingsPage.PERMISSIONS in pagesFor("accessibility"))
}
+ @Test
+ fun nightLightFindsTheScreenshotSwitch() {
+ for (query in listOf("night light", "night mode", "yellow tint")) {
+ val result = filterSettings(query).single { it.page == SettingsPage.ASSISTIVE_BALL }
+ assertEquals(query, "settings_pause_night_light", result.field?.testTag)
+ }
+ }
+
@Test
fun matchingIsCaseInsensitive() {
assertEquals(pagesFor("api key"), pagesFor("API KEY"))