"App blocked to protect your device" (Play Protect)
@@ -227,6 +227,6 @@ NotificationListenerService ──► NotificationStore ──► LedController
-[Changelog](CHANGELOG.md) · [All downloads](releases/) · [MIT License](LICENSE)
+[Changelog](CHANGELOG.md) · [All downloads](https://github.com/mx57/LED/releases) · [MIT License](LICENSE)
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 0774473..cf8a128 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -26,8 +26,13 @@ android {
applicationId = "com.glowled.app"
minSdk = 29
targetSdk = 35
- versionCode = 34
- versionName = "2.10.1"
+ versionCode = 36
+ versionName = "2.11.1"
+
+ val updateRepo = (project.findProperty("UPDATE_REPO") as? String) ?: "mx57/LED"
+ val expectedSha = (project.findProperty("EXPECTED_SIGNING_SHA256") as? String) ?: ""
+ buildConfigField("String", "UPDATE_REPO", "\"$updateRepo\"")
+ buildConfigField("String", "EXPECTED_SIGNING_SHA256", "\"$expectedSha\"")
}
signingConfigs {
@@ -47,8 +52,38 @@ android {
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
- val release = signingConfigs.getByName("release")
- signingConfig = if (release.storeFile != null) release else signingConfigs.getByName("debug")
+ val releaseSign = signingConfigs.getByName("release")
+ // The guard only fires when the invocation actually wants release OUTPUT
+ // (assembleRelease / bundle / build). Lint and unit tests also configure the
+ // release build type, and must stay runnable before the signing env exists -
+ // on a push event CI runs them before the keystore step decodes the secret.
+ val wantsReleaseOutput = gradle.startParameter.taskNames.any { name ->
+ val t = name.substringAfterLast(':')
+ t.equals("build", true) || t.equals("assemble", true) || t.equals("bundle", true) ||
+ t.contains("Release", true) || t.contains("Bundle", true)
+ }
+ when {
+ releaseSign.storeFile != null -> signingConfig = releaseSign
+ // Pull requests from other forks see no signing secrets: build a clearly marked
+ // test APK instead of failing the check. It is debug-signed and the CI publish
+ // gate (SIGNED != 'release' in build.yml) never publishes it.
+ System.getenv("GITHUB_EVENT_NAME") == "pull_request" -> {
+ signingConfig = signingConfigs.getByName("debug")
+ versionNameSuffix = "-test"
+ logger.warn("Glow LED: no release keystore on CI - building a TEST APK signed with the debug key; never publish it.")
+ }
+ // A release artifact without the release keystore fails loudly: a debug-signed
+ // 'release' breaks in-app updates (the updater pins the release certificate)
+ // and looks like a trustworthy build while it is not.
+ wantsReleaseOutput -> throw GradleException(
+ "Glow LED: no release keystore found (keystore.properties locally, or the " +
+ "GLOWLED_KEYSTORE env variables on CI). Refusing to build a release APK signed " +
+ "with the debug key. Configure release signing first, or build assembleDebug instead.",
+ )
+ // Lint/test only configure the release type; no release-signed output is
+ // produced, so let them run with the dormant debug signing config.
+ else -> signingConfig = signingConfigs.getByName("debug")
+ }
}
debug {
applicationIdSuffix = ".debug"
@@ -69,6 +104,13 @@ android {
testOptions {
unitTests.isReturnDefaultValues = true
}
+ lint {
+ // MissingTranslation stays ENABLED: every string must ship translated into all 12
+ // languages, and CI fails the build otherwise. (A blanket disable hid 32 untranslated
+ // keys in 11 locales for two releases.)
+ abortOnError = true
+ checkReleaseBuilds = false
+ }
dependenciesInfo {
includeInApk = false
includeInBundle = false
@@ -84,4 +126,5 @@ dependencies {
implementation("androidx.viewpager2:viewpager2:1.1.0")
testImplementation("junit:junit:4.13.2")
+ testImplementation("org.json:json:20240303")
}
diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro
index 88527e6..87f92de 100644
--- a/app/proguard-rules.pro
+++ b/app/proguard-rules.pro
@@ -1 +1,28 @@
-# Services, receivers, activities and XML-inflated views are kept via the manifest/aapt rules.
+# Services, receivers, activities and XML-inflated views are kept via manifest/aapt rules,
+# but explicit rules ensure R8 optimizer doesn't strip constructors, reflection targets, or data classes.
+
+# Preserve line numbers and source files for readable stacktraces in DebugLog and issue reports
+-keepattributes SourceFile,LineNumberTable
+
+# Custom Views instantiated programmatically or from XML
+-keep public class * extends android.view.View {
+ public (android.content.Context);
+ public (android.content.Context, android.util.AttributeSet);
+ public (android.content.Context, android.util.AttributeSet, int);
+}
+
+# Explicitly preserve all BroadcastReceivers and Services
+-keep class * extends android.content.BroadcastReceiver { *; }
+-keep class * extends android.app.Service { *; }
+
+# Data models used in updater, battery telemetry, and notification store
+-keep class com.glowled.app.core.Updater$Release { *; }
+-keep class com.glowled.app.core.BatteryInfo { *; }
+-keep class com.glowled.app.core.NotificationStore$Entry { *; }
+-keep class com.glowled.app.core.NotificationStore$AppEntry { *; }
+
+# Preserve Enums used in settings (e.g. LedStyle, CutoutShape, MultiMode)
+-keepclassmembers enum * {
+ public static **[] values();
+ public static ** valueOf(java.lang.String);
+}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 4761702..584146a 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -27,6 +27,8 @@
()
+ val row2 = mutableListOf()
+
+ if (showPercent && level in 0..100) {
+ row1.add("$level%")
+ }
+ if (showVoltage && voltageMv > 0) {
+ val vVolts = if (voltageMv > 100) voltageMv / 1000f else voltageMv.toFloat()
+ row1.add(String.format(Locale.US, "%.2fV", vVolts))
+ }
+ if (showCurrent && abs(currentMa) > 0) {
+ row2.add(String.format(Locale.US, "%d mA", abs(currentMa)))
+ }
+ if (showPower && powerWatts > 0.05f) {
+ row2.add(String.format(Locale.US, "%.1fW", powerWatts))
+ }
+
+ return when {
+ row1.isNotEmpty() && row2.isNotEmpty() -> "${row1.joinToString(" · ")}\n${row2.joinToString(" · ")}"
+ row1.isNotEmpty() -> row1.joinToString(" · ")
+ row2.isNotEmpty() -> row2.joinToString(" · ")
+ else -> null
+ }
+ }
+}
+
+object BatteryStats {
+ fun getInfo(context: Context): BatteryInfo {
+ val bm = context.getSystemService(BatteryManager::class.java)
+ val intent = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
+
+ val rawLevel = intent?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1
+ val scale = intent?.getIntExtra(BatteryManager.EXTRA_SCALE, 100) ?: 100
+ val level = if (rawLevel >= 0 && scale > 0) (rawLevel * 100 / scale).coerceIn(0, 100)
+ else (bm?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) ?: 100).coerceIn(0, 100)
+
+ val voltageMv = intent?.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1) ?: -1
+ val plugged = (intent?.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) ?: 0) != 0
+ val status = intent?.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN) ?: 0
+ val isCharging = plugged || status == BatteryManager.BATTERY_STATUS_CHARGING || bm?.isCharging == true
+
+ var rawCurrent = bm?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW) ?: 0
+ if (rawCurrent == Int.MIN_VALUE || rawCurrent == Int.MAX_VALUE) rawCurrent = 0
+ var currentMa = when {
+ abs(rawCurrent) > 10_000 -> rawCurrent / 1000
+ else -> rawCurrent
+ }
+
+ if (currentMa == 0 && isCharging) {
+ val avg = bm?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE) ?: 0
+ if (avg != Int.MIN_VALUE && avg != Int.MAX_VALUE && avg != 0) {
+ currentMa = if (abs(avg) > 10_000) avg / 1000 else avg
+ }
+ }
+
+ val effectiveCurrentMa = if (isCharging) abs(currentMa) else -abs(currentMa)
+
+ val vVolts = if (voltageMv > 100) voltageMv / 1000f else voltageMv.toFloat()
+ val cAmps = abs(effectiveCurrentMa) / 1000f
+ val powerWatts = if (vVolts > 0f && cAmps > 0f) vVolts * cAmps else 0f
+
+ return BatteryInfo(
+ level = level,
+ voltageMv = voltageMv,
+ currentMa = effectiveCurrentMa,
+ powerWatts = powerWatts,
+ isCharging = isCharging,
+ )
+ }
+
+ data class AodTelemetry(
+ val sessionCount: Int,
+ val animDurationMs: Long,
+ val staticDurationMs: Long,
+ )
+
+ private const val KEY_AOD_SESSIONS_COUNT = "aod_sessions_count"
+ private const val KEY_AOD_ANIM_MS = "aod_anim_ms"
+ private const val KEY_AOD_STATIC_MS = "aod_static_ms"
+ private const val KEY_AOD_RESET_TIME = "aod_stats_reset"
+
+ /** Records duration of one completed AOD session (zero I/O on draw frames). */
+ fun recordAodSession(context: Context, animDurationMs: Long, staticDurationMs: Long) {
+ try {
+ val sp = context.applicationContext.getSharedPreferences("device_state", Context.MODE_PRIVATE)
+ val now = System.currentTimeMillis()
+ val lastReset = sp.getLong(KEY_AOD_RESET_TIME, 0L)
+ val e = sp.edit()
+ if (lastReset == 0L || now - lastReset > 24 * 3600 * 1000L) {
+ e.putLong(KEY_AOD_RESET_TIME, now)
+ e.putInt(KEY_AOD_SESSIONS_COUNT, 1)
+ e.putLong(KEY_AOD_ANIM_MS, animDurationMs.coerceAtLeast(0L))
+ e.putLong(KEY_AOD_STATIC_MS, staticDurationMs.coerceAtLeast(0L))
+ } else {
+ val count = sp.getInt(KEY_AOD_SESSIONS_COUNT, 0) + 1
+ val anim = sp.getLong(KEY_AOD_ANIM_MS, 0L) + animDurationMs.coerceAtLeast(0L)
+ val st = sp.getLong(KEY_AOD_STATIC_MS, 0L) + staticDurationMs.coerceAtLeast(0L)
+ e.putInt(KEY_AOD_SESSIONS_COUNT, count)
+ e.putLong(KEY_AOD_ANIM_MS, anim)
+ e.putLong(KEY_AOD_STATIC_MS, st)
+ }
+ e.apply()
+ } catch (_: Exception) {}
+ }
+
+ fun getAodTelemetry(context: Context): AodTelemetry {
+ return try {
+ val sp = context.applicationContext.getSharedPreferences("device_state", Context.MODE_PRIVATE)
+ val now = System.currentTimeMillis()
+ val lastReset = sp.getLong(KEY_AOD_RESET_TIME, 0L)
+ if (lastReset != 0L && now - lastReset > 24 * 3600 * 1000L) {
+ AodTelemetry(0, 0L, 0L)
+ } else {
+ AodTelemetry(
+ sessionCount = sp.getInt(KEY_AOD_SESSIONS_COUNT, 0),
+ animDurationMs = sp.getLong(KEY_AOD_ANIM_MS, 0L),
+ staticDurationMs = sp.getLong(KEY_AOD_STATIC_MS, 0L),
+ )
+ }
+ } catch (_: Exception) {
+ AodTelemetry(0, 0L, 0L)
+ }
+ }
+}
+
diff --git a/app/src/main/java/com/glowled/app/core/BurnInShift.kt b/app/src/main/java/com/glowled/app/core/BurnInShift.kt
new file mode 100644
index 0000000..2cb53b3
--- /dev/null
+++ b/app/src/main/java/com/glowled/app/core/BurnInShift.kt
@@ -0,0 +1,36 @@
+package com.glowled.app.core
+
+import kotlin.math.cos
+import kotlin.math.sin
+import kotlin.math.sqrt
+
+/**
+ * Calculates a small deterministic pixel shift (<= maxShiftPx) that updates every
+ * [intervalMs] (e.g. 60 seconds) to protect AMOLED screens from pixel burn-in during static AOD.
+ */
+object BurnInShiftCalculator {
+ const val DEFAULT_MAX_SHIFT_PX = 2f
+ const val DEFAULT_INTERVAL_MS = 60_000L
+
+ /**
+ * Returns (dx, dy) pixel offset for the given [uptimeMs].
+ * Traverses a smooth 8-point cycle around the original position.
+ */
+ fun calculateShift(
+ uptimeMs: Long,
+ maxShiftPx: Float = DEFAULT_MAX_SHIFT_PX,
+ intervalMs: Long = DEFAULT_INTERVAL_MS,
+ ): Pair {
+ if (maxShiftPx <= 0f || intervalMs <= 0L) return 0f to 0f
+ val step = (uptimeMs / intervalMs) % 8
+ val angleRad = step * (Math.PI / 4.0)
+ val dx = (maxShiftPx * cos(angleRad)).toFloat()
+ val dy = (maxShiftPx * sin(angleRad)).toFloat()
+ return dx to dy
+ }
+
+ fun isWithinBounds(dx: Float, dy: Float, maxShiftPx: Float): Boolean {
+ val dist = sqrt(dx * dx + dy * dy)
+ return dist <= maxShiftPx + 0.001f
+ }
+}
diff --git a/app/src/main/java/com/glowled/app/core/CpuStats.kt b/app/src/main/java/com/glowled/app/core/CpuStats.kt
new file mode 100644
index 0000000..a448f94
--- /dev/null
+++ b/app/src/main/java/com/glowled/app/core/CpuStats.kt
@@ -0,0 +1,184 @@
+package com.glowled.app.core
+
+import android.os.Handler
+import android.os.Looper
+import android.util.Log
+import java.io.BufferedReader
+import java.io.File
+import java.io.FileReader
+import java.io.InputStreamReader
+import java.util.concurrent.Executors
+import java.util.concurrent.TimeUnit
+
+/**
+ * Reads overall device CPU usage percentage (0..100%).
+ * Uses /proc/stat if accessible, falling back to top -b -n 1 -m 1 or sysfs frequencies.
+ * All sampling runs off the UI thread via [updateAsync].
+ */
+object CpuStats {
+ private const val TAG = "CpuStats"
+ private val executor = Executors.newSingleThreadExecutor { r ->
+ Thread(r, "CpuStatsWorker").apply { isDaemon = true }
+ }
+ private val mainHandler = Handler(Looper.getMainLooper())
+
+ private var lastTotal: Long = 0L
+ private var lastIdle: Long = 0L
+ @Volatile var cachedUsage: Int = -1
+ private set
+
+ /** Submits a background sample and returns the percentage to [callback] on the main thread. */
+ fun updateAsync(callback: (Int) -> Unit) {
+ executor.execute {
+ val usage = sample()
+ if (usage >= 0) cachedUsage = usage
+ val result = if (usage >= 0) usage else (if (cachedUsage >= 0) cachedUsage else 0)
+ mainHandler.post { callback(result) }
+ }
+ }
+
+ /** Samples total CPU usage percentage synchronously (call off main thread). */
+ fun sample(): Int {
+ val fromProc = readProcStat()
+ if (fromProc in 0..100) return fromProc
+
+ val fromTop = readTop()
+ if (fromTop in 0..100) return fromTop
+
+ val fromFreq = readFreqRatio()
+ if (fromFreq in 0..100) return fromFreq
+
+ return if (cachedUsage >= 0) cachedUsage else -1
+ }
+
+ /** Reads /proc/stat if available to the process. */
+ private fun readProcStat(): Int = try {
+ val file = File("/proc/stat")
+ if (!file.canRead()) -1
+ else {
+ val line = BufferedReader(FileReader(file)).use { it.readLine() } ?: return -1
+ parseProcStatLine(line)
+ }
+ } catch (_: Throwable) {
+ -1
+ }
+
+ /** Parses the first line of /proc/stat: "cpu user nice sys idle iowait irq softirq steal..." */
+ internal fun parseProcStatLine(line: String): Int {
+ val parts = line.trim().split(Regex("\\s+"))
+ if (parts.size < 5 || parts[0] != "cpu") return -1
+ val user = parts[1].toLongOrNull() ?: return -1
+ val nice = parts[2].toLongOrNull() ?: return -1
+ val system = parts[3].toLongOrNull() ?: return -1
+ val idle = parts[4].toLongOrNull() ?: return -1
+ val iowait = if (parts.size > 5) parts[5].toLongOrNull() ?: 0L else 0L
+ val irq = if (parts.size > 6) parts[6].toLongOrNull() ?: 0L else 0L
+ val softirq = if (parts.size > 7) parts[7].toLongOrNull() ?: 0L else 0L
+ val steal = if (parts.size > 8) parts[8].toLongOrNull() ?: 0L else 0L
+
+ val totalIdle = idle + iowait
+ val totalActive = user + nice + system + irq + softirq + steal
+ val total = totalIdle + totalActive
+
+ val diffTotal = total - lastTotal
+ val diffIdle = totalIdle - lastIdle
+ lastTotal = total
+ lastIdle = totalIdle
+
+ return if (diffTotal > 0) {
+ (((diffTotal - diffIdle) * 100) / diffTotal).toInt().coerceIn(0, 100)
+ } else {
+ -1
+ }
+ }
+
+ /**
+ * Runs top in batch mode (-b) with 1 iteration (-n 1) and max 1 process (-m 1).
+ * Does not require an interactive TTY, finishes in ~10-20ms, and outputs clean stats.
+ */
+ private fun readTop(): Int {
+ var proc: Process? = null
+ return try {
+ val cmd = if (File("/system/bin/top").exists()) {
+ arrayOf("/system/bin/top", "-b", "-n", "1", "-m", "1")
+ } else {
+ arrayOf("top", "-b", "-n", "1", "-m", "1")
+ }
+ proc = ProcessBuilder(*cmd).redirectErrorStream(true).start()
+ var matchedLine: String? = null
+ BufferedReader(InputStreamReader(proc.inputStream)).use { reader ->
+ var l: String?
+ var linesRead = 0
+ while (reader.readLine().also { l = it } != null && linesRead < 15) {
+ linesRead++
+ val str = l ?: continue
+ if (str.contains("%cpu", ignoreCase = true) || str.contains("%idle", ignoreCase = true) ||
+ (str.contains("User", ignoreCase = true) && str.contains("%"))
+ ) {
+ matchedLine = str
+ break
+ }
+ }
+ }
+ proc.waitFor(800, TimeUnit.MILLISECONDS)
+ if (matchedLine != null) parseTopLine(matchedLine!!) else -1
+ } catch (e: Throwable) {
+ Log.d(TAG, "readTop failed: ${e.message}")
+ -1
+ } finally {
+ try {
+ proc?.destroy()
+ } catch (_: Throwable) {}
+ }
+ }
+
+ private val ANSI_REGEX = Regex("\u001B\\[[;\\d]*[ -/]*[@-~]")
+
+ /**
+ * Parses top output line.
+ * Format 1 (modern toybox): "800%cpu 125%user 0%nice 68%sys 600%idle ..."
+ * Format 2: "User 25%, System 10%, IOW 0%, IRQ 0%"
+ */
+ internal fun parseTopLine(rawLine: String): Int {
+ val line = rawLine.replace(ANSI_REGEX, "")
+ // Modern toybox: "800%cpu ... 600%idle"
+ val match = Regex("""(\d+)%cpu.*?(\d+)%idle""").find(line)
+ if (match != null) {
+ val total = match.groupValues[1].toIntOrNull() ?: 0
+ val idle = match.groupValues[2].toIntOrNull() ?: 0
+ if (total > 0) {
+ return (((total - idle) * 100) / total).coerceIn(0, 100)
+ }
+ }
+ // Legacy: "User 25%, System 10%..."
+ val user = Regex("""User\s+(\d+)%""", RegexOption.IGNORE_CASE).find(line)?.groupValues?.get(1)?.toIntOrNull() ?: 0
+ val sys = Regex("""System\s+(\d+)%""", RegexOption.IGNORE_CASE).find(line)?.groupValues?.get(1)?.toIntOrNull() ?: 0
+ val irq = Regex("""IRQ\s+(\d+)%""", RegexOption.IGNORE_CASE).find(line)?.groupValues?.get(1)?.toIntOrNull() ?: 0
+ val sum = user + sys + irq
+ if (sum > 0) return sum.coerceIn(0, 100)
+ return -1
+ }
+
+ /** Fallback: estimates load from current scaling frequency vs maximum frequency across cores. */
+ private fun readFreqRatio(): Int = try {
+ var count = 0
+ var sumRatio = 0f
+ for (i in 0 until 16) {
+ val curFile = File("/sys/devices/system/cpu/cpu$i/cpufreq/scaling_cur_freq")
+ val maxFile = File("/sys/devices/system/cpu/cpu$i/cpufreq/cpuinfo_max_freq")
+ if (!curFile.exists() || !maxFile.exists()) {
+ if (i > 0 && !File("/sys/devices/system/cpu/cpu$i").exists()) break
+ continue
+ }
+ val cur = curFile.readText().trim().toFloatOrNull() ?: continue
+ val max = maxFile.readText().trim().toFloatOrNull() ?: continue
+ if (max > 0f) {
+ sumRatio += (cur / max).coerceIn(0f, 1f)
+ count++
+ }
+ }
+ if (count > 0) ((sumRatio / count) * 100).toInt().coerceIn(0, 100) else -1
+ } catch (_: Throwable) {
+ -1
+ }
+}
diff --git a/app/src/main/java/com/glowled/app/core/CutoutGeometry.kt b/app/src/main/java/com/glowled/app/core/CutoutGeometry.kt
index ae8292c..c711bf4 100644
--- a/app/src/main/java/com/glowled/app/core/CutoutGeometry.kt
+++ b/app/src/main/java/com/glowled/app/core/CutoutGeometry.kt
@@ -47,7 +47,10 @@ object CutoutGeometry {
if (d.rotation != Surface.ROTATION_0) return null
val cutout = d.cutout ?: return null
val screenW = naturalSize(context).x.toFloat()
+ return fromDisplayCutout(cutout, screenW)
+ }
+ fun fromDisplayCutout(cutout: android.view.DisplayCutout, screenW: Float): Geometry? {
val bounds = RectF()
var exact = false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
@@ -70,12 +73,11 @@ object CutoutGeometry {
var h = bounds.height()
var cx = bounds.centerX()
var cy = bounds.centerY()
- val shape: CutoutShape
- when {
- w > screenW * 0.2f -> shape = CutoutShape.NOTCH
- w / h > 1.5f -> shape = CutoutShape.PILL
- else -> {
- shape = CutoutShape.CIRCLE
+ val shape = classifyShape(w, h, screenW)
+ when (shape) {
+ CutoutShape.NOTCH -> {}
+ CutoutShape.PILL -> {}
+ CutoutShape.DOT, CutoutShape.CIRCLE -> {
if (!exact && bounds.top <= 0.5f && h > w * 1.15f) {
// Bounding rects of punch holes usually extend to the top edge.
h = w
@@ -121,4 +123,11 @@ object CutoutGeometry {
}
return prefs.edgeRadiusDp * context.resources.displayMetrics.density
}
+
+ /** Pure heuristic classifying cutout shape from dimensions and screen width. */
+ fun classifyShape(w: Float, h: Float, screenW: Float): CutoutShape = when {
+ w > screenW * 0.2f -> CutoutShape.NOTCH
+ h > 0f && w / h > 1.5f -> CutoutShape.PILL
+ else -> CutoutShape.CIRCLE
+ }
}
diff --git a/app/src/main/java/com/glowled/app/core/LedController.kt b/app/src/main/java/com/glowled/app/core/LedController.kt
index dadc951..4fcc0cd 100644
--- a/app/src/main/java/com/glowled/app/core/LedController.kt
+++ b/app/src/main/java/com/glowled/app/core/LedController.kt
@@ -81,11 +81,10 @@ object LedController {
/** Set when an AOD session ended (timeout / user) so we don't relight for the same notifications. */
private var suppressed = false
private var ourWakeUntil = 0L
- private var initialized = false
+ private val initialized = java.util.concurrent.atomic.AtomicBoolean(false)
fun init(context: Context) {
- if (initialized) return
- initialized = true
+ if (!initialized.compareAndSet(false, true)) return
app = context.applicationContext
prefs = Prefs(app)
colors = ColorResolver(app, prefs)
@@ -99,6 +98,7 @@ object LedController {
}
ContextCompat.registerReceiver(app, screenReceiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED)
syncBatteryWatch()
+ syncCpuWatch()
watchDisplayState()
prefs.sp.registerOnSharedPreferenceChangeListener(prefListener)
// The job service can be missing or over its limit on some builds; updates are optional.
@@ -109,6 +109,7 @@ object LedController {
private val prefsChanged = Runnable {
NotifyListenerService.instance?.rebuild()
syncBatteryWatch()
+ syncCpuWatch()
refreshAll()
}
private val prefListener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, _ ->
@@ -120,7 +121,13 @@ object LedController {
fun addListener(l: () -> Unit) = listeners.add(l)
fun removeListener(l: () -> Unit) = listeners.remove(l)
- private fun notifyListeners() = listeners.forEach { it() }
+ private fun notifyListeners() {
+ if (Looper.myLooper() == Looper.getMainLooper()) {
+ listeners.forEach { it() }
+ } else {
+ main.post { listeners.forEach { it() } }
+ }
+ }
fun refreshAll() {
notifyListeners()
@@ -143,6 +150,9 @@ object LedController {
main.postDelayed({ if (NotificationStore.remove(key)) onNotificationsChanged(false) }, 60_000)
}
+ private var pendingDropletColor: Int? = null
+ private var pendingDropletUntil = 0L
+
fun onNotificationsChanged(newPost: Boolean) = main.post {
if (newPost) {
suppressed = false
@@ -152,12 +162,24 @@ object LedController {
if (NotificationStore.isEmpty()) {
cancelPulse()
disarmMotion()
+ pendingDropletColor = null
} else if (newPost && !isInteractive() && prefs.aodOnNew) {
startAod(pulse = false)
}
updateOverlay()
if (newPost && prefs.droplet && isInteractive() && !aodVisible) {
- NotificationStore.apps().firstOrNull()?.let { OverlayHost.droplet(it.color) }
+ val app = NotificationStore.apps().firstOrNull()
+ if (app != null) {
+ DebugLog.add("Droplet triggered for ${app.pkg}")
+ OverlayHost.droplet(app.color)
+ // If overlay wasn't ready (e.g. app in foreground), retry shortly when it appears.
+ pendingDropletColor = app.color
+ pendingDropletUntil = SystemClock.uptimeMillis() + 6000
+ } else {
+ DebugLog.add("Droplet skipped: no app")
+ }
+ } else if (newPost) {
+ DebugLog.add("Droplet skipped: droplet=${prefs.droplet} interactive=${isInteractive()} aod=$aodVisible")
}
}
@@ -166,6 +188,10 @@ object LedController {
when (i.action) {
Intent.ACTION_SCREEN_OFF -> {
OverlayHost.hide()
+ syncCpuWatch()
+ if (plugged && prefs.chargeLed && prefs.chargeAod && prefs.chargeTimeoutAodSec > 0) {
+ chargeAodUntil = SystemClock.uptimeMillis() + prefs.chargeTimeoutAodSec * 1000L
+ }
when {
aodVisible -> DebugLog.add("Screen OFF while the light is showing")
!prefs.aodOnScreenOff -> DebugLog.add("Screen off (show-on-screen-off is disabled)")
@@ -187,6 +213,7 @@ object LedController {
cancelPulse()
disarmMotion()
}
+ syncCpuWatch()
updateOverlay()
}
Intent.ACTION_USER_PRESENT -> {
@@ -197,13 +224,23 @@ object LedController {
NotificationStore.markAllSeen()
notifyListeners()
}
+ syncCpuWatch()
updateOverlay()
}
Intent.ACTION_CONFIGURATION_CHANGED -> updateOverlay()
Intent.ACTION_POWER_CONNECTED -> {
- // Show the charging ring for a moment even over the notification light.
- chargeFlashUntil = SystemClock.uptimeMillis() + CHARGE_FLASH_MS
- main.postDelayed({ updateOverlay(); notifyListeners() }, CHARGE_FLASH_MS + 50)
+ val now = SystemClock.uptimeMillis()
+ chargeFlashUntil = now + CHARGE_FLASH_MS
+ chargeScreenOnUntil = if (prefs.chargeTimeoutOnSec > 0) now + prefs.chargeTimeoutOnSec * 1000L else Long.MAX_VALUE
+ chargeAodUntil = if (prefs.chargeTimeoutAodSec > 0) now + prefs.chargeTimeoutAodSec * 1000L else Long.MAX_VALUE
+ main.removeCallbacks(chargeTimeoutTask)
+ val next = listOfNotNull(
+ chargeScreenOnUntil.takeIf { it > now && it < Long.MAX_VALUE },
+ chargeAodUntil.takeIf { it > now && it < Long.MAX_VALUE },
+ ).minOrNull()
+ if (next != null) {
+ main.postDelayed(chargeTimeoutTask, (next - now) + 50)
+ }
syncBatteryWatch(pluggedHint = true)
updateOverlay()
notifyListeners()
@@ -211,6 +248,10 @@ object LedController {
}
Intent.ACTION_POWER_DISCONNECTED -> {
DebugLog.add("Charger disconnected, ${state()}")
+ main.removeCallbacks(chargeTimeoutTask)
+ chargeFlashUntil = 0L
+ chargeScreenOnUntil = 0L
+ chargeAodUntil = 0L
syncBatteryWatch(pluggedHint = false)
updateOverlay()
notifyListeners()
@@ -239,7 +280,7 @@ object LedController {
fun canLaunchFromBackground(): Boolean =
LedAccessibilityService.instance != null || Settings.canDrawOverlays(app)
- fun startAod(pulse: Boolean, preview: Boolean = false, durationOverrideSec: Int = 0) {
+ fun startAod(pulse: Boolean, preview: Boolean = false, durationOverrideSec: Int = -1) {
if (!preview) {
if (!prefs.enabled) return DebugLog.add("Skipped: Glow LED is off")
if (!prefs.aodEnabled) return DebugLog.add("Skipped: screen-off light is off")
@@ -248,7 +289,8 @@ object LedController {
PowerGuard.blockReason(app, prefs)?.let { return DebugLog.add("Skipped: $it") }
}
val duration = when {
- durationOverrideSec > 0 -> durationOverrideSec
+ durationOverrideSec >= 0 -> durationOverrideSec
+ NotificationStore.isEmpty() && prefs.chargeLed && plugged && prefs.chargeAod -> prefs.chargeTimeoutAodSec
pulse -> prefs.pulseDurationSec
else -> prefs.aodTimeoutSec
}
@@ -266,10 +308,10 @@ object LedController {
// HyperOS/MIUI draw their lock screen over the lock-screen window for a moment when the
// display wakes (a bright flash before the black screen), so use the overlay there.
else -> !canLaunchFromBackground() || OemHelper.isXiaomi || OemHelper.miuiLockScreenAllowed(app) == false ||
- prefs.sp.getBoolean(PREF_WINDOW_BLOCKED, false)
+ prefs.deviceSp.getBoolean(PREF_WINDOW_BLOCKED, false)
}
DebugLog.add("Method: ${if (useOverlay) "overlay" else "lock-screen window"} (setting: ${prefs.aodMethod}" +
- ", window blocked before: ${prefs.sp.getBoolean(PREF_WINDOW_BLOCKED, false)}), ${state()}")
+ ", window blocked before: ${prefs.deviceSp.getBoolean(PREF_WINDOW_BLOCKED, false)}), ${state()}")
if (useOverlay) {
startOverlay(duration, preview)
return
@@ -283,7 +325,7 @@ object LedController {
main.postDelayed({
if (!aodVisible && !AodOverlay.isShowing && hasAodContent()) {
DebugLog.add("Lock-screen window was blocked by the system - switching to overlay")
- prefs.sp.edit().putBoolean(PREF_WINDOW_BLOCKED, true).apply()
+ prefs.deviceSp.edit().putBoolean(PREF_WINDOW_BLOCKED, true).apply()
startOverlay(duration, false)
}
}, 1300)
@@ -329,7 +371,7 @@ object LedController {
val overlay = LedAccessibilityService.instance != null && prefs.aodMethod != "activity"
return if (overlay) {
DebugLog.add("Window started $px px below the camera - switching to the overlay now")
- prefs.sp.edit().putBoolean(PREF_WINDOW_BLOCKED, true).apply()
+ prefs.deviceSp.edit().putBoolean(PREF_WINDOW_BLOCKED, true).apply()
// Let the activity finish first, then show the overlay for the rest of the session.
main.postDelayed({ startOverlay(durationSec, false) }, 120)
true
@@ -423,6 +465,7 @@ object LedController {
schedulePulse()
}
if (reason == EndReason.TIMEOUT && !NotificationStore.isEmpty()) armMotion()
+ syncCpuWatch()
updateOverlay()
}
@@ -547,13 +590,29 @@ object LedController {
// ---- screen-on overlay ------------------------------------------------------------------------
fun updateOverlay() {
- if (!initialized) return
+ if (!initialized.get()) return
val launching = SystemClock.uptimeMillis() < ourWakeUntil
- val canShow = prefs.enabled && !aodVisible && !launching && !appInForeground && isInteractive() &&
- (prefs.style.isEdge || CutoutGeometry.isPortrait(app))
+ val portrait = prefs.style.isEdge || CutoutGeometry.isPortrait(app)
+ val canShow = prefs.enabled && !aodVisible && !launching && !appInForeground && isInteractive() && portrait
val notifRing = prefs.overlayEnabled && !NotificationStore.isEmpty() && (!prefs.overlayLockOnly || isLocked())
overlayMeter = if (canShow) computeMeter(notifRing) else null
- if (canShow && (notifRing || overlayMeter != null || prefs.batteryIndicator)) OverlayHost.show(app) else OverlayHost.hide()
+ val show = canShow && (notifRing || overlayMeter != null || prefs.batteryIndicator || prefs.cpuIndicator)
+ if (!show && isInteractive() && !isLocked() && !NotificationStore.isEmpty()) {
+ DebugLog.add("Overlay off: can=$canShow enabled=${prefs.enabled} aod=$aodVisible fg=$appInForeground portrait=$portrait oE=${prefs.overlayEnabled} lockOnly=${prefs.overlayLockOnly} meter=${overlayMeter != null} batt=${prefs.batteryIndicator} cpu=${prefs.cpuIndicator}")
+ }
+ if (show) {
+ OverlayHost.show(app)
+ val pending = pendingDropletColor
+ if (pending != null && SystemClock.uptimeMillis() <= pendingDropletUntil) {
+ pendingDropletColor = null
+ main.postDelayed({ OverlayHost.droplet(pending) }, 150)
+ } else if (pending != null) {
+ pendingDropletColor = null
+ }
+ } else {
+ OverlayHost.hide()
+ }
+ syncCpuWatch()
}
// ---- charging ring and transfer ring (both views) ----------------------------------------------
@@ -570,19 +629,55 @@ object LedController {
private var plugged = false
private var batteryPct = 0
private var chargeFlashUntil = 0L
+ private var chargeAodUntil = 0L
+ private var chargeScreenOnUntil = 0L
private var batteryWatching = false
+ private val chargeTimeoutTask = object : Runnable {
+ override fun run() {
+ updateOverlay()
+ notifyListeners()
+ val now = SystemClock.uptimeMillis()
+ val next = listOfNotNull(
+ chargeScreenOnUntil.takeIf { it > now && it < Long.MAX_VALUE },
+ chargeAodUntil.takeIf { it > now && it < Long.MAX_VALUE },
+ ).minOrNull()
+ if (next != null) {
+ main.postDelayed(this, (next - now) + 50)
+ }
+ }
+ }
+
/**
* Whether there is anything for the screen-off light to show. Only things worth waking the
* screen for: unread notifications, a transfer with real progress (not just a spinner - many
* background tasks show one), and charging only if the user asked for it.
*/
- fun hasAodContent(): Boolean = !NotificationStore.isEmpty() ||
- (prefs.progressLed && (ProgressStore.current()?.fraction ?: -1f) >= 0f) ||
- (prefs.chargeLed && plugged && (prefs.chargeAod || SystemClock.uptimeMillis() < chargeFlashUntil))
+ fun hasAodContent(): Boolean {
+ if (!NotificationStore.isEmpty()) return true
+ if (prefs.progressLed && (ProgressStore.current()?.fraction ?: -1f) >= 0f) return true
+ if (prefs.chargeLed && plugged && prefs.chargeAod) {
+ if (prefs.chargeTimeoutAodSec == 0 || SystemClock.uptimeMillis() < chargeAodUntil) return true
+ }
+ if (prefs.chargeLed && plugged && SystemClock.uptimeMillis() < chargeFlashUntil) return true
+ return false
+ }
fun batteryPercent(): Int? = if (prefs.batteryIndicator) batteryPct else null
+ fun batteryStatusText(): String? {
+ if (plugged && prefs.chargeLed) {
+ val statsText = BatteryStats.getInfo(app).formatString(
+ showPercent = prefs.chargeShowPercent,
+ showVoltage = prefs.chargeShowVoltage,
+ showCurrent = prefs.chargeShowCurrent,
+ showPower = prefs.chargeShowPower,
+ )
+ if (statsText != null) return statsText
+ }
+ return if (prefs.batteryIndicator) "$batteryPct%" else null
+ }
+
fun computeMeter(notifRing: Boolean): Meter? {
if (prefs.progressLed) ProgressStore.current()?.let {
val look = TransferInfo.look(it.pkg, it.direction, prefs.appArrow(it.pkg), prefs.unknownArrow)
@@ -599,8 +694,20 @@ object LedController {
val icon = if (prefs.progressArrow) look.icon else MeterIcon.NONE
return Meter(it.fraction.coerceAtLeast(0f), color, icon, it.fraction < 0f)
}
- if (prefs.chargeLed && plugged && (!notifRing || SystemClock.uptimeMillis() < chargeFlashUntil)) {
- return Meter(batteryPct / 100f, prefs.chargeColor(batteryPct), MeterIcon.BOLT)
+ val on = isInteractive()
+ val now = SystemClock.uptimeMillis()
+ val chargingActive = if (on) {
+ prefs.chargeLed && plugged && prefs.chargeScreenOn &&
+ (prefs.chargeTimeoutOnSec == 0 || now < chargeScreenOnUntil)
+ } else {
+ prefs.chargeLed && plugged && prefs.chargeAod &&
+ (prefs.chargeTimeoutAodSec == 0 || now < chargeAodUntil)
+ }
+ val flashActive = prefs.chargeLed && plugged && now < chargeFlashUntil
+ if (chargingActive || flashActive) {
+ if (!notifRing || flashActive) {
+ return Meter(batteryPct / 100f, prefs.chargeColor(batteryPct), MeterIcon.BOLT)
+ }
}
return null
}
@@ -626,6 +733,57 @@ object LedController {
override fun onReceive(c: Context, i: Intent) = onBatteryChanged(i)
}
+ private val batteryTicker = object : Runnable {
+ override fun run() {
+ if (!batteryWatching || !plugged) return
+ if (aodVisible || overlayMeter != null) {
+ notifyListeners()
+ OverlayHost.updateBatteryText()
+ }
+ main.postDelayed(this, 3000L)
+ }
+ }
+
+ private const val CPU_TICK_MS = 2000L
+ private var cpuWatching = false
+ var cpuUsage: Int = -1
+ private set
+
+ fun cpuStatusText(): String? {
+ if (!prefs.cpuIndicator || cpuUsage < 0) return null
+ return if (prefs.cpuShowLabel) "CPU $cpuUsage%" else "$cpuUsage%"
+ }
+
+ private val cpuTicker = object : Runnable {
+ override fun run() {
+ if (!isInteractive() || !prefs.enabled || !prefs.cpuIndicator || aodVisible) {
+ cpuWatching = false
+ return
+ }
+ CpuStats.updateAsync { usage ->
+ if (!cpuWatching) return@updateAsync
+ cpuUsage = usage
+ notifyListeners()
+ OverlayHost.updateCpuText()
+ main.postDelayed(this, CPU_TICK_MS)
+ }
+ }
+ }
+
+ fun syncCpuWatch() {
+ val want = prefs.enabled && prefs.cpuIndicator && isInteractive() && !aodVisible
+ if (want && !cpuWatching) {
+ cpuWatching = true
+ main.removeCallbacks(cpuTicker)
+ main.post(cpuTicker)
+ } else if (!want && cpuWatching) {
+ cpuWatching = false
+ main.removeCallbacks(cpuTicker)
+ cpuUsage = -1
+ OverlayHost.updateCpuText()
+ }
+ }
+
/**
* Listens for battery changes while an enabled indicator needs them. These broadcasts update
* existing views and never wake the display.
@@ -641,12 +799,24 @@ object LedController {
app, batteryReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED), ContextCompat.RECEIVER_NOT_EXPORTED,
)?.let { onBatteryChanged(it) }
batteryWatching = true
+ if (isPlugged && prefs.chargeLed) {
+ main.removeCallbacks(batteryTicker)
+ main.postDelayed(batteryTicker, 3000L)
+ }
} else if (!want && batteryWatching) {
try {
app.unregisterReceiver(batteryReceiver)
} catch (_: Exception) {
}
batteryWatching = false
+ main.removeCallbacks(batteryTicker)
+ } else if (want && batteryWatching) {
+ if (isPlugged && prefs.chargeLed) {
+ main.removeCallbacks(batteryTicker)
+ main.postDelayed(batteryTicker, 3000L)
+ } else {
+ main.removeCallbacks(batteryTicker)
+ }
}
}
@@ -663,14 +833,14 @@ object LedController {
val locked = isLocked()
DebugLog.add("Charger connected, ${state()}")
when {
- !prefs.chargeLed -> DebugLog.add("Charging ring is off (Screen on → Charging ring)")
- !prefs.aodEnabled -> DebugLog.add("Screen-off light is off, charging ring shown only while the screen is on")
- aodVisible -> Unit // the light is up: it switches to the charging ring for a moment by itself
+ !prefs.chargeLed || !prefs.chargeAod -> DebugLog.add("Charging ring on lock screen is off")
+ !prefs.aodEnabled -> DebugLog.add("Screen-off light is off")
+ aodVisible -> Unit // the light is up: it updates itself
on && !locked -> Unit // in use: the screen-on ring shows it
on && LedAccessibilityService.instance != null -> Unit // the accessibility overlay shows above the lock screen
else -> {
- DebugLog.add("Showing the charging ring on the black screen")
- startAod(pulse = true, durationOverrideSec = CHARGE_FLASH_AOD_SEC)
+ DebugLog.add("Showing the charging ring on the black screen (timeout: ${prefs.chargeTimeoutAodSec}s)")
+ startAod(pulse = false, durationOverrideSec = prefs.chargeTimeoutAodSec)
}
}
}
@@ -684,9 +854,21 @@ object LedController {
private fun onBatteryChanged(i: Intent) {
val p = i.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0
val pct = levelOf(i) ?: batteryPct
+ val gainedPercent = p && pct > batteryPct
if (p == plugged && pct == batteryPct) return
plugged = p
batteryPct = pct
+ if (gainedPercent) {
+ val now = SystemClock.uptimeMillis()
+ if (prefs.chargeTimeoutOnSec > 0) {
+ chargeScreenOnUntil = now + prefs.chargeTimeoutOnSec * 1000L
+ main.postDelayed({ updateOverlay(); notifyListeners() }, prefs.chargeTimeoutOnSec * 1000L + 50)
+ }
+ if (prefs.chargeTimeoutAodSec > 0) {
+ chargeAodUntil = now + prefs.chargeTimeoutAodSec * 1000L
+ main.postDelayed({ updateOverlay(); notifyListeners() }, prefs.chargeTimeoutAodSec * 1000L + 50)
+ }
+ }
if (!p) syncBatteryWatch(pluggedHint = false)
updateOverlay()
notifyListeners()
diff --git a/app/src/main/java/com/glowled/app/core/LedStateMachine.kt b/app/src/main/java/com/glowled/app/core/LedStateMachine.kt
new file mode 100644
index 0000000..be7f365
--- /dev/null
+++ b/app/src/main/java/com/glowled/app/core/LedStateMachine.kt
@@ -0,0 +1,118 @@
+package com.glowled.app.core
+
+data class SignalSnapshot(
+ val enabled: Boolean,
+ val aodEnabled: Boolean,
+ val overlayEnabled: Boolean,
+ val isInteractive: Boolean,
+ val isLocked: Boolean,
+ val hasUnreadNotifs: Boolean,
+ val overlayLockOnly: Boolean,
+ val transferFraction: Float? = null, // null if no transfer, < 0 if indeterminate, >= 0 if progress
+ val isPlugged: Boolean = false,
+ val chargeLed: Boolean = false,
+ val chargeAod: Boolean = false,
+ val chargeScreenOn: Boolean = false,
+ val isChargeAodActive: Boolean = false,
+ val isChargeScreenOnActive: Boolean = false,
+ val isChargeFlashActive: Boolean = false,
+ val batteryIndicator: Boolean = false,
+ val cpuIndicator: Boolean = false,
+ val blockReason: String? = null,
+)
+
+sealed class TargetState {
+ object Idle : TargetState()
+ data class Blocked(val reason: String) : TargetState()
+ data class Aod(
+ val kind: AodKind,
+ val timeoutSec: Int,
+ ) : TargetState()
+ data class Overlay(
+ val showNotifRing: Boolean,
+ val showMeter: Boolean,
+ val showBattery: Boolean,
+ val showCpu: Boolean,
+ ) : TargetState()
+}
+
+enum class AodKind {
+ NOTIFICATION,
+ TRANSFER,
+ CHARGING,
+}
+
+object LedStateMachine {
+
+ fun hasAodContent(
+ hasUnreadNotifs: Boolean,
+ hasTransferProgress: Boolean,
+ chargeLed: Boolean,
+ isPlugged: Boolean,
+ chargeAod: Boolean,
+ isChargeAodActive: Boolean,
+ isChargeFlashActive: Boolean,
+ ): Boolean {
+ if (hasUnreadNotifs) return true
+ if (hasTransferProgress) return true
+ if (chargeLed && isPlugged && chargeAod && isChargeAodActive) return true
+ if (chargeLed && isPlugged && isChargeFlashActive) return true
+ return false
+ }
+
+ fun computeTarget(
+ signal: SignalSnapshot,
+ defaultAodTimeoutSec: Int,
+ chargeTimeoutAodSec: Int,
+ progressLed: Boolean,
+ ): TargetState {
+ if (!signal.enabled) return TargetState.Idle
+
+ if (signal.isInteractive) {
+ // Screen ON: Overlay mode
+ val notifRing = signal.overlayEnabled && signal.hasUnreadNotifs && (!signal.overlayLockOnly || signal.isLocked)
+ val hasTransfer = progressLed && signal.transferFraction != null
+ val chargingActive = (signal.chargeLed && signal.isPlugged && signal.chargeScreenOn && signal.isChargeScreenOnActive) ||
+ (signal.chargeLed && signal.isPlugged && signal.isChargeFlashActive)
+ val showMeter = hasTransfer || (chargingActive && (!notifRing || signal.isChargeFlashActive))
+ val show = notifRing || showMeter || signal.batteryIndicator || signal.cpuIndicator
+ return if (show) {
+ TargetState.Overlay(
+ showNotifRing = notifRing,
+ showMeter = showMeter,
+ showBattery = signal.batteryIndicator,
+ showCpu = signal.cpuIndicator,
+ )
+ } else {
+ TargetState.Idle
+ }
+ } else {
+ // Screen OFF: AOD mode
+ if (!signal.aodEnabled) return TargetState.Idle
+ if (signal.blockReason != null) return TargetState.Blocked(signal.blockReason)
+
+ val hasTransfer = progressLed && signal.transferFraction != null && signal.transferFraction >= 0f
+ val hasAod = hasAodContent(
+ hasUnreadNotifs = signal.hasUnreadNotifs,
+ hasTransferProgress = hasTransfer,
+ chargeLed = signal.chargeLed,
+ isPlugged = signal.isPlugged,
+ chargeAod = signal.chargeAod,
+ isChargeAodActive = signal.isChargeAodActive,
+ isChargeFlashActive = signal.isChargeFlashActive,
+ )
+ if (!hasAod) return TargetState.Idle
+
+ val kind = when {
+ signal.hasUnreadNotifs -> AodKind.NOTIFICATION
+ hasTransfer -> AodKind.TRANSFER
+ else -> AodKind.CHARGING
+ }
+ val timeout = when (kind) {
+ AodKind.CHARGING -> chargeTimeoutAodSec
+ else -> defaultAodTimeoutSec
+ }
+ return TargetState.Aod(kind, timeout)
+ }
+ }
+}
diff --git a/app/src/main/java/com/glowled/app/core/NotificationStore.kt b/app/src/main/java/com/glowled/app/core/NotificationStore.kt
index 682cf7f..bff62fd 100644
--- a/app/src/main/java/com/glowled/app/core/NotificationStore.kt
+++ b/app/src/main/java/com/glowled/app/core/NotificationStore.kt
@@ -28,9 +28,10 @@ object NotificationStore {
val readAction: android.app.Notification.Action? = null,
/** Can be swiped away (used for "Dismiss" when the app has no mark-as-read action). */
val clearable: Boolean = true,
+ val isPriority: Boolean = false,
) {
/** Same LED/peek appearance (ignores the PendingIntent identity). */
- fun sameLook(o: Entry?) = o != null && o.color == color && o.title == title && o.lines == lines && o.kind == kind
+ fun sameLook(o: Entry?) = o != null && o.color == color && o.title == title && o.lines == lines && o.kind == kind && o.isPriority == isPriority
}
private val entries = LinkedHashMap()
@@ -110,11 +111,13 @@ object NotificationStore {
val smallIcon: android.graphics.drawable.Icon? = null,
)
- /** Apps with unseen notifications, newest first, with how many each has. */
+ /** Apps with unseen notifications, priority apps first then newest first, with how many each has. */
@Synchronized
fun apps(): List {
val out = LinkedHashMap()
- entries.values.sortedByDescending { it.time }.forEach {
+ entries.values.sortedWith(
+ compareByDescending { it.isPriority }.thenByDescending { it.time }
+ ).forEach {
if (it.key in seen) return@forEach
val prev = out[it.pkg]
out[it.pkg] = if (prev == null) AppInfo(it.pkg, it.color, 1, it.smallIcon) else prev.copy(count = prev.count + 1)
@@ -131,11 +134,13 @@ object NotificationStore {
fun entriesFor(pkg: String): List =
entries.values.filter { it.pkg == pkg && it.key !in seen }.sortedByDescending { it.time }
- /** Distinct colors of unseen notifications, newest first (max [limit]). */
+ /** Distinct colors of unseen notifications, priority apps first then newest first (max [limit]). */
@Synchronized
fun colors(limit: Int = 6): IntArray {
val out = LinkedHashSet()
- entries.values.sortedByDescending { it.time }.forEach {
+ entries.values.sortedWith(
+ compareByDescending { it.isPriority }.thenByDescending { it.time }
+ ).forEach {
if (it.key !in seen) out.add(it.color)
}
return out.take(limit).toIntArray()
diff --git a/app/src/main/java/com/glowled/app/core/PowerGuard.kt b/app/src/main/java/com/glowled/app/core/PowerGuard.kt
index 7e4cb96..27ca92c 100644
--- a/app/src/main/java/com/glowled/app/core/PowerGuard.kt
+++ b/app/src/main/java/com/glowled/app/core/PowerGuard.kt
@@ -43,8 +43,23 @@ object PowerGuard {
mode == AudioManager.MODE_RINGTONE
}
+ fun isSnoozed(pausedUntilMs: Long, nowMs: Long = System.currentTimeMillis()): Boolean {
+ if (pausedUntilMs <= 0L) return false
+ return nowMs < pausedUntilMs
+ }
+
+ fun isSnoozed(prefs: Prefs, nowMs: Long = System.currentTimeMillis()): Boolean {
+ val until = prefs.pausedUntilEpochMs
+ if (!isSnoozed(until, nowMs)) {
+ if (until > 0L) prefs.clearSnooze()
+ return false
+ }
+ return true
+ }
+
/** Returns null if allowed, otherwise a short reason (shown on the dashboard). */
- fun blockReason(context: Context, prefs: Prefs): String? = when {
+ fun blockReason(context: Context, prefs: Prefs, nowMs: Long = System.currentTimeMillis()): String? = when {
+ isSnoozed(prefs, nowMs) -> context.getString(com.glowled.app.R.string.block_snoozed)
inQuietHours(prefs) -> context.getString(com.glowled.app.R.string.block_quiet)
!isCharging(context) && batteryLevel(context) < prefs.minBattery -> context.getString(com.glowled.app.R.string.block_battery)
inCall(context) -> context.getString(com.glowled.app.R.string.block_call)
diff --git a/app/src/main/java/com/glowled/app/core/Prefs.kt b/app/src/main/java/com/glowled/app/core/Prefs.kt
index 9c5d549..9338cd5 100644
--- a/app/src/main/java/com/glowled/app/core/Prefs.kt
+++ b/app/src/main/java/com/glowled/app/core/Prefs.kt
@@ -10,6 +10,39 @@ class Prefs(context: Context) {
it.getSharedPreferences("${it.packageName}_preferences", Context.MODE_PRIVATE)
}
+ /** Device-specific / runtime state excluded from Android Auto Backup. */
+ val deviceSp: SharedPreferences = context.applicationContext.let {
+ it.getSharedPreferences("device_state", Context.MODE_PRIVATE)
+ }
+
+ init {
+ migrateDeviceState()
+ }
+
+ private fun migrateDeviceState() {
+ val keys = listOf(
+ "aod_window_blocked", K_TRANSFER_APPS,
+ "update_latest", "update_notes", "update_checked", "update_notified",
+ )
+ val toMigrate = keys.filter { sp.contains(it) }
+ if (toMigrate.isNotEmpty()) {
+ val oldEdit = sp.edit()
+ val newEdit = deviceSp.edit()
+ for (k in toMigrate) {
+ when (val v = sp.all[k]) {
+ is Boolean -> newEdit.putBoolean(k, v)
+ is Int -> newEdit.putInt(k, v)
+ is Long -> newEdit.putLong(k, v)
+ is Float -> newEdit.putFloat(k, v)
+ is String -> newEdit.putString(k, v)
+ }
+ oldEdit.remove(k)
+ }
+ newEdit.apply()
+ oldEdit.apply()
+ }
+ }
+
private fun int(key: String, def: Int) = sp.getInt(key, def)
private fun bool(key: String, def: Boolean) = sp.getBoolean(key, def)
private fun str(key: String, def: String) = sp.getString(key, def) ?: def
@@ -57,8 +90,22 @@ class Prefs(context: Context) {
val showContent get() = bool("show_content", true)
/** Liquid droplet from the camera when a notification arrives. */
val droplet get() = bool("droplet", true)
+ /** Droplet size (radius) in dp for the camera droplet animation. */
+ val dropletSizeDp get() = int("droplet_size", 10).coerceIn(4, 28)
+ /** App icon size in dp in the notification icon row (screen-on / AOD). */
+ val appIconDp get() = int("app_icon_size", 36).coerceIn(24, 72)
/** Reply / Mark as read buttons on the message peek. */
val peekActions get() = bool("peek_actions", true)
+ /** Expandable notification messages with individual replies. */
+ val peekExpandable get() = bool("peek_expandable", true)
+ /** Message plate width in dp. */
+ val peekWidthDp get() = int("peek_width", 340).coerceIn(180, 480)
+ /** Message plate max height in dp. */
+ val peekHeightDp get() = int("peek_height", 380).coerceIn(150, 700)
+ /** Message body preview line count. */
+ val peekLines get() = int("peek_lines", 4).coerceIn(1, 20)
+ /** Message font size in sp. */
+ val peekFontSizeSp get() = int("peek_font_size", 14).coerceIn(10, 24)
/** Always-on icons as monochrome glyphs (One UI AOD style) instead of full-colour app icons. */
val aodIcons get() = bool("aod_icons", true)
@@ -79,6 +126,13 @@ class Prefs(context: Context) {
// Screen-on overlay
val overlayEnabled get() = bool("overlay_enabled", true)
val overlayLockOnly get() = bool("overlay_lock_only", false)
+ /** Tap the ring on the unlocked screen to expand app icons and read messages. */
+ val onTapMessages get() = bool("overlay_tap_messages", true)
+ // Screen-on tap response zone (collapsed ring). Offsets/sizes in dp; 0 width/height = automatic.
+ val tapZoneOffsetXDp get() = int("tap_zone_dx", 0).coerceIn(-300, 300)
+ val tapZoneOffsetYDp get() = int("tap_zone_dy", 0).coerceIn(-300, 500)
+ val tapZoneWidthDp get() = int("tap_zone_w", 0).coerceIn(0, 500)
+ val tapZoneHeightDp get() = int("tap_zone_h", 0).coerceIn(0, 800)
// Charging and download rings (screen on, also over the lock screen)
/**
@@ -92,8 +146,29 @@ class Prefs(context: Context) {
val uploadColor get() = int("upload_color", 0xFF00E676.toInt())
val downloadColor get() = int("download_color", 0xFF2979FF.toInt())
val chargeLed get() = bool("charge_led", true)
- /** Light up the screen-off view for charging alone (otherwise it only shows with notifications). */
- val chargeAod get() = bool("charge_aod", false)
+ /** Light up the screen-off view for charging alone. */
+ val chargeAod get() = bool("charge_aod", true)
+ /** Show charging ring on active screen. */
+ val chargeScreenOn get() = bool("charge_screen_on", true)
+ /** Separate timer for charging ring on screen-off / AOD (0 = continuous while charging). */
+ val chargeTimeoutAodSec get() = strInt("charge_timeout_aod", 0)
+ /** Separate timer for charging ring on active screen (0 = continuous while charging). */
+ val chargeTimeoutOnSec get() = strInt("charge_timeout_on", 0)
+
+ // Battery metrics under the charging ring (each individually toggleable)
+ val chargeShowPercent get() = bool("charge_show_percent", true)
+ val chargeShowVoltage get() = bool("charge_show_voltage", true)
+ val chargeShowCurrent get() = bool("charge_show_current", true)
+ val chargeShowPower get() = bool("charge_show_power", true)
+
+ // CPU load indicator (screen on)
+ val cpuIndicator get() = bool("cpu_indicator", false)
+ val cpuPos get() = sp.getString("cpu_pos", "below") ?: "below"
+ val cpuOffsetXDp get() = int("cpu_offset_x", 0).coerceIn(-150, 150)
+ val cpuOffsetYDp get() = int("cpu_offset_y", 0).coerceIn(-150, 150)
+ val cpuFontSizeSp get() = int("cpu_font_size", 12).coerceIn(8, 24)
+ val cpuShowLabel get() = bool("cpu_show_label", true)
+
val chargeColorLow get() = int("charge_color_low", 0xFFFF1744.toInt())
val chargeColorMid get() = int("charge_color_mid", 0xFFFFC400.toInt())
val chargeColorHigh get() = int("charge_color_high", 0xFF00E676.toInt())
@@ -111,9 +186,29 @@ class Prefs(context: Context) {
// Filters
val appMode get() = str("app_mode", "all")
val ignoreLowImportance get() = bool("ignore_low", true)
+ val ignoreSilentNotifications get() = ignoreLowImportance
val respectDnd get() = bool("respect_dnd", true)
val clearOnUnlock get() = bool("clear_on_unlock", false)
+ // Snooze / temporary pause
+ var pausedUntilEpochMs: Long
+ get() = sp.getLong("paused_until", 0L)
+ set(v) = sp.edit().putLong("paused_until", v).apply()
+
+ val isPaused: Boolean
+ get() {
+ val until = pausedUntilEpochMs
+ return until > 0 && System.currentTimeMillis() < until
+ }
+
+ fun snooze(minutes: Int) {
+ pausedUntilEpochMs = System.currentTimeMillis() + minutes * 60_000L
+ }
+
+ fun clearSnooze() {
+ pausedUntilEpochMs = 0L
+ }
+
// Power
val minBattery get() = int("min_battery", 10)
val quietEnabled get() = bool("quiet_enabled", false)
@@ -146,6 +241,13 @@ class Prefs(context: Context) {
fun setAppEnabled(pkg: String, on: Boolean) = sp.edit().putBoolean("app_en_$pkg", on).apply()
+ fun appPriority(pkg: String): Boolean = sp.getBoolean("app_prio_$pkg", false)
+
+ fun setAppPriority(pkg: String, priority: Boolean) {
+ if (!priority) sp.edit().remove("app_prio_$pkg").apply()
+ else sp.edit().putBoolean("app_prio_$pkg", true).apply()
+ }
+
/** 0 means "automatic". */
fun appColor(pkg: String): Int = sp.getInt("app_color_$pkg", 0)
@@ -170,12 +272,12 @@ class Prefs(context: Context) {
/** Apps that have shown a progress bar, so the per-app arrow list can offer them (comma separated). */
val transferApps: Set
- get() = str(K_TRANSFER_APPS, "").split(',').filter { it.isNotBlank() }.toSet()
+ get() = (deviceSp.getString(K_TRANSFER_APPS, "") ?: "").split(',').filter { it.isNotBlank() }.toSet()
fun noteTransferApp(pkg: String) {
val now = transferApps
if (pkg in now) return
- sp.edit().putString(K_TRANSFER_APPS, (now.toList() + pkg).takeLast(MAX_TRANSFER_APPS).joinToString(",")).apply()
+ deviceSp.edit().putString(K_TRANSFER_APPS, (now.toList() + pkg).takeLast(MAX_TRANSFER_APPS).joinToString(",")).apply()
}
companion object {
diff --git a/app/src/main/java/com/glowled/app/core/Updater.kt b/app/src/main/java/com/glowled/app/core/Updater.kt
index 0ba39ea..ecbb3f9 100644
--- a/app/src/main/java/com/glowled/app/core/Updater.kt
+++ b/app/src/main/java/com/glowled/app/core/Updater.kt
@@ -17,17 +17,24 @@ import java.security.MessageDigest
/**
* The in-app updater: asks GitHub for the latest release, downloads its APK, checks it is a newer
- * Glow LED signed with the official release key, and hands it to the system installer.
+ * Glow LED signed with this fork's release key, and hands it to the system installer.
* Checking for updates is the only thing Glow LED uses the internet for.
*/
object Updater {
- private const val API = "https://api.github.com/repos/ankitchanki/LED/releases/latest"
- const val RELEASES_PAGE = "https://github.com/ankitchanki/LED/releases"
+ val UPDATE_REPO: String get() = BuildConfig.UPDATE_REPO
+ val API: String get() = "https://api.github.com/repos/$UPDATE_REPO/releases/latest"
+ val RELEASES_PAGE: String get() = "https://github.com/$UPDATE_REPO/releases"
private const val APK_NAME = "GlowLED-latest.apk"
const val ACTION_INSTALL_STATUS = "com.glowled.app.UPDATE_INSTALL_STATUS"
- /** SHA-256 of the Glow LED release signing certificate; updates must carry it. */
- private const val RELEASE_SHA256 = "5d04de1a96a80107ec87658382b063f15c53cfea8043f554a339f285fe0c5023"
+ /**
+ * SHA-256 of the certificate this fork signs its releases with; updates must carry it.
+ * This is the key the mx57/LED GitHub Actions release workflow signs with (the
+ * GLOWLED_KEYSTORE_* repository secrets), so the in-app updater accepts this fork's own
+ * builds. Never put the upstream key back here: with the matching applicationId it would
+ * let an upstream build silently replace this fork and all of its changes.
+ */
+ private const val RELEASE_SHA256 = "c5b891b739a0dac9c58b6307f764172713866dca344d9d78a6e29a8a0011f4c5"
// Last result, kept in prefs so the Settings row and the notification can show it.
const val K_LATEST = "update_latest"
@@ -41,7 +48,7 @@ object Updater {
/** Fetches the latest release (network: call off the main thread). */
@Throws(IOException::class)
fun fetchLatest(): Release {
- val json = JSONObject(get(API).bufferedReader().use { it.readText() })
+ val json = JSONObject(readText(API))
val version = json.getString("tag_name").removePrefix("v")
val assets = json.optJSONArray("assets")
var url = ""
@@ -60,7 +67,7 @@ object Updater {
/** Checks and remembers the result; returns the release, or null when the check failed. */
fun check(context: Context): Release? = try {
fetchLatest().also { r ->
- LedController.prefs.sp.edit()
+ LedController.prefs.deviceSp.edit()
.putString(K_LATEST, r.version)
.putString(K_NOTES, r.notes)
.putLong(K_CHECKED, System.currentTimeMillis())
@@ -73,20 +80,30 @@ object Updater {
/** The newest version seen by the last check, if it is newer than this one. */
fun pendingVersion(): String? =
- LedController.prefs.sp.getString(K_LATEST, null)?.takeIf { isNewer(it, BuildConfig.VERSION_NAME) }
+ LedController.prefs.deviceSp.getString(K_LATEST, null)?.takeIf { isNewer(it, BuildConfig.VERSION_NAME) }
- private fun get(url: String): java.io.InputStream {
+ fun openConnection(url: String): HttpURLConnection {
val c = URL(url).openConnection() as HttpURLConnection
c.connectTimeout = 15_000
c.readTimeout = 30_000
c.instanceFollowRedirects = true
c.setRequestProperty("Accept", "application/vnd.github+json")
c.setRequestProperty("User-Agent", "GlowLED/${BuildConfig.VERSION_NAME}")
- if (c.responseCode !in 200..299) {
+ return c
+ }
+
+ fun readText(url: String): String {
+ val c = openConnection(url)
+ return try {
+ val code = c.responseCode
+ if (code !in 200..299) {
+ val err = c.errorStream?.bufferedReader()?.use { it.readText() }
+ throw IOException("HTTP $code${if (!err.isNullOrBlank()) ": $err" else ""}")
+ }
+ c.inputStream.bufferedReader().use { it.readText() }
+ } finally {
c.disconnect()
- throw IOException("HTTP ${c.responseCode}")
}
- return c.inputStream
}
/** "2.10.0" is newer than "2.9.1"; anything after a "-" (like "-debug") is ignored. */
@@ -136,28 +153,59 @@ object Updater {
val dir = File(context.cacheDir, "updates").apply { mkdirs() }
dir.listFiles()?.forEach { it.delete() }
val file = File(dir, "GlowLED-${r.version}.apk")
- get(r.apkUrl).use { input ->
- file.outputStream().use { out ->
- val buf = ByteArray(64 * 1024)
- var done = 0L
- while (true) {
- if (cancelled()) throw IOException("cancelled")
- val n = input.read(buf)
- if (n < 0) break
- out.write(buf, 0, n)
- done += n
- if (r.size > 0) progress((done.toFloat() / r.size).coerceIn(0f, 1f))
+ val c = openConnection(r.apkUrl)
+ try {
+ val code = c.responseCode
+ if (code !in 200..299) {
+ val err = c.errorStream?.bufferedReader()?.use { it.readText() }
+ throw IOException("HTTP $code${if (!err.isNullOrBlank()) ": $err" else ""}")
+ }
+ c.inputStream.use { input ->
+ file.outputStream().use { out ->
+ val buf = ByteArray(64 * 1024)
+ var done = 0L
+ while (true) {
+ if (cancelled()) throw IOException("cancelled")
+ val n = input.read(buf)
+ if (n < 0) break
+ out.write(buf, 0, n)
+ done += n
+ if (r.size > 0) progress((done.toFloat() / r.size).coerceIn(0f, 1f))
+ }
}
}
+ } finally {
+ c.disconnect()
}
return file
}
+ fun currentAppCertSha256(context: Context): Set {
+ val pm = context.packageManager
+ @Suppress("DEPRECATION")
+ val flags = PackageManager.GET_SIGNING_CERTIFICATES or PackageManager.GET_SIGNATURES
+ val myInfo = try {
+ pm.getPackageInfo(context.packageName, flags)
+ } catch (_: Exception) {
+ return emptySet()
+ }
+ @Suppress("DEPRECATION")
+ val certs = myInfo.signingInfo?.apkContentsSigners ?: myInfo.signatures ?: return emptySet()
+ val sha = MessageDigest.getInstance("SHA-256")
+ return certs.map { sha.digest(it.toByteArray()).joinToString("") { b -> "%02x".format(b) } }.toSet()
+ }
+
/**
- * True when [apk] is Glow LED, newer than this install and signed with the official release
- * key. Android refuses a different key anyway; this stops anything else before the prompt.
+ * True when [apk] is Glow LED, newer than this install and signed with this fork's release
+ * key (or with the very key this install itself is signed with, so debug builds keep
+ * updating). Android refuses a different key anyway; this stops anything else before the
+ * prompt.
*/
fun verify(context: Context, apk: File): Boolean {
+ if (RELEASE_SHA256.isEmpty()) {
+ DebugLog.add("Updates disabled: RELEASE_SHA256 in Updater.kt is not set to this fork's signing certificate yet")
+ return false
+ }
val pm = context.packageManager
@Suppress("DEPRECATION")
val flags = PackageManager.GET_SIGNING_CERTIFICATES or PackageManager.GET_SIGNATURES
@@ -166,9 +214,14 @@ object Updater {
if (info.longVersionCode <= BuildConfig.VERSION_CODE) return false
@Suppress("DEPRECATION")
val certs = info.signingInfo?.apkContentsSigners ?: info.signatures ?: return false
+ val expectedSha = when {
+ BuildConfig.EXPECTED_SIGNING_SHA256.isNotBlank() -> setOf(BuildConfig.EXPECTED_SIGNING_SHA256.lowercase())
+ else -> currentAppCertSha256(context).ifEmpty { setOf(RELEASE_SHA256) }
+ }
val sha = MessageDigest.getInstance("SHA-256")
- return certs.isNotEmpty() && certs.all {
- sha.digest(it.toByteArray()).joinToString("") { b -> "%02x".format(b) } == RELEASE_SHA256
+ return certs.isNotEmpty() && certs.all { cert ->
+ val certHex = sha.digest(cert.toByteArray()).joinToString("") { b -> "%02x".format(b) }
+ certHex in expectedSha || certHex == RELEASE_SHA256
}
}
diff --git a/app/src/main/java/com/glowled/app/service/LedTileService.kt b/app/src/main/java/com/glowled/app/service/LedTileService.kt
index e1a4da6..cd0c318 100644
--- a/app/src/main/java/com/glowled/app/service/LedTileService.kt
+++ b/app/src/main/java/com/glowled/app/service/LedTileService.kt
@@ -1,10 +1,13 @@
package com.glowled.app.service
+import android.os.Build
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
+import com.glowled.app.R
import com.glowled.app.core.LedController
+import com.glowled.app.core.PowerGuard
-/** Quick Settings tile to toggle the LED on/off. */
+/** Quick Settings tile to toggle the LED on/off or resume from snooze. */
class LedTileService : TileService() {
override fun onStartListening() {
@@ -16,13 +19,32 @@ class LedTileService : TileService() {
override fun onClick() {
super.onClick()
val p = LedController.prefs
- p.enabled = !p.enabled
+ if (p.isPaused) {
+ p.clearSnooze()
+ p.enabled = true
+ } else {
+ p.enabled = !p.enabled
+ }
update()
}
private fun update() {
val tile = qsTile ?: return
- tile.state = if (LedController.prefs.enabled) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
+ val p = LedController.prefs
+ val snoozed = PowerGuard.isSnoozed(p)
+ if (snoozed) {
+ tile.state = Tile.STATE_INACTIVE
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ val leftMin = ((p.pausedUntilEpochMs - System.currentTimeMillis()) / 60_000L).coerceAtLeast(1)
+ tile.subtitle = getString(R.string.tile_snooze_sub, leftMin)
+ }
+ } else {
+ tile.state = if (p.enabled) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ tile.subtitle = if (p.enabled) getString(R.string.state_on) else getString(R.string.state_off)
+ }
+ }
tile.updateTile()
}
}
+
diff --git a/app/src/main/java/com/glowled/app/service/NotifyListenerService.kt b/app/src/main/java/com/glowled/app/service/NotifyListenerService.kt
index 8241d11..a6a4340 100644
--- a/app/src/main/java/com/glowled/app/service/NotifyListenerService.kt
+++ b/app/src/main/java/com/glowled/app/service/NotifyListenerService.kt
@@ -136,6 +136,7 @@ class NotifyListenerService : NotificationListenerService() {
replyAction = replyActionOf(n),
readAction = readActionOf(n),
clearable = sbn.isClearable,
+ isPriority = prefs.appPriority(pkg),
)
}
@@ -164,7 +165,7 @@ class NotifyListenerService : NotificationListenerService() {
companion object {
const val TEST_TAG = "glowled_test"
- private val READ_WORDS = Regex("\\bread\\b|\\blida\\b|\\blido\\b")
+ internal val READ_WORDS = Regex("\\bread\\b|\\blida\\b|\\blido\\b|прочит", RegexOption.IGNORE_CASE)
@Volatile
var instance: NotifyListenerService? = null
diff --git a/app/src/main/java/com/glowled/app/service/OverlayHost.kt b/app/src/main/java/com/glowled/app/service/OverlayHost.kt
index 13812b6..32816fd 100644
--- a/app/src/main/java/com/glowled/app/service/OverlayHost.kt
+++ b/app/src/main/java/com/glowled/app/service/OverlayHost.kt
@@ -18,7 +18,7 @@ import com.glowled.app.view.LedView
* Screen-on indicator window. Over apps it is a "display over other apps" window, which apps that
* guard against overlays (banking, payments) can hide; the accessibility overlay is only used on
* the lock screen, or when there is no overlay permission.
- * The window is sized tightly around the camera so the compositor has almost nothing to blend.
+ * The passive window is sized tightly around the camera; the interactive message view uses its own window.
*/
object OverlayHost {
@@ -27,7 +27,18 @@ object OverlayHost {
private var usingA11y = false
private val listener: () -> Unit = { refresh() }
+ private fun shouldUseInteractive(): Boolean = ScreenOnOverlay.shouldBeInteractive()
+
fun show(context: Context) {
+ if (shouldUseInteractive()) {
+ hidePassive()
+ if (ScreenOnOverlay.isShowing()) ScreenOnOverlay.refresh() else ScreenOnOverlay.show(context)
+ if (ScreenOnOverlay.isShowing()) return
+ com.glowled.app.core.DebugLog.add("Screen-on interactive unavailable, using passive")
+ // Interactive failed to show; fall back to passive so the ring still appears.
+ } else {
+ if (ScreenOnOverlay.isShowing()) ScreenOnOverlay.hide()
+ }
val a11y = LedAccessibilityService.instance?.takeIf {
!Settings.canDrawOverlays(context) || LedController.isLocked()
}
@@ -35,7 +46,7 @@ object OverlayHost {
refresh()
return
}
- hide()
+ hidePassive()
val ctx: Context
val type: Int
if (a11y != null) {
@@ -48,7 +59,7 @@ object OverlayHost {
return
}
val manager = ctx.getSystemService(WindowManager::class.java)
- val v = LedView(ctx)
+ val v = LedView(ctx).apply { intro = 1f }
val params = buildParams(ctx, v, type)
try {
manager.addView(v, params)
@@ -70,7 +81,15 @@ object OverlayHost {
(!prefs.overlayLockOnly || LedController.isLocked())
val m = LedController.overlayMeter
v.setMeter(m?.fraction, m?.color ?: 0, m?.icon ?: MeterIcon.NONE, m?.indeterminate ?: false)
- v.setBattery(LedController.batteryPercent())
+ v.setBatteryText(LedController.batteryStatusText())
+ v.setCpuLoad(
+ LedController.cpuStatusText(),
+ prefs.cpuPos,
+ prefs.cpuOffsetXDp,
+ prefs.cpuOffsetYDp,
+ prefs.cpuFontSizeSp,
+ )
+ v.dropletRadiusDp = prefs.dropletSizeDp.toFloat()
val flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
@@ -85,13 +104,35 @@ object OverlayHost {
p.gravity = Gravity.TOP or Gravity.START
} else {
val e = v.extentPx(g)
- // Extra room below the ring for the droplet that drips out on a new notification.
- val dropRoom = (DROP_DP * ctx.resources.displayMetrics.density).toInt() * 2
- val width = maxOf(e * 2, (80 * ctx.resources.displayMetrics.density).toInt())
- p = WindowManager.LayoutParams(width, e * 2 + dropRoom, type, flags, PixelFormat.TRANSLUCENT)
+ val d = ctx.resources.displayMetrics.density
+ val dropRoom = (DROP_DP * d).toInt() * 2
+ val extraLeft = if (prefs.cpuIndicator) {
+ var ex = if (prefs.cpuPos == "left") (90 * d).toInt() else (40 * d).toInt()
+ if (prefs.cpuOffsetXDp < 0) ex += (-prefs.cpuOffsetXDp * d).toInt()
+ ex
+ } else 0
+ val extraRight = if (prefs.cpuIndicator) {
+ var ex = if (prefs.cpuPos == "right") (90 * d).toInt() else (40 * d).toInt()
+ if (prefs.cpuOffsetXDp > 0) ex += (prefs.cpuOffsetXDp * d).toInt()
+ ex
+ } else 0
+ val extraTop = if (prefs.cpuIndicator) {
+ var ey = if (prefs.cpuPos == "above") (45 * d).toInt() else (10 * d).toInt()
+ if (prefs.cpuOffsetYDp < 0) ey += (-prefs.cpuOffsetYDp * d).toInt()
+ ey
+ } else 0
+ val extraBottom = if (prefs.cpuIndicator) {
+ var ey = if (prefs.cpuPos == "below") (45 * d).toInt() else (10 * d).toInt()
+ if (prefs.cpuOffsetYDp > 0) ey += (prefs.cpuOffsetYDp * d).toInt()
+ ey
+ } else 0
+
+ val width = maxOf(e * 2 + extraLeft + extraRight, (80 * d).toInt())
+ val height = e * 2 + dropRoom + extraTop + extraBottom
+ p = WindowManager.LayoutParams(width, height, type, flags, PixelFormat.TRANSLUCENT)
p.gravity = Gravity.TOP or Gravity.START
- p.x = (g.cx - p.width / 2f).toInt()
- p.y = (g.cy - e).toInt()
+ p.x = (g.cx - e - extraLeft).toInt()
+ p.y = (g.cy - e - extraTop).toInt().coerceAtLeast(0)
}
p.layoutInDisplayCutoutMode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
@@ -109,7 +150,19 @@ object OverlayHost {
/** Re-applies settings, colours and the gauge; repositions the window if geometry or style changed. */
fun refresh() {
- val v = view ?: return
+ if (shouldUseInteractive()) {
+ hidePassive()
+ if (ScreenOnOverlay.isShowing()) ScreenOnOverlay.refresh() else ScreenOnOverlay.show(LedController.app)
+ if (ScreenOnOverlay.isShowing()) return
+ // fell back to passive below if interactive couldn't be shown
+ } else if (ScreenOnOverlay.isShowing()) {
+ ScreenOnOverlay.hide()
+ }
+ val v = view ?: run {
+ // No passive view yet (e.g. after interactive fallback) - let show() create it.
+ runCatching { LedController.app }.getOrNull()?.let { show(it) }
+ return
+ }
val manager = wm ?: return
val type = (v.layoutParams as? WindowManager.LayoutParams)?.type ?: return
val old = v.layoutParams as? WindowManager.LayoutParams ?: return
@@ -125,22 +178,49 @@ object OverlayHost {
/** New notification while the screen is on: a drop stretches out of the camera and springs back. */
fun droplet(color: Int) {
- val v = view ?: return
+ if (ScreenOnOverlay.isShowing()) {
+ ScreenOnOverlay.droplet(color)
+ return
+ }
+ val v = view ?: run {
+ com.glowled.app.core.DebugLog.add("Droplet skipped: no overlay")
+ return
+ }
+ com.glowled.app.core.DebugLog.add("Droplet on passive ring")
// Post: the window may have just been added and not laid out yet.
v.post { v.playDropletBelow(color, DROP_DP * v.resources.displayMetrics.density, retract = true) }
}
private const val DROP_DP = 26f
- fun hide() {
+ private fun hidePassive() {
val v = view ?: return
- LedController.removeListener(listener)
+ try { LedController.removeListener(listener) } catch (_: Exception) {}
v.visibility = View.GONE
- try {
- wm?.removeViewImmediate(v)
- } catch (_: Exception) {
- }
+ try { wm?.removeViewImmediate(v) } catch (_: Exception) {}
view = null
wm = null
}
+
+ fun hide() {
+ hidePassive()
+ if (ScreenOnOverlay.isShowing()) ScreenOnOverlay.hide()
+ }
+
+ fun updateBatteryText() {
+ view?.setBatteryText(LedController.batteryStatusText())
+ ScreenOnOverlay.updateBatteryText()
+ }
+
+ fun updateCpuText() {
+ val prefs = LedController.prefs
+ view?.setCpuLoad(
+ LedController.cpuStatusText(),
+ prefs.cpuPos,
+ prefs.cpuOffsetXDp,
+ prefs.cpuOffsetYDp,
+ prefs.cpuFontSizeSp,
+ )
+ ScreenOnOverlay.updateCpuText()
+ }
}
diff --git a/app/src/main/java/com/glowled/app/service/ScreenOnOverlay.kt b/app/src/main/java/com/glowled/app/service/ScreenOnOverlay.kt
new file mode 100644
index 0000000..7a4292e
--- /dev/null
+++ b/app/src/main/java/com/glowled/app/service/ScreenOnOverlay.kt
@@ -0,0 +1,624 @@
+package com.glowled.app.service
+
+import android.annotation.SuppressLint
+import android.content.Context
+import android.graphics.Color
+import android.graphics.PixelFormat
+import android.graphics.Rect
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import android.provider.Settings
+import android.util.Log
+import android.view.Gravity
+import android.view.MotionEvent
+import android.view.View
+import android.view.WindowManager
+import android.widget.FrameLayout
+import androidx.core.view.doOnLayout
+import com.glowled.app.core.CutoutGeometry
+import com.glowled.app.core.DebugLog
+import com.glowled.app.core.Geometry
+import com.glowled.app.core.LedController
+import com.glowled.app.core.MeterIcon
+import com.glowled.app.core.NotificationStore
+import com.glowled.app.ui.ReplyActivity
+import com.glowled.app.view.AppInfoView
+import com.glowled.app.view.LedView
+import com.glowled.app.view.NotificationPeekView
+import kotlin.math.abs
+import kotlin.math.max
+import kotlin.math.roundToInt
+
+/**
+ * Interactive notification overlay for screen-on (unlocked) use.
+ *
+ * - collapsed: ring around the camera only; tap the ring to expand;
+ * - icons: one circle/icon per source app below the camera; tap an icon to read;
+ * - peek: message card for the selected app, with reply / mark-as-read / open.
+ *
+ * Actions mirror the screen-off message view. The window is sized to the visible UI so touches
+ * outside it reach the apps below.
+ */
+@SuppressLint("ClickableViewAccessibility")
+object ScreenOnOverlay {
+
+ private enum class State { COLLAPSED, ICONS, PEEK }
+
+ private var state = State.COLLAPSED
+ private var root: RootLayout? = null
+ private var led: LedView? = null
+ private var info: AppInfoView? = null
+ private var peek: NotificationPeekView? = null
+ private var wm: WindowManager? = null
+ private var windowCtx: Context? = null
+ private var usingA11y = false
+
+ private val main = Handler(Looper.getMainLooper())
+ private val hidePeekRunnable = Runnable { hidePeek(showIconsAfter = true) }
+
+ private var peekPkg: String? = null
+ private var newestTime = 0L
+
+ private val listener: () -> Unit = { main.post { onStoreChanged() } }
+
+ private open class RootLayout(context: Context) : FrameLayout(context) {
+ var onLaidOut: (() -> Unit)? = null
+
+ override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
+ super.onLayout(changed, l, t, r, b)
+ onLaidOut?.invoke()
+ }
+ }
+
+ fun isShowing(): Boolean = root != null
+
+ /** True when the screen-on overlay should be the interactive (tappable) one. */
+ fun shouldBeInteractive(): Boolean {
+ val p = LedController.prefs
+ return p.overlayEnabled && p.onTapMessages && !NotificationStore.isEmpty() &&
+ !LedController.isLocked() && !p.overlayLockOnly && !p.style.isEdge
+ }
+
+ fun show(context: Context) {
+ val prefs = LedController.prefs
+ if (!prefs.enabled) return hide()
+ // Prefer accessibility overlay for interactive/touch input (better cutout touch behavior on some devices).
+ val a11y = LedAccessibilityService.instance
+ val wantA11y = a11y != null
+ if (root != null && usingA11y == wantA11y) {
+ refresh()
+ return
+ }
+ hide()
+ val ctx: Context
+ val type: Int
+ if (a11y != null) {
+ ctx = a11y; type = WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY
+ } else if (Settings.canDrawOverlays(context)) {
+ ctx = context.applicationContext; type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
+ } else {
+ DebugLog.add("Screen-on overlay: no permission/service")
+ return
+ }
+
+ val r = object : RootLayout(ctx) {
+ private var downX = 0f; private var downY = 0f; private var downT = 0L
+ override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
+ if (ev.actionMasked == MotionEvent.ACTION_DOWN) {
+ downX = ev.rawX; downY = ev.rawY; downT = ev.eventTime
+ val loc = IntArray(2); getLocationOnScreen(loc)
+ DebugLog.add("Screen-on touch down ($state) at ${ev.rawX.toInt()},${ev.rawY.toInt()} win=${loc[0]},${loc[1]} ${width}x${height}")
+ }
+ val handled = super.dispatchTouchEvent(ev)
+ if (ev.actionMasked == MotionEvent.ACTION_UP) {
+ val slop = 48 * resources.displayMetrics.density
+ val isTap = ev.eventTime - downT < 400 && abs(ev.rawX - downX) < slop && abs(ev.rawY - downY) < slop
+ if (isTap && !hitInteractive(ev)) {
+ DebugLog.add("Screen-on ring tapped ($state)")
+ onBackgroundTap()
+ }
+ }
+ if (ev.actionMasked == MotionEvent.ACTION_DOWN) return true
+ return handled || ev.actionMasked == MotionEvent.ACTION_UP || ev.actionMasked == MotionEvent.ACTION_CANCEL
+ }
+ private fun hitInteractive(ev: MotionEvent): Boolean {
+ val i = info
+ if (i != null && i.visibility == View.VISIBLE && pointInView(i, ev.rawX, ev.rawY)) return true
+ val p = peek
+ if (p != null && p.isShowing() && pointInView(p, ev.rawX, ev.rawY)) return true
+ return false
+ }
+ private fun pointInView(v: View, rawX: Float, rawY: Float): Boolean {
+ val loc = IntArray(2); v.getLocationOnScreen(loc)
+ return rawX >= loc[0] && rawX <= loc[0] + v.width && rawY >= loc[1] && rawY <= loc[1] + v.height
+ }
+ }.apply {
+ setBackgroundColor(Color.TRANSPARENT)
+ isForceDarkAllowed = false
+ clipChildren = false
+ clipToPadding = false
+ isClickable = true
+ isFocusable = false
+ }
+
+ val ledView = LedView(ctx).apply { useScreenCoords = true; intro = 1f; dropletRadiusDp = prefs.dropletSizeDp.toFloat() }
+ val infoView = AppInfoView(ctx).apply {
+ monochrome = prefs.aodIcons
+ iconDp = prefs.appIconDp
+ onAppTap = { pkg -> onAppTapped(pkg) }
+ }
+ val d = ctx.resources.displayMetrics.density
+ val peekWidth = (prefs.peekWidthDp * d).toInt().coerceIn((180 * d).toInt(), (ctx.resources.displayMetrics.widthPixels - (24 * d).toInt()))
+ val peekView = NotificationPeekView(ctx).apply {
+ actionsEnabled = prefs.peekActions
+ expandableEnabled = prefs.peekExpandable
+ applyCustomization(prefs.peekFontSizeSp.toFloat(), prefs.peekLines, prefs.peekHeightDp)
+ onOpen = { e -> openNotification(e) }
+ onReply = { e -> replyTo(e) }
+ onMarkRead = { e -> markRead(e) }
+ onMarkAllRead = { list -> markAllRead(list) }
+ onInteraction = { resetPeekTimeout() }
+ onExpandedChanged = {
+ resetPeekTimeout()
+ val type = windowType()
+ if (type != 0) applyWindow(type)
+ root?.requestLayout()
+ root?.post { positionChildren() }
+ }
+ }
+
+ r.addView(ledView, FrameLayout.LayoutParams(-1, -1))
+ r.addView(infoView, FrameLayout.LayoutParams(-2, -2))
+ r.addView(peekView, FrameLayout.LayoutParams(peekWidth, -2))
+ r.onLaidOut = { positionChildren() }
+
+ root = r; led = ledView; info = infoView; peek = peekView
+ windowCtx = ctx; usingA11y = wantA11y
+ wm = ctx.getSystemService(WindowManager::class.java)
+ state = State.COLLAPSED; peekPkg = null
+ newestTime = NotificationStore.newestTime()
+
+ applyWindow(type)
+ if (root == null) return
+ LedController.addListener(listener)
+ DebugLog.add("Screen-on interactive overlay shown (${if (wantA11y) "a11y" else "app"})")
+ refresh()
+ }
+
+ private fun geometry(ctx: Context): Geometry = CutoutGeometry.resolve(ctx, LedController.prefs)
+
+ private fun extentPx(g: Geometry, prefs: com.glowled.app.core.Prefs, d: Float): Int {
+ val thickness = prefs.thicknessDp * d
+ val gap = prefs.gapDp * d
+ val glowRadius = if (prefs.glow) thickness * 1.6f + 3 * d else 0f
+ val half = max(g.w, g.h) / 2f + gap + thickness
+ return (half + thickness * 7 + glowRadius * 2 + 4 * d).toInt()
+ }
+
+ /** Screen-space tap/response zone for the collapsed screen-on ring. */
+ fun tapZoneRect(ctx: Context): android.graphics.Rect {
+ val prefs = LedController.prefs
+ val g = geometry(ctx)
+ val d = ctx.resources.displayMetrics.density
+ val e = extentPx(g, prefs, d)
+ val ringW = maxOf(e * 2, (120 * d).toInt())
+ val autoW = ringW
+ val autoH = (g.cy.toInt() + e + (DROP_DP * d).toInt() * 2 + (120 * d).toInt())
+ .coerceAtLeast(e * 2 + (DROP_DP * d).toInt() * 2)
+ val w = if (prefs.tapZoneWidthDp > 0) (prefs.tapZoneWidthDp * d).toInt().coerceAtLeast((40 * d).toInt()) else autoW
+ val h = if (prefs.tapZoneHeightDp > 0) (prefs.tapZoneHeightDp * d).toInt().coerceAtLeast((40 * d).toInt()) else autoH
+ val dm = ctx.resources.displayMetrics
+ var x = (g.cx - w / 2f).toInt() + (prefs.tapZoneOffsetXDp * d).toInt()
+ var y = 0 + (prefs.tapZoneOffsetYDp * d).toInt()
+ // Keep on screen.
+ x = x.coerceIn(0, (dm.widthPixels - w).coerceAtLeast(0))
+ y = y.coerceIn(0, (dm.heightPixels - h).coerceAtLeast(0))
+ return android.graphics.Rect(x, y, x + w, y + h)
+ }
+
+ private fun currentParams(): WindowManager.LayoutParams? = root?.layoutParams as? WindowManager.LayoutParams
+ private fun windowType(): Int = currentParams()?.type ?: 0
+
+ private fun applyWindow(type: Int) {
+ val r = root ?: return
+ val ctx = windowCtx ?: return
+ val manager = wm ?: return
+ val p = buildParams(ctx, type)
+ if (r.parent == null) {
+ try { manager.addView(r, p) } catch (e: Exception) {
+ Log.w("GlowLED", "interactive overlay add failed", e); cleanupRefs(); return
+ }
+ } else {
+ try { manager.updateViewLayout(r, p) } catch (e: Exception) {
+ Log.w("GlowLED", "interactive overlay update failed", e)
+ }
+ }
+ }
+
+ private fun buildParams(ctx: Context, type: Int): WindowManager.LayoutParams {
+ val prefs = LedController.prefs
+ val g = geometry(ctx)
+ val ledView = led!!
+ val d = ctx.resources.displayMetrics.density
+ ledView.configure(prefs, g, NotificationStore.colors())
+ ledView.notificationRingVisible = prefs.overlayEnabled && !NotificationStore.isEmpty() &&
+ (!prefs.overlayLockOnly || LedController.isLocked())
+ val m = LedController.overlayMeter
+ ledView.setMeter(m?.fraction, m?.color ?: 0, m?.icon ?: MeterIcon.NONE, m?.indeterminate ?: false)
+ ledView.setBatteryText(LedController.batteryStatusText())
+ ledView.setCpuLoad(
+ LedController.cpuStatusText(),
+ prefs.cpuPos,
+ prefs.cpuOffsetXDp,
+ prefs.cpuOffsetYDp,
+ prefs.cpuFontSizeSp,
+ )
+
+ val flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
+ WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
+ WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
+ WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS or
+ WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED
+ val p: WindowManager.LayoutParams
+ if (prefs.style.isEdge) {
+ p = WindowManager.LayoutParams(
+ WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT,
+ type, flags, PixelFormat.TRANSLUCENT,
+ )
+ p.gravity = Gravity.TOP or Gravity.START
+ } else {
+ val e = ledView.extentPx(g)
+ val peekW = (prefs.peekWidthDp * d).toInt().coerceIn((180 * d).toInt(), (ctx.resources.displayMetrics.widthPixels - (24 * d).toInt()))
+ val ringW = maxOf(e * 2, (120 * d).toInt())
+ val expandedW = maxOf(ringW, peekW + (24 * d).toInt(), (220 * d).toInt())
+ if (state == State.COLLAPSED) {
+ val tz = tapZoneRect(ctx)
+ val extraLeft = if (prefs.cpuIndicator) {
+ var ex = if (prefs.cpuPos == "left") (90 * d).toInt() else (40 * d).toInt()
+ if (prefs.cpuOffsetXDp < 0) ex += (-prefs.cpuOffsetXDp * d).toInt()
+ ex
+ } else 0
+ val extraRight = if (prefs.cpuIndicator) {
+ var ex = if (prefs.cpuPos == "right") (90 * d).toInt() else (40 * d).toInt()
+ if (prefs.cpuOffsetXDp > 0) ex += (prefs.cpuOffsetXDp * d).toInt()
+ ex
+ } else 0
+ val extraTop = if (prefs.cpuIndicator) {
+ var ey = if (prefs.cpuPos == "above") (45 * d).toInt() else (10 * d).toInt()
+ if (prefs.cpuOffsetYDp < 0) ey += (-prefs.cpuOffsetYDp * d).toInt()
+ ey
+ } else 0
+ val extraBottom = if (prefs.cpuIndicator) {
+ var ey = if (prefs.cpuPos == "below") (45 * d).toInt() else (10 * d).toInt()
+ if (prefs.cpuOffsetYDp > 0) ey += (prefs.cpuOffsetYDp * d).toInt()
+ ey
+ } else 0
+
+ val w = tz.width() + extraLeft + extraRight
+ val h = tz.height() + extraTop + extraBottom
+ p = WindowManager.LayoutParams(w, h, type, flags, PixelFormat.TRANSLUCENT)
+ p.gravity = Gravity.TOP or Gravity.START
+ p.x = (tz.left - extraLeft).coerceAtLeast(0)
+ p.y = (tz.top - extraTop).coerceAtLeast(0)
+ } else {
+ val w = expandedW
+ val x = (g.cx - w / 2f).toInt()
+ val y = (g.cy - e).toInt()
+ val h = when (state) {
+ State.ICONS -> e + (300 * d).toInt()
+ State.PEEK -> (ctx.resources.displayMetrics.heightPixels - y).coerceAtLeast(e + (prefs.peekHeightDp * d).toInt() + (80 * d).toInt())
+ else -> e * 2
+ }
+ p = WindowManager.LayoutParams(w, h, type, flags, PixelFormat.TRANSLUCENT)
+ p.gravity = Gravity.TOP or Gravity.START
+ p.x = x; p.y = y
+ }
+ }
+ p.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) p.fitInsetsTypes = 0
+ if (type == WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ p.alpha = 0.8f
+ }
+ p.title = "GlowLED"
+ return p
+ }
+
+ fun refresh() {
+ val r = root ?: return
+ val ctx = windowCtx ?: return
+ val prefs = LedController.prefs
+ val ledView = led ?: return
+ val g = geometry(ctx)
+ ledView.configure(prefs, g, NotificationStore.colors())
+ ledView.notificationRingVisible = prefs.overlayEnabled && !NotificationStore.isEmpty() &&
+ (!prefs.overlayLockOnly || LedController.isLocked())
+ val m = LedController.overlayMeter
+ ledView.setMeter(m?.fraction, m?.color ?: 0, m?.icon ?: MeterIcon.NONE, m?.indeterminate ?: false)
+ ledView.setBatteryText(LedController.batteryStatusText())
+ ledView.setCpuLoad(
+ LedController.cpuStatusText(),
+ prefs.cpuPos,
+ prefs.cpuOffsetXDp,
+ prefs.cpuOffsetYDp,
+ prefs.cpuFontSizeSp,
+ )
+ ledView.dropletRadiusDp = prefs.dropletSizeDp.toFloat()
+ info?.monochrome = prefs.aodIcons
+ info?.iconDp = prefs.appIconDp
+
+ val d = ctx.resources.displayMetrics.density
+ val peekW = (prefs.peekWidthDp * d).toInt().coerceIn((180 * d).toInt(), (ctx.resources.displayMetrics.widthPixels - (24 * d).toInt()))
+ peek?.layoutParams?.width = peekW
+ peek?.actionsEnabled = prefs.peekActions
+ peek?.expandableEnabled = prefs.peekExpandable
+ peek?.applyCustomization(prefs.peekFontSizeSp.toFloat(), prefs.peekLines, prefs.peekHeightDp)
+
+ val type = windowType()
+ if (type != 0) applyWindow(type)
+ r.requestLayout()
+ r.post { positionChildren() }
+ }
+
+ private fun positionChildren() {
+ val r = root ?: return
+ val ctx = windowCtx ?: return
+ val ledView = led ?: return
+ val infoView = info ?: return
+ val peekView = peek ?: return
+ if (!r.isAttachedToWindow) return
+ val loc = IntArray(2)
+ r.getLocationOnScreen(loc)
+ val g = geometry(ctx)
+ val d = ctx.resources.displayMetrics.density
+ val safeTop = max(ledView.indicatorBottom() + 16 * d, 8 * d)
+ val infoX = g.cx - loc[0] - infoView.measuredWidth / 2f
+ val infoY = safeTop
+ place(infoView, infoX, infoY)
+ val peekY = infoY + (if (infoView.visibility == View.VISIBLE) infoView.measuredHeight + 14 * d else 0f)
+ place(peekView, g.cx - loc[0] - peekView.measuredWidth / 2f, peekY)
+ }
+
+ private fun place(v: View, x: Float, y: Float) {
+ val l = x.roundToInt(); val t = y.roundToInt()
+ v.layout(l, t, l + v.measuredWidth, t + v.measuredHeight)
+ }
+
+ private fun setState(newState: State) {
+ if (state == newState && root != null) return
+ state = newState
+ val type = windowType()
+ if (type != 0) applyWindow(type)
+ root?.requestLayout()
+ root?.post { positionChildren() }
+ }
+
+ private fun bindApps() { info?.bind(NotificationStore.apps()) }
+
+ private fun expandToIcons(withDroplet: Boolean = false) {
+ val prefs = LedController.prefs
+ bindApps()
+ // show icons (even if one app) to satisfy "раскрывается несколько кружков"
+ if (state == State.COLLAPSED) setState(State.ICONS) else setState(State.ICONS)
+ main.removeCallbacks(hidePeekRunnable)
+ val newest = NotificationStore.apps().firstOrNull()
+ if (withDroplet && prefs.droplet && newest != null) {
+ info?.visibility = View.VISIBLE
+ info?.alpha = 1f
+ info?.doOnLayout {
+ if (root == null) return@doOnLayout
+ info?.prepareDrop()
+ val ctx = windowCtx ?: return@doOnLayout
+ val loc = IntArray(2); root!!.getLocationOnScreen(loc)
+ val g = geometry(ctx)
+ val infoView = info ?: return@doOnLayout
+ val infoX = g.cx - loc[0] - infoView.measuredWidth / 2f
+ val tx = infoX + infoView.newestCenterX()
+ val ty = infoView.top.toFloat() + infoView.iconCenterY()
+ led?.playDroplet(newest.color, ty, targetX = tx) { info?.popNewest() }
+ }
+ } else {
+ info?.show()
+ }
+ }
+
+ private fun collapseToRing() {
+ main.removeCallbacks(hidePeekRunnable)
+ hidePeek(showIconsAfter = false)
+ info?.clearSelection()
+ info?.hide()
+ setState(State.COLLAPSED)
+ }
+
+ private fun onAppTapped(pkg: String) {
+ val prefs = LedController.prefs
+ main.removeCallbacks(hidePeekRunnable)
+ if (!prefs.showContent) {
+ info?.clearSelection()
+ return
+ }
+ val entries = NotificationStore.entriesFor(pkg)
+ if (entries.isEmpty() || (peek?.isShowing() == true && peekPkg == pkg)) {
+ hidePeek(showIconsAfter = true)
+ return
+ }
+ peekPkg = pkg
+ peek?.actionsEnabled = prefs.peekActions
+ peek?.expandableEnabled = prefs.peekExpandable
+ peek?.applyCustomization(prefs.peekFontSizeSp.toFloat(), prefs.peekLines, prefs.peekHeightDp)
+ peek?.bind(entries)
+ peek?.show()
+ setState(State.PEEK)
+ root?.post { positionChildren() }
+ resetPeekTimeout()
+ }
+
+ private fun resetPeekTimeout() {
+ main.removeCallbacks(hidePeekRunnable)
+ main.postDelayed(hidePeekRunnable, PEEK_MS)
+ }
+
+ private fun hidePeek(showIconsAfter: Boolean) {
+ main.removeCallbacks(hidePeekRunnable)
+ peekPkg = null
+ peek?.hide()
+ info?.clearSelection()
+ if (state == State.PEEK) setState(State.ICONS)
+ }
+
+ private fun onBackgroundTap() {
+ when (state) {
+ State.PEEK -> hidePeek(showIconsAfter = true)
+ State.ICONS -> collapseToRing()
+ State.COLLAPSED -> {
+ if (!NotificationStore.isEmpty()) expandToIcons(withDroplet = true)
+ else DebugLog.add("Screen-on tap: no notifications")
+ }
+ }
+ }
+
+ // ---- actions (same as AOD, but on unlocked screen) ----
+
+ private fun openNotification(e: NotificationStore.Entry) {
+ val pi = e.intent ?: return
+ root?.performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY)
+ try {
+ val opts = android.app.ActivityOptions.makeBasic()
+ if (Build.VERSION.SDK_INT >= 34) {
+ opts.setPendingIntentBackgroundActivityStartMode(
+ android.app.ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED,
+ )
+ }
+ pi.send(windowCtx ?: LedController.app, 0, null, null, null, null, opts.toBundle())
+ } catch (ex: Exception) {
+ DebugLog.add("Could not open notification: ${ex.javaClass.simpleName}")
+ }
+ collapseToRing()
+ }
+
+ private fun replyTo(e: NotificationStore.Entry) {
+ root?.performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY)
+ if (ReplyActivity.start(LedController.app, e.key)) collapseToRing()
+ }
+
+ private fun markRead(e: NotificationStore.Entry) {
+ root?.performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY)
+ val action = e.readAction
+ if (action != null) {
+ try { action.actionIntent.send() } catch (ex: Exception) {
+ DebugLog.add("Mark as read failed: ${ex.javaClass.simpleName}")
+ }
+ NotificationStore.markSeen(e.key)
+ LedController.refreshAll()
+ } else {
+ NotifyListenerService.instance?.cancelNotification(e.key)
+ }
+ DebugLog.add("Marked as read from screen-on overlay")
+ // store change will update; keep UX responsive
+ if (NotificationStore.isEmpty()) collapseToRing() else {
+ if (NotificationStore.entriesFor(peekPkg ?: "").isEmpty()) hidePeek(true)
+ }
+ }
+
+ private fun markAllRead(list: List) {
+ root?.performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY)
+ for (e in list) {
+ val action = e.readAction
+ if (action != null) {
+ try { action.actionIntent.send() } catch (ex: Exception) {
+ DebugLog.add("Mark as read failed: ${ex.javaClass.simpleName}")
+ }
+ NotificationStore.markSeen(e.key)
+ } else {
+ NotifyListenerService.instance?.cancelNotification(e.key)
+ }
+ }
+ LedController.refreshAll()
+ collapseToRing()
+ }
+
+ private fun onStoreChanged() {
+ if (root == null) return
+ if (NotificationStore.isEmpty()) {
+ // let controller decide (may keep overlay for meter/battery) -> will hide interactive
+ LedController.updateOverlay()
+ return
+ }
+ val apps = NotificationStore.apps()
+ if (apps.isEmpty()) { LedController.updateOverlay(); return }
+ bindApps()
+ val newest = NotificationStore.newestTime()
+ if (newest > newestTime) {
+ val newestApp = apps.firstOrNull()
+ newestTime = newest
+ if (state != State.COLLAPSED && newestApp != null && LedController.prefs.droplet) {
+ info?.doOnLayout {
+ if (root == null) return@doOnLayout
+ info?.prepareDrop()
+ val ctx = windowCtx ?: return@doOnLayout
+ val loc = IntArray(2); root!!.getLocationOnScreen(loc)
+ val g = geometry(ctx)
+ val infoView = info ?: return@doOnLayout
+ val infoX = g.cx - loc[0] - infoView.measuredWidth / 2f
+ val tx = infoX + infoView.newestCenterX()
+ val ty = infoView.top.toFloat() + infoView.iconCenterY()
+ led?.playDroplet(newestApp.color, ty, targetX = tx) { info?.popNewest() }
+ }
+ } else if (state != State.COLLAPSED) {
+ info?.show()
+ }
+ // collapsed: ring droplet handled by LedController/OverlayHost path
+ }
+ peekPkg?.let { pkg ->
+ val entries = NotificationStore.entriesFor(pkg)
+ if (entries.isEmpty()) hidePeek(showIconsAfter = true) else peek?.bind(entries)
+ }
+ refresh()
+ root?.post { positionChildren() }
+ }
+
+ /** Droplet on the ring while collapsed. */
+ fun droplet(color: Int) {
+ val ledView = led ?: run {
+ DebugLog.add("Droplet skipped: no overlay view")
+ return
+ }
+ if (state == State.COLLAPSED) {
+ DebugLog.add("Droplet on screen-on ring")
+ ledView.post { ledView.playDropletBelow(color, DROP_DP * ledView.resources.displayMetrics.density, retract = true) }
+ } else {
+ DebugLog.add("Droplet skipped: state=$state")
+ }
+ }
+
+ fun hide() {
+ val r = root ?: return
+ try { LedController.removeListener(listener) } catch (_: Exception) {}
+ main.removeCallbacksAndMessages(null)
+ try { wm?.removeViewImmediate(r) } catch (_: Exception) {}
+ cleanupRefs()
+ }
+
+ private fun cleanupRefs() {
+ root = null; led = null; info = null; peek = null; wm = null; windowCtx = null
+ usingA11y = false; state = State.COLLAPSED; peekPkg = null
+ }
+
+ private const val DROP_DP = 26f
+ private const val PEEK_MS = 12_000L
+
+ fun updateBatteryText() {
+ led?.setBatteryText(LedController.batteryStatusText())
+ }
+
+ fun updateCpuText() {
+ val prefs = LedController.prefs
+ led?.setCpuLoad(
+ LedController.cpuStatusText(),
+ prefs.cpuPos,
+ prefs.cpuOffsetXDp,
+ prefs.cpuOffsetYDp,
+ prefs.cpuFontSizeSp,
+ )
+ }
+}
diff --git a/app/src/main/java/com/glowled/app/service/UpdateCheckJob.kt b/app/src/main/java/com/glowled/app/service/UpdateCheckJob.kt
index eb207d2..92fc47b 100644
--- a/app/src/main/java/com/glowled/app/service/UpdateCheckJob.kt
+++ b/app/src/main/java/com/glowled/app/service/UpdateCheckJob.kt
@@ -63,7 +63,7 @@ class UpdateCheckJob : JobService() {
/** One notification per new version. */
fun notifyIfNew(context: Context, r: Updater.Release) {
- val sp = LedController.prefs.sp
+ val sp = LedController.prefs.deviceSp
if (!Updater.isNewer(r.version, BuildConfig.VERSION_NAME)) return
if (sp.getString(Updater.K_NOTIFIED, null) == r.version) return
if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.POST_NOTIFICATIONS) !=
diff --git a/app/src/main/java/com/glowled/app/ui/AodActivity.kt b/app/src/main/java/com/glowled/app/ui/AodActivity.kt
index 5c935e0..ec6f5e4 100644
--- a/app/src/main/java/com/glowled/app/ui/AodActivity.kt
+++ b/app/src/main/java/com/glowled/app/ui/AodActivity.kt
@@ -65,11 +65,13 @@ class AodActivity : Activity() {
override fun releaseKeepScreenOn() {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
- ContextCompat.registerReceiver(
- this@AodActivity, finishOnOff, IntentFilter(Intent.ACTION_SCREEN_OFF),
- ContextCompat.RECEIVER_NOT_EXPORTED,
- )
- waitingForOff = true
+ if (!waitingForOff) {
+ ContextCompat.registerReceiver(
+ this@AodActivity, finishOnOff, IntentFilter(Intent.ACTION_SCREEN_OFF),
+ ContextCompat.RECEIVER_NOT_EXPORTED,
+ )
+ waitingForOff = true
+ }
}
// Show the PIN/fingerprint prompt, then open the chat once unlocked.
diff --git a/app/src/main/java/com/glowled/app/ui/AodSession.kt b/app/src/main/java/com/glowled/app/ui/AodSession.kt
index e2aa29d..c4360ae 100644
--- a/app/src/main/java/com/glowled/app/ui/AodSession.kt
+++ b/app/src/main/java/com/glowled/app/ui/AodSession.kt
@@ -106,8 +106,16 @@ class AodSession(
/** When the panel last came on, to tell the system switching it off from the user doing it. */
private var panelOnAt = 0L
private var rewoken = false
+ private var settledAt = 0L
+ private var isSettled = false
/** Eco: once the entrance and droplet have played, hold a still ring (no more redraws). */
- private val settle = Runnable { led.settle() }
+ private val settle = Runnable {
+ led.settle()
+ if (!isSettled) {
+ isSettled = true
+ settledAt = android.os.SystemClock.uptimeMillis()
+ }
+ }
/** Re-dims the ring as the notifications get older. */
private val ageTick = object : Runnable {
override fun run() {
@@ -117,8 +125,9 @@ class AodSession(
}
private val burnIn = object : Runnable {
override fun run() {
- led.shiftX = Random.nextInt(-3, 4).toFloat()
- led.shiftY = Random.nextInt(-3, 4).toFloat()
+ val (dx, dy) = com.glowled.app.core.BurnInShiftCalculator.calculateShift(android.os.SystemClock.uptimeMillis())
+ led.shiftX = dx
+ led.shiftY = dy
led.invalidate()
root.requestLayout() // re-place the strip with the new shift
handler.postDelayed(this, BURN_IN_MS)
@@ -137,6 +146,9 @@ class AodSession(
panelOnAt = android.os.SystemClock.uptimeMillis()
playEntrance()
}
+ Intent.ACTION_POWER_DISCONNECTED -> {
+ if (NotificationStore.isEmpty()) end(EndReason.TIMEOUT, lock = true)
+ }
}
}
}
@@ -193,15 +205,18 @@ class AodSession(
}
// No overlay available: keep the ring visible right under the window's top edge.
val g = CutoutGeometry.resolve(context, prefs)
- val ringTop = g.cy - led.ringBottom() + g.cy // mirror of the bottom around the centre
+ val ledLoc = IntArray(2); led.getLocationOnScreen(ledLoc)
+ val ringBottomScreen = ledLoc[1] + led.ringBottom()
+ val ringTop = g.cy - (ringBottomScreen - g.cy) // mirror of the bottom around the centre
if (ringTop < loc[1]) {
yShift = loc[1] - ringTop + 6 * density
led.configure(prefs, geometry(), currentColors())
+ led.dropletRadiusDp = prefs.dropletSizeDp.toFloat()
}
}
val g = geometry()
// Window coordinates: below the ring, below the status-bar/cutout band, never at the very edge.
- val safeTop = max(led.indicatorBottom() + 16 * density - loc[1], statusBandPx() + 8 * density)
+ val safeTop = max(led.indicatorBottom() + 16 * density, statusBandPx() + 8 * density)
infoX = g.cx - loc[0] - info.measuredWidth / 2f + led.shiftX
infoY = max(safeTop, 8 * density) + led.shiftY
place(info, infoX, infoY)
@@ -236,6 +251,7 @@ class AodSession(
private fun bindInfo() {
if (!prefs.showAppInfo) return
info.monochrome = prefs.aodIcons
+ info.iconDp = prefs.appIconDp
var apps = NotificationStore.apps()
if (preview && apps.isEmpty()) apps = sampleApps
info.bind(apps)
@@ -308,9 +324,18 @@ class AodSession(
return
}
peekPkg = pkg
+ val peekWidth = (prefs.peekWidthDp * density).toInt()
+ .coerceIn((180 * density).toInt(), (context.resources.displayMetrics.widthPixels - 24 * density).toInt())
+ peek.layoutParams.width = peekWidth
peek.actionsEnabled = prefs.peekActions
+ peek.expandableEnabled = prefs.peekExpandable
+ peek.applyCustomization(prefs.peekFontSizeSp.toFloat(), prefs.peekLines, prefs.peekHeightDp)
peek.bind(entries)
peek.show()
+ resetPeekTimeout()
+ }
+
+ private fun resetPeekTimeout() {
handler.removeCallbacks(hidePeekRunnable)
handler.postDelayed(hidePeekRunnable, PEEK_MS)
}
@@ -373,6 +398,28 @@ class AodSession(
DebugLog.add("Marked as read from the always-on screen")
}
+ /** Marks all notifications in the list as read / dismissed. */
+ private fun markAllRead(list: List) {
+ root.performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY)
+ for (e in list) {
+ val action = e.readAction
+ if (action != null) {
+ try {
+ action.actionIntent.send()
+ } catch (ex: Exception) {
+ DebugLog.add("Mark as read failed: ${ex.javaClass.simpleName}")
+ }
+ NotificationStore.markSeen(e.key)
+ } else {
+ com.glowled.app.service.NotifyListenerService.instance?.cancelNotification(e.key)
+ NotificationStore.markSeen(e.key)
+ }
+ }
+ LedController.refreshAll()
+ hidePeek()
+ DebugLog.add("Marked all as read (${list.size} notifications)")
+ }
+
/** Call once the host window is visible. */
fun start() {
LedController.aodVisible = true
@@ -385,6 +432,7 @@ class AodSession(
addAction(Intent.ACTION_SCREEN_OFF)
addAction(Intent.ACTION_SCREEN_ON)
addAction(Intent.ACTION_USER_PRESENT)
+ addAction(Intent.ACTION_POWER_DISCONNECTED)
},
ContextCompat.RECEIVER_NOT_EXPORTED,
)
@@ -421,7 +469,9 @@ class AodSession(
}
fun restartAnimation() {
- led.configure(prefs, geometry(), currentColors()) // undoes an eco still ring
+ isSettled = false
+ led.configure(prefs, geometry(), currentColors())
+ led.dropletRadiusDp = prefs.dropletSizeDp.toFloat() // undoes an eco still ring
updateMeters()
updateAgeFade()
led.restartAnimation()
@@ -434,7 +484,7 @@ class AodSession(
led.notificationRingVisible = preview || !NotificationStore.isEmpty()
val meter = LedController.computeMeter(!NotificationStore.isEmpty())
led.setMeter(meter?.fraction, meter?.color ?: 0, meter?.icon ?: com.glowled.app.core.MeterIcon.NONE, meter?.indeterminate ?: false)
- led.setBattery(LedController.batteryPercent())
+ led.setBatteryText(LedController.batteryStatusText())
root.requestLayout()
}
@@ -522,6 +572,7 @@ class AodSession(
return
}
led.configure(prefs, geometry(), currentColors())
+ led.dropletRadiusDp = prefs.dropletSizeDp.toFloat()
updateMeters()
updateAgeFade()
armSettle()
@@ -567,15 +618,24 @@ class AodSession(
init {
led.useScreenCoords = true
led.configure(prefs, geometry(), currentColors())
+ led.dropletRadiusDp = prefs.dropletSizeDp.toFloat()
led.intro = 0f
updateAgeFade()
root.addView(info, FrameLayout.LayoutParams(-2, -2))
- val peekWidth = (context.resources.displayMetrics.widthPixels - 48 * density).toInt().coerceAtMost((380 * density).toInt())
+ val peekWidth = (prefs.peekWidthDp * density).toInt()
+ .coerceIn((180 * density).toInt(), (context.resources.displayMetrics.widthPixels - 24 * density).toInt())
root.addView(peek, FrameLayout.LayoutParams(peekWidth, -2))
info.onAppTap = { pkg -> onAppTapped(pkg) }
peek.onOpen = { e -> openNotification(e) }
peek.onReply = { e -> replyTo(e) }
peek.onMarkRead = { e -> markRead(e) }
+ peek.onMarkAllRead = { list -> markAllRead(list) }
+ peek.onInteraction = { resetPeekTimeout() }
+ peek.onExpandedChanged = {
+ resetPeekTimeout()
+ root.requestLayout()
+ root.post { positionInfo() }
+ }
bindInfo()
installGestures()
if (durationSec > 0) handler.postDelayed(timeout, durationSec * 1000L)
@@ -638,6 +698,17 @@ class AodSession(
}
sensorManager?.unregisterListener(proximityListener)
sensorManager = null
+ if (!preview) {
+ val sessionTotal = android.os.SystemClock.uptimeMillis() - startedAt
+ val (animMs, staticMs) = if (isSettled && settledAt >= startedAt) {
+ val a = settledAt - startedAt
+ val s = sessionTotal - a
+ a.coerceAtLeast(0L) to s.coerceAtLeast(0L)
+ } else {
+ sessionTotal.coerceAtLeast(0L) to 0L
+ }
+ com.glowled.app.core.BatteryStats.recordAodSession(context, animMs, staticMs)
+ }
}
companion object {
diff --git a/app/src/main/java/com/glowled/app/ui/AppsActivity.kt b/app/src/main/java/com/glowled/app/ui/AppsActivity.kt
index eb8ec98..4b387cc 100644
--- a/app/src/main/java/com/glowled/app/ui/AppsActivity.kt
+++ b/app/src/main/java/com/glowled/app/ui/AppsActivity.kt
@@ -15,6 +15,7 @@ import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
+import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
@@ -36,6 +37,8 @@ class AppsActivity : AppCompatActivity() {
private var shown = emptyList()
private val prefs get() = LedController.prefs
private val adapter = Adapter()
+ /** The open colour picker, if any; dismissed in onDestroy so it cannot fire into a dead activity. */
+ private var colorDialog: AlertDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
goEdgeToEdge()
@@ -92,6 +95,7 @@ class AppsActivity : AppCompatActivity() {
}
override fun onDestroy() {
+ colorDialog?.dismiss()
io.shutdownNow()
super.onDestroy()
}
@@ -123,16 +127,19 @@ class AppsActivity : AppCompatActivity() {
val cached = icons.get(item.pkg)
h.icon.setImageDrawable(cached)
if (cached == null) {
- io.execute {
+ if (!isDestroyed && !io.isShutdown) io.execute {
val d = try { packageManager.getApplicationIcon(item.pkg) } catch (_: Exception) { null }
if (d != null) icons.put(item.pkg, d)
main.post { if (h.pkg == item.pkg) h.icon.setImageDrawable(d) }
}
}
val pick = View.OnClickListener {
- ColorPickerDialog.show(this@AppsActivity, prefs.appColor(item.pkg), allowAuto = true) { c ->
- prefs.setAppColor(item.pkg, c)
- bindColor(h, item.pkg)
+ colorDialog = ColorPickerDialog.show(this@AppsActivity, prefs.appColor(item.pkg), allowAuto = true) { c ->
+ // The activity may have been destroyed while the picker was open.
+ if (!isDestroyed) {
+ prefs.setAppColor(item.pkg, c)
+ bindColor(h, item.pkg)
+ }
}
}
h.swatch.setOnClickListener(pick)
@@ -147,7 +154,9 @@ class AppsActivity : AppCompatActivity() {
} else {
h.colorLabel.setText(R.string.apps_auto)
h.swatch.backgroundTintList = null
- io.execute {
+ // A late dialog callback can reach a destroyed activity whose executor is already
+ // shut down; without the guard this throws RejectedExecutionException.
+ if (!isDestroyed && !io.isShutdown) io.execute {
val c = LedController.colors.iconColor(pkg).takeIf { it != 0 } ?: prefs.defaultColor
main.post {
if (h.pkg == pkg && prefs.appColor(pkg) == 0) h.swatch.backgroundTintList = ColorStateList.valueOf(c)
diff --git a/app/src/main/java/com/glowled/app/ui/ColorPickerDialog.kt b/app/src/main/java/com/glowled/app/ui/ColorPickerDialog.kt
index 6caf8db..588cd4c 100644
--- a/app/src/main/java/com/glowled/app/ui/ColorPickerDialog.kt
+++ b/app/src/main/java/com/glowled/app/ui/ColorPickerDialog.kt
@@ -14,6 +14,7 @@ import android.widget.GridLayout
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
+import androidx.appcompat.app.AlertDialog
import com.glowled.app.R
import com.glowled.app.view.ColorWheelView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
@@ -32,8 +33,9 @@ object ColorPickerDialog {
0xFF25D366, 0xFF0088CC, 0xFFE1306C, 0xFF1877F2, 0xFFEA4335, 0xFFFFFFFF,
).map { it.toInt() }.toIntArray()
- /** [onPick] receives the chosen colour, or 0 when "Automatic" is chosen (if [allowAuto]). */
- fun show(context: Context, initial: Int, allowAuto: Boolean, onPick: (Int) -> Unit) {
+ /** [onPick] receives the chosen colour, or 0 when "Automatic" is chosen (if [allowAuto]).
+ * Returns the shown dialog so the caller can dismiss it when its activity dies. */
+ fun show(context: Context, initial: Int, allowAuto: Boolean, onPick: (Int) -> Unit): AlertDialog {
val dp = context.resources.displayMetrics.density
fun px(v: Int) = (v * dp).toInt()
var current = if (initial == 0) presets[0] else initial or 0xFF000000.toInt()
@@ -151,6 +153,6 @@ object ColorPickerDialog {
.setPositiveButton(R.string.ok) { _, _ -> onPick(current) }
.setNegativeButton(R.string.cancel, null)
if (allowAuto) b.setNeutralButton(R.string.color_auto) { _, _ -> onPick(0) }
- b.show()
+ return b.show()
}
}
diff --git a/app/src/main/java/com/glowled/app/ui/MainActivity.kt b/app/src/main/java/com/glowled/app/ui/MainActivity.kt
index 3a36aea..5815e6f 100644
--- a/app/src/main/java/com/glowled/app/ui/MainActivity.kt
+++ b/app/src/main/java/com/glowled/app/ui/MainActivity.kt
@@ -33,6 +33,7 @@ import android.widget.ScrollView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
+import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.os.LocaleListCompat
@@ -62,6 +63,7 @@ import com.glowled.app.core.PowerGuard
import com.glowled.app.core.Prefs
import com.glowled.app.service.LedAccessibilityService
import com.glowled.app.service.NotifyListenerService
+import com.glowled.app.service.ScreenOnOverlay
import com.glowled.app.ui.SettingsUi.Range
import com.glowled.app.ui.SettingsUi.Toggle
import com.glowled.app.ui.SettingsUi.ColorItem
@@ -90,6 +92,8 @@ class MainActivity : AppCompatActivity() {
/** Full-screen, touch-through layer that draws the ring on the phone's real camera cutout. */
private lateinit var cameraLed: LedView
private var introAnim: ValueAnimator? = null
+ /** Outline of the screen-on tap/response zone, shown while configuring it. */
+ private var tapZoneOutline: TapZoneOutlineView? = null
private lateinit var pager: ViewPager2
private lateinit var tabs: TabLayout
private lateinit var ui: SettingsUi
@@ -111,17 +115,28 @@ class MainActivity : AppCompatActivity() {
private var unknownSub: TextView? = null
private var updateSub: TextView? = null
private var setupIncomplete = false
+ /** Dialogs that must not outlive a rotation: dismissed in onDestroy, their callbacks guarded. */
+ private var quietPicker: TimePickerDialog? = null
+ private var tutorialDialog: AlertDialog? = null
private val prefs get() = LedController.prefs
private val density by lazy { resources.displayMetrics.density }
private fun dp(v: Int) = (v * density).toInt()
private val storeListener: () -> Unit = { runOnUiThread { refreshLive() } }
- // Any setting change re-renders the preview immediately.
+ // Any setting change re-renders the preview immediately. SharedPreferences listeners fire on
+ // the thread that wrote the change - and UpdateCheckJob writes prefs from a background thread
+ // while this body touches views - so hop to the UI thread first (the debounce that merges
+ // slider ticks lives in LedController; see P1-12 for doing the same here).
private val prefsListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
+ runOnUiThread { if (!isDestroyed) applyPrefChange(key) }
+ }
+
+ /** View work for one changed pref key; always called on the UI thread. */
+ private fun applyPrefChange(key: String?) {
if (key == "style") styleAdapter.notifyItemRangeChanged(0, styleAdapter.itemCount)
// A new method choice gets a fresh chance to use the flicker-free lock-screen window.
- if (key == "aod_method") prefs.sp.edit().remove(LedController.PREF_WINDOW_BLOCKED).apply()
+ if (key == "aod_method") prefs.deviceSp.edit().remove(LedController.PREF_WINDOW_BLOCKED).apply()
configureCameraLed()
if (key == "droplet" && prefs.droplet) {
// Show what the setting does: on the real camera, and in the one-handed preview.
@@ -132,6 +147,11 @@ class MainActivity : AppCompatActivity() {
if (key in REPLAY_KEYS) playCameraIntro()
if (key != null && (key.startsWith("charge_") || key.startsWith("progress_") || key == "upload_color" || key == "download_color")) previewMeter(key)
if (key == "style" || key == Prefs.K_ENABLED) ui.refresh()
+ if (key != null && key.startsWith("tap_zone_")) updateTapZoneOutline()
+ if (key == "snooze_choice") {
+ val mins = prefs.sp.getString("snooze_choice", "0")?.toIntOrNull() ?: 0
+ if (mins > 0) prefs.snooze(mins) else prefs.clearSnooze()
+ }
}
override fun onCreate(savedInstanceState: Bundle?) {
@@ -156,6 +176,13 @@ class MainActivity : AppCompatActivity() {
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
}
findViewById(android.R.id.content).addView(cameraLed, FrameLayout.LayoutParams(-1, -1))
+ tapZoneOutline = TapZoneOutlineView(this).apply {
+ isClickable = false
+ isFocusable = false
+ importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
+ visibility = View.GONE
+ }
+ findViewById(android.R.id.content).addView(tapZoneOutline, FrameLayout.LayoutParams(-1, -1))
cameraLed.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> configureCameraLed() }
master = findViewById(R.id.master)
@@ -258,6 +285,7 @@ class MainActivity : AppCompatActivity() {
refreshLive()
LedController.addListener(storeListener)
NotifyListenerService.forceReconnect(this)
+ if (prefs.cpuIndicator) com.glowled.app.core.CpuStats.updateAsync { runOnUiThread { refreshLive() } }
cameraLed.post { playCameraIntro() }
}
@@ -276,6 +304,8 @@ class MainActivity : AppCompatActivity() {
override fun onDestroy() {
prefs.sp.unregisterOnSharedPreferenceChangeListener(prefsListener)
+ quietPicker?.dismiss()
+ tutorialDialog?.dismiss()
super.onDestroy()
}
@@ -294,6 +324,24 @@ class MainActivity : AppCompatActivity() {
cameraLed.visibility = if (show) View.VISIBLE else View.INVISIBLE
if (!show) return
cameraLed.configure(prefs, CutoutGeometry.resolve(this, prefs), cameraColors())
+ if (prefs.cpuIndicator) {
+ val usage = if (LedController.cpuUsage >= 0) LedController.cpuUsage else com.glowled.app.core.CpuStats.cachedUsage
+ val text = if (usage >= 0) {
+ if (prefs.cpuShowLabel) "CPU $usage%" else "$usage%"
+ } else {
+ if (prefs.cpuShowLabel) "CPU …" else "…"
+ }
+ cameraLed.setCpuLoad(
+ text,
+ prefs.cpuPos,
+ prefs.cpuOffsetXDp,
+ prefs.cpuOffsetYDp,
+ prefs.cpuFontSizeSp
+ )
+ } else {
+ cameraLed.setCpuLoad(null)
+ }
+ updateTapZoneOutline()
}
/** The ring grows out of the camera and fades in (same entrance as the always-on screen). */
@@ -369,7 +417,13 @@ class MainActivity : AppCompatActivity() {
pager.adapter = PagesAdapter(pageViews)
pager.offscreenPageLimit = pages.size
TabLayoutMediator(tabs, pager) { tab, i -> tab.text = pages[i].first }.attach()
+ pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
+ override fun onPageSelected(position: Int) {
+ updateTapZoneOutline()
+ }
+ })
ui.refresh()
+ updateTapZoneOutline()
}
private class PagesAdapter(val pages: List) : RecyclerView.Adapter() {
@@ -499,8 +553,19 @@ class MainActivity : AppCompatActivity() {
section(col, R.string.sec_messages)
ui.toggles(col, listOf(
Toggle(getString(R.string.t_tap_read), "show_content", true, iconsOn),
+ Toggle(getString(R.string.t_peek_expandable), "peek_expandable", true) { iconsOn() && prefs.showContent },
Toggle(getString(R.string.t_peek_actions), "peek_actions", true) { iconsOn() && prefs.showContent },
))
+ val peekCardOff = ui.card(col)
+ ui.sliders(peekCardOff,
+ Range(getString(R.string.s_peek_width), "peek_width", 180, 480, 340, "dp"),
+ Range(getString(R.string.s_peek_height), "peek_height", 150, 700, 380, "dp"),
+ dependsOn = { iconsOn() && prefs.showContent })
+ ui.sliders(peekCardOff,
+ Range(getString(R.string.s_peek_lines), "peek_lines", 1, 20, 4, ""),
+ Range(getString(R.string.s_peek_font_size), "peek_font_size", 10, 24, 14, "sp"),
+ dependsOn = { iconsOn() && prefs.showContent })
+ ui.dependOn(peekCardOff.parent as View) { iconsOn() && prefs.showContent }
section(col, R.string.sec_gestures)
ui.toggles(col, listOf(
Toggle(getString(R.string.t_double_tap), "double_tap_wake", true, aodOn),
@@ -517,6 +582,8 @@ class MainActivity : AppCompatActivity() {
Range(getString(R.string.s_reminder), "pulse_duration", 3, 60, 10, "s"), dependsOn = aodOn)
ui.chips(c, getString(R.string.chips_off_delay), "off_delay",
labels(R.array.off_delay_labels), listOf("800", "1500", "3000"), "800", aodOn)
+ ui.chips(c, getString(R.string.chips_charge_timeout_aod), "charge_timeout_aod",
+ labels(R.array.charge_timeout_aod_labels), listOf("0", "5", "15", "30", "60", "300"), "0") { aodOn() && prefs.chargeLed && prefs.chargeAod }
ui.chips(c, getString(R.string.chips_method), "aod_method",
labels(R.array.method_labels), listOf("auto", "activity", "overlay"), "auto", aodOn)
return page
@@ -524,22 +591,96 @@ class MainActivity : AppCompatActivity() {
private fun pageScreenOn(): View {
val (page, col) = ui.page()
+ val ringOn = { prefs.overlayEnabled }
+ val tapOn = { prefs.overlayEnabled && prefs.onTapMessages && !prefs.overlayLockOnly }
section(col, R.string.sec_ring_on, first = true)
ui.toggles(col, listOf(
Toggle(getString(R.string.t_ring_on), "overlay_enabled", true),
- Toggle(getString(R.string.t_lock_only), "overlay_lock_only", false) { prefs.overlayEnabled },
+ Toggle(getString(R.string.t_lock_only), "overlay_lock_only", false, ringOn),
+ Toggle(getString(R.string.t_overlay_tap_messages), "overlay_tap_messages", true) { prefs.overlayEnabled && !prefs.overlayLockOnly },
+ Toggle(getString(R.string.t_droplet), "droplet", true, ringOn),
+ ))
+ val ringCard = ui.card(col)
+ ui.sliders(ringCard,
+ Range(getString(R.string.s_droplet_size), "droplet_size", 4, 28, 10, "dp"),
+ Range(getString(R.string.s_icon_size), "app_icon_size", 24, 72, 36, "dp"),
+ dependsOn = ringOn)
+ section(col, R.string.sec_tap_zone)
+ val tz = ui.card(col)
+ ui.sliders(tz,
+ Range(getString(R.string.s_tap_zone_x), "tap_zone_dx", -300, 300, 0, "dp"),
+ Range(getString(R.string.s_tap_zone_y), "tap_zone_dy", -300, 500, 0, "dp"),
+ dependsOn = tapOn)
+ ui.sliders(tz,
+ Range(getString(R.string.s_tap_zone_w), "tap_zone_w", 0, 500, 0, "dp"),
+ Range(getString(R.string.s_tap_zone_h), "tap_zone_h", 0, 800, 0, "dp"),
+ dependsOn = tapOn)
+ val tzHint = hint(getString(R.string.tap_zone_hint))
+ col.addView(tzHint)
+ ui.dependOn(tzHint, tapOn)
+ ui.dependOn(tz.parent as View, tapOn)
+ section(col, R.string.sec_messages)
+ ui.toggles(col, listOf(
+ Toggle(getString(R.string.t_aod_icons), "aod_icons", true, tapOn),
+ Toggle(getString(R.string.t_tap_read), "show_content", true, tapOn),
+ Toggle(getString(R.string.t_peek_expandable), "peek_expandable", true) { tapOn() && prefs.showContent },
+ Toggle(getString(R.string.t_peek_actions), "peek_actions", true) { tapOn() && prefs.showContent },
))
+ val peekCardOn = ui.card(col)
+ ui.sliders(peekCardOn,
+ Range(getString(R.string.s_peek_width), "peek_width", 180, 480, 340, "dp"),
+ Range(getString(R.string.s_peek_height), "peek_height", 150, 700, 380, "dp"),
+ dependsOn = { tapOn() && prefs.showContent })
+ ui.sliders(peekCardOn,
+ Range(getString(R.string.s_peek_lines), "peek_lines", 1, 20, 4, ""),
+ Range(getString(R.string.s_peek_font_size), "peek_font_size", 10, 24, 14, "sp"),
+ dependsOn = { tapOn() && prefs.showContent })
+ ui.dependOn(peekCardOn.parent as View) { tapOn() && prefs.showContent }
section(col, R.string.sec_charging)
+ val chargeOn = { prefs.chargeLed }
ui.toggles(col, listOf(
Toggle(getString(R.string.t_charge), "charge_led", true),
+ Toggle(getString(R.string.t_charge_screen_on), "charge_screen_on", true, chargeOn),
+ Toggle(getString(R.string.t_charge_aod), "charge_aod", false, chargeOn),
Toggle(getString(R.string.t_battery_indicator), "battery_indicator", false),
))
+ val chargeTimers = ui.card(col)
+ ui.chips(chargeTimers, getString(R.string.chips_charge_timeout_on), "charge_timeout_on",
+ labels(R.array.charge_timeout_on_labels), listOf("0", "5", "10", "30"), "0") { prefs.chargeLed && prefs.chargeScreenOn }
+ ui.chips(chargeTimers, getString(R.string.chips_charge_timeout_aod), "charge_timeout_aod",
+ labels(R.array.charge_timeout_aod_labels), listOf("0", "5", "15", "30", "60", "300"), "0") { prefs.chargeLed && prefs.chargeAod }
+ ui.dependOn(chargeTimers.parent as View) { prefs.chargeLed && (prefs.chargeScreenOn || prefs.chargeAod) }
+
+ col.addView(label(getString(R.string.sec_battery_metrics)))
+ ui.toggles(col, listOf(
+ Toggle(getString(R.string.t_charge_show_percent), "charge_show_percent", true, chargeOn),
+ Toggle(getString(R.string.t_charge_show_voltage), "charge_show_voltage", true, chargeOn),
+ Toggle(getString(R.string.t_charge_show_current), "charge_show_current", true, chargeOn),
+ Toggle(getString(R.string.t_charge_show_power), "charge_show_power", true, chargeOn),
+ ))
col.addView(label(getString(R.string.charge_colours)))
ui.colorTiles(col, listOf(
ColorItem(getString(R.string.c_low), "charge_color_low", 0xFFFF1744.toInt()),
ColorItem(getString(R.string.c_mid), "charge_color_mid", 0xFFFFC400.toInt()),
ColorItem(getString(R.string.c_high), "charge_color_high", 0xFF00E676.toInt()),
- ), dependsOn = { prefs.chargeLed })
+ ), dependsOn = chargeOn)
+ section(col, R.string.sec_cpu)
+ val cpuOn = { prefs.cpuIndicator }
+ ui.toggles(col, listOf(
+ Toggle(getString(R.string.t_cpu_indicator), "cpu_indicator", false),
+ Toggle(getString(R.string.t_cpu_show_label), "cpu_show_label", true, cpuOn),
+ ))
+ val cpuCard = ui.card(col)
+ ui.chips(cpuCard, getString(R.string.chips_cpu_pos), "cpu_pos",
+ labels(R.array.cpu_pos_labels), listOf("below", "right", "left", "above"), "below", cpuOn)
+ ui.sliders(cpuCard,
+ Range(getString(R.string.s_cpu_font_size), "cpu_font_size", 8, 24, 12, "sp"),
+ Range(getString(R.string.s_cpu_offset_x), "cpu_offset_x", -150, 150, 0, "dp"),
+ dependsOn = cpuOn)
+ ui.sliders(cpuCard,
+ Range(getString(R.string.s_cpu_offset_y), "cpu_offset_y", -150, 150, 0, "dp"),
+ dependsOn = cpuOn)
+ ui.dependOn(cpuCard.parent as View, cpuOn)
section(col, R.string.sec_transfers)
ui.toggles(col, listOf(
Toggle(getString(R.string.t_progress), "progress_led", true),
@@ -600,6 +741,22 @@ class MainActivity : AppCompatActivity() {
ui.chips(c, getString(R.string.chips_fps), "fps_cap",
labels(R.array.fps_labels), listOf("15", "24", "30", "60", "0"), "30")
ui.sliders(c, Range(getString(R.string.s_min_battery), "min_battery", 0, 50, 10, "%"))
+ section(col, R.string.sec_snooze)
+ val snoozeCard = ui.card(col)
+ ui.chips(snoozeCard, getString(R.string.snooze_title), "snooze_choice",
+ listOf(getString(R.string.snooze_off), "30m", "1h", "2h", "4h"),
+ listOf("0", "30", "60", "120", "240"),
+ if (prefs.isPaused) {
+ val left = (prefs.pausedUntilEpochMs - System.currentTimeMillis()) / 60_000L
+ when {
+ left > 180 -> "240"
+ left > 90 -> "120"
+ left > 45 -> "60"
+ left > 10 -> "30"
+ else -> "0"
+ }
+ } else "0"
+ )
section(col, R.string.t_quiet)
ui.toggles(col, listOf(Toggle(getString(R.string.t_quiet), "quiet_enabled", false)))
quietSub = ui.link(col, R.drawable.ic_s_clock, getString(R.string.quiet_time), quietText(), RowIcons.INDIGO) { pickQuietHours() }
@@ -616,7 +773,7 @@ class MainActivity : AppCompatActivity() {
private fun updateText(): String {
val cur = BuildConfig.VERSION_NAME.substringBefore('-')
return Updater.pendingVersion()?.let { getString(R.string.upd_sub_available, it) }
- ?: if (prefs.sp.contains(Updater.K_CHECKED)) getString(R.string.upd_sub_latest, cur)
+ ?: if (prefs.deviceSp.contains(Updater.K_CHECKED)) getString(R.string.upd_sub_latest, cur)
else getString(R.string.upd_sub_unknown, cur)
}
@@ -648,13 +805,28 @@ class MainActivity : AppCompatActivity() {
}
private val restoreLauncher = registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri == null) return@registerForActivityResult
- val n = SettingsBackup.read(this, prefs.sp, uri)
- if (n < 0) {
+ val text = try {
+ contentResolver.openInputStream(uri)?.use { it.readBytes().decodeToString() } ?: ""
+ } catch (_: Exception) { "" }
+ val summary = SettingsBackup.inspect(text)
+ if (!summary.isValid || summary.validSettingsCount == 0) {
Toast.makeText(this, R.string.restore_failed, Toast.LENGTH_SHORT).show()
- } else {
- Toast.makeText(this, getString(R.string.restore_done, n), Toast.LENGTH_SHORT).show()
- recreate() // rebuild every control from the restored values
+ return@registerForActivityResult
}
+ MaterialAlertDialogBuilder(this)
+ .setTitle(R.string.g_restore)
+ .setMessage(getString(R.string.restore_confirm_msg, summary.validSettingsCount, summary.appRulesCount, summary.appVersion))
+ .setPositiveButton(R.string.ok) { _, _ ->
+ val n = SettingsBackup.restoreFromJson(prefs.sp, text)
+ if (n < 0) {
+ Toast.makeText(this, R.string.restore_failed, Toast.LENGTH_SHORT).show()
+ } else {
+ Toast.makeText(this, getString(R.string.restore_done, n), Toast.LENGTH_SHORT).show()
+ recreate()
+ }
+ }
+ .setNegativeButton(R.string.cancel, null)
+ .show()
}
/** Settings: app theme and haptics, then everything else as a grid of tiles side by side. */
@@ -678,6 +850,7 @@ class MainActivity : AppCompatActivity() {
GridItem(R.drawable.ic_s_restore, getString(R.string.g_restore), getString(R.string.g_restore_sub), RowIcons.BROWN) {
restoreLauncher.launch(arrayOf("application/json", "text/plain", "*/*"))
},
+ GridItem(R.drawable.ic_s_shield, getString(R.string.g_diag), getString(R.string.g_diag_sub), RowIcons.RED) { showDiagnostics() },
GridItem(R.drawable.ic_s_log, getString(R.string.g_log), getString(R.string.g_log_sub), RowIcons.GREY) { showLog() },
)).getOrNull(0)
col.addView(hint(getString(R.string.reach_tip)))
@@ -692,15 +865,17 @@ class MainActivity : AppCompatActivity() {
)
var step = 0
fun showStep() {
- val dialog = MaterialAlertDialogBuilder(this)
+ if (isDestroyed) return
+ val builder = MaterialAlertDialogBuilder(this)
.setTitle(getString(R.string.tutorial_step, step + 1, sections.size))
.setMessage(sections[step])
.setPositiveButton(if (step == sections.lastIndex) R.string.tutorial_done else R.string.tutorial_next) { _, _ ->
if (step < sections.lastIndex) { step++; showStep() }
}
.setNegativeButton(R.string.tutorial_later, null)
- if (step > 0) dialog.setNeutralButton(R.string.tutorial_back) { _, _ -> step--; showStep() }
- dialog.show()
+ if (step > 0) builder.setNeutralButton(R.string.tutorial_back) { _, _ -> step--; showStep() }
+ tutorialDialog = builder.create()
+ tutorialDialog?.show()
}
showStep()
}
@@ -715,6 +890,89 @@ class MainActivity : AppCompatActivity() {
setPadding(dp(16), dp(14), dp(16), dp(6))
}
+ private fun showDiagnostics() {
+ val items = com.glowled.app.util.HealthCheck.runAll(this)
+ val container = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(dp(20), dp(10), dp(20), dp(10))
+ }
+
+ val aod = com.glowled.app.core.BatteryStats.getAodTelemetry(this)
+ val statsHeader = TextView(this).apply {
+ text = getString(R.string.diag_telemetry, aod.sessionCount, aod.animDurationMs / 1000, aod.staticDurationMs / 1000)
+ textSize = 12f
+ setTextColor(getColor(R.color.text_secondary))
+ setPadding(0, 0, 0, dp(12))
+ }
+ container.addView(statsHeader)
+
+ var dialog: androidx.appcompat.app.AlertDialog? = null
+
+ items.forEach { item ->
+ val row = LinearLayout(this).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ setPadding(0, dp(8), 0, dp(8))
+ }
+ val statusIcon = ImageView(this).apply {
+ setImageResource(if (item.isOk) R.drawable.ic_s_badge else R.drawable.ic_s_shield)
+ imageTintList = ColorStateList.valueOf(if (item.isOk) RowIcons.GREEN else RowIcons.ORANGE)
+ layoutParams = LinearLayout.LayoutParams(dp(22), dp(22)).apply { rightMargin = dp(12) }
+ }
+ val textCol = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)
+ }
+ val titleView = TextView(this).apply {
+ text = item.title
+ textSize = 14f
+ setTypeface(null, Typeface.BOLD)
+ setTextColor(getColor(R.color.text_primary))
+ }
+ val detailView = TextView(this).apply {
+ text = item.detail
+ textSize = 12f
+ setTextColor(getColor(R.color.text_secondary))
+ }
+ textCol.addView(titleView)
+ textCol.addView(detailView)
+ row.addView(statusIcon)
+ row.addView(textCol)
+
+ if (!item.isOk && item.fixAction != null) {
+ val fixBtn = TextView(this).apply {
+ setText(R.string.setup_open)
+ textSize = 12f
+ setTypeface(null, Typeface.BOLD)
+ setTextColor(getColor(R.color.accent))
+ setPadding(dp(8), dp(4), dp(4), dp(4))
+ setOnClickListener {
+ item.fixAction.invoke(this@MainActivity)
+ dialog?.dismiss()
+ }
+ }
+ row.addView(fixBtn)
+ }
+ container.addView(row)
+ }
+
+ dialog = MaterialAlertDialogBuilder(this)
+ .setTitle(R.string.g_diag)
+ .setView(ScrollView(this).apply { addView(container) })
+ .setPositiveButton(R.string.diag_export) { _, _ ->
+ val report = com.glowled.app.util.HealthCheck.generateReport(this)
+ val send = Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, report)
+ open(Intent.createChooser(send, getString(R.string.g_diag)))
+ }
+ .setNeutralButton(R.string.log_copy) { _, _ ->
+ val report = com.glowled.app.util.HealthCheck.generateReport(this)
+ getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("Glow LED Diagnostics", report))
+ Toast.makeText(this, R.string.log_copied, Toast.LENGTH_SHORT).show()
+ }
+ .setNegativeButton(R.string.close, null)
+ .show()
+ }
+
private fun showLog() {
val text = deviceInfo() + "\n\n" + DebugLog.text()
val tv = TextView(this).apply {
@@ -808,15 +1066,23 @@ class MainActivity : AppCompatActivity() {
private fun pickQuietHours() {
val is24 = DateFormat.is24HourFormat(this)
- TimePickerDialog(this, { _, h, m ->
+ quietPicker = quietTimePicker(R.string.quiet_start, prefs.quietStart, is24) { h, m ->
prefs.sp.edit().putInt("quiet_start", h * 60 + m).apply()
- TimePickerDialog(this, { _, h2, m2 ->
+ // The activity can die between the two pickers (rotation), so guard the second too.
+ quietPicker = quietTimePicker(R.string.quiet_end, prefs.quietEnd, is24) { h2, m2 ->
prefs.sp.edit().putInt("quiet_end", h2 * 60 + m2).apply()
quietSub?.text = quietText()
- }, prefs.quietEnd / 60, prefs.quietEnd % 60, is24).apply { setTitle(R.string.quiet_end) }.show()
- }, prefs.quietStart / 60, prefs.quietStart % 60, is24).apply { setTitle(R.string.quiet_start) }.show()
+ }
+ quietPicker?.show()
+ }
+ quietPicker?.show()
}
+ /** A quiet-hours picker whose callback is ignored once the activity is destroyed. */
+ private fun quietTimePicker(title: Int, minutes: Int, is24: Boolean, onPick: (Int, Int) -> Unit): TimePickerDialog =
+ TimePickerDialog(this, { _, h, m -> if (!isDestroyed) onPick(h, m) }, minutes / 60, minutes % 60, is24)
+ .apply { setTitle(title) }
+
// ---- animation carousel --------------------------------------------------------------------
private inner class StyleHolder(v: View) : RecyclerView.ViewHolder(v) {
@@ -1025,6 +1291,39 @@ class MainActivity : AppCompatActivity() {
buildSetup()
}
+ // ---- tap zone outline ---------------------------------------------------------------------
+
+ private fun updateTapZoneOutline() {
+ val v = tapZoneOutline ?: return
+ val onScreenOnTab = ::pager.isInitialized && pager.currentItem == 3
+ if (!onScreenOnTab) {
+ v.visibility = View.GONE
+ return
+ }
+ v.zoneRect = try { ScreenOnOverlay.tapZoneRect(this) } catch (_: Exception) { null }
+ v.visibility = if (v.zoneRect != null) View.VISIBLE else View.GONE
+ }
+
+ private inner class TapZoneOutlineView(context: android.content.Context) : View(context) {
+ private val strokePaint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply {
+ style = android.graphics.Paint.Style.STROKE
+ strokeWidth = 3f * resources.displayMetrics.density
+ color = context.getColor(R.color.accent)
+ }
+ private val fillPaint = android.graphics.Paint().apply {
+ style = android.graphics.Paint.Style.FILL
+ color = (context.getColor(R.color.accent) and 0x00FFFFFF) or 0x2A000000
+ }
+ var zoneRect: android.graphics.Rect? = null
+ set(value) { field = value; invalidate() }
+
+ override fun onDraw(c: android.graphics.Canvas) {
+ val r = zoneRect ?: return
+ c.drawRect(r, fillPaint)
+ c.drawRect(r, strokePaint)
+ }
+ }
+
// ---- test notification ---------------------------------------------------------------------
private var pillTucked = false
diff --git a/app/src/main/java/com/glowled/app/ui/ReplyActivity.kt b/app/src/main/java/com/glowled/app/ui/ReplyActivity.kt
index 92a4acd..d118b59 100644
--- a/app/src/main/java/com/glowled/app/ui/ReplyActivity.kt
+++ b/app/src/main/java/com/glowled/app/ui/ReplyActivity.kt
@@ -10,15 +10,18 @@ import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
+import android.view.HapticFeedbackConstants
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.FrameLayout
+import android.widget.HorizontalScrollView
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.LinearLayout
+import android.widget.ScrollView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
@@ -32,7 +35,7 @@ import com.glowled.app.core.NotificationStore
import com.glowled.app.view.AppInfoView
/**
- * Quick reply from the always-on screen: a small sheet with the last message and a text field.
+ * Quick reply from the always-on screen: a small sheet with message thread, quick responses, and a text field.
* The text goes to the app through its own notification "Reply" action, exactly like replying
* from the notification shade. On a locked phone Android asks to unlock first.
*/
@@ -97,15 +100,86 @@ class ReplyActivity : AppCompatActivity() {
ellipsize = TextUtils.TruncateAt.END
}, LinearLayout.LayoutParams(0, -2, 1f))
sheet.addView(head)
- if (!e.hidden && e.lines.isNotEmpty()) {
+
+ // Show recent context / conversation messages if available
+ val thread = NotificationStore.entriesFor(e.pkg).reversed()
+ if (thread.size > 1) {
+ val scrollBox = ScrollView(this).apply {
+ overScrollMode = View.OVER_SCROLL_IF_CONTENT_SCROLLS
+ }
+ val threadCol = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(dp(12), dp(8), dp(12), dp(8))
+ background = GradientDrawable().apply {
+ cornerRadius = 16f * resources.displayMetrics.density
+ setColor(getColor(R.color.surface_high))
+ }
+ }
+ for (item in thread) {
+ val itemText = item.lines.joinToString("\n")
+ if (itemText.isNotBlank()) {
+ val lineView = TextView(this).apply {
+ val sender = item.title?.let { "$it: " } ?: ""
+ text = "$sender$itemText"
+ setTextAppearance(com.google.android.material.R.style.TextAppearance_Material3_BodyMedium)
+ setTextColor(if (item.key == e.key) getColor(R.color.text_primary) else getColor(R.color.text_secondary))
+ }
+ threadCol.addView(lineView, LinearLayout.LayoutParams(-1, -2).apply {
+ topMargin = dp(4)
+ bottomMargin = dp(4)
+ })
+ }
+ }
+ scrollBox.addView(threadCol, LinearLayout.LayoutParams(-1, -2))
+ sheet.addView(scrollBox, LinearLayout.LayoutParams(-1, dp(120)).apply { topMargin = dp(10) })
+ } else if (!e.hidden && e.lines.isNotEmpty()) {
sheet.addView(TextView(this).apply {
- text = e.lines.takeLast(3).joinToString("\n")
+ text = e.lines.takeLast(5).joinToString("\n")
setTextAppearance(com.google.android.material.R.style.TextAppearance_Material3_BodyMedium)
setTextColor(getColor(R.color.text_secondary))
- maxLines = 3
+ maxLines = 5
ellipsize = TextUtils.TruncateAt.END
}, LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(10) })
}
+
+ // Quick replies chips
+ val quickReplies = listOf(
+ "👍", "👌", "❤️",
+ getString(R.string.quick_reply_ok),
+ getString(R.string.quick_reply_thanks),
+ getString(R.string.quick_reply_on_my_way),
+ getString(R.string.quick_reply_later),
+ )
+ val chipsScroll = HorizontalScrollView(this).apply {
+ isHorizontalScrollBarEnabled = false
+ overScrollMode = View.OVER_SCROLL_NEVER
+ }
+ val chipsRow = LinearLayout(this).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ }
+ for (replyStr in quickReplies) {
+ val chip = TextView(this).apply {
+ text = replyStr
+ textSize = 13f
+ setTextColor(getColor(R.color.text_primary))
+ setPadding(dp(12), dp(6), dp(12), dp(6))
+ background = GradientDrawable().apply {
+ cornerRadius = 16f * resources.displayMetrics.density
+ setColor(getColor(R.color.surface_high))
+ }
+ isClickable = true
+ setOnClickListener {
+ input.setText(replyStr)
+ input.setSelection(replyStr.length)
+ focusInput()
+ }
+ }
+ chipsRow.addView(chip, LinearLayout.LayoutParams(-2, -2).apply { marginEnd = dp(6) })
+ }
+ chipsScroll.addView(chipsRow, LinearLayout.LayoutParams(-2, -2))
+ sheet.addView(chipsScroll, LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(10) })
+
val row = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
@@ -139,7 +213,7 @@ class ReplyActivity : AppCompatActivity() {
}
setOnClickListener { send() }
}, LinearLayout.LayoutParams(dp(48), dp(48)).apply { marginStart = dp(10) })
- sheet.addView(row, LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(14) })
+ sheet.addView(row, LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(12) })
root.addView(sheet, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM))
// Edge-to-edge: keep the sheet above the keyboard and the navigation bar.
@@ -168,6 +242,7 @@ class ReplyActivity : AppCompatActivity() {
val action = e.replyAction ?: return finish()
val text = input.text.toString().trim()
if (text.isEmpty()) return
+ window.decorView.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
val inputs = action.remoteInputs ?: return finish()
val results = Bundle()
inputs.filter { it.allowFreeFormInput }.forEach { results.putCharSequence(it.resultKey, text) }
diff --git a/app/src/main/java/com/glowled/app/ui/RowIcons.kt b/app/src/main/java/com/glowled/app/ui/RowIcons.kt
index d133b9f..362c53f 100644
--- a/app/src/main/java/com/glowled/app/ui/RowIcons.kt
+++ b/app/src/main/java/com/glowled/app/ui/RowIcons.kt
@@ -34,6 +34,7 @@ object RowIcons {
"app_info_always" to (R.drawable.ic_s_pin to CYAN),
"droplet" to (R.drawable.ic_s_drop to TEAL),
"show_content" to (R.drawable.ic_s_eye to ORANGE),
+ "peek_expandable" to (R.drawable.ic_s_badge to BLUE),
"peek_actions" to (R.drawable.ic_s_reply to GREEN),
"double_tap_wake" to (R.drawable.ic_s_tap to PURPLE),
"proximity" to (R.drawable.ic_s_phone to BROWN),
@@ -46,17 +47,30 @@ object RowIcons {
"overlay_enabled" to (R.drawable.ic_s_ring to BLUE),
"overlay_lock_only" to (R.drawable.ic_s_lock to DARK_GREY),
"charge_led" to (R.drawable.ic_s_bolt to GREEN),
+ "charge_screen_on" to (R.drawable.ic_s_ring to GREEN),
+ "charge_timeout_aod" to (R.drawable.ic_s_clock to BLUE),
+ "charge_timeout_on" to (R.drawable.ic_s_timer to TEAL),
+ "charge_show_percent" to (R.drawable.ic_s_battery to GREEN),
+ "charge_show_voltage" to (R.drawable.ic_s_bolt to ORANGE),
+ "charge_show_current" to (R.drawable.ic_s_gauge to CYAN),
+ "charge_show_power" to (R.drawable.ic_s_sun to RED),
"battery_indicator" to (R.drawable.ic_s_battery to GREY),
"progress_led" to (R.drawable.ic_s_download to BLUE),
"progress_initials" to (R.drawable.ic_s_updown to BLUE),
"progress_app_color" to (R.drawable.ic_s_drop to PINK),
"progress_color" to (R.drawable.ic_s_palette to PURPLE),
+ "cpu_indicator" to (R.drawable.ic_s_gauge to ORANGE),
+ "cpu_show_label" to (R.drawable.ic_s_badge to BLUE),
+ "cpu_pos" to (R.drawable.ic_s_ring to CYAN),
+ "cpu_font_size" to (R.drawable.ic_s_theme to TEAL),
// Alerts
"app_mode" to (R.drawable.ic_s_filter to BLUE),
"ignore_low" to (R.drawable.ic_s_mute to GREY),
+ "ignore_silent" to (R.drawable.ic_s_mute to GREY),
"respect_dnd" to (R.drawable.ic_s_moon to INDIGO),
"clear_on_unlock" to (R.drawable.ic_s_unlock to GREEN),
// Battery
+ "snooze" to (R.drawable.ic_s_moon to PURPLE),
"eco_anim" to (R.drawable.ic_s_leaf to GREEN),
"age_fade" to (R.drawable.ic_s_clock to ORANGE),
"motion_glance" to (R.drawable.ic_s_motion to PURPLE),
diff --git a/app/src/main/java/com/glowled/app/util/HealthCheck.kt b/app/src/main/java/com/glowled/app/util/HealthCheck.kt
new file mode 100644
index 0000000..eb99505
--- /dev/null
+++ b/app/src/main/java/com/glowled/app/util/HealthCheck.kt
@@ -0,0 +1,165 @@
+package com.glowled.app.util
+
+import android.Manifest
+import android.app.NotificationManager
+import android.content.Context
+import android.content.pm.PackageManager
+import android.os.Build
+import android.os.PowerManager
+import android.provider.Settings
+import androidx.core.content.ContextCompat
+import com.glowled.app.core.BatteryStats
+import com.glowled.app.core.DebugLog
+import com.glowled.app.core.LedController
+import com.glowled.app.service.LedAccessibilityService
+import com.glowled.app.service.NotifyListenerService
+
+data class HealthItem(
+ val title: String,
+ val isOk: Boolean,
+ val detail: String,
+ val fixAction: ((Context) -> Unit)? = null,
+)
+
+object HealthCheck {
+
+ fun runAll(context: Context): List {
+ val list = mutableListOf()
+
+ // 1. Notification Listener
+ val notifAccess = NotifyListenerService.isEnabled(context)
+ val notifConnected = NotifyListenerService.instance != null
+ list.add(HealthItem(
+ title = "Notification Access",
+ isOk = notifAccess && notifConnected,
+ detail = when {
+ !notifAccess -> "Permission not granted"
+ !notifConnected -> "Granted but disconnected by system"
+ else -> "Active and connected"
+ },
+ fixAction = { c ->
+ try {
+ c.startActivity(android.content.Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
+ } catch (_: Exception) {}
+ }
+ ))
+
+ // 2. Display over other apps (SYSTEM_ALERT_WINDOW)
+ val canDraw = Settings.canDrawOverlays(context)
+ list.add(HealthItem(
+ title = "Display over other apps",
+ isOk = canDraw,
+ detail = if (canDraw) "Granted" else "Required for screen-on indicator and overlay",
+ fixAction = { c ->
+ try {
+ c.startActivity(android.content.Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, android.net.Uri.parse("package:${c.packageName}")).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
+ } catch (_: Exception) {}
+ }
+ ))
+
+ // 3. Battery optimization
+ val pm = context.getSystemService(PowerManager::class.java)
+ val ignoringBattery = pm?.isIgnoringBatteryOptimizations(context.packageName) == true
+ list.add(HealthItem(
+ title = "Battery optimization",
+ isOk = ignoringBattery,
+ detail = if (ignoringBattery) "Unrestricted" else "System may kill background services",
+ fixAction = { c ->
+ try {
+ c.startActivity(android.content.Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
+ } catch (_: Exception) {}
+ }
+ ))
+
+ // 4. Accessibility service
+ val a11y = LedAccessibilityService.instance != null
+ list.add(HealthItem(
+ title = "Accessibility service",
+ isOk = a11y,
+ detail = if (a11y) "Active (prevents screen flashes on lock screen)" else "Optional but recommended for Xiaomi/OLED",
+ fixAction = { c ->
+ try {
+ c.startActivity(android.content.Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
+ } catch (_: Exception) {}
+ }
+ ))
+
+ // 5. Post notifications (Android 13+)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ val postNotifs = ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
+ list.add(HealthItem(
+ title = "Post notifications",
+ isOk = postNotifs,
+ detail = if (postNotifs) "Granted" else "Needed for update alerts",
+ fixAction = null
+ ))
+ }
+
+ // 6. Full screen intents (Android 14+)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
+ val nm = context.getSystemService(NotificationManager::class.java)
+ val canFsi = nm?.canUseFullScreenIntent() == true
+ list.add(HealthItem(
+ title = "Full-screen alerts",
+ isOk = canFsi,
+ detail = if (canFsi) "Allowed" else "Needed to wake screen for lock-screen AOD window",
+ fixAction = { c ->
+ try {
+ c.startActivity(android.content.Intent(Settings.ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT, android.net.Uri.parse("package:${c.packageName}")).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
+ } catch (_: Exception) {}
+ }
+ ))
+ }
+
+ // 7. Lock-screen window blocked state
+ val blocked = LedController.prefs.deviceSp.getBoolean(LedController.PREF_WINDOW_BLOCKED, false)
+ list.add(HealthItem(
+ title = "Lock-screen window status",
+ isOk = !blocked,
+ detail = if (blocked) "Blocked by system (using Accessibility overlay fallback)" else "Operational",
+ fixAction = { _ ->
+ LedController.prefs.deviceSp.edit().remove(LedController.PREF_WINDOW_BLOCKED).apply()
+ }
+ ))
+
+ return list
+ }
+
+ /**
+ * Generates a clean diagnostic text report excluding any personal data or notification content.
+ */
+ fun generateReport(context: Context): String {
+ val b = StringBuilder()
+ b.appendLine("=== Glow LED Diagnostics ===")
+ b.appendLine("App Version: ${com.glowled.app.BuildConfig.VERSION_NAME} (${com.glowled.app.BuildConfig.VERSION_CODE})")
+ b.appendLine("Device: ${Build.MANUFACTURER} ${Build.MODEL} (${Build.DEVICE})")
+ b.appendLine("Android: ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})")
+ b.appendLine("Fingerprint: ${Build.FINGERPRINT}")
+ b.appendLine("OEM Xiaomi/HyperOS: ${OemHelper.isXiaomi}")
+ b.appendLine()
+ b.appendLine("--- Health Checks ---")
+ runAll(context).forEach {
+ b.appendLine("[${if (it.isOk) "PASS" else "WARN"}] ${it.title}: ${it.detail}")
+ }
+ b.appendLine()
+ b.appendLine("--- Battery Info ---")
+ try {
+ val bi = BatteryStats.getInfo(context)
+ b.appendLine("Level: ${bi.level}%, Voltage: ${bi.voltageMv} mV, Current: ${bi.currentMa} mA, Charging: ${bi.isCharging}")
+ } catch (e: Exception) {
+ b.appendLine("BatteryStats error: ${e.message}")
+ }
+ b.appendLine()
+ b.appendLine("--- AOD Telemetry (Last 24h) ---")
+ try {
+ val aod = BatteryStats.getAodTelemetry(context)
+ b.appendLine("AOD Wakeups: ${aod.sessionCount}, Animated: ${aod.animDurationMs / 1000}s, Static: ${aod.staticDurationMs / 1000}s")
+ } catch (e: Exception) {
+ b.appendLine("AodTelemetry error: ${e.message}")
+ }
+ b.appendLine()
+ b.appendLine("--- Event Log (Sanitized) ---")
+ b.appendLine(DebugLog.text())
+ return b.toString()
+ }
+}
diff --git a/app/src/main/java/com/glowled/app/util/SettingsBackup.kt b/app/src/main/java/com/glowled/app/util/SettingsBackup.kt
index 6ccca54..05ae3ce 100644
--- a/app/src/main/java/com/glowled/app/util/SettingsBackup.kt
+++ b/app/src/main/java/com/glowled/app/util/SettingsBackup.kt
@@ -12,15 +12,18 @@ import org.json.JSONObject
object SettingsBackup {
// Device-specific runtime state that shouldn't travel to a new install.
- private val skip = setOf(
+ val skip = setOf(
"aod_window_blocked", "transfer_apps",
"update_latest", "update_notes", "update_checked", "update_notified",
)
- fun write(context: Context, sp: SharedPreferences, uri: Uri): Boolean = try {
+ fun serialize(sp: SharedPreferences, appVersion: String = "2.11.0"): JSONObject {
val json = JSONObject()
json.put("_app", "glowled")
- json.put("_version", 1)
+ json.put("_version", 2)
+ json.put("schemaVersion", 2)
+ json.put("appVersion", appVersion)
+ json.put("exportedAt", System.currentTimeMillis())
val values = JSONObject()
sp.all.forEach { (k, v) ->
if (k in skip || v == null) return@forEach
@@ -35,6 +38,11 @@ object SettingsBackup {
values.put(k, JSONObject().put("t", t).put("v", v))
}
json.put("prefs", values)
+ return json
+ }
+
+ fun write(context: Context, sp: SharedPreferences, uri: Uri): Boolean = try {
+ val json = serialize(sp)
context.contentResolver.openOutputStream(uri, "wt")?.use { it.write(json.toString(2).toByteArray()) }
true
} catch (_: Exception) {
@@ -44,29 +52,117 @@ object SettingsBackup {
/** Returns the number of settings restored, or -1 if the file isn't a Glow LED backup. */
fun read(context: Context, sp: SharedPreferences, uri: Uri): Int = try {
val text = context.contentResolver.openInputStream(uri)?.use { it.readBytes().decodeToString() } ?: ""
- val json = JSONObject(text)
- if (json.optString("_app") == "glowled") restore(sp, json.getJSONObject("prefs")) else -1
+ restoreFromJson(sp, text)
} catch (_: Exception) {
-1
}
- private fun restore(sp: SharedPreferences, values: JSONObject): Int {
+ data class BackupSummary(
+ val schemaVersion: Int,
+ val appVersion: String,
+ val exportedAt: Long,
+ val validSettingsCount: Int,
+ val appRulesCount: Int,
+ val skippedKeysCount: Int,
+ val isValid: Boolean,
+ )
+
+ fun inspect(text: String): BackupSummary {
+ if (text.isBlank()) return BackupSummary(0, "", 0L, 0, 0, 0, false)
+ return try {
+ val json = JSONObject(text)
+ inspect(json)
+ } catch (_: Exception) {
+ BackupSummary(0, "", 0L, 0, 0, 0, false)
+ }
+ }
+
+ fun inspect(json: JSONObject): BackupSummary {
+ if (json.optString("_app") != "glowled") {
+ return BackupSummary(0, "", 0L, 0, 0, 0, false)
+ }
+ val schemaVer = if (json.has("schemaVersion")) json.getInt("schemaVersion") else json.optInt("_version", 1)
+ val appVer = json.optString("appVersion", "unknown")
+ val exportedAt = json.optLong("exportedAt", 0L)
+ val prefsObj = json.optJSONObject("prefs") ?: JSONObject()
+
+ var validSettings = 0
+ var appRules = 0
+ var skipped = 0
+
+ prefsObj.keys().forEach { k ->
+ if (k in skip) {
+ skipped++
+ } else {
+ val o = prefsObj.optJSONObject(k)
+ if (o != null && o.has("v")) {
+ validSettings++
+ if (k.startsWith("app_") || k.startsWith("color_")) {
+ appRules++
+ }
+ } else {
+ skipped++
+ }
+ }
+ }
+
+ return BackupSummary(
+ schemaVersion = schemaVer,
+ appVersion = appVer,
+ exportedAt = exportedAt,
+ validSettingsCount = validSettings,
+ appRulesCount = appRules,
+ skippedKeysCount = skipped,
+ isValid = true,
+ )
+ }
+
+ fun migrate(json: JSONObject, fromVersion: Int): JSONObject {
+ if (fromVersion < 2) {
+ json.put("schemaVersion", 2)
+ }
+ return json
+ }
+
+ fun restoreFromJson(sp: SharedPreferences, text: String): Int = try {
+ if (text.isBlank()) -1
+ else {
+ val json = JSONObject(text)
+ if (json.optString("_app") == "glowled") {
+ val version = if (json.has("schemaVersion")) json.getInt("schemaVersion") else json.optInt("_version", 1)
+ val migrated = if (version < 2) migrate(json, version) else json
+ val prefsObj = migrated.optJSONObject("prefs") ?: JSONObject()
+ restore(sp, prefsObj)
+ } else -1
+ }
+ } catch (_: Exception) {
+ -1
+ }
+
+ fun restore(sp: SharedPreferences, values: JSONObject): Int {
val e = sp.edit()
var n = 0
values.keys().forEach { k ->
if (k in skip) return@forEach
- val o = values.getJSONObject(k)
- when (o.getString("t")) {
- "b" -> e.putBoolean(k, o.getBoolean("v"))
- "i" -> e.putInt(k, o.getInt("v"))
- "l" -> e.putLong(k, o.getLong("v"))
- "f" -> e.putFloat(k, o.getDouble("v").toFloat())
- "s" -> e.putString(k, o.getString("v"))
- else -> return@forEach
+ val o = values.optJSONObject(k) ?: return@forEach
+ val t = o.optString("t")
+ if (!o.has("v")) return@forEach
+ try {
+ when (t) {
+ "b" -> e.putBoolean(k, o.getBoolean("v"))
+ "i" -> e.putInt(k, o.getInt("v"))
+ "l" -> e.putLong(k, o.getLong("v"))
+ "f" -> e.putFloat(k, o.getDouble("v").toFloat())
+ "s" -> e.putString(k, o.getString("v"))
+ else -> return@forEach
+ }
+ n++
+ } catch (_: Exception) {
+ // Ignore individual malformed entry without failing the whole restore
}
- n++
}
e.apply()
return n
}
}
+
diff --git a/app/src/main/java/com/glowled/app/view/AppInfoView.kt b/app/src/main/java/com/glowled/app/view/AppInfoView.kt
index 895c847..04bc96b 100644
--- a/app/src/main/java/com/glowled/app/view/AppInfoView.kt
+++ b/app/src/main/java/com/glowled/app/view/AppInfoView.kt
@@ -32,6 +32,10 @@ class AppInfoView(context: Context) : LinearLayout(context) {
/** AOD-style monochrome glyphs instead of full-colour app icons (set before [bind]). */
var monochrome = true
+ /** Icon diameter in dp. */
+ var iconDp: Int = 36
+ set(v) { field = v.coerceIn(24, 72) }
+
private val d = resources.displayMetrics.density
private fun dp(v: Float) = (v * d).toInt()
private val icons = LinearLayout(context).apply {
@@ -54,7 +58,7 @@ class AppInfoView(context: Context) : LinearLayout(context) {
}
/** Vertical centre of the icon row, relative to this view (where the droplet should land). */
- fun iconCenterY(): Float = icons.top + dp(ICON_DP / 2f).toFloat()
+ fun iconCenterY(): Float = icons.top + dp(iconDp / 2f).toFloat()
/** Horizontal centre of the newest app's icon, relative to this view. */
fun newestCenterX(): Float {
@@ -72,7 +76,7 @@ class AppInfoView(context: Context) : LinearLayout(context) {
centreOut(shownApps).forEachIndexed { i, app ->
val chip = iconChip(pm, app)
chips[app.pkg] = chip
- icons.addView(chip, LayoutParams(dp(ICON_DP), dp(ICON_DP)).apply { if (i > 0) marginStart = dp(16f) })
+ icons.addView(chip, LayoutParams(dp(iconDp.toFloat()), dp(iconDp.toFloat())).apply { if (i > 0) marginStart = dp(16f) })
}
if (selected != null && shownApps.none { it.pkg == selected }) selected = null
applySelection()
@@ -216,7 +220,6 @@ class AppInfoView(context: Context) : LinearLayout(context) {
companion object {
private const val MAX_ICONS = 5
- private const val ICON_DP = 36f
private const val GLYPH_PAD_DP = 7f
private const val MONO_GREY = 0xFFB4B4B4.toInt()
private val GREYSCALE = ColorMatrixColorFilter(
diff --git a/app/src/main/java/com/glowled/app/view/LedView.kt b/app/src/main/java/com/glowled/app/view/LedView.kt
index 334423c..a5ab39e 100644
--- a/app/src/main/java/com/glowled/app/view/LedView.kt
+++ b/app/src/main/java/com/glowled/app/view/LedView.kt
@@ -20,6 +20,7 @@ import com.glowled.app.core.LedStyle
import com.glowled.app.core.MeterIcon
import com.glowled.app.core.MultiMode
import com.glowled.app.core.Prefs
+import com.glowled.app.view.renderer.*
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.max
@@ -39,7 +40,7 @@ import kotlin.math.sin
class LedView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
-) : View(context, attrs) {
+) : View(context, attrs), LedRenderContext {
private val density = resources.displayMetrics.density
@@ -47,7 +48,8 @@ class LedView @JvmOverloads constructor(
var style = LedStyle.PULSE
private set
private var multiMode = MultiMode.CYCLE
- private var colors = intArrayOf(Prefs.DEFAULT_COLOR)
+ private var _colors = intArrayOf(Prefs.DEFAULT_COLOR)
+ override val colors: IntArray get() = _colors
private var geometry: Geometry? = null
private var thickness = 3 * density
private var gap = 2 * density
@@ -59,6 +61,20 @@ class LedView @JvmOverloads constructor(
private var rotateRing = true
private var cornerRadius = 40 * density
+ private val styleRenderers: Map = mapOf(
+ LedStyle.STATIC to StaticStyleRenderer(),
+ LedStyle.BREATHE to BreatheStyleRenderer(),
+ LedStyle.EDGE_PULSE to EdgePulseStyleRenderer(),
+ LedStyle.BLINK to BlinkStyleRenderer(),
+ LedStyle.HEARTBEAT to HeartbeatStyleRenderer(),
+ LedStyle.PULSE to PulseStyleRenderer(),
+ LedStyle.SPIN to SpinStyleRenderer(),
+ LedStyle.EDGE to EdgeStyleRenderer(),
+ LedStyle.RAINBOW to RainbowStyleRenderer(),
+ LedStyle.ORBIT to OrbitStyleRenderer(),
+ LedStyle.SPARKLE to SparkleStyleRenderer(),
+ )
+
/**
* When true (overlay / AOD) the geometry is in absolute screen pixels. When false (in-app
* previews) it is relative to this view, so scrolling or collapsing headers never shift it.
@@ -87,8 +103,8 @@ class LedView @JvmOverloads constructor(
private var sweep: SweepGradient? = null
private val loc = IntArray(2)
private val screen = Point()
- private var cx = 0f
- private var cy = 0f
+ override var cx = 0f
+ override var cy = 0f
private var startTime = SystemClock.uptimeMillis()
private var dirty = true
@@ -122,7 +138,7 @@ class LedView @JvmOverloads constructor(
}
fun setColors(c: IntArray) {
- colors = if (c.isEmpty()) intArrayOf(Prefs.DEFAULT_COLOR) else c
+ _colors = if (c.isEmpty()) intArrayOf(Prefs.DEFAULT_COLOR) else c
invalidate()
}
@@ -145,6 +161,15 @@ class LedView @JvmOverloads constructor(
textSize = 10 * resources.displayMetrics.scaledDensity
typeface = android.graphics.Typeface.DEFAULT_BOLD
}
+ private var cpuLabel: String? = null
+ private var cpuPos: String = "below"
+ private var cpuOffsetXPx: Float = 0f
+ private var cpuOffsetYPx: Float = 0f
+ private val cpuPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ textAlign = Paint.Align.CENTER
+ textSize = 12 * resources.displayMetrics.scaledDensity
+ typeface = android.graphics.Typeface.DEFAULT_BOLD
+ }
private var meterColor = 0
private var meterStart = 0L
/** Where on the outline its top-centre point is (0..1), so the gauge fills from 12 o'clock. */
@@ -170,27 +195,98 @@ class LedView @JvmOverloads constructor(
invalidate()
}
- fun setBattery(percent: Int?) {
- val text = percent?.coerceIn(0, 100)?.let { "$it%" }
+ fun setBatteryText(text: String?) {
if (batteryLabel == text) return
batteryLabel = text
invalidate()
}
- private val indicatorLineHeight get() = max(16 * density, labelPaint.fontSpacing + 2 * density)
+ fun setBattery(percent: Int?) {
+ setBatteryText(percent?.coerceIn(0, 100)?.let { "$it%" })
+ }
+
+ fun setCpuLoad(text: String?, pos: String = "below", offsetXDp: Int = 0, offsetYDp: Int = 0, fontSizeSp: Int = 12) {
+ val targetSize = fontSizeSp * resources.displayMetrics.scaledDensity
+ val targetX = offsetXDp * density
+ val targetY = offsetYDp * density
+ if (cpuLabel == text && cpuPos == pos && cpuOffsetXPx == targetX && cpuOffsetYPx == targetY && cpuPaint.textSize == targetSize) return
+ cpuLabel = text
+ cpuPos = pos
+ cpuOffsetXPx = targetX
+ cpuOffsetYPx = targetY
+ cpuPaint.textSize = targetSize
+ dirty = true
+ invalidate()
+ }
+
+ private val lineSpacing get() = max(14 * density, labelPaint.fontSpacing + 2 * density)
- /** Leave space for the battery % without overlapping notification icons. */
- fun indicatorBottom(): Float = ringBottom() + (if (batteryLabel != null) indicatorLineHeight else 0f)
+ /** Leave space for the battery stats without overlapping notification icons. */
+ fun indicatorBottom(): Float {
+ var bottom = ringBottom()
+ batteryLabel?.let { label ->
+ val count = label.count { it == '\n' } + 1
+ bottom += count * lineSpacing + 2 * density
+ }
+ if (cpuLabel != null && cpuPos == "below") {
+ bottom += max(14 * density, cpuPaint.fontSpacing + 2 * density) + max(0f, cpuOffsetYPx)
+ }
+ return bottom
+ }
private fun drawLabels(c: Canvas) {
- val y = ringBottom() - (geometry?.cy ?: cy) + cy + indicatorLineHeight - labelPaint.descent()
- batteryLabel?.let {
- labelPaint.color = Color.WHITE
- labelPaint.alpha = (220 * alphaMul * intro).toInt()
- c.drawText(it, cx, y, labelPaint)
+ val label = batteryLabel ?: return
+ val lines = label.split("\n")
+ labelPaint.color = Color.WHITE
+ labelPaint.alpha = (220 * alphaMul * intro).toInt()
+ val spacing = lineSpacing
+ var y = ringBottom() + spacing - labelPaint.descent()
+ for (line in lines) {
+ c.drawText(line, cx, y, labelPaint)
+ y += spacing
}
}
+ private fun drawCpuLabel(c: Canvas) {
+ val text = cpuLabel ?: return
+ if (intro <= 0f || alphaMul <= 0f) return
+ cpuPaint.color = Color.WHITE
+ cpuPaint.alpha = (220 * alphaMul * intro).toInt().coerceIn(0, 255)
+ val r = ringRadius()
+ val glow = glowRadius()
+ val spacing = max(14 * density, cpuPaint.fontSpacing + 2 * density)
+
+ val tx: Float
+ val ty: Float
+ when (cpuPos) {
+ "right" -> {
+ cpuPaint.textAlign = Paint.Align.LEFT
+ tx = cx + r + glow + 6 * density + cpuOffsetXPx
+ ty = cy + (cpuPaint.textSize / 3f) + cpuOffsetYPx
+ }
+ "left" -> {
+ cpuPaint.textAlign = Paint.Align.RIGHT
+ tx = cx - r - glow - 6 * density + cpuOffsetXPx
+ ty = cy + (cpuPaint.textSize / 3f) + cpuOffsetYPx
+ }
+ "above" -> {
+ cpuPaint.textAlign = Paint.Align.CENTER
+ tx = cx + cpuOffsetXPx
+ ty = cy - r - glow - 6 * density - cpuPaint.descent() + cpuOffsetYPx
+ }
+ else -> { // "below"
+ cpuPaint.textAlign = Paint.Align.CENTER
+ tx = cx + cpuOffsetXPx
+ val base = if (batteryLabel != null) {
+ val count = batteryLabel!!.count { it == '\n' } + 1
+ ringBottom() + count * lineSpacing + 2 * density
+ } else ringBottom()
+ ty = base + spacing - cpuPaint.descent() + cpuOffsetYPx
+ }
+ }
+ c.drawText(text, tx, ty, cpuPaint)
+ }
+
private fun findTopFraction(): Float {
if (pathLength <= 0f) return 0f
var best = Float.MAX_VALUE
@@ -328,11 +424,11 @@ class LedView @JvmOverloads constructor(
private fun glowRadius() = if (glow) thickness * 1.6f + 3 * density else 0f
- /** Lowest point of the drawn ring, in the geometry's coordinates (to place content under it). */
+ /** Lowest point of the drawn ring, in view-local coordinates (to place content under it). */
fun ringBottom(): Float {
val g = geometry ?: return 0f
val r = if (g.shape == CutoutShape.DOT) max(g.w, g.h) / 2f else g.h / 2f + gap + thickness
- return g.cy + r + glowRadius()
+ return cy + r + glowRadius()
}
// ---- droplet: liquid drop that stretches out of the camera, detaches, falls and splashes ------
@@ -346,6 +442,8 @@ class LedView @JvmOverloads constructor(
private var dropTargetY = 0f
private var dropTargetX = Float.NaN // NaN = straight below the camera
private var dropRetract = false
+ /** Droplet radius in dp. */
+ var dropletRadiusDp: Float = 10f
/**
* Plays the droplet in [color] from the bottom of the ring down to [targetY] (view coordinates).
@@ -411,8 +509,7 @@ class LedView @JvmOverloads constructor(
val x = cx
val top = cy + ringR // bottom edge of the ring: where the liquid comes out
val dist = max(dropTargetY - top, ringR * 2f)
- // Big enough to read as a drop on a real phone (~5-7 dp radius).
- val rb = max(max(thickness * 2.2f, ringR * 0.45f), 5f * density)
+ val rb = max(dropletRadiusDp * density, thickness * 1.8f)
dropPaint.color = dropColor
if (glow) dropPaint.setShadowLayer(glowRadius(), 0f, 0f, dropColor) else dropPaint.clearShadowLayer()
@@ -570,7 +667,7 @@ class LedView @JvmOverloads constructor(
}
}
- private val isFilled get() = geometry?.shape == CutoutShape.DOT && !style.isEdge
+ override val isFilled get() = geometry?.shape == CutoutShape.DOT && !style.isEdge
override fun onDraw(canvas: Canvas) {
if (dirty) rebuild()
@@ -600,30 +697,14 @@ class LedView @JvmOverloads constructor(
}
}
- if (meterFrac >= 0f) drawMeter(canvas, now) else if (notificationRingVisible) when (style) {
- LedStyle.STATIC -> ring(canvas, color, 1f, segmented, rot)
- LedStyle.BREATHE -> ring(canvas, color, 0.12f + 0.88f * wave(p), segmented, rot)
- LedStyle.EDGE_PULSE -> ring(canvas, color, 0.1f + 0.9f * wave(p), segmented, rot)
- LedStyle.BLINK -> if (p < BLINK_ON) ring(canvas, color, 1f, segmented, rot)
- LedStyle.HEARTBEAT -> ring(canvas, color, 0.08f + 0.92f * heartbeat(p), segmented, rot)
- LedStyle.PULSE -> {
- ring(canvas, color, 0.55f + 0.45f * (1f - wave(p)), segmented, rot)
- ripple(canvas, color, p)
- }
- LedStyle.SPIN -> spin(canvas, p, segmented, color, tail = 0.38f, comets = 1, base = 0.16f)
- LedStyle.EDGE -> spin(canvas, p, segmented, color, tail = 0.16f, comets = 2, base = 0.06f)
- LedStyle.RAINBOW -> rainbow(canvas, p)
- LedStyle.ORBIT -> spin(canvas, p, segmented, color, tail = 0.22f, comets = 2, base = 0.08f)
- LedStyle.SPARKLE -> {
- for (i in 0 until 6) {
- val a = 0.12f + 0.88f * wave((p + i / 6f) % 1f).pow(4)
- val start = i / 6f + p * 0.1f
- segment(canvas, start, start + 0.075f, paintFor(colors[i % n], a, false))
- }
- }
+ if (meterFrac >= 0f) {
+ drawMeter(canvas, now)
+ } else if (notificationRingVisible) {
+ styleRenderers[style]?.render(canvas, p, color, segmented, rot, this)
}
drawLabels(canvas)
+ drawCpuLabel(canvas)
if (transformed) canvas.restore()
if (dropT >= 0f && !style.isEdge) {
if (shiftX != 0f || shiftY != 0f) {
@@ -637,19 +718,7 @@ class LedView @JvmOverloads constructor(
private fun Long.scaled() = max(1500L, (this * periodScale).toLong())
- private fun basePeriod(): Long = when (style) {
- LedStyle.STATIC -> 2500
- LedStyle.BREATHE -> 3200
- LedStyle.PULSE -> 2000
- LedStyle.BLINK -> 2400
- LedStyle.HEARTBEAT -> 1700
- LedStyle.SPIN -> 1500
- LedStyle.RAINBOW -> 3000
- LedStyle.EDGE -> 3200
- LedStyle.EDGE_PULSE -> 3000
- LedStyle.ORBIT -> 2400
- LedStyle.SPARKLE -> 3600
- }
+ private fun basePeriod(): Long = styleRenderers[style]?.basePeriodMs ?: 2000L
private fun scheduleNext(period: Long, inPeriod: Long, n: Int, segmented: Boolean) {
if (!isShown || windowVisibility != VISIBLE) return
@@ -686,7 +755,7 @@ class LedView @JvmOverloads constructor(
return paint
}
- private fun ring(c: Canvas, color: Int, a: Float, segmented: Boolean, rotation: Float) {
+ override fun ring(c: Canvas, color: Int, a: Float, segmented: Boolean, rotation: Float) {
if (a <= 0.01f) return
if (!segmented) {
c.drawPath(shapePath, paintFor(color, a, isFilled))
@@ -710,7 +779,7 @@ class LedView @JvmOverloads constructor(
}
}
- private fun ripple(c: Canvas, color: Int, p: Float) {
+ override fun ripple(c: Canvas, color: Int, p: Float) {
val travel = thickness * 2f + 10 * density
ripplePath.reset()
buildShape(ripplePath, travel * p)
@@ -718,7 +787,7 @@ class LedView @JvmOverloads constructor(
c.drawPath(ripplePath, paintFor(color, a, false))
}
- private fun spin(c: Canvas, p: Float, segmented: Boolean, color: Int, tail: Float, comets: Int, base: Float) {
+ override fun spin(c: Canvas, p: Float, segmented: Boolean, color: Int, tail: Float, comets: Int, base: Float) {
val n = if (segmented) colors.size else comets
if (base > 0f) {
c.drawPath(shapePath, paintFor(colors[0], base, false).also { it.clearShadowLayer() })
@@ -738,7 +807,7 @@ class LedView @JvmOverloads constructor(
}
}
- private fun rainbow(c: Canvas, p: Float) {
+ override fun rainbow(c: Canvas, p: Float) {
val s = sweep ?: return
shaderMatrix.setRotate(p * 360f, cx, cy)
s.setLocalMatrix(shaderMatrix)
@@ -752,6 +821,10 @@ class LedView @JvmOverloads constructor(
paint.shader = null
}
+ override fun drawSegment(c: Canvas, from: Float, to: Float, color: Int, a: Float) {
+ segment(c, from, to, paintFor(color, a, false))
+ }
+
/** Draws the part of the shape between path fractions [from]..[to] (wraps around). */
private fun segment(c: Canvas, from: Float, to: Float, paint: Paint) {
val a = from - kotlin.math.floor(from)
@@ -768,13 +841,6 @@ class LedView @JvmOverloads constructor(
c.drawPath(segPath, paint)
}
- private fun wave(p: Float) = (0.5f - 0.5f * cos(2f * PI.toFloat() * p))
-
- private fun heartbeat(p: Float): Float {
- fun bump(s: Float, e: Float) = if (p in s..e) sin(PI.toFloat() * (p - s) / (e - s)) else 0f
- return max(bump(0f, 0.14f), bump(0.22f, 0.38f) * 0.8f)
- }
-
override fun onVisibilityChanged(changedView: View, visibility: Int) {
super.onVisibilityChanged(changedView, visibility)
if (visibility == VISIBLE) invalidate()
diff --git a/app/src/main/java/com/glowled/app/view/NotificationPeekView.kt b/app/src/main/java/com/glowled/app/view/NotificationPeekView.kt
index ac98872..f17a12d 100644
--- a/app/src/main/java/com/glowled/app/view/NotificationPeekView.kt
+++ b/app/src/main/java/com/glowled/app/view/NotificationPeekView.kt
@@ -1,5 +1,6 @@
package com.glowled.app.view
+import android.animation.LayoutTransition
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
@@ -7,12 +8,16 @@ import android.graphics.Typeface
import android.graphics.drawable.GradientDrawable
import android.text.TextUtils
import android.text.format.DateUtils
+import android.transition.AutoTransition
+import android.transition.TransitionManager
import android.view.Gravity
import android.view.View
+import android.view.ViewGroup
import android.view.animation.DecelerateInterpolator
import android.view.animation.OvershootInterpolator
import android.widget.ImageView
import android.widget.LinearLayout
+import android.widget.ScrollView
import android.widget.TextView
import com.glowled.app.R
import com.glowled.app.core.NotificationContent
@@ -20,29 +25,36 @@ import com.glowled.app.core.NotificationStore
/**
* Samsung AOD-style notification peek under the app icons: pitch black (no box, so AMOLED pixels
- * stay off), soft dimmed text, everything left-aligned on one edge like a notification:
+ * stay off), soft dimmed text, everything left-aligned on one edge like a notification.
*
- * [icon] WhatsApp · 2 min
- * Ana
- * See you at 8?
- * [📷 Photo] +2 more
- * [↩ Reply] [✓ Mark as read]
- *
- * Tap the text to open the chat; the buttons use the app's own Reply / Mark as read actions.
+ * Supports expanding messages with individual replies and mark-as-read actions, full text preview,
+ * and mark-all-as-read batch action.
*/
class NotificationPeekView(context: Context) : LinearLayout(context) {
var onOpen: ((NotificationStore.Entry) -> Unit)? = null
var onReply: ((NotificationStore.Entry) -> Unit)? = null
var onMarkRead: ((NotificationStore.Entry) -> Unit)? = null
+ var onMarkAllRead: ((List) -> Unit)? = null
+ var onInteraction: (() -> Unit)? = null
+ var onExpandedChanged: ((Boolean) -> Unit)? = null
/** Show the Reply / Mark as read buttons. */
var actionsEnabled = true
+ /** Allow expanding to show all messages in the conversation/app. */
+ var expandableEnabled = true
private val d = resources.displayMetrics.density
private fun dp(v: Float) = (v * d).toInt()
+
+ private var entries: List = emptyList()
private var current: NotificationStore.Entry? = null
private var shown = false
+ private var isExpanded = false
+
+ private var baseFontSize = 14f
+ private var bodyMaxLines = 4
+ private var customMaxHeightDp = 380
// Dim greys on black, like an always-on display: readable without lighting the panel up.
private fun grey(alpha: Float) = Color.argb((255 * alpha).toInt(), 255, 255, 255)
@@ -56,14 +68,55 @@ class NotificationPeekView(context: Context) : LinearLayout(context) {
textAlignment = View.TEXT_ALIGNMENT_VIEW_START
}
+ // Top Header
private val appIcon = ImageView(context).apply { alpha = 0.6f }
private val appName = line(12f, 0.42f, 1)
+ private val headerChevron = ImageView(context).apply {
+ setImageResource(R.drawable.ic_expand_more)
+ imageTintList = ColorStateList.valueOf(grey(0.42f))
+ visibility = GONE
+ }
+
+ // Collapsed Views
+ private val collapsedContent = LinearLayout(context).apply {
+ orientation = VERTICAL
+ gravity = Gravity.START
+ }
private val title = line(15f, 0.75f, 1).apply { typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) }
private val body = line(14f, 0.55f, 4).apply { setLineSpacing(0f, 1.12f) }
private val media = line(12f, 0.6f, 1).apply { setPadding(dp(10f), dp(3f), dp(10f), dp(3f)) }
- private val more = line(12f, 0.35f, 1)
- private val reply = actionButton(R.drawable.ic_reply, R.string.peek_reply) { current?.let { onReply?.invoke(it) } }
- private val markRead = actionButton(R.drawable.ic_done_all, R.string.peek_mark_read) { current?.let { onMarkRead?.invoke(it) } }
+ private val expandButton = actionButton(R.drawable.ic_expand_more, R.string.peek_expand_single) {
+ toggleExpanded()
+ }
+
+ fun applyCustomization(fontSizeSp: Float, maxLines: Int, maxHeightDp: Int) {
+ baseFontSize = fontSizeSp
+ bodyMaxLines = maxLines
+ customMaxHeightDp = maxHeightDp
+
+ appName.textSize = (baseFontSize - 2f).coerceAtLeast(10f)
+ title.textSize = baseFontSize + 1f
+ body.textSize = baseFontSize
+ body.maxLines = bodyMaxLines
+ media.textSize = (baseFontSize - 2.5f).coerceAtLeast(10f)
+ expandButton.textSize = (baseFontSize - 1f).coerceAtLeast(11f)
+ reply.textSize = (baseFontSize - 1f).coerceAtLeast(11f)
+ markRead.textSize = (baseFontSize - 1f).coerceAtLeast(11f)
+ collapseButton.textSize = (baseFontSize - 1f).coerceAtLeast(11f)
+ markAllButton.textSize = (baseFontSize - 1f).coerceAtLeast(11f)
+
+ if (isExpanded) {
+ rebuildExpandedCards()
+ }
+ }
+ private val reply = actionButton(R.drawable.ic_reply, R.string.peek_reply) {
+ onInteraction?.invoke()
+ current?.let { onReply?.invoke(it) }
+ }
+ private val markRead = actionButton(R.drawable.ic_done_all, R.string.peek_mark_read) {
+ onInteraction?.invoke()
+ current?.let { onMarkRead?.invoke(it) }
+ }
private val actions = LinearLayout(context).apply {
orientation = HORIZONTAL
gravity = Gravity.START or Gravity.CENTER_VERTICAL
@@ -71,35 +124,92 @@ class NotificationPeekView(context: Context) : LinearLayout(context) {
addView(markRead, LayoutParams(-2, dp(36f)))
}
+ // Expanded Views
+ private val expandedScroll = ScrollView(context).apply {
+ isVerticalScrollBarEnabled = true
+ overScrollMode = View.OVER_SCROLL_IF_CONTENT_SCROLLS
+ visibility = GONE
+ }
+ private val expandedList = LinearLayout(context).apply {
+ orientation = VERTICAL
+ gravity = Gravity.START
+ }
+ private val collapseButton = actionButton(R.drawable.ic_expand_less, R.string.peek_collapse) {
+ toggleExpanded()
+ }
+ private val markAllButton = actionButton(R.drawable.ic_done_all, R.string.peek_mark_all_read) {
+ onInteraction?.invoke()
+ onMarkAllRead?.invoke(entries)
+ }
+ private val expandedFooter = LinearLayout(context).apply {
+ orientation = HORIZONTAL
+ gravity = Gravity.START or Gravity.CENTER_VERTICAL
+ addView(collapseButton, LayoutParams(-2, dp(36f)).apply { marginEnd = dp(8f) })
+ addView(markAllButton, LayoutParams(-2, dp(36f)))
+ }
+
init {
orientation = VERTICAL
gravity = Gravity.START
setPadding(dp(16f), dp(10f), dp(16f), dp(10f))
setBackgroundColor(Color.BLACK)
+
+ layoutTransition = LayoutTransition().apply {
+ enableTransitionType(LayoutTransition.CHANGING)
+ setDuration(180)
+ }
+
+ // Header
val head = LinearLayout(context).apply {
orientation = HORIZONTAL
gravity = Gravity.START or Gravity.CENTER_VERTICAL
addView(appIcon, LayoutParams(dp(16f), dp(16f)).apply { marginEnd = dp(8f) })
addView(appName, LayoutParams(0, -2, 1f))
+ addView(headerChevron, LayoutParams(dp(20f), dp(20f)))
+ isClickable = true
+ setOnClickListener {
+ if (expandableEnabled && entries.isNotEmpty()) {
+ toggleExpanded()
+ } else {
+ current?.let { onOpen?.invoke(it) }
+ }
+ }
}
addView(head, LayoutParams(-1, -2))
- addView(title, LayoutParams(-1, -2).apply { topMargin = dp(8f) })
- addView(body, LayoutParams(-1, -2).apply { topMargin = dp(2f) })
+
+ // Collapsed layout
+ collapsedContent.addView(title, LayoutParams(-1, -2).apply { topMargin = dp(8f) })
+ collapsedContent.addView(body, LayoutParams(-1, -2).apply { topMargin = dp(2f) })
+
val tags = LinearLayout(context).apply {
orientation = HORIZONTAL
gravity = Gravity.START or Gravity.CENTER_VERTICAL
addView(media, LayoutParams(-2, -2).apply { marginEnd = dp(10f) })
- addView(more, LayoutParams(-2, -2))
+ addView(expandButton, LayoutParams(-2, dp(32f)))
+ }
+ collapsedContent.addView(tags, LayoutParams(-1, -2).apply { topMargin = dp(8f) })
+ collapsedContent.addView(actions, LayoutParams(-1, -2).apply { topMargin = dp(10f) })
+
+ collapsedContent.isClickable = true
+ collapsedContent.setOnClickListener {
+ onInteraction?.invoke()
+ if (expandableEnabled && entries.isNotEmpty()) {
+ toggleExpanded()
+ } else {
+ current?.let { onOpen?.invoke(it) }
+ }
}
- addView(tags, LayoutParams(-1, -2).apply { topMargin = dp(8f) })
- addView(actions, LayoutParams(-1, -2).apply { topMargin = dp(12f) })
+
+ addView(collapsedContent, LayoutParams(-1, -2))
+
+ // Expanded layout
+ expandedScroll.addView(expandedList, ViewGroup.LayoutParams(-1, -2))
+ addView(expandedScroll, LayoutParams(-1, -2).apply { topMargin = dp(8f) })
+
alpha = 0f
visibility = INVISIBLE
- isClickable = true
- setOnClickListener { current?.let { onOpen?.invoke(it) } }
}
- /** Outlined pill on black (no fill, so it costs almost no AMOLED power). */
private fun actionButton(icon: Int, label: Int, onClick: () -> Unit) = TextView(context).apply {
setText(label)
textSize = 13f
@@ -119,49 +229,207 @@ class NotificationPeekView(context: Context) : LinearLayout(context) {
setStroke(dp(1f), grey(0.22f))
}
isClickable = true
- setOnClickListener { onClick() }
+ setOnClickListener {
+ onInteraction?.invoke()
+ onClick()
+ }
+ }
+
+ private fun toggleExpanded() {
+ onInteraction?.invoke()
+ isExpanded = !isExpanded
+ TransitionManager.beginDelayedTransition(this, AutoTransition().setDuration(220))
+ updateExpandedState()
+ onExpandedChanged?.invoke(isExpanded)
+ }
+
+ private fun updateExpandedState() {
+ val count = entries.size
+ headerChevron.visibility = if (expandableEnabled && count > 0) VISIBLE else GONE
+ headerChevron.setImageResource(if (isExpanded) R.drawable.ic_expand_less else R.drawable.ic_expand_more)
+
+ if (isExpanded) {
+ collapsedContent.visibility = GONE
+ expandedScroll.visibility = VISIBLE
+ rebuildExpandedCards()
+ } else {
+ collapsedContent.visibility = VISIBLE
+ expandedScroll.visibility = GONE
+ }
+ }
+
+ private fun rebuildExpandedCards() {
+ expandedList.removeAllViews()
+ for (e in entries) {
+ val card = buildMessageCard(e)
+ expandedList.addView(card, LayoutParams(-1, -2).apply { bottomMargin = dp(8f) })
+ }
+ // Footer: collapse + mark all read
+ markAllButton.visibility = if (entries.size > 1 && actionsEnabled) VISIBLE else GONE
+ expandedList.addView(expandedFooter, LayoutParams(-1, -2).apply { topMargin = dp(4f); bottomMargin = dp(4f) })
}
- /** Fills the peek with the newest notification of an app (+ how many more). */
+ private fun buildMessageCard(e: NotificationStore.Entry): View {
+ val card = LinearLayout(context).apply {
+ orientation = VERTICAL
+ gravity = Gravity.START
+ setPadding(dp(12f), dp(10f), dp(12f), dp(10f))
+ background = GradientDrawable().apply {
+ cornerRadius = 14 * d
+ setColor(Color.BLACK)
+ setStroke(dp(1f), (e.color and 0x00FFFFFF) or 0x44000000)
+ }
+ isClickable = true
+ setOnClickListener {
+ onInteraction?.invoke()
+ onOpen?.invoke(e)
+ }
+ }
+
+ // Card header line: Sender/title + time ago
+ val topRow = LinearLayout(context).apply {
+ orientation = HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ }
+ val cardTitle = line(baseFontSize, 0.85f, 1).apply {
+ typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
+ text = e.title ?: AppInfoView.labelFor(context.packageManager, e.pkg)
+ }
+ val ago = DateUtils.getRelativeTimeSpanString(e.time, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS)
+ val cardTime = line((baseFontSize - 2.5f).coerceAtLeast(10f), 0.45f, 1).apply {
+ text = ago
+ gravity = Gravity.END
+ }
+ topRow.addView(cardTitle, LayoutParams(0, -2, 1f))
+ topRow.addView(cardTime, LayoutParams(-2, -2))
+ card.addView(topRow, LayoutParams(-1, -2))
+
+ // Message text
+ val text = e.lines.joinToString("\n")
+ if (text.isNotBlank()) {
+ val cardBody = line((baseFontSize - 0.5f).coerceAtLeast(11f), 0.65f, 100).apply {
+ this.text = text
+ setLineSpacing(0f, 1.15f)
+ }
+ card.addView(cardBody, LayoutParams(-1, -2).apply { topMargin = dp(4f) })
+ }
+
+ // Media tag if any
+ val label = NotificationContent.label(context, e.kind)
+ if (label.isNotEmpty()) {
+ val cardMedia = line((baseFontSize - 2.5f).coerceAtLeast(10f), 0.7f, 1).apply {
+ this.text = label
+ setPadding(dp(8f), dp(2f), dp(8f), dp(2f))
+ background = GradientDrawable().apply {
+ cornerRadius = 10 * d
+ setColor(Color.BLACK)
+ setStroke(dp(1f), (e.color and 0x00FFFFFF) or 0x66000000)
+ }
+ }
+ card.addView(cardMedia, LayoutParams(-2, -2).apply { topMargin = dp(6f) })
+ }
+
+ // Action buttons row for this message
+ if (actionsEnabled && (e.replyAction != null || e.readAction != null || e.clearable)) {
+ val cardActions = LinearLayout(context).apply {
+ orientation = HORIZONTAL
+ gravity = Gravity.START or Gravity.CENTER_VERTICAL
+ }
+ if (e.replyAction != null) {
+ val btnReply = actionButton(R.drawable.ic_reply, R.string.peek_reply) {
+ onInteraction?.invoke()
+ onReply?.invoke(e)
+ }
+ cardActions.addView(btnReply, LayoutParams(-2, dp(32f)).apply { marginEnd = dp(8f) })
+ }
+ val btnDismiss = actionButton(
+ if (e.readAction != null) R.drawable.ic_done_all else R.drawable.ic_check,
+ if (e.readAction != null) R.string.peek_mark_read else R.string.peek_dismiss,
+ ) {
+ onInteraction?.invoke()
+ onMarkRead?.invoke(e)
+ }
+ cardActions.addView(btnDismiss, LayoutParams(-2, dp(32f)))
+ card.addView(cardActions, LayoutParams(-1, -2).apply { topMargin = dp(8f) })
+ }
+
+ return card
+ }
+
+ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
+ val screenH = resources.displayMetrics.heightPixels
+ val maxH = (customMaxHeightDp * resources.displayMetrics.density).toInt()
+ .coerceIn((120 * resources.displayMetrics.density).toInt(), (screenH * 0.85f).toInt())
+ val hSpec = if (MeasureSpec.getSize(heightMeasureSpec) > maxH || MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED) {
+ MeasureSpec.makeMeasureSpec(maxH, MeasureSpec.AT_MOST)
+ } else {
+ heightMeasureSpec
+ }
+ super.onMeasure(widthMeasureSpec, hSpec)
+ }
+
+ /** Fills the peek with the notifications of an app. */
fun bind(entries: List) {
+ this.entries = entries
val e = entries.firstOrNull() ?: return
current = e
+
+ val p = com.glowled.app.core.LedController.prefs
+ applyCustomization(p.peekFontSizeSp.toFloat(), p.peekLines, p.peekHeightDp)
+
val pm = context.packageManager
val icon = AppInfoView.iconFor(pm, e.pkg)
appIcon.setImageDrawable(icon)
appIcon.visibility = if (icon == null) GONE else VISIBLE
+
+ val appLabel = AppInfoView.labelFor(pm, e.pkg)
val ago = DateUtils.getRelativeTimeSpanString(e.time, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS)
- appName.text = context.getString(R.string.peek_app_time, AppInfoView.labelFor(pm, e.pkg), ago)
+ if (entries.size > 1) {
+ appName.text = context.getString(R.string.peek_messages_count, appLabel, entries.size)
+ } else {
+ appName.text = context.getString(R.string.peek_app_time, appLabel, ago)
+ }
+
if (e.hidden) {
title.setText(R.string.peek_new)
body.setText(R.string.peek_hidden)
body.visibility = VISIBLE
media.visibility = GONE
} else {
- title.text = e.title ?: AppInfoView.labelFor(pm, e.pkg)
+ title.text = e.title ?: appLabel
val text = e.lines.joinToString("\n")
body.text = text
body.visibility = if (text.isBlank()) GONE else VISIBLE
val label = NotificationContent.label(context, e.kind)
media.text = label
media.visibility = if (label.isEmpty()) GONE else VISIBLE
- // Thin outline in the app's colour (no fill, keeps pixels off).
media.background = GradientDrawable().apply {
cornerRadius = 12 * d
setColor(Color.BLACK)
setStroke(dp(1f), (e.color and 0x00FFFFFF) or 0x66000000)
}
}
+
val extra = entries.size - 1
- more.text = if (extra > 0) context.getString(R.string.peek_more, extra) else ""
- more.visibility = if (extra > 0) VISIBLE else GONE
- (media.parent as View).visibility = if (media.visibility == GONE && more.visibility == GONE) GONE else VISIBLE
+ if (expandableEnabled && entries.isNotEmpty()) {
+ if (extra > 0) {
+ expandButton.text = String.format(context.getString(R.string.peek_expand), entries.size)
+ } else {
+ expandButton.setText(R.string.peek_expand_single)
+ }
+ expandButton.visibility = VISIBLE
+ } else {
+ expandButton.visibility = GONE
+ }
+
+ (media.parent as? View)?.visibility = if (media.visibility == GONE && expandButton.visibility == GONE) GONE else VISIBLE
reply.visibility = if (actionsEnabled && e.replyAction != null) VISIBLE else GONE
- // Without the app's own action, "Dismiss" clears the notification instead.
markRead.setText(if (e.readAction != null) R.string.peek_mark_read else R.string.peek_dismiss)
markRead.visibility = if (actionsEnabled && (e.readAction != null || e.clearable)) VISIBLE else GONE
actions.visibility = if (reply.visibility == GONE && markRead.visibility == GONE) GONE else VISIBLE
+
+ updateExpandedState()
}
fun isShowing() = shown
@@ -184,6 +452,12 @@ class NotificationPeekView(context: Context) : LinearLayout(context) {
animate().cancel()
animate().alpha(0f).translationY(-dp(8f).toFloat()).setDuration(220)
.setInterpolator(DecelerateInterpolator())
- .withEndAction { if (!shown) visibility = INVISIBLE }.start()
+ .withEndAction {
+ if (!shown) {
+ visibility = INVISIBLE
+ isExpanded = false
+ updateExpandedState()
+ }
+ }.start()
}
}
diff --git a/app/src/main/java/com/glowled/app/view/renderer/LedStyleRenderer.kt b/app/src/main/java/com/glowled/app/view/renderer/LedStyleRenderer.kt
new file mode 100644
index 0000000..148432c
--- /dev/null
+++ b/app/src/main/java/com/glowled/app/view/renderer/LedStyleRenderer.kt
@@ -0,0 +1,117 @@
+package com.glowled.app.view.renderer
+
+import android.graphics.Canvas
+import kotlin.math.PI
+import kotlin.math.cos
+import kotlin.math.max
+import kotlin.math.pow
+import kotlin.math.sin
+
+interface LedRenderContext {
+ val cx: Float
+ val cy: Float
+ val isFilled: Boolean
+ val colors: IntArray
+ fun ring(c: Canvas, color: Int, a: Float, segmented: Boolean, rotation: Float)
+ fun ripple(c: Canvas, color: Int, p: Float)
+ fun spin(c: Canvas, p: Float, segmented: Boolean, color: Int, tail: Float, comets: Int, base: Float)
+ fun rainbow(c: Canvas, p: Float)
+ fun drawSegment(c: Canvas, from: Float, to: Float, color: Int, a: Float)
+}
+
+interface LedStyleRenderer {
+ val basePeriodMs: Long
+ fun render(canvas: Canvas, p: Float, color: Int, segmented: Boolean, rot: Float, ctx: LedRenderContext)
+}
+
+fun wave(p: Float) = (0.5f - 0.5f * cos(2f * PI.toFloat() * p))
+
+fun heartbeat(p: Float): Float {
+ fun bump(s: Float, e: Float) = if (p in s..e) sin(PI.toFloat() * (p - s) / (e - s)) else 0f
+ return max(bump(0f, 0.14f), bump(0.22f, 0.38f) * 0.8f)
+}
+
+const val BLINK_ON = 0.5f
+
+class StaticStyleRenderer : LedStyleRenderer {
+ override val basePeriodMs: Long = 2500L
+ override fun render(canvas: Canvas, p: Float, color: Int, segmented: Boolean, rot: Float, ctx: LedRenderContext) {
+ ctx.ring(canvas, color, 1f, segmented, rot)
+ }
+}
+
+class BreatheStyleRenderer : LedStyleRenderer {
+ override val basePeriodMs: Long = 3200L
+ override fun render(canvas: Canvas, p: Float, color: Int, segmented: Boolean, rot: Float, ctx: LedRenderContext) {
+ ctx.ring(canvas, color, 0.12f + 0.88f * wave(p), segmented, rot)
+ }
+}
+
+class EdgePulseStyleRenderer : LedStyleRenderer {
+ override val basePeriodMs: Long = 3000L
+ override fun render(canvas: Canvas, p: Float, color: Int, segmented: Boolean, rot: Float, ctx: LedRenderContext) {
+ ctx.ring(canvas, color, 0.1f + 0.9f * wave(p), segmented, rot)
+ }
+}
+
+class BlinkStyleRenderer : LedStyleRenderer {
+ override val basePeriodMs: Long = 2400L
+ override fun render(canvas: Canvas, p: Float, color: Int, segmented: Boolean, rot: Float, ctx: LedRenderContext) {
+ if (p < BLINK_ON) ctx.ring(canvas, color, 1f, segmented, rot)
+ }
+}
+
+class HeartbeatStyleRenderer : LedStyleRenderer {
+ override val basePeriodMs: Long = 1700L
+ override fun render(canvas: Canvas, p: Float, color: Int, segmented: Boolean, rot: Float, ctx: LedRenderContext) {
+ ctx.ring(canvas, color, 0.08f + 0.92f * heartbeat(p), segmented, rot)
+ }
+}
+
+class PulseStyleRenderer : LedStyleRenderer {
+ override val basePeriodMs: Long = 2000L
+ override fun render(canvas: Canvas, p: Float, color: Int, segmented: Boolean, rot: Float, ctx: LedRenderContext) {
+ ctx.ring(canvas, color, 0.55f + 0.45f * (1f - wave(p)), segmented, rot)
+ ctx.ripple(canvas, color, p)
+ }
+}
+
+class SpinStyleRenderer : LedStyleRenderer {
+ override val basePeriodMs: Long = 1500L
+ override fun render(canvas: Canvas, p: Float, color: Int, segmented: Boolean, rot: Float, ctx: LedRenderContext) {
+ ctx.spin(canvas, p, segmented, color, tail = 0.38f, comets = 1, base = 0.16f)
+ }
+}
+
+class EdgeStyleRenderer : LedStyleRenderer {
+ override val basePeriodMs: Long = 3200L
+ override fun render(canvas: Canvas, p: Float, color: Int, segmented: Boolean, rot: Float, ctx: LedRenderContext) {
+ ctx.spin(canvas, p, segmented, color, tail = 0.16f, comets = 2, base = 0.06f)
+ }
+}
+
+class RainbowStyleRenderer : LedStyleRenderer {
+ override val basePeriodMs: Long = 3000L
+ override fun render(canvas: Canvas, p: Float, color: Int, segmented: Boolean, rot: Float, ctx: LedRenderContext) {
+ ctx.rainbow(canvas, p)
+ }
+}
+
+class OrbitStyleRenderer : LedStyleRenderer {
+ override val basePeriodMs: Long = 2400L
+ override fun render(canvas: Canvas, p: Float, color: Int, segmented: Boolean, rot: Float, ctx: LedRenderContext) {
+ ctx.spin(canvas, p, segmented, color, tail = 0.22f, comets = 2, base = 0.08f)
+ }
+}
+
+class SparkleStyleRenderer : LedStyleRenderer {
+ override val basePeriodMs: Long = 3600L
+ override fun render(canvas: Canvas, p: Float, color: Int, segmented: Boolean, rot: Float, ctx: LedRenderContext) {
+ val n = ctx.colors.size
+ for (i in 0 until 6) {
+ val a = 0.12f + 0.88f * wave((p + i / 6f) % 1f).pow(4)
+ val start = i / 6f + p * 0.1f
+ ctx.drawSegment(canvas, start, start + 0.075f, ctx.colors[i % n], a)
+ }
+ }
+}
diff --git a/app/src/main/res/drawable/ic_expand_less.xml b/app/src/main/res/drawable/ic_expand_less.xml
new file mode 100644
index 0000000..ab31cda
--- /dev/null
+++ b/app/src/main/res/drawable/ic_expand_less.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_expand_more.xml b/app/src/main/res/drawable/ic_expand_more.xml
new file mode 100644
index 0000000..57d58a8
--- /dev/null
+++ b/app/src/main/res/drawable/ic_expand_more.xml
@@ -0,0 +1,11 @@
+
+
+
+
diff --git a/app/src/main/res/values-ar/arrays.xml b/app/src/main/res/values-ar/arrays.xml
index 507f552..06724d3 100644
--- a/app/src/main/res/values-ar/arrays.xml
+++ b/app/src/main/res/values-ar/arrays.xml
@@ -62,4 +62,24 @@
- فاتح
- النظام
+
+ - دائمًا
+ - 5 ث
+ - 15 ث
+ - 30 ث
+ - 1 د
+ - 5 د
+
+
+ - دائمًا
+ - 5 ث
+ - 10 ث
+ - 30 ث
+
+
+ - أسفل
+ - يمين
+ - يسار
+ - أعلى
+
diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml
index c9e644d..cc133f6 100644
--- a/app/src/main/res/values-ar/strings.xml
+++ b/app/src/main/res/values-ar/strings.xml
@@ -342,4 +342,55 @@
يملأ التنزيل الحلقة مع سهم ↓.
الرفع
يملأ الرفع الحلقة مع سهم ↑.
+ رسائل قابلة للتوسيع
+ توسيع (%d)
+ توسيع
+ طي
+ تعليم الكل كمقروء
+ %1$s · %2$d من الرسائل
+ الرسائل الأخيرة
+ حسنًا
+ شكرًا!
+ أنا في الطريق
+ لاحقًا
+ انقر على الحلقة لقراءة الرسائل
+ حجم القطرة
+ حجم أيقونة التطبيق
+ منطقة الاستجابة باللمس
+ إزاحة منطقة اللمس X
+ إزاحة منطقة اللمس Y
+ عرض منطقة اللمس (0 = تلقائي)
+ ارتفاع منطقة اللمس (0 = تلقائي)
+ اضبطها إذا كانت اللمسات لا تصل إلى الحلقة. يظهر إطار منطقة اللمس أثناء ضبطها هنا.
+ عرض بطاقة الرسائل
+ أقصى ارتفاع لبطاقة الرسائل
+ أسطر معاينة الرسالة
+ حجم خط الرسالة
+ حلقة الشحن أثناء تشغيل الشاشة
+ مؤقت الشحن (الشاشة مطفأة)
+ مؤقت الشحن (الشاشة تعمل)
+ إحصاءات البطارية أسفل الحلقة
+ نسبة البطارية (%)
+ جهد البطارية (V)
+ التيار (mA)
+ قدرة الشحن (W)
+ تحميل المعالج
+ إظهار تحميل المعالج
+ إظهار بادئة \"CPU\"
+ الموضع بالنسبة للحلقة
+ حجم نص المعالج
+ الإزاحة X
+ الإزاحة Y
+ التشخيص
+ حالة النظام والصحة
+ تصدير التقرير
+ AOD (24 ساعة): %1$d استيقاظًا · %2$d ث متحرك · %3$d ث ثابت
+ تم العثور على %1$d إعدادات (بما فيها %2$d من قواعد التطبيقات) من الإصدار %3$s.
+
+هل تريد استبدال الإعدادات الحالية؟
+ إيقاف مؤقت
+ إيقاف LED مؤقتًا (Snooze)
+ إيقاف
+ متوقف مؤقتًا · %d د
+ متوقف مؤقتًا بواسطة المستخدم
diff --git a/app/src/main/res/values-de/arrays.xml b/app/src/main/res/values-de/arrays.xml
index 4020211..012ab79 100644
--- a/app/src/main/res/values-de/arrays.xml
+++ b/app/src/main/res/values-de/arrays.xml
@@ -62,4 +62,24 @@
- Hell
- System
+
+ - Immer
+ - 5 s
+ - 15 s
+ - 30 s
+ - 1 Min.
+ - 5 Min.
+
+
+ - Immer
+ - 5 s
+ - 10 s
+ - 30 s
+
+
+ - Unterhalb
+ - Rechts
+ - Links
+ - Oberhalb
+
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index 4ef3e71..4c292fd 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -342,4 +342,55 @@
Ein Download füllt den Ring, mit einem ↓-Pfeil.
Upload
Ein Upload füllt den Ring, mit einem ↑-Pfeil.
+ Erweiterbare Nachrichten
+ Ausklappen (%d)
+ Ausklappen
+ Einklappen
+ Alle als gelesen
+ %1$s · %2$d Nachrichten
+ Letzte Nachrichten
+ OK
+ Danke!
+ Bin unterwegs
+ Später
+ Ring antippen, um Nachrichten zu lesen
+ Tropfengröße
+ App-Symbolgröße
+ Tippzone
+ Tippzone-Versatz X
+ Tippzone-Versatz Y
+ Tippzone-Breite (0 = auto)
+ Tippzone-Höhe (0 = auto)
+ Passe die Tippzone an, wenn Antippen den Ring nicht erreicht. Während der Einrichtung zeigt ein Rahmen die Tippzone.
+ Breite der Nachrichtenkarte
+ Maximale Höhe der Nachrichtenkarte
+ Vorschauzeilen der Nachricht
+ Schriftgröße der Nachricht
+ Ladering bei eingeschaltetem Bildschirm
+ Lade-Timer (Bildschirm aus)
+ Lade-Timer (Bildschirm an)
+ Akku-Statistiken unter dem Ring
+ Akkustand (%)
+ Akku-Spannung (V)
+ Stromstärke (mA)
+ Ladeleistung (W)
+ CPU-Last
+ CPU-Last anzeigen
+ „CPU“-Präfix anzeigen
+ Position relativ zum Ring
+ CPU-Textgröße
+ Versatz X
+ Versatz Y
+ Diagnose
+ Systemstatus & Gesundheit
+ Bericht exportieren
+ AOD (24 h): %1$d Aufwachungen · %2$d s animiert · %3$d s statisch
+ %1$d Einstellungen gefunden (darunter %2$d App-Regeln) von Version %3$s.
+
+Aktuelle Einstellungen überschreiben?
+ Temporäre Pause
+ LED pausieren (Snooze)
+ Aus
+ Pausiert · %d Min.
+ Vom Nutzer pausiert
diff --git a/app/src/main/res/values-es/arrays.xml b/app/src/main/res/values-es/arrays.xml
index 9d1c804..4b2714d 100644
--- a/app/src/main/res/values-es/arrays.xml
+++ b/app/src/main/res/values-es/arrays.xml
@@ -62,4 +62,24 @@
- Claro
- Sistema
+
+ - Siempre
+ - 5 s
+ - 15 s
+ - 30 s
+ - 1 min
+ - 5 min
+
+
+ - Siempre
+ - 5 s
+ - 10 s
+ - 30 s
+
+
+ - Debajo
+ - Derecha
+ - Izquierda
+ - Arriba
+
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index d417e6a..7545d8e 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -342,4 +342,55 @@
Una descarga llena el anillo, con una flecha ↓.
Subiendo
Una subida llena el anillo, con una flecha ↑.
+ Mensajes expandibles
+ Expandir (%d)
+ Expandir
+ Contraer
+ Marcar todo como leído
+ %1$s · %2$d mensajes
+ Mensajes recientes
+ OK
+ ¡Gracias!
+ Voy en camino
+ Más tarde
+ Toca el anillo para leer los mensajes
+ Tamaño de la gota
+ Tamaño del icono de app
+ Zona de respuesta táctil
+ Desplazamiento X de la zona táctil
+ Desplazamiento Y de la zona táctil
+ Ancho de la zona táctil (0 = auto)
+ Alto de la zona táctil (0 = auto)
+ Ajusta si los toques no llegan al anillo. Un borde muestra la zona táctil mientras la configuras aquí.
+ Ancho de la tarjeta de mensajes
+ Altura máx. de la tarjeta de mensajes
+ Líneas de vista previa del mensaje
+ Tamaño de letra del mensaje
+ Anillo de carga con pantalla encendida
+ Temporizador de carga (pantalla apagada)
+ Temporizador de carga (pantalla encendida)
+ Estadísticas de batería bajo el anillo
+ Porcentaje de batería (%)
+ Voltaje de la batería (V)
+ Amperaje actual (mA)
+ Potencia de carga (W)
+ Carga de CPU
+ Mostrar carga de CPU
+ Mostrar prefijo «CPU»
+ Posición relativa al anillo
+ Tamaño del texto de CPU
+ Desplazamiento X
+ Desplazamiento Y
+ Diagnóstico
+ Estado del sistema y salud
+ Exportar informe
+ AOD (24 h): %1$d activaciones · %2$d s animado · %3$d s estático
+ Se encontraron %1$d ajustes (incluidas %2$d reglas de apps) de la versión %3$s.
+
+¿Sobrescribir los ajustes actuales?
+ Pausa temporal
+ Pausar LED (Snooze)
+ Apagado
+ Pausado · %d min
+ Pausado por el usuario
diff --git a/app/src/main/res/values-fr/arrays.xml b/app/src/main/res/values-fr/arrays.xml
index 4a5ac77..cd32c3f 100644
--- a/app/src/main/res/values-fr/arrays.xml
+++ b/app/src/main/res/values-fr/arrays.xml
@@ -62,4 +62,24 @@
- Clair
- Système
+
+ - Toujours
+ - 5 s
+ - 15 s
+ - 30 s
+ - 1 min
+ - 5 min
+
+
+ - Toujours
+ - 5 s
+ - 10 s
+ - 30 s
+
+
+ - En dessous
+ - À droite
+ - À gauche
+ - Au-dessus
+
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index 80cfd98..bcc13a0 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -342,4 +342,55 @@
Un téléchargement remplit l\'anneau, avec une flèche ↓.
Envoi
Un envoi remplit l\'anneau, avec une flèche ↑.
+ Messages dépliables
+ Déplier (%d)
+ Déplier
+ Replier
+ Tout marquer comme lu
+ %1$s · %2$d messages
+ Messages récents
+ OK
+ Merci !
+ J\'arrive
+ Plus tard
+ Touchez l\'anneau pour lire les messages
+ Taille de la goutte
+ Taille de l\'icône d\'app
+ Zone de réponse au toucher
+ Décalage X de la zone tactile
+ Décalage Y de la zone tactile
+ Largeur de la zone tactile (0 = auto)
+ Hauteur de la zone tactile (0 = auto)
+ Ajustez si les touches n\'atteignent pas l\'anneau. Une bordure affiche la zone tactile pendant que vous la configurez ici.
+ Largeur de la carte de messages
+ Hauteur max. de la carte de messages
+ Lignes d\'aperçu du message
+ Taille de police du message
+ Anneau de charge écran allumé
+ Minuteur de charge (écran éteint)
+ Minuteur de charge (écran allumé)
+ Statistiques de batterie sous l\'anneau
+ Pourcentage de batterie (%)
+ Tension de la batterie (V)
+ Intensité actuelle (mA)
+ Puissance de charge (W)
+ Charge CPU
+ Afficher la charge CPU
+ Afficher le préfixe « CPU »
+ Position par rapport à l\'anneau
+ Taille du texte CPU
+ Décalage X
+ Décalage Y
+ Diagnostic
+ État du système et santé
+ Exporter le rapport
+ AOD (24 h) : %1$d réveils · %2$d s animé · %3$d s statique
+ %1$d paramètres trouvés (dont %2$d règles d\'application) de la version %3$s.
+
+Remplacer les paramètres actuels ?
+ Pause temporaire
+ Mettre la LED en pause (Snooze)
+ Désactivé
+ En pause · %d min
+ En pause par l\'utilisateur
diff --git a/app/src/main/res/values-hi/arrays.xml b/app/src/main/res/values-hi/arrays.xml
index 8e116a1..f81304f 100644
--- a/app/src/main/res/values-hi/arrays.xml
+++ b/app/src/main/res/values-hi/arrays.xml
@@ -62,4 +62,24 @@
- हल्की
- सिस्टम
+
+ - हमेशा
+ - 5 सेकंड
+ - 15 सेकंड
+ - 30 सेकंड
+ - 1 मिनट
+ - 5 मिनट
+
+
+ - हमेशा
+ - 5 सेकंड
+ - 10 सेकंड
+ - 30 सेकंड
+
+
+ - नीचे
+ - दाएँ
+ - बाएँ
+ - ऊपर
+
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index 183ac1b..561cbb0 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -342,4 +342,55 @@
डाउनलोड रिंग को ↓ तीर के साथ भरता है।
अपलोड
अपलोड रिंग को ↑ तीर के साथ भरता है।
+ विस्तार योग्य संदेश
+ विस्तारित करें (%d)
+ विस्तारित करें
+ छोटा करें
+ सभी पढ़े हुए मार्क करें
+ %1$s · %2$d संदेश
+ हाल के संदेश
+ ठीक है
+ धन्यवाद!
+ मैं आ रहा हूँ
+ बाद में
+ संदेश पढ़ने के लिए रिंग पर टैप करें
+ बूंद का आकार
+ ऐप आइकन का आकार
+ टैप प्रतिक्रिया क्षेत्र
+ टैप क्षेत्र ऑफ़सेट X
+ टैप क्षेत्र ऑफ़सेट Y
+ टैप क्षेत्र की चौड़ाई (0 = ऑटो)
+ टैप क्षेत्र की ऊँचाई (0 = ऑटो)
+ अगर टैप रिंग तक नहीं पहुँचते तो समायोजित करें। यहाँ सेट करते समय बॉर्डर टैप क्षेत्र दिखाता है।
+ संदेश पैनल की चौड़ाई
+ संदेश पैनल की अधिकतम ऊँचाई
+ संदेश पूर्वावलोकन पंक्तियाँ
+ संदेश फ़ॉन्ट आकार
+ स्क्रीन चालू होने पर चार्जिंग रिंग
+ चार्ज टाइमर (स्क्रीन बंद)
+ चार्ज टाइमर (स्क्रीन चालू)
+ रिंग के नीचे बैटरी आँकड़े
+ बैटरी प्रतिशत (%)
+ बैटरी वोल्टेज (V)
+ वर्तमान एम्पीयर (mA)
+ चार्जिंग शक्ति (W)
+ CPU लोड
+ CPU लोड दिखाएँ
+ \"CPU\" उपसर्ग दिखाएँ
+ रिंग के सापेक्ष स्थिति
+ CPU टेक्स्ट आकार
+ ऑफ़सेट X
+ ऑफ़सेट Y
+ निदान
+ सिस्टम स्थिति और स्वास्थ्य
+ रिपोर्ट निर्यात करें
+ AOD (24 घं.): %1$d जागना · %2$d सेकंड एनिमेटेड · %3$d सेकंड स्थिर
+ संस्करण %3$s से %1$d सेटिंग्स मिलीं (%2$d ऐप नियम शामिल)।
+
+मौजूदा सेटिंग्स बदलें?
+ अस्थायी ठहराव
+ LED रोकें (स्नूज़)
+ बंद
+ रुका हुआ · %d मिनट
+ उपयोगकर्ता द्वारा रोका गया
diff --git a/app/src/main/res/values-in/arrays.xml b/app/src/main/res/values-in/arrays.xml
index a345ee7..f13151c 100644
--- a/app/src/main/res/values-in/arrays.xml
+++ b/app/src/main/res/values-in/arrays.xml
@@ -62,4 +62,24 @@
- Terang
- Sistem
+
+ - Selalu
+ - 5 dtk
+ - 15 dtk
+ - 30 dtk
+ - 1 mnt
+ - 5 mnt
+
+
+ - Selalu
+ - 5 dtk
+ - 10 dtk
+ - 30 dtk
+
+
+ - Di bawah
+ - Kanan
+ - Kiri
+ - Di atas
+
diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml
index c0834c8..6047615 100644
--- a/app/src/main/res/values-in/strings.xml
+++ b/app/src/main/res/values-in/strings.xml
@@ -342,4 +342,55 @@
Unduhan mengisi cincin, dengan panah ↓.
Mengunggah
Unggahan mengisi cincin, dengan panah ↑.
+ Pesan yang dapat diperluas
+ Perluas (%d)
+ Perluas
+ Tutup
+ Tandai semua dibaca
+ %1$s · %2$d pesan
+ Pesan terbaru
+ OK
+ Terima kasih!
+ Sedang dalam perjalanan
+ Nanti
+ Ketuk cincin untuk membaca pesan
+ Ukuran tetesan
+ Ukuran ikon aplikasi
+ Zona respons ketukan
+ Ofset zona ketuk X
+ Ofset zona ketuk Y
+ Lebar zona ketuk (0 = otomatis)
+ Tinggi zona ketuk (0 = otomatis)
+ Sesuaikan jika ketukan tidak mencapai cincin. Sebuah bingkai menampilkan zona ketuk saat Anda mengaturnya di sini.
+ Lebar kartu pesan
+ Tinggi maks. kartu pesan
+ Baris pratinjau pesan
+ Ukuran font pesan
+ Cincin pengisian saat layar menyala
+ Pengatur waktu pengisian (layar mati)
+ Pengatur waktu pengisian (layar menyala)
+ Statistik baterai di bawah cincin
+ Persentase baterai (%)
+ Tegangan baterai (V)
+ Arus sekarang (mA)
+ Daya pengisian (W)
+ Beban CPU
+ Tampilkan beban CPU
+ Tampilkan awalan \"CPU\"
+ Posisi relatif terhadap cincin
+ Ukuran teks CPU
+ Ofset X
+ Ofset Y
+ Diagnostik
+ Status & kesehatan sistem
+ Ekspor laporan
+ AOD (24 jam): %1$d kali bangun · %2$d dtk animasi · %3$d dtk statis
+ Menemukan %1$d pengaturan (termasuk %2$d aturan aplikasi) dari versi %3$s.
+
+Timpa pengaturan saat ini?
+ Jeda sementara
+ Jeda LED (Snooze)
+ Mati
+ Dijeda · %d mnt
+ Dijeda oleh pengguna
diff --git a/app/src/main/res/values-it/arrays.xml b/app/src/main/res/values-it/arrays.xml
index 3269eef..45514a1 100644
--- a/app/src/main/res/values-it/arrays.xml
+++ b/app/src/main/res/values-it/arrays.xml
@@ -62,4 +62,24 @@
- Chiaro
- Sistema
+
+ - Sempre
+ - 5 s
+ - 15 s
+ - 30 s
+ - 1 min
+ - 5 min
+
+
+ - Sempre
+ - 5 s
+ - 10 s
+ - 30 s
+
+
+ - Sotto
+ - A destra
+ - A sinistra
+ - Sopra
+
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index ac0de77..e8767ad 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -342,4 +342,55 @@
Un download riempie l\'anello, con una freccia ↓.
Caricamento
Un caricamento riempie l\'anello, con una freccia ↑.
+ Messaggi espandibili
+ Espandi (%d)
+ Espandi
+ Comprimi
+ Segna tutto come letto
+ %1$s · %2$d messaggi
+ Messaggi recenti
+ OK
+ Grazie!
+ Sto arrivando
+ Più tardi
+ Tocca l\'anello per leggere i messaggi
+ Dimensione della goccia
+ Dimensione dell\'icona app
+ Zona di risposta al tocco
+ Offset X della zona touch
+ Offset Y della zona touch
+ Larghezza della zona touch (0 = auto)
+ Altezza della zona touch (0 = auto)
+ Regola se i tocchi non raggiungono l\'anello. Un bordo mostra la zona touch mentre la configuri qui.
+ Larghezza della scheda messaggi
+ Altezza max. della scheda messaggi
+ Righe di anteprima del messaggio
+ Dimensione testo del messaggio
+ Anello di ricarica a schermo acceso
+ Timer di ricarica (schermo spento)
+ Timer di ricarica (schermo acceso)
+ Statistiche batteria sotto l\'anello
+ Percentuale batteria (%)
+ Tensione batteria (V)
+ Amperaggio attuale (mA)
+ Potenza di ricarica (W)
+ Carico CPU
+ Mostra carico CPU
+ Mostra prefisso «CPU»
+ Posizione relativa all\'anello
+ Dimensione testo CPU
+ Offset X
+ Offset Y
+ Diagnostica
+ Stato del sistema e integrità
+ Esporta rapporto
+ AOD (24 h): %1$d risvegli · %2$d s animato · %3$d s statico
+ Trovate %1$d impostazioni (incluse %2$d regole app) dalla versione %3$s.
+
+Sovrascrivere le impostazioni attuali?
+ Pausa temporanea
+ Metti in pausa LED (Snooze)
+ Disattivato
+ In pausa · %d min
+ In pausa per scelta dell\'utente
diff --git a/app/src/main/res/values-ja/arrays.xml b/app/src/main/res/values-ja/arrays.xml
index 2e724dc..42bd1b3 100644
--- a/app/src/main/res/values-ja/arrays.xml
+++ b/app/src/main/res/values-ja/arrays.xml
@@ -62,4 +62,24 @@
- ライト
- システム
+
+ - 常時
+ - 5秒
+ - 15秒
+ - 30秒
+ - 1分
+ - 5分
+
+
+ - 常時
+ - 5秒
+ - 10秒
+ - 30秒
+
+
+ - 下
+ - 右
+ - 左
+ - 上
+
diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml
index d19cda1..7d85f3a 100644
--- a/app/src/main/res/values-ja/strings.xml
+++ b/app/src/main/res/values-ja/strings.xml
@@ -342,4 +342,55 @@
ダウンロード中はリングが満ちていき、↓ 矢印が付きます。
アップロード
アップロード中はリングが満ちていき、↑ 矢印が付きます。
+ 展開可能なメッセージ
+ 展開 (%d)
+ 展開
+ 折りたたむ
+ すべて既読にする
+ %1$s · %2$d件のメッセージ
+ 最近のメッセージ
+ OK
+ ありがとう!
+ 今向かっています
+ 後で
+ リングをタップしてメッセージを読む
+ ドロップのサイズ
+ アプリアイコンのサイズ
+ タップ反応ゾーン
+ タップゾーンのオフセットX
+ タップゾーンのオフセットY
+ タップゾーンの幅 (0 = 自動)
+ タップゾーンの高さ (0 = 自動)
+ タップがリングに届かない場合は調整してください。ここで設定中は、枠線がタップゾーンを示します。
+ メッセージカードの幅
+ メッセージカードの最大高さ
+ メッセージプレビューの行数
+ メッセージのフォントサイズ
+ 画面オン時の充電リング
+ 充電タイマー(画面オフ時)
+ 充電タイマー(画面オン時)
+ リング下のバッテリー統計
+ バッテリーの割合 (%)
+ バッテリー電圧 (V)
+ 現在の電流 (mA)
+ 充電電力 (W)
+ CPU負荷
+ CPU負荷を表示
+ 「CPU」プレフィックスを表示
+ リングからの相対位置
+ CPUテキストサイズ
+ オフセットX
+ オフセットY
+ 診断
+ システムの状態と健全性
+ レポートを書き出す
+ AOD(24時間): %1$d回の復帰 · %2$d秒アニメーション · %3$d秒静止
+ バージョン%3$sから%1$d件の設定(うち%2$d件のアプリルール)が見つかりました。
+
+現在の設定を上書きしますか?
+ 一時停止
+ LEDを一時停止(スヌーズ)
+ オフ
+ 一時停止中 · %d分
+ ユーザーによる一時停止
diff --git a/app/src/main/res/values-pt-rBR/arrays.xml b/app/src/main/res/values-pt-rBR/arrays.xml
index a5fc456..5b1c408 100644
--- a/app/src/main/res/values-pt-rBR/arrays.xml
+++ b/app/src/main/res/values-pt-rBR/arrays.xml
@@ -61,4 +61,24 @@
- Claro
- Sistema
+
+ - Sempre
+ - 5 s
+ - 15 s
+ - 30 s
+ - 1 min
+ - 5 min
+
+
+ - Sempre
+ - 5 s
+ - 10 s
+ - 30 s
+
+
+ - Abaixo
+ - Direita
+ - Esquerda
+ - Acima
+
diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml
index 3d9da5f..20f033e 100644
--- a/app/src/main/res/values-pt-rBR/strings.xml
+++ b/app/src/main/res/values-pt-rBR/strings.xml
@@ -342,4 +342,55 @@
Um download enche o anel, com uma seta ↓.
Enviando
Um envio enche o anel, com uma seta ↑.
+ Mensagens expansíveis
+ Expandir (%d)
+ Expandir
+ Recolher
+ Marcar tudo como lido
+ %1$s · %2$d mensagens
+ Mensagens recentes
+ OK
+ Obrigado!
+ Estou indo
+ Depois
+ Toque no anel para ler as mensagens
+ Tamanho da gota
+ Tamanho do ícone do app
+ Zona de resposta ao toque
+ Deslocamento X da zona de toque
+ Deslocamento Y da zona de toque
+ Largura da zona de toque (0 = auto)
+ Altura da zona de toque (0 = auto)
+ Ajuste se os toques não alcançam o anel. Uma borda mostra a zona de toque enquanto você a configura aqui.
+ Largura do cartão de mensagens
+ Altura máx. do cartão de mensagens
+ Linhas de visualização da mensagem
+ Tamanho da fonte da mensagem
+ Anel de carregamento com a tela ligada
+ Timer de carregamento (tela desligada)
+ Timer de carregamento (tela ligada)
+ Estatísticas de bateria sob o anel
+ Porcentagem da bateria (%)
+ Voltagem da bateria (V)
+ Amperagem atual (mA)
+ Potência de carregamento (W)
+ Carga de CPU
+ Mostrar carga de CPU
+ Mostrar prefixo \"CPU\"
+ Posição relativa ao anel
+ Tamanho do texto da CPU
+ Deslocamento X
+ Deslocamento Y
+ Diagnóstico
+ Status do sistema e saúde
+ Exportar relatório
+ AOD (24 h): %1$d despertares · %2$d s animado · %3$d s estático
+ %1$d configurações encontradas (incluindo %2$d regras de apps) da versão %3$s.
+
+Sobrescrever as configurações atuais?
+ Pausa temporária
+ Pausar LED (Snooze)
+ Desligado
+ Pausado · %d min
+ Pausado pelo usuário
diff --git a/app/src/main/res/values-ru/arrays.xml b/app/src/main/res/values-ru/arrays.xml
index 0b0f8fc..443efd4 100644
--- a/app/src/main/res/values-ru/arrays.xml
+++ b/app/src/main/res/values-ru/arrays.xml
@@ -62,4 +62,24 @@
- Светлая
- Системная
+
+ - Постоянно
+ - 5 с
+ - 15 с
+ - 30 с
+ - 1 мин
+ - 5 мин
+
+
+ - Постоянно
+ - 5 с
+ - 10 с
+ - 30 с
+
+
+ - Под кольцом
+ - Справа
+ - Слева
+ - Сверху
+
diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml
index 0d844cd..5f7c7f8 100644
--- a/app/src/main/res/values-ru/strings.xml
+++ b/app/src/main/res/values-ru/strings.xml
@@ -153,10 +153,21 @@
Сначала дайте доступ к уведомлениям
+ Раскрывающиеся сообщения
%1$s · %2$s
Новое уведомление
Содержимое скрыто
Ещё: %d
+ Раскрыть (%d)
+ Раскрыть
+ Свернуть
+ Прочитать все
+ %1$s · %2$d сообщений
+ Предыдущие сообщения
+ ОК
+ Спасибо!
+ Скоро буду
+ Отвечу позже
Ответить
Прочитано
Закрыть
@@ -342,4 +353,43 @@
Загрузка заполняет кольцо, со стрелкой ↓.
Отправка
Отправка заполняет кольцо, со стрелкой ↑.
+ Нажатие на кольцо — читать сообщения
+ Размер капли
+ Размер иконок приложений
+ Зона нажатия на кольцо
+ Смещение зоны по X
+ Смещение зоны по Y
+ Ширина зоны (0 = авто)
+ Высота зоны (0 = авто)
+ Настройте, если нажатия не попадают по кольцу. Во время настройки показывается граница зоны.
+ Ширина плашки
+ Высота плашки
+ Длина сообщения (строк)
+ Размер шрифта
+ Кольцо при включённом экране
+ Таймер при выключенном экране
+ Таймер при включённом экране
+ Параметры батареи под кольцом
+ Процент заряда (%)
+ Напряжение батареи (В)
+ Сила тока (мА)
+ Мощность (Вт)
+ Нагрузка процессора
+ Показывать нагрузку процессора
+ Префикс «CPU»
+ Положение относительно кольца
+ Размер шрифта CPU
+ Смещение по X
+ Смещение по Y
+ Диагностика
+ Статус разрешений и системы
+ Экспорт отчёта
+ AOD за 24ч: %1$d сессий · %2$dс анимации · %3$dс статики
+ Найдено настроек: %1$d (из них %2$d правил приложений) из версии %3$s.\n\nПрименить и перезаписать текущие настройки?
+ Временная пауза
+ Приостановить индикатор
+ Выкл
+ Пауза · %d мин
+ Приостановлено пользователем
+
diff --git a/app/src/main/res/values-tr/arrays.xml b/app/src/main/res/values-tr/arrays.xml
index 9eadece..5090ebf 100644
--- a/app/src/main/res/values-tr/arrays.xml
+++ b/app/src/main/res/values-tr/arrays.xml
@@ -62,4 +62,24 @@
- Açık
- Sistem
+
+ - Her zaman
+ - 5 sn
+ - 15 sn
+ - 30 sn
+ - 1 dk
+ - 5 dk
+
+
+ - Her zaman
+ - 5 sn
+ - 10 sn
+ - 30 sn
+
+
+ - Altında
+ - Sağda
+ - Solda
+ - Üzerinde
+
diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml
index af94077..2c631a3 100644
--- a/app/src/main/res/values-tr/strings.xml
+++ b/app/src/main/res/values-tr/strings.xml
@@ -342,4 +342,55 @@
İndirme halkayı ↓ okuyla doldurur.
Yükleniyor
Yükleme halkayı ↑ okuyla doldurur.
+ Genişletilebilir mesajlar
+ Genişlet (%d)
+ Genişlet
+ Daralt
+ Tümünü okundu işaretle
+ %1$s · %2$d mesaj
+ Son mesajlar
+ Tamam
+ Teşekkürler!
+ Yoldayım
+ Sonra
+ Mesajları okumak için halkaya dokunun
+ Damla boyutu
+ Uygulama simge boyutu
+ Dokunma yanıt bölgesi
+ Dokunma bölgesi X ofseti
+ Dokunma bölgesi Y ofseti
+ Dokunma bölgesi genişliği (0 = otomatik)
+ Dokunma bölgesi yüksekliği (0 = otomatik)
+ Dokunuşlar halkaya ulaşmıyorsa ayarlayın. Burada yapılandırırken bir kenar dokunma bölgesini gösterir.
+ Mesaj kartı genişliği
+ Mesaj kartı azami yüksekliği
+ Mesaj önizleme satırları
+ Mesaj yazı boyutu
+ Ekran açıkken şarj halkası
+ Şarj zamanlayıcısı (ekran kapalı)
+ Şarj zamanlayıcısı (ekran açık)
+ Halka altında pil istatistikleri
+ Pil yüzdesi (%)
+ Pil voltajı (V)
+ Güncel amper (mA)
+ Şarj gücü (W)
+ İşlemci yükü
+ İşlemci yükünü göster
+ \"CPU\" önekini göster
+ Halkaya göre konum
+ CPU metin boyutu
+ X ofseti
+ Y ofseti
+ Teşhis
+ Sistem durumu ve sağlık
+ Raporu dışa aktar
+ AOD (24 sa): %1$d uyanma · %2$d sn animasyonlu · %3$d sn statik
+ %3$s sürümünden %1$d ayar bulundu (%2$d uygulama kuralı dahil).
+
+Mevcut ayarların üzerine yazılsın mı?
+ Geçici duraklatma
+ LED\'i duraklat (Erteleme)
+ Kapalı
+ Duraklatıldı · %d dk
+ Kullanıcı tarafından duraklatıldı
diff --git a/app/src/main/res/values-zh-rCN/arrays.xml b/app/src/main/res/values-zh-rCN/arrays.xml
index 787c26e..0639676 100644
--- a/app/src/main/res/values-zh-rCN/arrays.xml
+++ b/app/src/main/res/values-zh-rCN/arrays.xml
@@ -62,4 +62,24 @@
- 浅色
- 跟随系统
+
+ - 始终
+ - 5 秒
+ - 15 秒
+ - 30 秒
+ - 1 分钟
+ - 5 分钟
+
+
+ - 始终
+ - 5 秒
+ - 10 秒
+ - 30 秒
+
+
+ - 下方
+ - 右侧
+ - 左侧
+ - 上方
+
diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml
index a0e82a3..a582648 100644
--- a/app/src/main/res/values-zh-rCN/strings.xml
+++ b/app/src/main/res/values-zh-rCN/strings.xml
@@ -342,4 +342,55 @@
下载时光环逐渐填满,并带 ↓ 箭头。
上传中
上传时光环逐渐填满,并带 ↑ 箭头。
+ 可展开的消息
+ 展开(%d)
+ 展开
+ 收起
+ 全部标为已读
+ %1$s · %2$d 条消息
+ 最近消息
+ 好的
+ 谢谢!
+ 马上到
+ 稍后
+ 点按圆环以阅读消息
+ 水滴大小
+ 应用图标大小
+ 点按响应区域
+ 点按区域 X 偏移
+ 点按区域 Y 偏移
+ 点按区域宽度(0 = 自动)
+ 点按区域高度(0 = 自动)
+ 如果点按不到圆环,请在此调整。配置时会以边框显示点按区域。
+ 消息卡片宽度
+ 消息卡片最大高度
+ 消息预览行数
+ 消息字体大小
+ 屏幕点亮时的充电圆环
+ 充电计时器(息屏时)
+ 充电计时器(亮屏时)
+ 圆环下方的电池统计
+ 电池百分比(%)
+ 电池电压(V)
+ 当前电流(mA)
+ 充电功率(W)
+ CPU 负载
+ 显示 CPU 负载
+ 显示“CPU”前缀
+ 相对圆环的位置
+ CPU 文字大小
+ X 偏移
+ Y 偏移
+ 诊断
+ 系统状态与健康
+ 导出报告
+ AOD(24小时):%1$d 次唤醒 · %2$d 秒动画 · %3$d 秒静态
+ 从版本 %3$s 找到 %1$d 项设置(含 %2$d 条应用规则)。
+
+是否覆盖当前设置?
+ 暂时停用
+ 暂停 LED(稍后恢复)
+ 关
+ 已暂停 · %d 分钟
+ 已被用户暂停
diff --git a/app/src/main/res/values/arrays.xml b/app/src/main/res/values/arrays.xml
index 107da1a..227daad 100644
--- a/app/src/main/res/values/arrays.xml
+++ b/app/src/main/res/values/arrays.xml
@@ -75,4 +75,24 @@
- Light
- System
+
+ - Always
+ - 5 s
+ - 15 s
+ - 30 s
+ - 1 min
+ - 5 min
+
+
+ - Always
+ - 5 s
+ - 10 s
+ - 30 s
+
+
+ - Below
+ - Right
+ - Left
+ - Above
+
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 454b3f2..83adcd6 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -154,10 +154,21 @@
Grant notification access first
+ Expandable messages
%1$s · %2$s
New notification
Content hidden
+%d more
+ Expand (%d)
+ Expand
+ Collapse
+ Read all
+ %1$s · %2$d messages
+ Recent messages
+ OK
+ Thanks!
+ On my way
+ Later
Reply
Mark as read
Dismiss
@@ -343,4 +354,43 @@
A download fills the ring, with a ↓ arrow.
Uploading
An upload fills the ring, with a ↑ arrow.
+ Tap ring to read messages
+ Droplet size
+ App icon size
+ Tap response zone
+ Tap zone offset X
+ Tap zone offset Y
+ Tap zone width (0 = auto)
+ Tap zone height (0 = auto)
+ Adjust if taps don\'t reach the ring. A border shows the tap zone while you configure it here.
+ Message plate width
+ Message plate max height
+ Message preview lines
+ Message font size
+ Charging ring while screen on
+ Screen-off charging timer
+ Screen-on charging timer
+ Battery stats under ring
+ Battery percentage (%)
+ Battery voltage (V)
+ Current amperage (mA)
+ Power wattage (W)
+ CPU load
+ Show CPU load
+ Show \"CPU\" prefix
+ Position relative to ring
+ CPU text size
+ Offset X
+ Offset Y
+ Diagnostics
+ System status & health
+ Export report
+ AOD (24h): %1$d wakeups · %2$ds animated · %3$ds static
+ Found %1$d settings (including %2$d app rules) from version %3$s.\n\nOverwrite current settings?
+ Temporary pause
+ Pause LED (Snooze)
+ Off
+ Paused · %d min
+ Paused by user
+
diff --git a/app/src/main/res/xml/backup_rules.xml b/app/src/main/res/xml/backup_rules.xml
new file mode 100644
index 0000000..5b12051
--- /dev/null
+++ b/app/src/main/res/xml/backup_rules.xml
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/app/src/main/res/xml/data_extraction_rules.xml b/app/src/main/res/xml/data_extraction_rules.xml
new file mode 100644
index 0000000..4af8858
--- /dev/null
+++ b/app/src/main/res/xml/data_extraction_rules.xml
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
+
diff --git a/app/src/test/java/com/glowled/app/core/BurnInShiftTest.kt b/app/src/test/java/com/glowled/app/core/BurnInShiftTest.kt
new file mode 100644
index 0000000..cc29610
--- /dev/null
+++ b/app/src/test/java/com/glowled/app/core/BurnInShiftTest.kt
@@ -0,0 +1,55 @@
+package com.glowled.app.core
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class BurnInShiftTest {
+
+ @Test
+ fun shiftsAreBoundedByMaxShiftPx() {
+ val maxShift = 2.5f
+ val interval = 60_000L
+
+ // Check 24 hours of operation minute by minute
+ for (minute in 0 until 1440) {
+ val uptimeMs = minute * interval
+ val (dx, dy) = BurnInShiftCalculator.calculateShift(uptimeMs, maxShift, interval)
+ assertTrue(
+ "Shift ($dx, $dy) exceeded max radius $maxShift at minute $minute",
+ BurnInShiftCalculator.isWithinBounds(dx, dy, maxShift)
+ )
+ }
+ }
+
+ @Test
+ fun shiftsArePeriodicAndDeterministic() {
+ val maxShift = 2f
+ val interval = 60_000L
+
+ val shift0 = BurnInShiftCalculator.calculateShift(0L, maxShift, interval)
+ val shift8 = BurnInShiftCalculator.calculateShift(8 * interval, maxShift, interval)
+ assertEquals(shift0.first, shift8.first, 0.0001f)
+ assertEquals(shift0.second, shift8.second, 0.0001f)
+
+ // At step 0: angle = 0, dx = maxShift, dy = 0
+ assertEquals(maxShift, shift0.first, 0.0001f)
+ assertEquals(0f, shift0.second, 0.0001f)
+
+ // At step 2: angle = 90 deg (PI/2), dx = 0, dy = maxShift
+ val shift2 = BurnInShiftCalculator.calculateShift(2 * interval, maxShift, interval)
+ assertEquals(0f, shift2.first, 0.0001f)
+ assertEquals(maxShift, shift2.second, 0.0001f)
+ }
+
+ @Test
+ fun handlesZeroRadiusOrInterval() {
+ val (dx1, dy1) = BurnInShiftCalculator.calculateShift(100_000L, 0f, 60_000L)
+ assertEquals(0f, dx1, 0.0001f)
+ assertEquals(0f, dy1, 0.0001f)
+
+ val (dx2, dy2) = BurnInShiftCalculator.calculateShift(100_000L, 2f, 0L)
+ assertEquals(0f, dx2, 0.0001f)
+ assertEquals(0f, dy2, 0.0001f)
+ }
+}
diff --git a/app/src/test/java/com/glowled/app/core/CutoutGeometryTest.kt b/app/src/test/java/com/glowled/app/core/CutoutGeometryTest.kt
new file mode 100644
index 0000000..999fd74
--- /dev/null
+++ b/app/src/test/java/com/glowled/app/core/CutoutGeometryTest.kt
@@ -0,0 +1,50 @@
+package com.glowled.app.core
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class CutoutGeometryTest {
+
+ @Test
+ fun classifiesPunchHoleCircle() {
+ val screenW = 1080f
+ // Standard punch hole camera (35x35)
+ val shape = CutoutGeometry.classifyShape(35f, 35f, screenW)
+ assertEquals(CutoutShape.CIRCLE, shape)
+ }
+
+ @Test
+ fun classifiesPillCutout() {
+ val screenW = 1080f
+ // Dual camera or dynamic pill (80x35) -> aspect ratio 2.28 > 1.5
+ val shape = CutoutGeometry.classifyShape(80f, 35f, screenW)
+ assertEquals(CutoutShape.PILL, shape)
+ }
+
+ @Test
+ fun classifiesNotchCutout() {
+ val screenW = 1080f
+ // Wide waterdrop or bar notch (> 20% of screen width = 216px)
+ val shape = CutoutGeometry.classifyShape(250f, 60f, screenW)
+ assertEquals(CutoutShape.NOTCH, shape)
+ }
+
+ @Test
+ fun classifiesBorderlineAspectRatio() {
+ val screenW = 1080f
+ // Exactly 1.5 ratio: 60 / 40 = 1.5 -> CIRCLE (not strictly > 1.5)
+ val shape1 = CutoutGeometry.classifyShape(60f, 40f, screenW)
+ assertEquals(CutoutShape.CIRCLE, shape1)
+
+ // 1.51 ratio: 61 / 40 > 1.5 -> PILL
+ val shape2 = CutoutGeometry.classifyShape(61f, 40f, screenW)
+ assertEquals(CutoutShape.PILL, shape2)
+ }
+
+ @Test
+ fun zeroOrNegativeDimensionsFallbackSafely() {
+ val screenW = 1080f
+ val shape = CutoutGeometry.classifyShape(0f, 0f, screenW)
+ assertEquals(CutoutShape.CIRCLE, shape)
+ }
+}
diff --git a/app/src/test/java/com/glowled/app/core/LedStateMachineTest.kt b/app/src/test/java/com/glowled/app/core/LedStateMachineTest.kt
new file mode 100644
index 0000000..ce6ecd0
--- /dev/null
+++ b/app/src/test/java/com/glowled/app/core/LedStateMachineTest.kt
@@ -0,0 +1,138 @@
+package com.glowled.app.core
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class LedStateMachineTest {
+
+ @Test
+ fun returnsIdleWhenAppDisabled() {
+ val signal = SignalSnapshot(
+ enabled = false,
+ aodEnabled = true,
+ overlayEnabled = true,
+ isInteractive = false,
+ isLocked = true,
+ hasUnreadNotifs = true,
+ overlayLockOnly = false,
+ )
+ val target = LedStateMachine.computeTarget(signal, 120, 0, true)
+ assertEquals(TargetState.Idle, target)
+ }
+
+ @Test
+ fun aodPriorityNotificationsOverCharging() {
+ val signal = SignalSnapshot(
+ enabled = true,
+ aodEnabled = true,
+ overlayEnabled = true,
+ isInteractive = false,
+ isLocked = true,
+ hasUnreadNotifs = true,
+ overlayLockOnly = false,
+ isPlugged = true,
+ chargeLed = true,
+ chargeAod = true,
+ isChargeAodActive = true,
+ )
+ val target = LedStateMachine.computeTarget(signal, 120, 60, true)
+ assertTrue(target is TargetState.Aod)
+ val aod = target as TargetState.Aod
+ assertEquals(AodKind.NOTIFICATION, aod.kind)
+ assertEquals(120, aod.timeoutSec)
+ }
+
+ @Test
+ fun aodChargingAloneUsesChargeTimeout() {
+ val signal = SignalSnapshot(
+ enabled = true,
+ aodEnabled = true,
+ overlayEnabled = true,
+ isInteractive = false,
+ isLocked = true,
+ hasUnreadNotifs = false,
+ overlayLockOnly = false,
+ isPlugged = true,
+ chargeLed = true,
+ chargeAod = true,
+ isChargeAodActive = true,
+ )
+ val target = LedStateMachine.computeTarget(signal, 120, 45, true)
+ assertTrue(target is TargetState.Aod)
+ val aod = target as TargetState.Aod
+ assertEquals(AodKind.CHARGING, aod.kind)
+ assertEquals(45, aod.timeoutSec)
+ }
+
+ @Test
+ fun aodBlockedWhenPowerGuardReasonPresent() {
+ val signal = SignalSnapshot(
+ enabled = true,
+ aodEnabled = true,
+ overlayEnabled = true,
+ isInteractive = false,
+ isLocked = true,
+ hasUnreadNotifs = true,
+ overlayLockOnly = false,
+ blockReason = "Quiet hours",
+ )
+ val target = LedStateMachine.computeTarget(signal, 120, 0, true)
+ assertTrue(target is TargetState.Blocked)
+ assertEquals("Quiet hours", (target as TargetState.Blocked).reason)
+ }
+
+ @Test
+ fun screenOnOverlayShowsCpuAndBatteryWhenEnabled() {
+ val signal = SignalSnapshot(
+ enabled = true,
+ aodEnabled = true,
+ overlayEnabled = true,
+ isInteractive = true,
+ isLocked = false,
+ hasUnreadNotifs = false,
+ overlayLockOnly = false,
+ cpuIndicator = true,
+ batteryIndicator = true,
+ )
+ val target = LedStateMachine.computeTarget(signal, 120, 0, true)
+ assertTrue(target is TargetState.Overlay)
+ val overlay = target as TargetState.Overlay
+ assertEquals(false, overlay.showNotifRing)
+ assertEquals(false, overlay.showMeter)
+ assertEquals(true, overlay.showBattery)
+ assertEquals(true, overlay.showCpu)
+ }
+
+ @Test
+ fun screenOnOverlayLockOnlyHidesRingWhenUnlocked() {
+ val signal = SignalSnapshot(
+ enabled = true,
+ aodEnabled = true,
+ overlayEnabled = true,
+ isInteractive = true,
+ isLocked = false, // unlocked!
+ hasUnreadNotifs = true,
+ overlayLockOnly = true, // lock only!
+ )
+ val target = LedStateMachine.computeTarget(signal, 120, 0, true)
+ assertEquals(TargetState.Idle, target)
+ }
+
+ @Test
+ fun screenOnOverlayLockOnlyShowsRingWhenLocked() {
+ val signal = SignalSnapshot(
+ enabled = true,
+ aodEnabled = true,
+ overlayEnabled = true,
+ isInteractive = true,
+ isLocked = true, // locked!
+ hasUnreadNotifs = true,
+ overlayLockOnly = true, // lock only!
+ )
+ val target = LedStateMachine.computeTarget(signal, 120, 0, true)
+ assertTrue(target is TargetState.Overlay)
+ val overlay = target as TargetState.Overlay
+ assertEquals(true, overlay.showNotifRing)
+ }
+}
diff --git a/app/src/test/java/com/glowled/app/core/LogicTest.kt b/app/src/test/java/com/glowled/app/core/LogicTest.kt
index 5573d5f..6d22874 100644
--- a/app/src/test/java/com/glowled/app/core/LogicTest.kt
+++ b/app/src/test/java/com/glowled/app/core/LogicTest.kt
@@ -1,75 +1,9 @@
package com.glowled.app.core
-import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
-import org.junit.Before
import org.junit.Test
-class NotificationStoreTest {
-
- @Before
- fun reset() = NotificationStore.clear()
-
- @Test
- fun colorsAreNewestFirstAndDistinct() {
- NotificationStore.put(NotificationStore.Entry("a", "p1", 0xFFFF0000.toInt(), 1))
- NotificationStore.put(NotificationStore.Entry("b", "p2", 0xFF00FF00.toInt(), 3))
- NotificationStore.put(NotificationStore.Entry("c", "p1", 0xFFFF0000.toInt(), 2))
- assertArrayEquals(intArrayOf(0xFF00FF00.toInt(), 0xFFFF0000.toInt()), NotificationStore.colors())
- }
-
- @Test
- fun repostedSeenNotificationLightsAgain() {
- // e.g. "clear after unlock", then the same WhatsApp chat (same key) gets a new message.
- NotificationStore.put(NotificationStore.Entry("a", "p", 1, 1))
- NotificationStore.markAllSeen()
- NotificationStore.put(NotificationStore.Entry("a", "p", 1, 1))
- assertTrue(NotificationStore.isEmpty()) // a silent update stays seen
- assertTrue(NotificationStore.put(NotificationStore.Entry("a", "p", 1, 2), alert = true))
- assertFalse(NotificationStore.isEmpty())
- }
-
- @Test
- fun seenNotificationsDoNotLight() {
- NotificationStore.put(NotificationStore.Entry("a", "p", 1, 1))
- NotificationStore.markAllSeen()
- assertTrue(NotificationStore.isEmpty())
- NotificationStore.put(NotificationStore.Entry("b", "p", 2, 2))
- assertFalse(NotificationStore.isEmpty())
- assertArrayEquals(intArrayOf(2), NotificationStore.colors())
- }
-
- @Test
- fun appsAreGroupedNewestFirstWithCounts() {
- NotificationStore.put(NotificationStore.Entry("a1", "chat", 1, 1))
- NotificationStore.put(NotificationStore.Entry("b1", "mail", 2, 2))
- NotificationStore.put(NotificationStore.Entry("a2", "chat", 1, 3))
- val apps = NotificationStore.apps()
- org.junit.Assert.assertEquals(listOf("chat", "mail"), apps.map { it.pkg })
- org.junit.Assert.assertEquals(listOf(2, 1), apps.map { it.count })
- NotificationStore.markAllSeen()
- assertTrue(NotificationStore.apps().isEmpty())
- }
-
- @Test
- fun replaceAllReportsChangesOnly() {
- val list = listOf(NotificationStore.Entry("a", "p", 1, 1))
- assertTrue(NotificationStore.replaceAll(list))
- assertFalse(NotificationStore.replaceAll(list))
- assertTrue(NotificationStore.replaceAll(emptyList()))
- }
-
- @Test
- fun putReportsNewOrRecoloured() {
- assertTrue(NotificationStore.put(NotificationStore.Entry("a", "p", 1, 1)))
- assertFalse(NotificationStore.put(NotificationStore.Entry("a", "p", 1, 5)))
- assertTrue(NotificationStore.put(NotificationStore.Entry("a", "p", 2, 6)))
- assertTrue(NotificationStore.remove("a"))
- assertFalse(NotificationStore.remove("a"))
- }
-}
-
class NotificationContentTest {
@Test
fun mediaKindFromText() {
@@ -115,3 +49,109 @@ class QuietHoursTest {
@Test
fun emptyWindowNeverMatches() = assertFalse(PowerGuard.inWindow(0, 600, 600))
}
+
+class BatteryStatsTest {
+ @Test
+ fun formatsSelectedMetricsProperly() {
+ val info = BatteryInfo(
+ level = 85,
+ voltageMv = 4250,
+ currentMa = 1500,
+ powerWatts = 6.375f,
+ isCharging = true,
+ )
+ // All metrics enabled: 2 lines
+ val all = info.formatString(showPercent = true, showVoltage = true, showCurrent = true, showPower = true)
+ org.junit.Assert.assertEquals("85% · 4.25V\n1500 mA · 6.4W", all)
+
+ // Only percent and voltage
+ val pv = info.formatString(showPercent = true, showVoltage = true, showCurrent = false, showPower = false)
+ org.junit.Assert.assertEquals("85% · 4.25V", pv)
+
+ // Only current and power
+ val cp = info.formatString(showPercent = false, showVoltage = false, showCurrent = true, showPower = true)
+ org.junit.Assert.assertEquals("1500 mA · 6.4W", cp)
+
+ // None enabled
+ val none = info.formatString(showPercent = false, showVoltage = false, showCurrent = false, showPower = false)
+ org.junit.Assert.assertNull(none)
+ }
+
+ @Test
+ fun handlesZeroAndNegativeEdgeCases() {
+ val info = BatteryInfo(
+ level = -1, // invalid level
+ voltageMv = 0, // no voltage
+ currentMa = -500, // discharging
+ powerWatts = 0.02f, // too low power (< 0.05W)
+ isCharging = false,
+ )
+ // Level -1 and voltage 0 should be omitted from row1.
+ // Current -500 should show as 500 mA, power 0.02 should be omitted.
+ val res = info.formatString(showPercent = true, showVoltage = true, showCurrent = true, showPower = true)
+ org.junit.Assert.assertEquals("500 mA", res)
+ }
+}
+
+class NotifyListenerReadWordsTest {
+ @Test
+ fun matchesReadActionsInMultipleLanguages() {
+ val regex = com.glowled.app.service.NotifyListenerService.READ_WORDS
+ assertTrue(regex.containsMatchIn("read"))
+ assertTrue(regex.containsMatchIn("Mark as read"))
+ assertTrue(regex.containsMatchIn("lida"))
+ assertTrue(regex.containsMatchIn("marcar como lido"))
+ assertTrue(regex.containsMatchIn("Прочитано"))
+ assertTrue(regex.containsMatchIn("прочитать"))
+ assertTrue(regex.containsMatchIn("Отметить как прочитанное"))
+ }
+
+ @Test
+ fun doesNotMatchNonReadActions() {
+ val regex = com.glowled.app.service.NotifyListenerService.READ_WORDS
+ assertFalse(regex.containsMatchIn("reply"))
+ assertFalse(regex.containsMatchIn("ответить"))
+ assertFalse(regex.containsMatchIn("удалить"))
+ assertFalse(regex.containsMatchIn("archive"))
+ }
+}
+
+class CpuStatsTest {
+ @Test
+ fun parseTopLineModernToybox() {
+ val line = "800%cpu 125%user 0%nice 68%sys 600%idle 0%iow 5%irq 2%sirq 0%host"
+ val usage = CpuStats.parseTopLine(line)
+ org.junit.Assert.assertEquals(25, usage)
+ }
+
+ @Test
+ fun parseTopLineLegacyFormat() {
+ val line = "User 25%, System 10%, IOW 0%, IRQ 2%"
+ val usage = CpuStats.parseTopLine(line)
+ org.junit.Assert.assertEquals(37, usage)
+ }
+
+ @Test
+ fun parseTopLineInvalidReturnsMinusOne() {
+ val line = "unknown output format"
+ val usage = CpuStats.parseTopLine(line)
+ org.junit.Assert.assertEquals(-1, usage)
+ }
+
+ @Test
+ fun parseTopLineWithAnsiCodes() {
+ val line = "\u001B[7m800%cpu\u001B[0m 100%user 0%nice 50%sys \u001B[1m650%idle\u001B[0m 0%iow"
+ val usage = CpuStats.parseTopLine(line)
+ org.junit.Assert.assertEquals(18, usage)
+ }
+
+ @Test
+ fun parseProcStatDelta() {
+ val line1 = "cpu 1000 200 300 8000 50 10 20 0 0 0"
+ CpuStats.parseProcStatLine(line1)
+
+ val line2 = "cpu 1030 210 310 8050 50 10 20 0 0 0"
+ val usage = CpuStats.parseProcStatLine(line2)
+ org.junit.Assert.assertEquals(50, usage)
+ }
+}
diff --git a/app/src/test/java/com/glowled/app/core/NotificationStoreTest.kt b/app/src/test/java/com/glowled/app/core/NotificationStoreTest.kt
new file mode 100644
index 0000000..717b455
--- /dev/null
+++ b/app/src/test/java/com/glowled/app/core/NotificationStoreTest.kt
@@ -0,0 +1,148 @@
+package com.glowled.app.core
+
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
+import java.util.concurrent.atomic.AtomicInteger
+
+class NotificationStoreTest {
+
+ @Before
+ fun reset() = NotificationStore.clear()
+
+ @Test
+ fun colorsAreNewestFirstAndDistinct() {
+ NotificationStore.put(NotificationStore.Entry("a", "p1", 0xFFFF0000.toInt(), 1))
+ NotificationStore.put(NotificationStore.Entry("b", "p2", 0xFF00FF00.toInt(), 3))
+ NotificationStore.put(NotificationStore.Entry("c", "p1", 0xFFFF0000.toInt(), 2))
+ assertArrayEquals(intArrayOf(0xFF00FF00.toInt(), 0xFFFF0000.toInt()), NotificationStore.colors())
+ }
+
+ @Test
+ fun repostedSeenNotificationLightsAgain() {
+ // e.g. "clear after unlock", then the same WhatsApp chat (same key) gets a new message.
+ NotificationStore.put(NotificationStore.Entry("a", "p", 1, 1))
+ NotificationStore.markAllSeen()
+ NotificationStore.put(NotificationStore.Entry("a", "p", 1, 1))
+ assertTrue(NotificationStore.isEmpty()) // a silent update stays seen
+ assertTrue(NotificationStore.put(NotificationStore.Entry("a", "p", 1, 2), alert = true))
+ assertFalse(NotificationStore.isEmpty())
+ }
+
+ @Test
+ fun seenNotificationsDoNotLight() {
+ NotificationStore.put(NotificationStore.Entry("a", "p", 1, 1))
+ NotificationStore.markAllSeen()
+ assertTrue(NotificationStore.isEmpty())
+ NotificationStore.put(NotificationStore.Entry("b", "p", 2, 2))
+ assertFalse(NotificationStore.isEmpty())
+ assertArrayEquals(intArrayOf(2), NotificationStore.colors())
+ }
+
+ @Test
+ fun appsAreGroupedNewestFirstWithCounts() {
+ NotificationStore.put(NotificationStore.Entry("a1", "chat", 1, 1))
+ NotificationStore.put(NotificationStore.Entry("b1", "mail", 2, 2))
+ NotificationStore.put(NotificationStore.Entry("a2", "chat", 1, 3))
+ val apps = NotificationStore.apps()
+ assertEquals(listOf("chat", "mail"), apps.map { it.pkg })
+ assertEquals(listOf(2, 1), apps.map { it.count })
+ NotificationStore.markAllSeen()
+ assertTrue(NotificationStore.apps().isEmpty())
+ }
+
+ @Test
+ fun replaceAllReportsChangesOnly() {
+ val list = listOf(NotificationStore.Entry("a", "p", 1, 1))
+ assertTrue(NotificationStore.replaceAll(list))
+ assertFalse(NotificationStore.replaceAll(list))
+ assertTrue(NotificationStore.replaceAll(emptyList()))
+ }
+
+ @Test
+ fun putReportsNewOrRecoloured() {
+ assertTrue(NotificationStore.put(NotificationStore.Entry("a", "p", 1, 1)))
+ assertFalse(NotificationStore.put(NotificationStore.Entry("a", "p", 1, 5)))
+ assertTrue(NotificationStore.put(NotificationStore.Entry("a", "p", 2, 6)))
+ assertTrue(NotificationStore.remove("a"))
+ assertFalse(NotificationStore.remove("a"))
+ }
+
+ @Test
+ fun individualMarkSeenAndEntriesForApp() {
+ NotificationStore.put(NotificationStore.Entry("k1", "pkg1", 10, 100, title = "First"))
+ NotificationStore.put(NotificationStore.Entry("k2", "pkg1", 10, 200, title = "Second"))
+ NotificationStore.put(NotificationStore.Entry("k3", "pkg2", 20, 150, title = "Other"))
+
+ // Entries for pkg1 should be ordered newest first (k2 then k1)
+ val entries = NotificationStore.entriesFor("pkg1")
+ assertEquals(2, entries.size)
+ assertEquals("k2", entries[0].key)
+ assertEquals("k1", entries[1].key)
+
+ // Mark k2 as seen
+ NotificationStore.markSeen("k2")
+ val remaining = NotificationStore.entriesFor("pkg1")
+ assertEquals(1, remaining.size)
+ assertEquals("k1", remaining[0].key)
+
+ // Newest unseen time should be k3 (150)
+ assertEquals(150L, NotificationStore.newestTime())
+ }
+
+ @Test
+ fun concurrentAccessDoesNotThrowOrCorrupt() {
+ val threadCount = 8
+ val iterationsPerThread = 50
+ val latch = CountDownLatch(threadCount)
+ val errors = AtomicInteger(0)
+
+ for (t in 0 until threadCount) {
+ Thread {
+ try {
+ for (i in 0 until iterationsPerThread) {
+ val key = "key_${t}_$i"
+ NotificationStore.put(NotificationStore.Entry(key, "pkg_$t", t + 1, System.currentTimeMillis()))
+ NotificationStore.colors()
+ NotificationStore.apps()
+ if (i % 2 == 0) NotificationStore.markSeen(key)
+ if (i % 5 == 0) NotificationStore.remove(key)
+ }
+ } catch (e: Exception) {
+ errors.incrementAndGet()
+ } finally {
+ latch.countDown()
+ }
+ }.start()
+ }
+
+ assertTrue(latch.await(5, TimeUnit.SECONDS))
+ assertEquals(0, errors.get())
+ }
+
+ @Test
+ fun priorityEntriesTakePrecedenceOverNewerRegularEntries() {
+ // Regular notification arrived at t=200 with color 0x00FF00
+ NotificationStore.put(NotificationStore.Entry("reg", "pkg_reg", 0x00FF00, 200, isPriority = false))
+ // Priority notification arrived earlier at t=100 with color 0xFF0000
+ NotificationStore.put(NotificationStore.Entry("prio", "pkg_prio", 0xFF0000, 100, isPriority = true))
+
+ // In colors: priority color (0xFF0000) must appear before regular (0x00FF00)
+ val colors = NotificationStore.colors()
+ assertEquals(2, colors.size)
+ assertEquals(0xFF0000, colors[0])
+ assertEquals(0x00FF00, colors[1])
+
+ // In apps: priority app must appear first
+ val apps = NotificationStore.apps()
+ assertEquals(2, apps.size)
+ assertEquals("pkg_prio", apps[0].pkg)
+ assertEquals("pkg_reg", apps[1].pkg)
+ }
+}
+
diff --git a/app/src/test/java/com/glowled/app/core/PowerGuardTest.kt b/app/src/test/java/com/glowled/app/core/PowerGuardTest.kt
new file mode 100644
index 0000000..3fa1b0d
--- /dev/null
+++ b/app/src/test/java/com/glowled/app/core/PowerGuardTest.kt
@@ -0,0 +1,81 @@
+package com.glowled.app.core
+
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class PowerGuardTest {
+
+ @Test
+ fun regularWindowInsideAndOutside() {
+ // Window from 12:00 (720 min) to 14:00 (840 min)
+ val start = 12 * 60
+ val end = 14 * 60
+
+ // Exact start is inclusive
+ assertTrue(PowerGuard.inWindow(start, start, end))
+ // Inside
+ assertTrue(PowerGuard.inWindow(13 * 60, start, end))
+ assertTrue(PowerGuard.inWindow(839, start, end))
+ // Exact end is exclusive
+ assertFalse(PowerGuard.inWindow(end, start, end))
+ // Before start
+ assertFalse(PowerGuard.inWindow(719, start, end))
+ // Way after
+ assertFalse(PowerGuard.inWindow(18 * 60, start, end))
+ }
+
+ @Test
+ fun overnightWindowSpanningMidnight() {
+ // Window from 23:00 (1380 min) to 07:00 (420 min)
+ val start = 23 * 60
+ val end = 7 * 60
+
+ // Exact start is inclusive
+ assertTrue(PowerGuard.inWindow(start, start, end))
+ // Late night
+ assertTrue(PowerGuard.inWindow(23 * 60 + 30, start, end))
+ assertTrue(PowerGuard.inWindow(23 * 60 + 59, start, end))
+ // Midnight exact
+ assertTrue(PowerGuard.inWindow(0, start, end))
+ // Early morning
+ assertTrue(PowerGuard.inWindow(3 * 60, start, end))
+ assertTrue(PowerGuard.inWindow(7 * 60 - 1, start, end))
+ // Exact end is exclusive
+ assertFalse(PowerGuard.inWindow(end, start, end))
+ // Daytime
+ assertFalse(PowerGuard.inWindow(12 * 60, start, end))
+ assertFalse(PowerGuard.inWindow(22 * 60 + 59, start, end))
+ }
+
+ @Test
+ fun emptyWindowNeverMatches() {
+ assertFalse(PowerGuard.inWindow(0, 600, 600))
+ assertFalse(PowerGuard.inWindow(600, 600, 600))
+ assertFalse(PowerGuard.inWindow(1200, 600, 600))
+ }
+
+ @Test
+ fun boundaryMinuteValues() {
+ // Whole day window minus one minute: 00:00 to 23:59
+ assertTrue(PowerGuard.inWindow(0, 0, 1439))
+ assertTrue(PowerGuard.inWindow(1200, 0, 1439))
+ assertFalse(PowerGuard.inWindow(1439, 0, 1439))
+ }
+
+ @Test
+ fun snoozeActiveAndExpired() {
+ val now = 1_000_000L
+ // Zero or negative -> not snoozed
+ assertFalse(PowerGuard.isSnoozed(0L, now))
+ assertFalse(PowerGuard.isSnoozed(-1L, now))
+
+ // Paused until future -> snoozed
+ assertTrue(PowerGuard.isSnoozed(now + 60_000L, now))
+
+ // Paused until past or exact now -> expired
+ assertFalse(PowerGuard.isSnoozed(now, now))
+ assertFalse(PowerGuard.isSnoozed(now - 1000L, now))
+ }
+}
+
diff --git a/app/src/test/java/com/glowled/app/core/UpdaterTest.kt b/app/src/test/java/com/glowled/app/core/UpdaterTest.kt
index ebf6c84..a1df99a 100644
--- a/app/src/test/java/com/glowled/app/core/UpdaterTest.kt
+++ b/app/src/test/java/com/glowled/app/core/UpdaterTest.kt
@@ -6,13 +6,21 @@ import org.junit.Assert.assertTrue
import org.junit.Test
class UpdaterTest {
+ @Test fun repoUrlsMatchBuildConfig() {
+ assertEquals("mx57/LED", Updater.UPDATE_REPO)
+ assertEquals("https://api.github.com/repos/mx57/LED/releases/latest", Updater.API)
+ assertEquals("https://github.com/mx57/LED/releases", Updater.RELEASES_PAGE)
+ }
+
@Test fun comparesVersionsNumerically() {
assertTrue(Updater.isNewer("2.8.0", "2.7.0"))
assertTrue(Updater.isNewer("v2.10.0", "2.9.9"))
+ assertTrue(Updater.isNewer("2.11.0", "2.10.1"))
assertTrue(Updater.isNewer("3.0", "2.99.1"))
assertFalse(Updater.isNewer("2.7.0", "2.7.0"))
assertFalse(Updater.isNewer("2.7.0", "2.7.0-debug"))
assertFalse(Updater.isNewer("2.6.9", "2.7.0"))
+ assertFalse(Updater.isNewer("2.10.1", "2.11.0"))
}
@Test fun releaseNotesBecomePlainText() {
diff --git a/app/src/test/java/com/glowled/app/util/SettingsBackupTest.kt b/app/src/test/java/com/glowled/app/util/SettingsBackupTest.kt
new file mode 100644
index 0000000..2b06adb
--- /dev/null
+++ b/app/src/test/java/com/glowled/app/util/SettingsBackupTest.kt
@@ -0,0 +1,217 @@
+package com.glowled.app.util
+
+import android.content.SharedPreferences
+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 class FakeEditor(private val map: MutableMap) : SharedPreferences.Editor {
+ private val temp = mutableMapOf()
+ private val removed = mutableSetOf()
+
+ override fun putString(key: String, value: String?): SharedPreferences.Editor {
+ temp[key] = value; removed.remove(key); return this
+ }
+ override fun putStringSet(key: String, values: Set?): SharedPreferences.Editor {
+ temp[key] = values; removed.remove(key); return this
+ }
+ override fun putInt(key: String, value: Int): SharedPreferences.Editor {
+ temp[key] = value; removed.remove(key); return this
+ }
+ override fun putLong(key: String, value: Long): SharedPreferences.Editor {
+ temp[key] = value; removed.remove(key); return this
+ }
+ override fun putFloat(key: String, value: Float): SharedPreferences.Editor {
+ temp[key] = value; removed.remove(key); return this
+ }
+ override fun putBoolean(key: String, value: Boolean): SharedPreferences.Editor {
+ temp[key] = value; removed.remove(key); return this
+ }
+ override fun remove(key: String): SharedPreferences.Editor {
+ removed.add(key); temp.remove(key); return this
+ }
+ override fun clear(): SharedPreferences.Editor {
+ removed.addAll(map.keys); temp.clear(); return this
+ }
+ override fun commit(): Boolean {
+ apply()
+ return true
+ }
+ override fun apply() {
+ removed.forEach { map.remove(it) }
+ temp.forEach { (k, v) -> map[k] = v }
+ temp.clear()
+ removed.clear()
+ }
+ }
+
+ private class FakeSharedPreferences(val map: MutableMap = mutableMapOf()) : SharedPreferences {
+ override fun getAll(): MutableMap = map
+ override fun getString(key: String, defValue: String?): String? = (map[key] as? String) ?: defValue
+ @Suppress("UNCHECKED_CAST")
+ override fun getStringSet(key: String, defValues: Set?): Set? = (map[key] as? Set) ?: defValues
+ override fun getInt(key: String, defValue: Int): Int = (map[key] as? Int) ?: defValue
+ override fun getLong(key: String, defValue: Long): Long = (map[key] as? Long) ?: defValue
+ override fun getFloat(key: String, defValue: Float): Float = (map[key] as? Float) ?: defValue
+ override fun getBoolean(key: String, defValue: Boolean): Boolean = (map[key] as? Boolean) ?: defValue
+ override fun contains(key: String): Boolean = map.containsKey(key)
+ override fun edit(): SharedPreferences.Editor = FakeEditor(map)
+ override fun registerOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener?) {}
+ override fun unregisterOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener?) {}
+ }
+
+ @Test
+ fun serializesPreferencesExcludingSkipKeys() {
+ val sp = FakeSharedPreferences(mutableMapOf(
+ "enabled" to true,
+ "speed" to 5,
+ "thickness" to 4,
+ "app_theme" to "dark",
+ "aod_window_blocked" to true, // should be skipped
+ "transfer_apps" to "org.telegram.messenger", // should be skipped
+ "update_latest" to "2.12.0", // should be skipped
+ ))
+
+ val json = SettingsBackup.serialize(sp, "2.11.0")
+ assertEquals("glowled", json.getString("_app"))
+ assertEquals(2, json.getInt("_version"))
+ assertEquals("2.11.0", json.getString("appVersion"))
+ assertTrue(json.has("exportedAt"))
+
+ val prefs = json.getJSONObject("prefs")
+ assertTrue(prefs.has("enabled"))
+ assertTrue(prefs.has("speed"))
+ assertTrue(prefs.has("thickness"))
+ assertTrue(prefs.has("app_theme"))
+
+ assertFalse(prefs.has("aod_window_blocked"))
+ assertFalse(prefs.has("transfer_apps"))
+ assertFalse(prefs.has("update_latest"))
+ }
+
+ @Test
+ fun restoresValidPreferences() {
+ val sp = FakeSharedPreferences()
+ val jsonText = """
+ {
+ "_app": "glowled",
+ "_version": 2,
+ "prefs": {
+ "enabled": { "t": "b", "v": true },
+ "speed": { "t": "i", "v": 7 },
+ "app_theme": { "t": "s", "v": "light" }
+ }
+ }
+ """.trimIndent()
+
+ val count = SettingsBackup.restoreFromJson(sp, jsonText)
+ assertEquals(3, count)
+ assertEquals(true, sp.getBoolean("enabled", false))
+ assertEquals(7, sp.getInt("speed", 0))
+ assertEquals("light", sp.getString("app_theme", ""))
+ }
+
+ @Test
+ fun ignoresSkipKeysDuringRestore() {
+ val sp = FakeSharedPreferences()
+ val jsonText = """
+ {
+ "_app": "glowled",
+ "_version": 2,
+ "prefs": {
+ "enabled": { "t": "b", "v": true },
+ "aod_window_blocked": { "t": "b", "v": true },
+ "update_latest": { "t": "s", "v": "9.9.9" }
+ }
+ }
+ """.trimIndent()
+
+ val count = SettingsBackup.restoreFromJson(sp, jsonText)
+ assertEquals(1, count)
+ assertEquals(true, sp.getBoolean("enabled", false))
+ assertFalse(sp.contains("aod_window_blocked"))
+ assertFalse(sp.contains("update_latest"))
+ }
+
+ @Test
+ fun handlesCorruptedAndUnknownEntriesGracefully() {
+ val sp = FakeSharedPreferences()
+ val jsonText = """
+ {
+ "_app": "glowled",
+ "_version": 2,
+ "prefs": {
+ "valid_key": { "t": "i", "v": 42 },
+ "unknown_type": { "t": "unknown", "v": 100 },
+ "missing_value": { "t": "s" },
+ "corrupted_object": "not a json object"
+ }
+ }
+ """.trimIndent()
+
+ val count = SettingsBackup.restoreFromJson(sp, jsonText)
+ assertEquals(1, count)
+ assertEquals(42, sp.getInt("valid_key", 0))
+ }
+
+ @Test
+ fun rejectsInvalidOrForeignJson() {
+ val sp = FakeSharedPreferences()
+ // Non-glowled json
+ assertEquals(-1, SettingsBackup.restoreFromJson(sp, """{"_app": "otherapp"}"""))
+ // Empty text
+ assertEquals(-1, SettingsBackup.restoreFromJson(sp, ""))
+ // Broken JSON
+ assertEquals(-1, SettingsBackup.restoreFromJson(sp, "{ broken json"))
+ }
+
+ @Test
+ fun inspectsBackupSummaryAccurately() {
+ val jsonText = """
+ {
+ "_app": "glowled",
+ "_version": 1,
+ "appVersion": "2.10.0",
+ "exportedAt": 1700000000000,
+ "prefs": {
+ "enabled": { "t": "b", "v": true },
+ "speed": { "t": "i", "v": 5 },
+ "app_en_com.whatsapp": { "t": "b", "v": true },
+ "app_color_com.whatsapp": { "t": "i", "v": 12345 },
+ "aod_window_blocked": { "t": "b", "v": true },
+ "malformed": "bad"
+ }
+ }
+ """.trimIndent()
+
+ val summary = SettingsBackup.inspect(jsonText)
+ assertTrue(summary.isValid)
+ assertEquals(1, summary.schemaVersion)
+ assertEquals("2.10.0", summary.appVersion)
+ assertEquals(1700000000000L, summary.exportedAt)
+ assertEquals(4, summary.validSettingsCount) // enabled, speed, app_en, app_color
+ assertEquals(2, summary.appRulesCount) // app_en, app_color
+ assertEquals(2, summary.skippedKeysCount) // aod_window_blocked, malformed
+ }
+
+ @Test
+ fun migratesV1ToV2Successfully() {
+ val v1Json = JSONObject("""
+ {
+ "_app": "glowled",
+ "_version": 1,
+ "prefs": {
+ "enabled": { "t": "b", "v": true }
+ }
+ }
+ """.trimIndent())
+
+ val migrated = SettingsBackup.migrate(v1Json, 1)
+ assertEquals(2, migrated.getInt("schemaVersion"))
+ }
+}
+
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index d4081da..37f853b 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
diff --git a/releases/GlowLED-latest.apk b/releases/GlowLED-latest.apk
deleted file mode 100644
index fad7e13..0000000
Binary files a/releases/GlowLED-latest.apk and /dev/null differ
diff --git a/releases/GlowLED-v2.10.1.apk b/releases/GlowLED-v2.10.1.apk
deleted file mode 100644
index fad7e13..0000000
Binary files a/releases/GlowLED-v2.10.1.apk and /dev/null differ
diff --git a/releases/README.md b/releases/README.md
deleted file mode 100644
index 1b89a4c..0000000
--- a/releases/README.md
+++ /dev/null
@@ -1,54 +0,0 @@
-# Download Glow LED
-
-| File | What it is |
-|---|---|
-| [`GlowLED-latest.apk`](GlowLED-latest.apk) | Always the newest version. **Download this one.** |
-| `GlowLED-v2.10.1.apk` | The same build, named by version. |
-| [`SHA256SUMS.txt`](SHA256SUMS.txt) | Checksums, if you want to verify the download. |
-
-## ✅ This is a signed build
-
-Every APK in this folder is signed with the official Glow LED release key:
-
-```
-SHA-256: 5D:04:DE:1A:96:A8:01:07:EC:87:65:83:82:B0:63:F1:5C:53:CF:EA:80:43:F5:54:A3:39:F2:85:FE:0C:50:23
-```
-
-Android only installs an update over an app signed with the **same** key. All builds here use
-this key, so **from now on every new version installs straight over the old one** and keeps
-your settings.
-
-## Install or update
-
-1. Download **`GlowLED-latest.apk`** (on GitHub tap the file, then **Download raw file** / the ⬇ icon).
-2. Open it and tap **Install** (or **Update**). Allow "Install unknown apps" for your browser or
- file manager if asked.
-3. Open Glow LED and follow the **Setup** tab.
-
-## "App not installed" / "Invalid package" / "Package conflicts"?
-
-This happens **only once**, if the Glow LED on your phone came from an older build signed with a
-different key (the early v1.0.0–v1.2.0 GitHub releases). Fix it like this:
-
-1. *(Optional)* Save your settings first: Glow LED → **Settings** tab → **Back up settings**.
-2. Uninstall the old app: long-press the **Glow LED** icon → **App info** → **Uninstall**
- (or *Settings → Apps → Glow LED → Uninstall*).
-3. Install `GlowLED-latest.apk` again.
-4. *(Optional)* Glow LED → **Settings** → **Restore settings** and pick the file you saved.
-
-After this one-time reinstall, every future update installs over it normally.
-
-**Updating:** from v2.8.0 on, Glow LED → **Settings → Updates** downloads and installs new versions
-itself (it only accepts files signed with the official key).
-
-## Android 13+ "Restricted setting"
-
-Apps installed from an APK file can't turn on Notification access / Accessibility until you allow
-it: *App info → ⋮ (top right) → Allow restricted settings*.
-
-## "App blocked to protect your device"
-
-Play Protect's fraud protection (India and some other countries) blocks apps installed from a
-browser or file manager when they ask for Notification access, which Glow LED needs. Install with
-`adb install GlowLED-latest.apk` from a computer, or pause *Play Store → profile → Play Protect →
-⚙ → Scan apps with Play Protect*, install, and turn it back on right away.
diff --git a/releases/SHA256SUMS.txt b/releases/SHA256SUMS.txt
deleted file mode 100644
index 35b64ba..0000000
--- a/releases/SHA256SUMS.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-1a20e75bff56b371824ab4b4b8e4eaa77b05ff03587935b37cd6408f3a296621 GlowLED-latest.apk
-1a20e75bff56b371824ab4b4b8e4eaa77b05ff03587935b37cd6408f3a296621 GlowLED-v2.10.1.apk
diff --git a/settings.gradle.kts b/settings.gradle.kts
index b505a6f..576b091 100644
--- a/settings.gradle.kts
+++ b/settings.gradle.kts
@@ -1,15 +1,14 @@
pluginManagement {
repositories {
google()
- mavenCentral()
- gradlePluginPortal()
+ maven("https://mirrors.cloud.tencent.com/nexus/repository/maven-public/")
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
- mavenCentral()
+ maven("https://mirrors.cloud.tencent.com/nexus/repository/maven-public/")
}
}
rootProject.name = "GlowLED"
diff --git a/tools/ci.yml b/tools/ci.yml
new file mode 100644
index 0000000..7e7c256
--- /dev/null
+++ b/tools/ci.yml
@@ -0,0 +1,23 @@
+name: CI
+
+on:
+ push:
+ branches: ["**"]
+ pull_request:
+ branches: [main]
+
+jobs:
+ test-and-lint:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-java@v4
+ with:
+ distribution: temurin
+ java-version: "17"
+
+ - uses: gradle/actions/setup-gradle@v4
+
+ - name: Run unit tests & lint
+ run: ./gradlew --no-daemon testDebugUnitTest lintDebug