From 6b0200728ab6bb5bdde92837ee1dd655d49f40b2 Mon Sep 17 00:00:00 2001 From: FacuM Date: Tue, 17 Nov 2026 12:33:48 -0300 Subject: [PATCH 1/7] Add pixel shift and a wake threshold for the screensaver Pixel shift protects OLED screens from fixed parts of the picture: the stream moves by one pixel at most every 60 s, only 3 s after the last pointer event with no pointer down and no stylus hovering, or while the screensaver covers it. MainActivity translates a layer above the stage and takes the offset out of every position before it reaches the input engine, so the mapping stays exact with and without the local zoom. A switch and a distance slider (1 to 8 px) are in the Display section; it is on by default only for OLED. The screensaver no longer wakes on any new frame. The stream surface is sampled and the screen wakes when the changed part of the picture reaches the wake threshold (a new setting, default 50 %), or when the PC cursor appears or moves inside the tablet screen. --- android/AGENTS.md | 16 +- .../com/librestatic/ezdisplay/InputPrefs.kt | 12 ++ .../com/librestatic/ezdisplay/MainActivity.kt | 111 ++++++++++++- .../ezdisplay/display/PixelShift.kt | 127 +++++++++++++++ .../ezdisplay/screensaver/IdleTracker.kt | 47 ++++-- .../screensaver/ScreenChangeDetector.kt | 51 ++++++ .../ezdisplay/screensaver/ScreensaverPrefs.kt | 10 ++ .../ezdisplay/settings/DisplaySection.kt | 115 ++++++++++++- .../ezdisplay/settings/SettingsStore.kt | 42 +++++ .../app/src/main/res/values-de/strings.xml | 9 + .../app/src/main/res/values-es/strings.xml | 10 ++ .../app/src/main/res/values-fr/strings.xml | 10 ++ .../app/src/main/res/values-it/strings.xml | 10 ++ .../app/src/main/res/values-pt/strings.xml | 10 ++ android/app/src/main/res/values/strings.xml | 9 + .../ezdisplay/display/PixelShiftTest.kt | 154 ++++++++++++++++++ .../ezdisplay/screensaver/IdleTrackerTest.kt | 112 +++++++++++-- .../screensaver/ScreenChangeDetectorTest.kt | 75 +++++++++ .../screensaver/ScreensaverPrefsTest.kt | 13 ++ .../ezdisplay/settings/SettingsDisplayTest.kt | 20 +++ .../settings/SettingsScreenshotTest.kt | 11 ++ .../ezdisplay/settings/SettingsStoreTest.kt | 30 ++++ 22 files changed, 962 insertions(+), 42 deletions(-) create mode 100644 android/app/src/main/kotlin/com/librestatic/ezdisplay/display/PixelShift.kt create mode 100644 android/app/src/main/kotlin/com/librestatic/ezdisplay/screensaver/ScreenChangeDetector.kt create mode 100644 android/app/src/test/kotlin/com/librestatic/ezdisplay/display/PixelShiftTest.kt create mode 100644 android/app/src/test/kotlin/com/librestatic/ezdisplay/screensaver/ScreenChangeDetectorTest.kt diff --git a/android/AGENTS.md b/android/AGENTS.md index 0b3bed6..4062905 100644 --- a/android/AGENTS.md +++ b/android/AGENTS.md @@ -19,7 +19,7 @@ Repository-wide rules (languages and localization, naming) are in the root `AGEN At 1691x978 dp the Wide page must not scroll (covered by `SettingsWideTest`); for that the Wide page shows Video (codec and quality) as one row that opens a dialog, like the Connection hosts. - `Sections.kt`: shared components. Colours and type come from `MaterialTheme` only. - - `DisplaySection.kt`: the Display section (screensaver switch, idle / brightness / blank-after / shape speed sliders, + - `DisplaySection.kt`: the Display section (screensaver switch, idle / wake threshold / brightness / blank-after / shape speed sliders, movement mode (cross the screen or bounce), preview, replay of the getting-started guide). The Wide page must stay free of scrolling, so it has no Display block: a `DisplaySheetButton` on the title row ("Screensaver · 5 minutes" or "Screensaver off") opens the full `DisplayContent` in a `ModalBottomSheet` (`DisplaySheet`). @@ -36,7 +36,19 @@ Repository-wide rules (languages and localization, naming) are in the root `AGEN prefs; `screensaver/` holds `ScreensaverContent` (its own dim monochrome field of themed silhouettes from `ScreensaverGlyphs`: monitor, tablet, stylus, brush, palette, mouse; not `ShapeBackdrop`), `ScreensaverMotion` (pure Kotlin motion model: Drift or Bounce, speed level 1..10 at 10 dp/s each, rare steps with reduced motion) and - `ScreensaverPrefs`. The screensaver prefs live in the `input` file but are never part of `InputPrefs.toJson`. + `ScreensaverPrefs`. `IdleTracker` rules: new frames are not activity; `MainActivity` samples the stream surface with + `PixelCopy` (96x54) on each frame increase and `ScreenChangeDetector` (pure Kotlin, tolerance 24/255 per channel, + reference = screen at the last content activity) gives the changed fraction, which wakes only at `wakePct` (setting + "wake threshold", default 50, 5..100 step 5). A PC cursor appearing or moving inside the tablet screen always wakes + Saver and Blank (`onHostCursor`); content never wakes Blank; local input is unchanged. The screensaver prefs live in the `input` file but are never part of `InputPrefs.toJson`. +- `display/PixelShift.kt` is the burn-in protection for the stream (pure Kotlin, time passed in; `PixelShiftPrefs` next + to it, on by default only for OLED, radius 1..8 px, default 4). The offset walks a serpentine over the + (2r+1) x (2r+1) grid, one pixel per step, at most one step every 60 s, and only 3 s after the last pointer event with + no pointer down and no stylus hovering, or while the screensaver covers the picture. `MainActivity` translates + `shiftLayer` (the parent of `stage`, so the local zoom keeps `stage.translationX/Y` to itself) and `forward()` + subtracts the offset from every position before `NativeBridge.inputEvent`; the native engine never sees the shift. + The uncovered edge shows the black `root`. `PixelCopy` reads the surface buffer, so the shift is not a screen change. + The switch and the distance slider are in `DisplaySection.kt`; the prefs are not part of `InputPrefs.toJson` either. ## Build and test - Set `ANDROID_HOME` when `local.properties` is missing. diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/InputPrefs.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/InputPrefs.kt index 2985d94..070106e 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/InputPrefs.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/InputPrefs.kt @@ -32,6 +32,9 @@ object InputPrefs { const val SCREENSAVER_BLANK_MIN = "screensaver_blank_min" const val SCREENSAVER_SPEED = "screensaver_speed" const val SCREENSAVER_MOTION = "screensaver_motion" + const val SCREENSAVER_WAKE_PCT = "screensaver_wake_pct" + const val PIXEL_SHIFT_ENABLED = "pixel_shift_enabled" + const val PIXEL_SHIFT_PX = "pixel_shift_px" const val PANEL_TYPE_DETECTED = "panel_type_detected" const val SCREENSAVER_IDLE_DEFAULT = 5 @@ -49,6 +52,15 @@ object InputPrefs { const val SCREENSAVER_SPEED_DEFAULT = 4 const val SCREENSAVER_SPEED_MIN_VALUE = 1 const val SCREENSAVER_SPEED_MAX_VALUE = 10 + /** Share of the screen that must change before new content wakes the screensaver. */ + const val SCREENSAVER_WAKE_DEFAULT = 50 + const val SCREENSAVER_WAKE_MIN_VALUE = 5 + const val SCREENSAVER_WAKE_MAX_VALUE = 100 + const val SCREENSAVER_WAKE_STEP = 5 + /** Largest distance the picture moves from its centre position, in pixels. */ + const val DEFAULT_PIXEL_SHIFT_PX = 4 + const val MIN_PIXEL_SHIFT_PX = 1 + const val MAX_PIXEL_SHIFT_PX = 8 const val MOD_CTRL = 1 const val MOD_SHIFT = 2 diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt index ef5582f..17e4110 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt @@ -26,6 +26,7 @@ import android.view.Gravity import android.view.InputDevice import android.view.KeyEvent import android.view.MotionEvent +import android.view.PixelCopy import android.view.PointerIcon import android.view.SurfaceHolder import android.view.SurfaceView @@ -47,10 +48,13 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ComposeView +import com.librestatic.ezdisplay.display.PixelShift +import com.librestatic.ezdisplay.display.PixelShiftPrefs import com.librestatic.ezdisplay.onboarding.OnboardingActivity import com.librestatic.ezdisplay.onboarding.OnboardingStore import com.librestatic.ezdisplay.screensaver.IdleState import com.librestatic.ezdisplay.screensaver.IdleTracker +import com.librestatic.ezdisplay.screensaver.ScreenChangeDetector import com.librestatic.ezdisplay.screensaver.ScreensaverConfig import com.librestatic.ezdisplay.screensaver.ScreensaverController import com.librestatic.ezdisplay.screensaver.ScreensaverOverlay @@ -100,6 +104,8 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. const val BACKOFF_MIN_MS = 1000L const val BACKOFF_MAX_MS = 5000L const val STATS_INTERVAL_MS = 250L + const val SAMPLE_W = 96 + const val SAMPLE_H = 54 const val STATUS_HIDE_MS = 3000L const val NOTE_SHOW_MS = 6000L const val AIR_HINT_SHOW_MS = 8000L @@ -183,6 +189,19 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. private lateinit var screensaver: ScreensaverController private var idleConfig = ScreensaverConfig(enabled = false, idleMin = 5, brightnessPct = 10, blankMin = 0) private val idle = IdleTracker(idleConfig) + private val changeDetector = ScreenChangeDetector() + + // Burn-in protection: the whole stage moves by a few pixels; forward() takes the offset out of the input. + private lateinit var shiftLayer: FrameLayout + private val shift = PixelShift(nowMs = SystemClock.uptimeMillis()) + private val sampleBitmap = Bitmap.createBitmap(SAMPLE_W, SAMPLE_H, Bitmap.Config.ARGB_8888) + private val samplePixels = IntArray(SAMPLE_W * SAMPLE_H) + private var sampling = false + private var rebaseSample = false // the next sample becomes the reference (the screensaver just started) + private var samplingFailureLogged = false + private var hostCursorInside = false + private var hostCursorX = 0L + private var hostCursorY = 0L private var saverSpeed by mutableStateOf(idleConfig.speed) private var saverMotion by mutableStateOf(idleConfig.motion) private var swallowTouch = false // the gesture that woke the screen, dropped until it ends @@ -276,7 +295,10 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. pivotY = 0f addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> fitSurface() } } - root.addView(stage, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) + // Pixel shift translates this layer, so the zoom keeps the stage's own translation to itself. + shiftLayer = FrameLayout(this) + root.addView(shiftLayer, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) + shiftLayer.addView(stage, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) surfaceView = SurfaceView(this).also { it.holder.addCallback(this) } stage.addView(surfaceView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) @@ -415,6 +437,8 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. saverMotion = idleConfig.motion idle.setConfig(idleConfig, now) idle.setArmed(true, now) + if (shift.setConfig(PixelShiftPrefs.read(this), now)) applyShift() + changeDetector.reset() applyInputConfig() updateDiscovery() checkAccessory() @@ -633,6 +657,8 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. applyInputConfig() wasStreaming = false idle.resetFrames() + changeDetector.reset() + rebaseSample = false lastInputNote = "" keysHintShown = false hostLacksKeys = false @@ -676,6 +702,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. activeWifi = null activeAccessory = false cursorVisible = false + hostCursorInside = false cursorView.visibility = View.GONE cursorSeq = 0 cursorShapeId = -1 @@ -702,6 +729,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. idle.tick(SystemClock.uptimeMillis()) applyIdle() if (!sessionActive) return + if (shift.tick(SystemClock.uptimeMillis(), screensaver.state != IdleState.Active)) applyShift() val view = NativeBridge.pollView() applyStage(view) NativeBridge.inputTick() @@ -715,6 +743,11 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. } } + private fun applyShift() { + shiftLayer.translationX = shift.offsetX.toFloat() + shiftLayer.translationY = shift.offsetY.toFloat() + } + private fun applyStage(view: FloatArray) { if (view[0] == stageScale && view[1] == stageTx && view[2] == stageTy) return stageScale = view[0] @@ -752,9 +785,59 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. cursorVisible = visible cursorView.visibility = if (visible) View.VISIBLE else View.GONE } + if (seq != 0L && visible) { + val x = c[1] + val y = c[2] + val inside = x in 0 until streamW.toLong() && y in 0 until streamH.toLong() + if (inside && (!hostCursorInside || x != hostCursorX || y != hostCursorY)) { + idle.onHostCursor(SystemClock.uptimeMillis()) + } + hostCursorInside = inside + hostCursorX = x + hostCursorY = y + } else { + hostCursorInside = false + } cursorSeq = seq } + /** + * Copies the streaming surface into a small bitmap and asks the idle tracker whether enough of the screen + * changed to count as activity. Failures only mean that content does not wake the screen. + */ + private fun sampleScreen() { + if (sampling || !sessionActive || !surfaceView.holder.surface.isValid) return + sampling = true + try { + PixelCopy.request(surfaceView, sampleBitmap, { result -> + sampling = false + if (result != PixelCopy.SUCCESS) { + logSamplingFailure("PixelCopy result $result") + return@request + } + if (!started || !sessionActive) return@request + sampleBitmap.getPixels(samplePixels, 0, SAMPLE_W, 0, 0, SAMPLE_W, SAMPLE_H) + if (rebaseSample) { + rebaseSample = false + changeDetector.accept(samplePixels) + return@request + } + val fraction = changeDetector.changedFraction(samplePixels) ?: return@request + if (idle.onScreenChange(fraction, SystemClock.uptimeMillis())) changeDetector.accept(samplePixels) + applyIdle() + }, handler) + } catch (e: IllegalArgumentException) { + sampling = false + logSamplingFailure("PixelCopy failed: ${e.message}") + } + } + + private fun logSamplingFailure(msg: String) { + if (samplingFailureLogged) return + samplingFailureLogged = true + Log.w(TAG, "screen sampling unavailable: $msg") + } + private fun applyCursorSize() { if (cursorBmpW == 0) return val lp = cursorView.layoutParams @@ -820,7 +903,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. Log.w(TAG, "bad stats", e) return } - if (j.optString("phase") == "streaming") idle.onFramesReceived(j.optLong("frames_received"), now) + if (j.optString("phase") == "streaming" && idle.onFramesReceived(j.optLong("frames_received"), now)) sampleScreen() val bw = j.optInt("buffer_width") val bh = j.optInt("buffer_height") if (bw > 0 && bh > 0 && (bw != bufW || bh != bufH)) { @@ -994,10 +1077,17 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. // --- Input forwarding --- - /** Pushes the idle state to the screensaver; coming back from it asks the host for a fresh frame. */ + /** + * Pushes the idle state to the screensaver; coming back from it asks the host for a fresh frame. When the + * screensaver starts, the picture it covers becomes the reference for the wake threshold. + */ private fun applyIdle() { val before = screensaver.state screensaver.apply(idle.state, idleConfig) + if (before == IdleState.Active && idle.state == IdleState.Saver) { + rebaseSample = true + sampleScreen() + } if (before != IdleState.Active && idle.state == IdleState.Active && sessionActive) NativeBridge.requestKeyframe() } @@ -1005,6 +1095,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. if (routedAway) return super.dispatchTouchEvent(ev) val action = ev.actionMasked val ending = action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL + shift.onPointer(!ending, SystemClock.uptimeMillis()) if (swallowTouch) { if (ending) swallowTouch = false return true @@ -1088,6 +1179,9 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. if (routedAway) return super.dispatchGenericMotionEvent(ev) if (ev.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { val exit = ev.actionMasked == MotionEvent.ACTION_HOVER_EXIT + // A hovering stylus holds the picture still; a resting mouse sends no exit, so only its pause counts. + val stylus = ev.getToolType(0) == MotionEvent.TOOL_TYPE_STYLUS + shift.onPointer(stylus && !exit, SystemClock.uptimeMillis()) if (swallowHover) { if (exit) swallowHover = false return true @@ -1202,12 +1296,15 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. } floats[0] = ev.getAxisValue(MotionEvent.AXIS_VSCROLL) floats[1] = ev.getAxisValue(MotionEvent.AXIS_HSCROLL) + // The picture is drawn shifted (pixel shift), so positions go to the engine relative to the picture. + val shiftX = shift.offsetX.toFloat() + val shiftY = shift.offsetY.toFloat() var o = FLOAT_HEADER for (h in 0 until history) { times[h] = historicalTimeNanos(ev, h) for (p in 0 until n) { - floats[o] = ev.getHistoricalX(p, h) - floats[o + 1] = ev.getHistoricalY(p, h) + floats[o] = ev.getHistoricalX(p, h) - shiftX + floats[o + 1] = ev.getHistoricalY(p, h) - shiftY floats[o + 2] = ev.getHistoricalPressure(p, h) floats[o + 3] = ev.getHistoricalAxisValue(MotionEvent.AXIS_TILT, p, h) floats[o + 4] = ev.getHistoricalAxisValue(MotionEvent.AXIS_ORIENTATION, p, h) @@ -1216,8 +1313,8 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. } times[history] = timeNanos(ev) for (p in 0 until n) { - floats[o] = ev.getX(p) - floats[o + 1] = ev.getY(p) + floats[o] = ev.getX(p) - shiftX + floats[o + 1] = ev.getY(p) - shiftY floats[o + 2] = ev.getPressure(p) floats[o + 3] = ev.getAxisValue(MotionEvent.AXIS_TILT, p) floats[o + 4] = ev.getAxisValue(MotionEvent.AXIS_ORIENTATION, p) diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/display/PixelShift.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/display/PixelShift.kt new file mode 100644 index 0000000..e130e79 --- /dev/null +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/display/PixelShift.kt @@ -0,0 +1,127 @@ +package com.librestatic.ezdisplay.display + +import android.content.Context +import android.content.SharedPreferences +import com.librestatic.ezdisplay.InputPrefs + +/** Pixel shift settings: [radiusPx] is the largest distance from the centre on each axis. */ +data class PixelShiftConfig( + val enabled: Boolean = false, + val radiusPx: Int = InputPrefs.DEFAULT_PIXEL_SHIFT_PX, +) + +/** + * Burn-in protection: moves the picture by one pixel every [STEP_INTERVAL_MS], only while the user is not + * touching the screen (or while the screensaver hides the picture). Pure logic; time is passed on every call. + * + * The offsets follow a serpentine walk over the (2r+1) x (2r+1) grid, forward and then backward, so each step + * changes exactly one axis by exactly 1 px and an end-to-end pass visits every position. + */ +class PixelShift(config: PixelShiftConfig = PixelShiftConfig(), nowMs: Long = 0L) { + private var config = config + private var pathIndex = 0 + private var direction = 1 + private var lastStepMs = nowMs + private var lastPointerMs = nowMs + private var pointerActive = false + + var offsetX: Int = 0 + private set + var offsetY: Int = 0 + private set + + init { + restart(nowMs) + } + + /** Returns true when the offset changed. */ + fun setConfig(config: PixelShiftConfig, nowMs: Long): Boolean { + if (config == this.config) return false + val restart = !config.enabled || config.radiusPx != this.config.radiusPx || !this.config.enabled + this.config = config + if (!restart) return false + return restart(nowMs) + } + + /** Call for every local pointer event; [active] is true while a pointer is down or hovering. */ + fun onPointer(active: Boolean, nowMs: Long) { + pointerActive = active + lastPointerMs = nowMs + } + + /** Takes one pending step when due; returns true when the offset changed. */ + fun tick(nowMs: Long, covered: Boolean): Boolean { + if (!config.enabled) return false + if (nowMs - lastStepMs < STEP_INTERVAL_MS) return false + val quiet = !pointerActive && nowMs - lastPointerMs >= QUIET_MS + if (!covered && !quiet) return false + lastStepMs = nowMs + val last = side() * side() - 1 + if (last == 0) return false + if (pathIndex + direction !in 0..last) direction = -direction + pathIndex += direction + return apply() + } + + private fun side() = 2 * config.radiusPx + 1 + + /** Back to the centre; returns true when the offset changed. */ + private fun restart(nowMs: Long): Boolean { + direction = 1 + lastStepMs = nowMs + pathIndex = centreIndex() + return apply() + } + + private fun centreIndex(): Int { + val r = config.radiusPx + // The middle row is r; its centre cell is at column r whichever way the row is walked. + return r * side() + r + } + + private fun apply(): Boolean { + val oldX = offsetX + val oldY = offsetY + if (!config.enabled) { + offsetX = 0 + offsetY = 0 + } else { + val n = side() + val row = pathIndex / n + val col = pathIndex % n + val x = if (row % 2 == 0) col else n - 1 - col + offsetX = x - config.radiusPx + offsetY = row - config.radiusPx + } + return offsetX != oldX || offsetY != oldY + } + + companion object { + const val STEP_INTERVAL_MS = 60_000L + const val QUIET_MS = 3_000L + } +} + +/** Reads the pixel shift prefs (file `input`, but never part of the engine JSON). */ +object PixelShiftPrefs { + /** Clamps a stored or typed value to the allowed range. */ + fun normalizePx(v: Int): Int = v.coerceIn(InputPrefs.MIN_PIXEL_SHIFT_PX, InputPrefs.MAX_PIXEL_SHIFT_PX) + + /** Enabled flag; when the user never chose, on exactly for OLED screens. */ + fun enabled(prefs: SharedPreferences, panel: PanelType): Boolean = + if (prefs.contains(InputPrefs.PIXEL_SHIFT_ENABLED)) { + prefs.getBoolean(InputPrefs.PIXEL_SHIFT_ENABLED, false) + } else { + panel == PanelType.Oled + } + + fun radiusPx(prefs: SharedPreferences): Int = + normalizePx(prefs.getInt(InputPrefs.PIXEL_SHIFT_PX, InputPrefs.DEFAULT_PIXEL_SHIFT_PX)) + + fun read(prefs: SharedPreferences, panel: PanelType): PixelShiftConfig = + PixelShiftConfig(enabled = enabled(prefs, panel), radiusPx = radiusPx(prefs)) + + /** Reads the config for the device, detecting (and caching) the panel type when needed. */ + fun read(context: Context): PixelShiftConfig = + read(InputPrefs.prefs(context), PanelDetector.cached(context)) +} diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/screensaver/IdleTracker.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/screensaver/IdleTracker.kt index a7ded3d..53b8b99 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/screensaver/IdleTracker.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/screensaver/IdleTracker.kt @@ -7,9 +7,12 @@ enum class IdleState { Active, Saver, Blank } * Decides when the screensaver starts and stops. Pure Kotlin: the caller passes the clock (milliseconds, any * monotonic base) so it can be tested with a fake one. * - * - Active -> Saver after `idleMin` without local input and without new frames. + * - Active -> Saver after `idleMin` without activity. Activity is local input, a host cursor entering the tablet + * screen, or new content: at least `wakePct` percent of the screen changed ([onScreenChange]). New frames alone + * are not activity ([onFramesReceived] only says when to measure), so a blinking taskbar icon does not count. * - Saver -> Blank after `blankMin` in Saver (0 = never). - * - In Saver a new frame or any local input goes back to Active; in Blank only local input does. + * - In Saver, local input, the host cursor or enough changed content goes back to Active. In Blank only local + * input and the host cursor do; changed content is ignored. * - A disabled config or a disarmed tracker is always Active, with the timers reset. */ class IdleTracker(config: ScreensaverConfig, nowMs: Long = 0) { @@ -48,19 +51,37 @@ class IdleTracker(config: ScreensaverConfig, nowMs: Long = 0) { return woke } - /** [total] is the running count of received frames; only an increase counts as activity. */ - fun onFramesReceived(total: Long, nowMs: Long) { + /** + * [total] is the running count of received frames. Returns true when it grew while the tracker runs and the + * screen is not Blank: the caller should then measure how much of the screen changed and call [onScreenChange]. + * A new frame is not activity by itself. + */ + fun onFramesReceived(total: Long, nowMs: Long): Boolean { val previous = lastFrames lastFrames = total - if (!running || previous < 0 || total <= previous) return - when (state) { - IdleState.Active -> lastActivityMs = nowMs - IdleState.Saver -> { - state = IdleState.Active - lastActivityMs = nowMs - } - IdleState.Blank -> Unit // only local input wakes a blank screen - } + return running && previous >= 0 && total > previous && state != IdleState.Blank + } + + /** + * [fraction] (0..1) of the screen changed since the last content activity. Counts as activity when it reaches + * `wakePct`: Active restarts the idle timer, Saver goes back to Active, Blank ignores it. Returns true when it + * counted, so the caller makes the measured sample the new reference. + */ + fun onScreenChange(fraction: Float, nowMs: Long): Boolean { + if (!running || state == IdleState.Blank || fraction * 100f + 1e-3f < config.wakePct) return false + state = IdleState.Active + lastActivityMs = nowMs + return true + } + + /** + * The PC cursor appeared or moved inside the tablet screen: wakes Saver and Blank, whatever the threshold. Not + * local input, so nothing is swallowed. + */ + fun onHostCursor(nowMs: Long) { + if (!running) return + state = IdleState.Active + lastActivityMs = nowMs } /** Forget the frame counter, e.g. when a new session starts and counts from zero. */ diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/screensaver/ScreenChangeDetector.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/screensaver/ScreenChangeDetector.kt new file mode 100644 index 0000000..10837a9 --- /dev/null +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/screensaver/ScreenChangeDetector.kt @@ -0,0 +1,51 @@ +package com.librestatic.ezdisplay.screensaver + +/** + * Measures how much of the screen changed, from small ARGB samples of it. Pure Kotlin. + * + * The reference is the screen at the last content activity, not the previous sample: a slow transition adds up + * until it crosses the wake threshold, while an icon that blinks on and off never does. + */ +class ScreenChangeDetector { + private var reference: IntArray? = null + + /** + * Fraction (0..1) of the cells whose R, G or B differs from the reference by more than [TOLERANCE], or null + * when there was no reference yet (then [sample] becomes the reference). Does not move the reference. + */ + fun changedFraction(sample: IntArray): Float? { + val ref = reference + if (ref == null || ref.size != sample.size) { + reference = sample.copyOf() + return null + } + if (sample.isEmpty()) return 0f + var changed = 0 + for (i in sample.indices) { + val a = ref[i] + val b = sample[i] + if (channelDiff(a, b, 16) > TOLERANCE || channelDiff(a, b, 8) > TOLERANCE || channelDiff(a, b, 0) > TOLERANCE) { + changed++ + } + } + return changed.toFloat() / sample.size + } + + /** Makes [sample] the new reference. */ + fun accept(sample: IntArray) { + val ref = reference + if (ref != null && ref.size == sample.size) sample.copyInto(ref) else reference = sample.copyOf() + } + + /** Forgets the reference; the next sample becomes the new one. */ + fun reset() { + reference = null + } + + private fun channelDiff(a: Int, b: Int, shift: Int): Int = Math.abs(((a shr shift) and 0xFF) - ((b shr shift) and 0xFF)) + + companion object { + /** Per-channel difference (of 255) that is ignored as codec noise or dithering. */ + const val TOLERANCE = 24 + } +} diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/screensaver/ScreensaverPrefs.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/screensaver/ScreensaverPrefs.kt index 236a65e..ad980f3 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/screensaver/ScreensaverPrefs.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/screensaver/ScreensaverPrefs.kt @@ -15,6 +15,8 @@ data class ScreensaverConfig( val blankMin: Int, val speed: Int = InputPrefs.SCREENSAVER_SPEED_DEFAULT, val motion: ScreensaverMotionMode = ScreensaverMotionMode.Drift, + /** Percent of the screen that must change for new content to count as activity. */ + val wakePct: Int = InputPrefs.SCREENSAVER_WAKE_DEFAULT, ) /** Clamps a stored or typed value to the allowed ranges. */ @@ -27,6 +29,13 @@ fun normalizeBrightnessPct(v: Int): Int = fun normalizeSpeed(v: Int): Int = v.coerceIn(InputPrefs.SCREENSAVER_SPEED_MIN_VALUE, InputPrefs.SCREENSAVER_SPEED_MAX_VALUE) +/** Clamps to 5..100 and rounds to the slider step. */ +fun normalizeWakePct(v: Int): Int { + val step = InputPrefs.SCREENSAVER_WAKE_STEP + val rounded = (v.toFloat() / step).roundToInt() * step + return rounded.coerceIn(InputPrefs.SCREENSAVER_WAKE_MIN_VALUE, InputPrefs.SCREENSAVER_WAKE_MAX_VALUE) +} + /** 0 (never) or 5..120; anything between 1 and 4 is raised to 5. */ fun normalizeBlankMin(v: Int): Int = if (v <= 0) 0 else v.coerceIn(InputPrefs.SCREENSAVER_BLANK_MIN_VALUE, InputPrefs.SCREENSAVER_BLANK_MAX_VALUE) @@ -57,6 +66,7 @@ object ScreensaverPrefs { blankMin = normalizeBlankMin(prefs.getInt(InputPrefs.SCREENSAVER_BLANK_MIN, InputPrefs.SCREENSAVER_BLANK_DEFAULT)), speed = normalizeSpeed(prefs.getInt(InputPrefs.SCREENSAVER_SPEED, InputPrefs.SCREENSAVER_SPEED_DEFAULT)), motion = ScreensaverMotionMode.fromKey(prefs.getString(InputPrefs.SCREENSAVER_MOTION, null)), + wakePct = normalizeWakePct(prefs.getInt(InputPrefs.SCREENSAVER_WAKE_PCT, InputPrefs.SCREENSAVER_WAKE_DEFAULT)), ) /** Reads the config for the device, detecting (and caching) the panel type when needed. */ diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/DisplaySection.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/DisplaySection.kt index b726e75..205449f 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/DisplaySection.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/DisplaySection.kt @@ -59,13 +59,14 @@ private fun panelName(type: PanelType): String = stringResource( fun DisplayContent(state: SettingsState, actions: SettingsActions, modifier: Modifier = Modifier) { Column(modifier.fillMaxWidth()) { Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(2.dp)) { - ScreensaverSwitchRow(state, actions, segmentShape(0, 7)) - IdleSlider(state, actions, segmentShape(1, 7)) - BrightnessSlider(state, actions, segmentShape(2, 7)) - BlankSlider(state, actions, segmentShape(3, 7)) - SpeedSlider(state, actions, segmentShape(4, 7)) - MotionRow(state, actions, segmentShape(5, 7)) - Surface(shape = segmentShape(6, 7), color = MaterialTheme.colorScheme.surfaceBright, modifier = Modifier.fillMaxWidth()) { + ScreensaverSwitchRow(state, actions, segmentShape(0, 8)) + IdleSlider(state, actions, segmentShape(1, 8)) + WakeSlider(state, actions, segmentShape(2, 8)) + BrightnessSlider(state, actions, segmentShape(3, 8)) + BlankSlider(state, actions, segmentShape(4, 8)) + SpeedSlider(state, actions, segmentShape(5, 8)) + MotionRow(state, actions, segmentShape(6, 8)) + Surface(shape = segmentShape(7, 8), color = MaterialTheme.colorScheme.surfaceBright, modifier = Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { Box(Modifier.fillMaxWidth().height(140.dp).clip(RoundedCornerShape(20.dp)).testTag("screensaver_preview_box")) { ScreensaverContent( @@ -77,6 +78,10 @@ fun DisplayContent(state: SettingsState, actions: SettingsActions, modifier: Mod } } } + Column(Modifier.fillMaxWidth().padding(top = 12.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) { + PixelShiftSwitchRow(state, actions, segmentShape(0, 2)) + ShiftSlider(state, actions, segmentShape(1, 2)) + } ReplayRow(actions, Modifier.padding(top = 12.dp)) } } @@ -161,6 +166,70 @@ private fun ScreensaverSwitchRow(state: SettingsState, actions: SettingsActions, } } +@Composable +private fun PixelShiftSwitchRow(state: SettingsState, actions: SettingsActions, shape: androidx.compose.ui.graphics.Shape) { + val colors = MaterialTheme.colorScheme + val on = state.pixelShiftEnabled + Surface( + checked = on, + onCheckedChange = actions::setPixelShiftEnabled, + shape = shape, + color = colors.surfaceBright, + modifier = Modifier.fillMaxWidth().semantics { role = Role.Switch }.testTag("pixel_shift_row"), + ) { + Row( + Modifier.heightIn(min = DisplayRowMinHeight).padding(DisplayRowPadding), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Symbol(R.drawable.ic_tune, tint = colors.secondary) + Column(Modifier.weight(1f)) { + Text( + stringResource(R.string.pixel_shift_title), + style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, + ) + Text( + stringResource(R.string.pixel_shift_desc), + style = MaterialTheme.typography.bodySmall, color = colors.onSurfaceVariant, + ) + } + Switch( + checked = on, + onCheckedChange = null, + thumbContent = if (on) { + { Symbol(R.drawable.ic_check, size = 16.dp) } + } else { + null + }, + ) + } + } +} + +@Composable +private fun ShiftSlider( + state: SettingsState, + actions: SettingsActions, + shape: androidx.compose.ui.graphics.Shape, +) { + val min = InputPrefs.MIN_PIXEL_SHIFT_PX + val max = InputPrefs.MAX_PIXEL_SHIFT_PX + ValueSliderRow( + icon = R.drawable.ic_tune, + title = stringResource(R.string.pixel_shift_amount_title), + value = state.pixelShiftPx.toFloat(), + valueText = pluralStringResource(R.plurals.settings_pixels, state.pixelShiftPx, state.pixelShiftPx), + range = min.toFloat()..max.toFloat(), + steps = max - min - 1, + minText = pluralStringResource(R.plurals.settings_pixels, min, min), + maxText = pluralStringResource(R.plurals.settings_pixels, max, max), + enabled = state.pixelShiftEnabled, + tag = "pixel_shift_slider", + shape = shape, + onChange = { actions.setPixelShiftPx(roundShiftPx(it)) }, + ) +} + @Composable private fun IdleSlider( state: SettingsState, @@ -185,6 +254,31 @@ private fun IdleSlider( ) } +@Composable +private fun WakeSlider( + state: SettingsState, + actions: SettingsActions, + shape: androidx.compose.ui.graphics.Shape, +) { + val min = InputPrefs.SCREENSAVER_WAKE_MIN_VALUE + val max = InputPrefs.SCREENSAVER_WAKE_MAX_VALUE + ValueSliderRow( + icon = R.drawable.ic_timer, + title = stringResource(R.string.screensaver_wake_title), + value = state.screensaverWakePct.toFloat(), + valueText = stringResource(R.string.settings_percent, state.screensaverWakePct), + range = min.toFloat()..max.toFloat(), + steps = (max - min) / InputPrefs.SCREENSAVER_WAKE_STEP - 1, + minText = stringResource(R.string.settings_percent, min), + maxText = stringResource(R.string.settings_percent, max), + enabled = state.screensaverEnabled, + tag = "screensaver_wake_slider", + shape = shape, + supporting = stringResource(R.string.screensaver_wake_desc), + onChange = { actions.setScreensaverWakePct(roundWakePct(it)) }, + ) +} + @Composable private fun BrightnessSlider( state: SettingsState, @@ -350,6 +444,7 @@ private fun ValueSliderRow( enabled: Boolean, tag: String, shape: androidx.compose.ui.graphics.Shape, + supporting: String? = null, onChange: (Float) -> Unit, ) { val colors = MaterialTheme.colorScheme @@ -380,6 +475,12 @@ private fun ValueSliderRow( Text(minText, style = style, color = colors.onSurfaceVariant) Text(maxText, style = style, color = colors.onSurfaceVariant) } + if (supporting != null) { + Text( + supporting, Modifier.padding(top = 8.dp), + style = MaterialTheme.typography.bodySmall, color = colors.onSurfaceVariant, + ) + } } } } diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/SettingsStore.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/SettingsStore.kt index 3476e00..661ea94 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/SettingsStore.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/SettingsStore.kt @@ -15,10 +15,12 @@ import com.librestatic.ezdisplay.InputPrefs.KeyCombo import com.librestatic.ezdisplay.R import com.librestatic.ezdisplay.display.PanelDetector import com.librestatic.ezdisplay.display.PanelType +import com.librestatic.ezdisplay.display.PixelShiftPrefs import com.librestatic.ezdisplay.screensaver.ScreensaverMotionMode import com.librestatic.ezdisplay.screensaver.ScreensaverPrefs import com.librestatic.ezdisplay.screensaver.normalizeBlankMin import com.librestatic.ezdisplay.screensaver.normalizeBrightnessPct +import com.librestatic.ezdisplay.screensaver.normalizeWakePct import com.librestatic.ezdisplay.screensaver.normalizeIdleMin import com.librestatic.ezdisplay.screensaver.normalizeSpeed import com.librestatic.ezdisplay.wifi.DiscoveredHost @@ -154,6 +156,12 @@ data class SettingsState( val screensaverSpeed: Int = InputPrefs.SCREENSAVER_SPEED_DEFAULT, /** How the shapes travel: across the screen or bouncing off the edges. */ val screensaverMotion: ScreensaverMotionMode = ScreensaverMotionMode.Drift, + /** Percent of the screen that must change before new content wakes the screensaver (5..100, step 5). */ + val screensaverWakePct: Int = InputPrefs.SCREENSAVER_WAKE_DEFAULT, + /** Moves the picture by a pixel now and then in input pauses (burn-in protection). */ + val pixelShiftEnabled: Boolean = false, + /** Largest pixel shift from the centre (1..8). */ + val pixelShiftPx: Int = InputPrefs.DEFAULT_PIXEL_SHIFT_PX, val airActions: AirActions = AirActions.NotSamsung, /** Play the PC's audio on this device. */ val audioEnabled: Boolean = true, @@ -234,6 +242,10 @@ fun roundBrightnessPct(raw: Float): Int = normalizeBrightnessPct(raw.roundToInt( fun roundSpeed(raw: Float): Int = normalizeSpeed(raw.roundToInt()) +fun roundWakePct(raw: Float): Int = normalizeWakePct(raw.roundToInt()) + +fun roundShiftPx(raw: Float): Int = PixelShiftPrefs.normalizePx(raw.roundToInt()) + /** Reads the Samsung S Pen "Air actions" system setting. */ fun readAirActions(context: Context): AirActions { if (!Build.MANUFACTURER.equals("samsung", ignoreCase = true)) return AirActions.NotSamsung @@ -272,6 +284,14 @@ interface SettingsActions { fun setScreensaverMotion(mode: ScreensaverMotionMode) + /** Share of the screen that must change to wake the screensaver, 5..100 in steps of 5. */ + fun setScreensaverWakePct(pct: Int) + + fun setPixelShiftEnabled(on: Boolean) + + /** Largest pixel shift, 1..8. */ + fun setPixelShiftPx(px: Int) + /** Shows the screensaver once, as it would appear when idle. */ fun previewScreensaver() {} @@ -333,6 +353,11 @@ class SettingsStore( prefs.getInt(InputPrefs.SCREENSAVER_SPEED, InputPrefs.SCREENSAVER_SPEED_DEFAULT), ), screensaverMotion = ScreensaverMotionMode.fromKey(prefs.getString(InputPrefs.SCREENSAVER_MOTION, null)), + screensaverWakePct = normalizeWakePct( + prefs.getInt(InputPrefs.SCREENSAVER_WAKE_PCT, InputPrefs.SCREENSAVER_WAKE_DEFAULT), + ), + pixelShiftEnabled = PixelShiftPrefs.enabled(prefs, panelType), + pixelShiftPx = PixelShiftPrefs.radiusPx(prefs), airActions = airActions, audioEnabled = prefs.getBoolean(AUDIO_ENABLED, true), wifiEnabled = prefs.getBoolean(WIFI_ENABLED, false), @@ -426,11 +451,28 @@ class SettingsStore( _state.value = _state.value.copy(screensaverSpeed = v) } + override fun setScreensaverWakePct(pct: Int) { + val v = normalizeWakePct(pct) + prefs.edit { putInt(InputPrefs.SCREENSAVER_WAKE_PCT, v) } + _state.value = _state.value.copy(screensaverWakePct = v) + } + override fun setScreensaverMotion(mode: ScreensaverMotionMode) { prefs.edit { putString(InputPrefs.SCREENSAVER_MOTION, mode.key) } _state.value = _state.value.copy(screensaverMotion = mode) } + override fun setPixelShiftEnabled(on: Boolean) { + prefs.edit { putBoolean(InputPrefs.PIXEL_SHIFT_ENABLED, on) } + _state.value = _state.value.copy(pixelShiftEnabled = on) + } + + override fun setPixelShiftPx(px: Int) { + val v = PixelShiftPrefs.normalizePx(px) + prefs.edit { putInt(InputPrefs.PIXEL_SHIFT_PX, v) } + _state.value = _state.value.copy(pixelShiftPx = v) + } + override fun previewScreensaver() = onPreviewScreensaver() override fun replayOnboarding() = onReplayOnboarding() diff --git a/android/app/src/main/res/values-de/strings.xml b/android/app/src/main/res/values-de/strings.xml index 124e9df..509909c 100644 --- a/android/app/src/main/res/values-de/strings.xml +++ b/android/app/src/main/res/values-de/strings.xml @@ -200,6 +200,11 @@ Helligkeit des Bildschirmschoners Komplett schwarz nach Nie + Aufweck-Schwelle + Der Bildschirm wacht auf, wenn sich so viel vom Bild ändert. Wenn der PC-Cursor auf den Tablet-Bildschirm wechselt, wacht er immer auf. + Pixelverschiebung + Verschiebt das Bild ab und zu um einen Pixel, damit feste Bildteile den Bildschirm nicht abnutzen. Es bewegt sich nie, während du zeichnest oder tippst. + Verschiebungsdistanz Geschwindigkeit der Formen Langsam Schnell @@ -214,6 +219,10 @@ %1$d Minute %1$d Minuten + + %1$d Pixel + %1$d Pixel + Trennen Überspringen diff --git a/android/app/src/main/res/values-es/strings.xml b/android/app/src/main/res/values-es/strings.xml index 9369093..b25e365 100644 --- a/android/app/src/main/res/values-es/strings.xml +++ b/android/app/src/main/res/values-es/strings.xml @@ -203,6 +203,11 @@ Brillo del protector Poner todo en negro después de Nunca + Umbral de despertar + La pantalla se despierta cuando cambia esta parte de la imagen. Si el cursor de la PC entra en la pantalla de la tablet, siempre se despierta. + Desplazamiento de píxeles + Mueve la imagen un píxel de vez en cuando para que las partes fijas no desgasten la pantalla. Nunca se mueve mientras dibujás o tocás. + Distancia de desplazamiento Velocidad de las formas Lenta Rápida @@ -218,6 +223,11 @@ %1$d minutos %1$d minutos + + %1$d píxel + %1$d píxeles + %1$d píxeles + Desconectar Omitir diff --git a/android/app/src/main/res/values-fr/strings.xml b/android/app/src/main/res/values-fr/strings.xml index 3b9cde1..9fd8729 100644 --- a/android/app/src/main/res/values-fr/strings.xml +++ b/android/app/src/main/res/values-fr/strings.xml @@ -203,6 +203,11 @@ Luminosité de l\'économiseur Passer au noir complet après Jamais + Seuil de réveil + L\'écran se réveille lorsque cette part de l\'image change. Lorsque le curseur du PC entre sur l\'écran de la tablette, il se réveille toujours. + Décalage des pixels + Décale l\'image d\'un pixel de temps en temps afin que les éléments fixes n\'usent pas l\'écran. Elle ne bouge jamais pendant que vous dessinez ou touchez l\'écran. + Distance de décalage Vitesse des formes Lente Rapide @@ -218,6 +223,11 @@ %1$d minutes %1$d minutes + + %1$d pixel + %1$d pixels + %1$d pixels + Déconnecter Passer diff --git a/android/app/src/main/res/values-it/strings.xml b/android/app/src/main/res/values-it/strings.xml index 3d0dd3b..ec360a2 100644 --- a/android/app/src/main/res/values-it/strings.xml +++ b/android/app/src/main/res/values-it/strings.xml @@ -203,6 +203,11 @@ Luminosità del salvaschermo Schermo nero dopo Mai + Soglia di risveglio + Lo schermo si risveglia quando cambia questa parte dell\'immagine. Se il cursore del PC entra nello schermo del tablet, si risveglia sempre. + Spostamento dei pixel + Sposta l\'immagine di un pixel ogni tanto, così le parti fisse non consumano lo schermo. Non si muove mai mentre disegni o tocchi. + Distanza di spostamento Velocità delle forme Lenta Veloce @@ -218,6 +223,11 @@ %1$d minuti %1$d minuti + + %1$d pixel + %1$d pixel + %1$d pixel + Disconnetti Salta diff --git a/android/app/src/main/res/values-pt/strings.xml b/android/app/src/main/res/values-pt/strings.xml index 6863e8d..2cf8479 100644 --- a/android/app/src/main/res/values-pt/strings.xml +++ b/android/app/src/main/res/values-pt/strings.xml @@ -203,6 +203,11 @@ Brilho do protetor Ficar totalmente preto após Nunca + Limite para despertar + A tela desperta quando essa parte da imagem muda. Quando o cursor do PC entra na tela do tablet, ela sempre desperta. + Deslocamento de pixels + Move a imagem um pixel de vez em quando para que as partes fixas não desgastem a tela. Ela nunca se move enquanto você desenha ou toca. + Distância de deslocamento Velocidade das formas Lenta Rápida @@ -218,6 +223,11 @@ %1$d minutos %1$d minutos + + %1$d pixel + %1$d pixels + %1$d pixels + Desconectar Pular diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index ffa7725..a5e80be 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -202,6 +202,11 @@ Screensaver brightness Turn fully black after Never + Wake threshold + The screen wakes when this much of the picture changes. The PC cursor entering the tablet screen always wakes it. + Pixel shift + Moves the picture by one pixel now and then so that fixed parts do not wear the screen. It never moves while you draw or touch. + Shift distance Shape speed Slow Fast @@ -216,6 +221,10 @@ %1$d minute %1$d minutes + + %1$d pixel + %1$d pixels + Disconnect Skip diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/display/PixelShiftTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/display/PixelShiftTest.kt new file mode 100644 index 0000000..a625997 --- /dev/null +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/display/PixelShiftTest.kt @@ -0,0 +1,154 @@ +package com.librestatic.ezdisplay.display + +import android.content.SharedPreferences +import androidx.test.core.app.ApplicationProvider +import com.librestatic.ezdisplay.InputPrefs +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import kotlin.math.abs + +private const val STEP = PixelShift.STEP_INTERVAL_MS +private const val QUIET = PixelShift.QUIET_MS + +class PixelShiftTest { + private fun on(r: Int = 4) = PixelShiftConfig(enabled = true, radiusPx = r) + + private fun PixelShift.pos() = offsetX to offsetY + + /** Takes one step per interval, with no input, and returns the position after each. */ + private fun walk(shift: PixelShift, steps: Int, startMs: Long = 0L): List> { + var now = startMs + return List(steps) { + now += STEP + assertTrue(shift.tick(now, covered = false)) + shift.pos() + } + } + + @Test fun startsAtTheCentre() { + assertEquals(0 to 0, PixelShift(on()).pos()) + } + + @Test fun staysWithinTheRadiusOverSeveralCycles() { + for (r in listOf(1, 2, 4, 8)) { + val n = 2 * r + 1 + for ((x, y) in walk(PixelShift(on(r)), n * n * 4)) { + assertTrue(abs(x) <= r && abs(y) <= r) + } + } + } + + @Test fun everyStepChangesOneAxisByOne() { + var prev = 0 to 0 + for (p in walk(PixelShift(on(3)), 7 * 7 * 3)) { + assertEquals(1, abs(p.first - prev.first) + abs(p.second - prev.second)) + prev = p + } + } + + @Test fun anEndToEndPassVisitsEveryPosition() { + for (r in listOf(1, 4)) { + val n = 2 * r + 1 + // Out to one end, back through the centre to the other end: two passes cover the grid. + val seen = walk(PixelShift(on(r)), 2 * n * n).toSet() + (0 to 0) + assertEquals(n * n, seen.size) + } + } + + @Test fun noStepBeforeTheIntervalOrWhileAPointerIsActive() { + val s = PixelShift(on()) + assertFalse(s.tick(STEP - 1, covered = false)) + s.onPointer(true, STEP) + assertFalse(s.tick(STEP + QUIET + 10_000, covered = false)) + assertEquals(0 to 0, s.pos()) + } + + @Test fun noStepUntilTheQuietTimeAfterTheLastPointerEvent() { + val s = PixelShift(on()) + s.onPointer(false, STEP) + assertFalse(s.tick(STEP + QUIET - 1, covered = false)) + assertTrue(s.tick(STEP + QUIET, covered = false)) + } + + @Test fun aPendingStepFiresOnceAndStepsDoNotAccumulate() { + val s = PixelShift(on()) + s.onPointer(true, 0) + assertFalse(s.tick(10 * STEP, covered = false)) + s.onPointer(false, 10 * STEP) + assertTrue(s.tick(10 * STEP + QUIET, covered = false)) + assertEquals(1, abs(s.offsetX) + abs(s.offsetY)) + // The next step is a full interval after the one just taken. + assertFalse(s.tick(10 * STEP + QUIET + STEP - 1, covered = false)) + assertTrue(s.tick(10 * STEP + QUIET + STEP, covered = false)) + } + + @Test fun coveredStepsDespiteRecentInput() { + val s = PixelShift(on()) + s.onPointer(true, STEP) + assertTrue(s.tick(STEP, covered = true)) + } + + @Test fun changingTheRadiusOrDisablingReturnsToTheCentre() { + val s = PixelShift(on(4)) + walk(s, 5) + assertTrue(s.offsetX != 0 || s.offsetY != 0) + assertTrue(s.setConfig(on(2), 1_000_000L)) + assertEquals(0 to 0, s.pos()) + walk(s, 3, startMs = 1_000_000L) + assertTrue(s.setConfig(PixelShiftConfig(enabled = false, radiusPx = 2), 2_000_000L)) + assertEquals(0 to 0, s.pos()) + assertFalse(s.setConfig(PixelShiftConfig(enabled = false, radiusPx = 2), 2_000_001L)) + } + + @Test fun theSameConfigChangesNothingAndAResetRestartsTheTimer() { + val s = PixelShift(on()) + assertFalse(s.setConfig(on(), 5L)) + walk(s, 1) + assertFalse(s.setConfig(on(), STEP + 1)) + assertTrue(s.setConfig(on(3), 10 * STEP)) + assertFalse(s.tick(11 * STEP - 1, covered = true)) + assertTrue(s.tick(11 * STEP, covered = true)) + } + + @Test fun disabledNeverMoves() { + val s = PixelShift(PixelShiftConfig(enabled = false)) + for (i in 1..10) assertFalse(s.tick(i * STEP, covered = true)) + assertEquals(0 to 0, s.pos()) + } +} + +@RunWith(RobolectricTestRunner::class) +class PixelShiftPrefsTest { + private lateinit var prefs: SharedPreferences + + @Before fun setUp() { + prefs = InputPrefs.prefs(ApplicationProvider.getApplicationContext()) + prefs.edit().clear().commit() + } + + @Test fun defaultsFollowThePanel() { + assertTrue(PixelShiftPrefs.read(prefs, PanelType.Oled).enabled) + assertFalse(PixelShiftPrefs.read(prefs, PanelType.Lcd).enabled) + assertFalse(PixelShiftPrefs.read(prefs, PanelType.Unknown).enabled) + assertEquals(PixelShiftConfig(true, 4), PixelShiftPrefs.read(prefs, PanelType.Oled)) + } + + @Test fun aStoredValueWins() { + prefs.edit().putBoolean(InputPrefs.PIXEL_SHIFT_ENABLED, false).commit() + assertFalse(PixelShiftPrefs.read(prefs, PanelType.Oled).enabled) + prefs.edit().putBoolean(InputPrefs.PIXEL_SHIFT_ENABLED, true).commit() + assertTrue(PixelShiftPrefs.read(prefs, PanelType.Lcd).enabled) + } + + @Test fun theRadiusIsClamped() { + prefs.edit().putInt(InputPrefs.PIXEL_SHIFT_PX, 99).commit() + assertEquals(8, PixelShiftPrefs.radiusPx(prefs)) + prefs.edit().putInt(InputPrefs.PIXEL_SHIFT_PX, 0).commit() + assertEquals(1, PixelShiftPrefs.read(prefs, PanelType.Lcd).radiusPx) + } +} diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/screensaver/IdleTrackerTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/screensaver/IdleTrackerTest.kt index 3dd815f..febeb58 100644 --- a/android/app/src/test/kotlin/com/librestatic/ezdisplay/screensaver/IdleTrackerTest.kt +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/screensaver/IdleTrackerTest.kt @@ -34,34 +34,123 @@ class IdleTrackerTest { assertEquals(IdleState.Saver, t.state) } - @Test fun newFramesRestartTheIdleTimerButRepeatedTotalsDoNot() { + @Test fun framesAloneNeitherWakeNorPostponeTheSaver() { val t = tracker() - t.onFramesReceived(10, 0) - t.onFramesReceived(11, 4 * min) - t.onFramesReceived(11, 5 * min) // same total: no activity + assertFalse(t.onFramesReceived(10, 0)) // first count: nothing to compare with + assertTrue(t.onFramesReceived(11, 4 * min)) // grew: the caller should measure + assertFalse(t.onFramesReceived(11, 4 * min + 1)) // same total + t.tick(5 * min) + assertEquals(IdleState.Saver, t.state) + assertTrue(t.onFramesReceived(12, 5 * min + 1)) + assertEquals(IdleState.Saver, t.state) + } + + @Test fun framesInBlankOrWhenNotRunningAreNotMeasured() { + val t = tracker() + t.onFramesReceived(1, 0) + t.tick(5 * min) + t.tick(15 * min) + assertFalse(t.onFramesReceived(2, 16 * min)) + val off = tracker(config(enabled = false)) + off.onFramesReceived(1, 0) + assertFalse(off.onFramesReceived(2, 1)) + } + + @Test fun changeBelowTheThresholdIsNotActivity() { + val t = tracker() + assertFalse(t.onScreenChange(0.49f, 4 * min)) + t.tick(5 * min) + assertEquals(IdleState.Saver, t.state) + assertFalse(t.onScreenChange(0.49f, 5 * min + 1)) + assertEquals(IdleState.Saver, t.state) + } + + @Test fun changeAtTheThresholdRestartsTheIdleTimerInActive() { + val t = tracker() + assertTrue(t.onScreenChange(0.5f, 4 * min)) t.tick(5 * min) assertEquals(IdleState.Active, t.state) t.tick(9 * min) assertEquals(IdleState.Saver, t.state) } - @Test fun goesBlankBlankMinutesAfterEnteringSaver() { + @Test fun changeAboveTheThresholdWakesTheSaver() { val t = tracker() t.tick(5 * min) - t.tick(15 * min - 1) + assertTrue(t.onScreenChange(0.9f, 5 * min + 1)) + assertEquals(IdleState.Active, t.state) + } + + @Test fun thresholdOf100NeedsTheWholeScreen() { + val t = tracker(config().copy(wakePct = 100)) + t.tick(5 * min) + assertFalse(t.onScreenChange(0.99f, 5 * min + 1)) assertEquals(IdleState.Saver, t.state) + assertTrue(t.onScreenChange(1f, 5 * min + 2)) + assertEquals(IdleState.Active, t.state) + } + + @Test fun thresholdFollowsTheConfig() { + val t = tracker(config().copy(wakePct = 5)) + t.tick(5 * min) + assertTrue(t.onScreenChange(0.05f, 5 * min + 1)) + assertEquals(IdleState.Active, t.state) + } + + @Test fun screenChangeDoesNotWakeBlank() { + val t = tracker() + t.tick(5 * min) t.tick(15 * min) + assertFalse(t.onScreenChange(1f, 16 * min)) assertEquals(IdleState.Blank, t.state) } - @Test fun aFrameInSaverWakesWithoutConsumingInput() { + @Test fun hostCursorWakesTheSaverAndBlankAtAnyThreshold() { + val t = tracker(config().copy(wakePct = 100)) + t.tick(5 * min) + t.onHostCursor(5 * min + 1) + assertEquals(IdleState.Active, t.state) + t.tick(10 * min + 1) + t.tick(20 * min + 1) + assertEquals(IdleState.Blank, t.state) + t.onHostCursor(21 * min) + assertEquals(IdleState.Active, t.state) + } + + @Test fun hostCursorRestartsTheIdleTimerAndIsNotLocalInput() { + val t = tracker() + t.onHostCursor(4 * min) + t.tick(5 * min) + assertEquals(IdleState.Active, t.state) + t.tick(9 * min) + assertEquals(IdleState.Saver, t.state) + t.onHostCursor(9 * min + 1) + assertFalse(t.onLocalInput(9 * min + 2)) // nothing left to swallow + } + + @Test fun disabledOrDisarmedTrackerIgnoresContentAndCursor() { + val off = tracker(config(enabled = false)) + assertFalse(off.onScreenChange(1f, 1)) + off.onHostCursor(1) + assertEquals(IdleState.Active, off.state) val t = tracker() - t.onFramesReceived(1, 0) t.tick(5 * min) - t.onFramesReceived(2, 5 * min + 1) + t.setArmed(false, 6 * min) + assertFalse(t.onScreenChange(1f, 7 * min)) + t.tick(100 * min) + t.onHostCursor(101 * min) assertEquals(IdleState.Active, t.state) } + @Test fun goesBlankBlankMinutesAfterEnteringSaver() { + val t = tracker() + t.tick(5 * min) + t.tick(15 * min - 1) + assertEquals(IdleState.Saver, t.state) + t.tick(15 * min) + assertEquals(IdleState.Blank, t.state) + } + @Test fun inputInSaverWakesAndIsConsumed() { val t = tracker() t.tick(5 * min) @@ -70,13 +159,10 @@ class IdleTrackerTest { assertFalse(t.onLocalInput(5 * min + 20)) } - @Test fun framesDoNotWakeBlankButInputDoes() { + @Test fun inputWakesBlank() { val t = tracker() - t.onFramesReceived(1, 0) t.tick(5 * min) t.tick(15 * min) - t.onFramesReceived(50, 16 * min) - assertEquals(IdleState.Blank, t.state) assertTrue(t.onLocalInput(17 * min)) assertEquals(IdleState.Active, t.state) } diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/screensaver/ScreenChangeDetectorTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/screensaver/ScreenChangeDetectorTest.kt new file mode 100644 index 0000000..1251301 --- /dev/null +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/screensaver/ScreenChangeDetectorTest.kt @@ -0,0 +1,75 @@ +package com.librestatic.ezdisplay.screensaver + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class ScreenChangeDetectorTest { + private fun solid(rgb: Int, n: Int = 100) = IntArray(n) { 0xFF000000.toInt() or rgb } + + @Test fun firstSampleHasNoReference() { + val d = ScreenChangeDetector() + assertNull(d.changedFraction(solid(0x102030))) + assertEquals(0f, d.changedFraction(solid(0x102030))!!, 0f) + } + + @Test fun identicalSamplesChangeNothing() { + val d = ScreenChangeDetector() + d.changedFraction(solid(0x808080)) + assertEquals(0f, d.changedFraction(solid(0x808080))!!, 0f) + } + + @Test fun noiseWithinTheToleranceIsIgnored() { + val d = ScreenChangeDetector() + d.changedFraction(solid(0x808080)) + val noisy = solid(0x808080 + 0x180000 + 0x001800 + 0x000018) // +24 on every channel + assertEquals(0f, d.changedFraction(noisy)!!, 0f) + val past = solid(0x808080 + 0x190000) // +25 on red + assertEquals(1f, d.changedFraction(past)!!, 0f) + } + + @Test fun halfTheCellsChanged() { + val d = ScreenChangeDetector() + d.changedFraction(solid(0x000000)) + val sample = solid(0x000000) + for (i in 0 until 50) sample[i] = 0xFFFFFFFF.toInt() + assertEquals(0.5f, d.changedFraction(sample)!!, 0f) + } + + @Test fun anySingleChannelCounts() { + val d = ScreenChangeDetector() + d.changedFraction(solid(0x000000, 10)) + val sample = solid(0x000000, 10) + sample[0] = 0xFF000000.toInt() or 0x0000FF // blue only + sample[1] = 0xFF000000.toInt() or 0x00FF00 // green only + assertEquals(0.2f, d.changedFraction(sample)!!, 1e-6f) + } + + @Test fun referenceMovesOnlyOnAccept() { + val d = ScreenChangeDetector() + d.changedFraction(solid(0x000000)) + val other = solid(0xFFFFFF) + assertEquals(1f, d.changedFraction(other)!!, 0f) + assertEquals(1f, d.changedFraction(other)!!, 0f) // still compared with the first one + d.accept(other) + assertEquals(0f, d.changedFraction(other)!!, 0f) + assertEquals(1f, d.changedFraction(solid(0x000000))!!, 0f) + } + + @Test fun acceptedSampleIsCopied() { + val d = ScreenChangeDetector() + val s = solid(0x000000) + d.changedFraction(s) + d.accept(s) + s.fill(0xFFFFFFFF.toInt()) + assertEquals(1f, d.changedFraction(s)!!, 0f) + } + + @Test fun resetForgetsTheReference() { + val d = ScreenChangeDetector() + d.changedFraction(solid(0x000000)) + d.reset() + assertNull(d.changedFraction(solid(0xFFFFFF))) + assertEquals(0f, d.changedFraction(solid(0xFFFFFF))!!, 0f) + } +} diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/screensaver/ScreensaverPrefsTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/screensaver/ScreensaverPrefsTest.kt index aa67e56..c1dba74 100644 --- a/android/app/src/test/kotlin/com/librestatic/ezdisplay/screensaver/ScreensaverPrefsTest.kt +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/screensaver/ScreensaverPrefsTest.kt @@ -46,6 +46,19 @@ class ScreensaverPrefsTest { assertEquals(0, ScreensaverPrefs.read(prefs, PanelType.Lcd).blankMin) } + @Test fun wakeThresholdDefaultsClampsAndRoundsToTheStep() { + assertEquals(50, ScreensaverPrefs.read(prefs, PanelType.Oled).wakePct) + prefs.edit().putInt(InputPrefs.SCREENSAVER_WAKE_PCT, 0).commit() + assertEquals(5, ScreensaverPrefs.read(prefs, PanelType.Oled).wakePct) + prefs.edit().putInt(InputPrefs.SCREENSAVER_WAKE_PCT, 500).commit() + assertEquals(100, ScreensaverPrefs.read(prefs, PanelType.Oled).wakePct) + prefs.edit().putInt(InputPrefs.SCREENSAVER_WAKE_PCT, 42).commit() + assertEquals(40, ScreensaverPrefs.read(prefs, PanelType.Oled).wakePct) + assertEquals(45, normalizeWakePct(43)) + assertEquals(5, normalizeWakePct(7)) + assertEquals(10, normalizeWakePct(8)) + } + @Test fun blankSliderRounding() { assertEquals(0, roundBlankMin(0f)) assertEquals(0, roundBlankMin(2f)) diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsDisplayTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsDisplayTest.kt index d1d4d67..d572bd4 100644 --- a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsDisplayTest.kt +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsDisplayTest.kt @@ -1,6 +1,8 @@ package com.librestatic.ezdisplay.settings import androidx.compose.ui.semantics.SemanticsActions +import androidx.compose.ui.test.assertIsEnabled +import androidx.compose.ui.test.assertIsNotEnabled import androidx.compose.ui.test.assertIsSelected import androidx.compose.ui.test.assertTextContains import androidx.compose.ui.test.onAllNodesWithText @@ -24,8 +26,11 @@ class SettingsDisplayTest : SettingsUiTestBase() { tag("screensaver_idle_slider").assertExists() tag("screensaver_brightness_slider").assertExists() tag("screensaver_blank_slider").assertExists() + tag("screensaver_wake_slider").assertExists() if (previewBox) tag("screensaver_preview_box").assertExists() else tag("screensaver_preview_box").assertDoesNotExist() tag("screensaver_preview").assertExists() + tag("pixel_shift_row").assertExists() + tag("pixel_shift_slider").assertExists() tag("replay_onboarding").assertExists() } @@ -60,7 +65,9 @@ class SettingsDisplayTest : SettingsUiTestBase() { tag("screensaver_idle_slider").performScrollTo().performSemanticsAction(SemanticsActions.SetProgress) { it(12f) } tag("screensaver_brightness_slider").performScrollTo().performSemanticsAction(SemanticsActions.SetProgress) { it(300f) } tag("screensaver_blank_slider").performScrollTo().performSemanticsAction(SemanticsActions.SetProgress) { it(47f) } + tag("screensaver_wake_slider").performScrollTo().performSemanticsAction(SemanticsActions.SetProgress) { it(62f) } rule.waitForIdle() + assertEquals(60, prefs.getInt(InputPrefs.SCREENSAVER_WAKE_PCT, 0)) assertEquals(12, prefs.getInt(InputPrefs.SCREENSAVER_IDLE_MIN, 0)) assertEquals(30, prefs.getInt(InputPrefs.SCREENSAVER_BRIGHTNESS_PCT, 0)) assertEquals(45, prefs.getInt(InputPrefs.SCREENSAVER_BLANK_MIN, 0)) @@ -68,6 +75,19 @@ class SettingsDisplayTest : SettingsUiTestBase() { assertEquals(2, rule.onAllNodesWithText("30%").fetchSemanticsNodes().size) } + @Test @Config(sdk = [36], qualifiers = "w412dp-h915dp") + fun pixelShiftSliderFollowsTheSwitchAndSaves() { + launch { putBoolean(InputPrefs.PIXEL_SHIFT_ENABLED, false) } + tag("pixel_shift_slider").performScrollTo().assertIsNotEnabled() + tag("pixel_shift_row").performClick() + assertTrue(prefs.getBoolean(InputPrefs.PIXEL_SHIFT_ENABLED, false)) + tag("pixel_shift_slider").assertIsEnabled() + tag("pixel_shift_slider").performSemanticsAction(SemanticsActions.SetProgress) { it(6f) } + rule.waitForIdle() + assertEquals(6, prefs.getInt(InputPrefs.PIXEL_SHIFT_PX, 0)) + rule.onNodeWithText(rule.activity.resources.getQuantityString(R.plurals.settings_pixels, 6, 6)).assertExists() + } + @Test @Config(sdk = [36], qualifiers = "w412dp-h915dp") fun blankSliderShowsNever() { launch { putBoolean(InputPrefs.SCREENSAVER_ENABLED, true) } diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsScreenshotTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsScreenshotTest.kt index 68d3be5..a36b069 100644 --- a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsScreenshotTest.kt +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsScreenshotTest.kt @@ -52,7 +52,10 @@ class SettingsScreenshotTest { override fun setScreensaverBrightnessPct(pct: Int) {} override fun setScreensaverBlankMin(min: Int) {} override fun setScreensaverSpeed(level: Int) {} + override fun setScreensaverWakePct(pct: Int) {} override fun setScreensaverMotion(mode: ScreensaverMotionMode) {} + override fun setPixelShiftEnabled(on: Boolean) {} + override fun setPixelShiftPx(px: Int) {} override fun setAudioEnabled(on: Boolean) {} override fun setVideoCodec(codec: String) {} override fun setStreamQuality(quality: String) {} @@ -207,6 +210,14 @@ class SettingsScreenshotTest { capture("phone_display_dark") } + @Test @Config(sdk = [36], qualifiers = "w412dp-h915dp-night") + fun phone_pixel_shift_dark() { + show(displayState.copy(pixelShiftEnabled = true, pixelShiftPx = 4)) + rule.onNodeWithTag("replay_onboarding").performScrollTo() + rule.waitForIdle() + capture("phone_pixel_shift_dark") + } + @Test @Config(sdk = [36], qualifiers = "w841dp-h701dp-night") fun foldable_display_dark() { show(displayState) diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsStoreTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsStoreTest.kt index 8ec05d6..c5b7b07 100644 --- a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsStoreTest.kt +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsStoreTest.kt @@ -363,6 +363,36 @@ class SettingsStoreTest { assertEquals(120, s.screensaverBlankMin) } + @Test fun screensaverWakeThresholdDefaultsWritesAndClamps() { + assertEquals(50, s.screensaverWakePct) + store.setScreensaverWakePct(75) + assertEquals(75, prefs.getInt(InputPrefs.SCREENSAVER_WAKE_PCT, 0)) + assertEquals(75, s.screensaverWakePct) + store.setScreensaverWakePct(0) + assertEquals(5, s.screensaverWakePct) + store.setScreensaverWakePct(999) + assertEquals(100, s.screensaverWakePct) + assertEquals(35, roundWakePct(33f)) + } + + @Test fun pixelShiftDefaultsWritesAndClamps() { + assertFalse(s.pixelShiftEnabled) + assertEquals(4, s.pixelShiftPx) + store.setPixelShiftEnabled(true) + store.setPixelShiftPx(6) + assertTrue(prefs.getBoolean(InputPrefs.PIXEL_SHIFT_ENABLED, false)) + assertEquals(6, prefs.getInt(InputPrefs.PIXEL_SHIFT_PX, 0)) + assertTrue(s.pixelShiftEnabled) + assertEquals(6, s.pixelShiftPx) + store.setPixelShiftPx(0) + assertEquals(1, s.pixelShiftPx) + store.setPixelShiftPx(99) + assertEquals(8, s.pixelShiftPx) + assertEquals(8, prefs.getInt(InputPrefs.PIXEL_SHIFT_PX, 0)) + assertEquals(3, roundShiftPx(3.4f)) + assertFalse(InputPrefs.toJson(context).contains("pixel_shift")) + } + @Test fun screensaverSpeedAndMotionDefaultsWriteAndClamp() { assertEquals(4, s.screensaverSpeed) assertEquals(ScreensaverMotionMode.Drift, s.screensaverMotion) From 40ad595d67ff5f0af037244641439951b3b08c2e Mon Sep 17 00:00:00 2001 From: FacuM Date: Tue, 17 Nov 2026 12:49:28 -0300 Subject: [PATCH 2/7] Track touch and pen hover apart for pixel shift A mouse hover event cleared the shared flag while a finger was still down, and the eraser end of a pen in hover was treated like a mouse. Both let the picture move under a pointer. The touch state and the hover state are now separate, either end of the pen counts as hovering, and both are cleared when the activity resumes because a pointer that left meanwhile sent no up or exit. --- android/AGENTS.md | 2 +- .../com/librestatic/ezdisplay/MainActivity.kt | 13 +++++--- .../ezdisplay/display/PixelShift.kt | 20 +++++++++--- .../ezdisplay/display/PixelShiftTest.kt | 31 ++++++++++++++++--- 4 files changed, 51 insertions(+), 15 deletions(-) diff --git a/android/AGENTS.md b/android/AGENTS.md index 4062905..1679e35 100644 --- a/android/AGENTS.md +++ b/android/AGENTS.md @@ -44,7 +44,7 @@ Repository-wide rules (languages and localization, naming) are in the root `AGEN - `display/PixelShift.kt` is the burn-in protection for the stream (pure Kotlin, time passed in; `PixelShiftPrefs` next to it, on by default only for OLED, radius 1..8 px, default 4). The offset walks a serpentine over the (2r+1) x (2r+1) grid, one pixel per step, at most one step every 60 s, and only 3 s after the last pointer event with - no pointer down and no stylus hovering, or while the screensaver covers the picture. `MainActivity` translates + no pointer down and no pen hovering (either end; touch and hover are tracked apart), or while the screensaver covers the picture. `MainActivity` translates `shiftLayer` (the parent of `stage`, so the local zoom keeps `stage.translationX/Y` to itself) and `forward()` subtracts the offset from every position before `NativeBridge.inputEvent`; the native engine never sees the shift. The uncovered edge shows the black `root`. `PixelCopy` reads the surface buffer, so the shift is not a screen change. diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt index 17e4110..2148bff 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt @@ -437,6 +437,9 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. saverMotion = idleConfig.motion idle.setConfig(idleConfig, now) idle.setArmed(true, now) + // A pointer that left while the activity was away sent no up or exit here. + shift.onTouch(false, now) + shift.onHover(false, now) if (shift.setConfig(PixelShiftPrefs.read(this), now)) applyShift() changeDetector.reset() applyInputConfig() @@ -1095,7 +1098,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. if (routedAway) return super.dispatchTouchEvent(ev) val action = ev.actionMasked val ending = action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL - shift.onPointer(!ending, SystemClock.uptimeMillis()) + shift.onTouch(!ending, SystemClock.uptimeMillis()) if (swallowTouch) { if (ending) swallowTouch = false return true @@ -1179,9 +1182,11 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. if (routedAway) return super.dispatchGenericMotionEvent(ev) if (ev.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { val exit = ev.actionMasked == MotionEvent.ACTION_HOVER_EXIT - // A hovering stylus holds the picture still; a resting mouse sends no exit, so only its pause counts. - val stylus = ev.getToolType(0) == MotionEvent.TOOL_TYPE_STYLUS - shift.onPointer(stylus && !exit, SystemClock.uptimeMillis()) + // A hovering pen (either end) holds the picture still; a resting mouse sends no exit, so only its + // pause counts. + val tool = ev.getToolType(0) + val pen = tool == MotionEvent.TOOL_TYPE_STYLUS || tool == MotionEvent.TOOL_TYPE_ERASER + shift.onHover(pen && !exit, SystemClock.uptimeMillis()) if (swallowHover) { if (exit) swallowHover = false return true diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/display/PixelShift.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/display/PixelShift.kt index e130e79..ed6371c 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/display/PixelShift.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/display/PixelShift.kt @@ -23,7 +23,8 @@ class PixelShift(config: PixelShiftConfig = PixelShiftConfig(), nowMs: Long = 0L private var direction = 1 private var lastStepMs = nowMs private var lastPointerMs = nowMs - private var pointerActive = false + private var touchDown = false + private var hovering = false var offsetX: Int = 0 private set @@ -43,9 +44,18 @@ class PixelShift(config: PixelShiftConfig = PixelShiftConfig(), nowMs: Long = 0L return restart(nowMs) } - /** Call for every local pointer event; [active] is true while a pointer is down or hovering. */ - fun onPointer(active: Boolean, nowMs: Long) { - pointerActive = active + /** Call for every touch event (finger, pen or mouse button); [down] is true until the last pointer lifts. */ + fun onTouch(down: Boolean, nowMs: Long) { + touchDown = down + lastPointerMs = nowMs + } + + /** + * Call for every hover or other generic pointer event; [hovering] is true while a pen stays in range. A mouse + * passes false, because it sends no exit when it stops: only its pause counts. Never changes the touch state. + */ + fun onHover(hovering: Boolean, nowMs: Long) { + this.hovering = hovering lastPointerMs = nowMs } @@ -53,7 +63,7 @@ class PixelShift(config: PixelShiftConfig = PixelShiftConfig(), nowMs: Long = 0L fun tick(nowMs: Long, covered: Boolean): Boolean { if (!config.enabled) return false if (nowMs - lastStepMs < STEP_INTERVAL_MS) return false - val quiet = !pointerActive && nowMs - lastPointerMs >= QUIET_MS + val quiet = !touchDown && !hovering && nowMs - lastPointerMs >= QUIET_MS if (!covered && !quiet) return false lastStepMs = nowMs val last = side() * side() - 1 diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/display/PixelShiftTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/display/PixelShiftTest.kt index a625997..f47412a 100644 --- a/android/app/src/test/kotlin/com/librestatic/ezdisplay/display/PixelShiftTest.kt +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/display/PixelShiftTest.kt @@ -63,23 +63,23 @@ class PixelShiftTest { @Test fun noStepBeforeTheIntervalOrWhileAPointerIsActive() { val s = PixelShift(on()) assertFalse(s.tick(STEP - 1, covered = false)) - s.onPointer(true, STEP) + s.onTouch(true, STEP) assertFalse(s.tick(STEP + QUIET + 10_000, covered = false)) assertEquals(0 to 0, s.pos()) } @Test fun noStepUntilTheQuietTimeAfterTheLastPointerEvent() { val s = PixelShift(on()) - s.onPointer(false, STEP) + s.onTouch(false, STEP) assertFalse(s.tick(STEP + QUIET - 1, covered = false)) assertTrue(s.tick(STEP + QUIET, covered = false)) } @Test fun aPendingStepFiresOnceAndStepsDoNotAccumulate() { val s = PixelShift(on()) - s.onPointer(true, 0) + s.onTouch(true, 0) assertFalse(s.tick(10 * STEP, covered = false)) - s.onPointer(false, 10 * STEP) + s.onTouch(false, 10 * STEP) assertTrue(s.tick(10 * STEP + QUIET, covered = false)) assertEquals(1, abs(s.offsetX) + abs(s.offsetY)) // The next step is a full interval after the one just taken. @@ -87,9 +87,30 @@ class PixelShiftTest { assertTrue(s.tick(10 * STEP + QUIET + STEP, covered = false)) } + @Test fun aHoverThatIsNotAPenDoesNotReleaseAHeldTouch() { + val s = PixelShift(on()) + s.onTouch(true, 0) + s.onHover(false, STEP) + assertFalse(s.tick(STEP + QUIET + 10_000, covered = false)) + s.onTouch(false, 2 * STEP) + assertTrue(s.tick(2 * STEP + QUIET, covered = false)) + } + + @Test fun aHoveringPenHoldsThePictureUntilItLeaves() { + val s = PixelShift(on()) + s.onHover(true, STEP) + assertFalse(s.tick(STEP + QUIET + 10_000, covered = false)) + // A touch that ends while the pen is still in range does not release it either. + s.onTouch(true, 2 * STEP) + s.onTouch(false, 2 * STEP + 1) + assertFalse(s.tick(3 * STEP, covered = false)) + s.onHover(false, 3 * STEP) + assertTrue(s.tick(3 * STEP + QUIET, covered = false)) + } + @Test fun coveredStepsDespiteRecentInput() { val s = PixelShift(on()) - s.onPointer(true, STEP) + s.onTouch(true, STEP) assertTrue(s.tick(STEP, covered = true)) } From 679356c4b2bcc8c7b4516c4785b9e40376023752 Mon Sep 17 00:00:00 2001 From: FacuM Date: Tue, 17 Nov 2026 12:58:40 -0300 Subject: [PATCH 3/7] Keep the pen hover state when a mouse moves A mouse event went through the hover path with false and cleared the hover of a pen still in range, so a due step could move the picture under it. Mouse events now only record the activity time. --- .../com/librestatic/ezdisplay/MainActivity.kt | 2 +- .../ezdisplay/display/PixelShift.kt | 13 +++++++++---- .../ezdisplay/display/PixelShiftTest.kt | 18 ++++++++++++++++-- 3 files changed, 26 insertions(+), 7 deletions(-) diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt index 2148bff..5218ef7 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt @@ -1186,7 +1186,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. // pause counts. val tool = ev.getToolType(0) val pen = tool == MotionEvent.TOOL_TYPE_STYLUS || tool == MotionEvent.TOOL_TYPE_ERASER - shift.onHover(pen && !exit, SystemClock.uptimeMillis()) + if (pen) shift.onHover(!exit, SystemClock.uptimeMillis()) else shift.onActivity(SystemClock.uptimeMillis()) if (swallowHover) { if (exit) swallowHover = false return true diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/display/PixelShift.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/display/PixelShift.kt index ed6371c..ddbf196 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/display/PixelShift.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/display/PixelShift.kt @@ -50,15 +50,20 @@ class PixelShift(config: PixelShiftConfig = PixelShiftConfig(), nowMs: Long = 0L lastPointerMs = nowMs } - /** - * Call for every hover or other generic pointer event; [hovering] is true while a pen stays in range. A mouse - * passes false, because it sends no exit when it stops: only its pause counts. Never changes the touch state. - */ + /** Call for every hover event of a pen; [hovering] is true while it stays in range. Leaves the touch state alone. */ fun onHover(hovering: Boolean, nowMs: Long) { this.hovering = hovering lastPointerMs = nowMs } + /** + * Call for pointer events that hold nothing: a mouse moving or scrolling sends no exit when it stops, so only + * its pause counts. Leaves the touch and pen hover states alone. + */ + fun onActivity(nowMs: Long) { + lastPointerMs = nowMs + } + /** Takes one pending step when due; returns true when the offset changed. */ fun tick(nowMs: Long, covered: Boolean): Boolean { if (!config.enabled) return false diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/display/PixelShiftTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/display/PixelShiftTest.kt index f47412a..ebc75cf 100644 --- a/android/app/src/test/kotlin/com/librestatic/ezdisplay/display/PixelShiftTest.kt +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/display/PixelShiftTest.kt @@ -87,10 +87,24 @@ class PixelShiftTest { assertTrue(s.tick(10 * STEP + QUIET + STEP, covered = false)) } - @Test fun aHoverThatIsNotAPenDoesNotReleaseAHeldTouch() { + @Test fun mouseActivityDoesNotReleaseAHoveringPen() { + val s = PixelShift(on()) + s.onHover(true, 0) + s.onActivity(STEP) + assertFalse(s.tick(STEP + QUIET + 10_000, covered = false)) + } + + @Test fun mouseActivityOnlyDelaysTheStep() { + val s = PixelShift(on()) + s.onActivity(STEP) + assertFalse(s.tick(STEP + QUIET - 1, covered = false)) + assertTrue(s.tick(STEP + QUIET, covered = false)) + } + + @Test fun mouseActivityDoesNotReleaseAHeldTouch() { val s = PixelShift(on()) s.onTouch(true, 0) - s.onHover(false, STEP) + s.onActivity(STEP) assertFalse(s.tick(STEP + QUIET + 10_000, covered = false)) s.onTouch(false, 2 * STEP) assertTrue(s.tick(2 * STEP + QUIET, covered = false)) From 5c4ec823761810eed77fb10f4e71f003b566d185 Mon Sep 17 00:00:00 2001 From: FacuM Date: Tue, 17 Nov 2026 13:08:48 -0300 Subject: [PATCH 4/7] Sample the screen again once the last frame is shown A frame is counted before it is decoded and shown, so the sample taken on that count could still hold the picture before it; with a damage-driven stream no later frame came to measure it. The poll after the last new frame now samples once more. A sample asked for while a copy is under way is no longer dropped: it runs when the copy ends. --- android/AGENTS.md | 4 +- .../com/librestatic/ezdisplay/MainActivity.kt | 56 ++++++++++++++----- 2 files changed, 44 insertions(+), 16 deletions(-) diff --git a/android/AGENTS.md b/android/AGENTS.md index 1679e35..f2e0435 100644 --- a/android/AGENTS.md +++ b/android/AGENTS.md @@ -37,7 +37,9 @@ Repository-wide rules (languages and localization, naming) are in the root `AGEN `ScreensaverGlyphs`: monitor, tablet, stylus, brush, palette, mouse; not `ShapeBackdrop`), `ScreensaverMotion` (pure Kotlin motion model: Drift or Bounce, speed level 1..10 at 10 dp/s each, rare steps with reduced motion) and `ScreensaverPrefs`. `IdleTracker` rules: new frames are not activity; `MainActivity` samples the stream surface with - `PixelCopy` (96x54) on each frame increase and `ScreenChangeDetector` (pure Kotlin, tolerance 24/255 per channel, + `PixelCopy` (96x54) on each frame increase, and once more on the stats poll after the last increase because a frame + is counted before it is decoded and shown (a request made during a copy runs when the copy ends), and + `ScreenChangeDetector` (pure Kotlin, tolerance 24/255 per channel, reference = screen at the last content activity) gives the changed fraction, which wakes only at `wakePct` (setting "wake threshold", default 50, 5..100 step 5). A PC cursor appearing or moving inside the tablet screen always wakes Saver and Blank (`onHostCursor`); content never wakes Blank; local input is unchanged. The screensaver prefs live in the `input` file but are never part of `InputPrefs.toJson`. diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt index 5218ef7..b958ebe 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt @@ -197,6 +197,8 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. private val sampleBitmap = Bitmap.createBitmap(SAMPLE_W, SAMPLE_H, Bitmap.Config.ARGB_8888) private val samplePixels = IntArray(SAMPLE_W * SAMPLE_H) private var sampling = false + private var samplePending = false // a sample was asked for while a copy was under way + private var settleSample = false // the last poll saw new frames: sample once more when they stop private var rebaseSample = false // the next sample becomes the reference (the screensaver just started) private var samplingFailureLogged = false private var hostCursorInside = false @@ -660,6 +662,8 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. applyInputConfig() wasStreaming = false idle.resetFrames() + samplePending = false + settleSample = false changeDetector.reset() rebaseSample = false lastInputNote = "" @@ -809,32 +813,46 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. * changed to count as activity. Failures only mean that content does not wake the screen. */ private fun sampleScreen() { - if (sampling || !sessionActive || !surfaceView.holder.surface.isValid) return + if (!sessionActive || !surfaceView.holder.surface.isValid) return + if (sampling) { + // The copy under way may predate the newest frame: sample once more when it ends. + samplePending = true + return + } sampling = true try { PixelCopy.request(surfaceView, sampleBitmap, { result -> sampling = false - if (result != PixelCopy.SUCCESS) { - logSamplingFailure("PixelCopy result $result") - return@request + onScreenSample(result) + if (samplePending) { + samplePending = false + sampleScreen() } - if (!started || !sessionActive) return@request - sampleBitmap.getPixels(samplePixels, 0, SAMPLE_W, 0, 0, SAMPLE_W, SAMPLE_H) - if (rebaseSample) { - rebaseSample = false - changeDetector.accept(samplePixels) - return@request - } - val fraction = changeDetector.changedFraction(samplePixels) ?: return@request - if (idle.onScreenChange(fraction, SystemClock.uptimeMillis())) changeDetector.accept(samplePixels) - applyIdle() }, handler) } catch (e: IllegalArgumentException) { sampling = false + samplePending = false logSamplingFailure("PixelCopy failed: ${e.message}") } } + private fun onScreenSample(result: Int) { + if (result != PixelCopy.SUCCESS) { + logSamplingFailure("PixelCopy result $result") + return + } + if (!started || !sessionActive) return + sampleBitmap.getPixels(samplePixels, 0, SAMPLE_W, 0, 0, SAMPLE_W, SAMPLE_H) + if (rebaseSample) { + rebaseSample = false + changeDetector.accept(samplePixels) + return + } + val fraction = changeDetector.changedFraction(samplePixels) ?: return + if (idle.onScreenChange(fraction, SystemClock.uptimeMillis())) changeDetector.accept(samplePixels) + applyIdle() + } + private fun logSamplingFailure(msg: String) { if (samplingFailureLogged) return samplingFailureLogged = true @@ -906,7 +924,15 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. Log.w(TAG, "bad stats", e) return } - if (j.optString("phase") == "streaming" && idle.onFramesReceived(j.optLong("frames_received"), now)) sampleScreen() + if (j.optString("phase") == "streaming") { + // A received frame is decoded and shown a little later, so the poll after the last new frame samples + // once more: otherwise a single large update would be measured on the picture before it. + val grew = idle.onFramesReceived(j.optLong("frames_received"), now) + if (grew || settleSample) sampleScreen() + settleSample = grew + } else { + settleSample = false + } val bw = j.optInt("buffer_width") val bh = j.optInt("buffer_height") if (bw > 0 && bh > 0 && (bw != bufW || bh != bufH)) { From f8c072de351c56531a8dee324e6a9442c8fbd152 Mon Sep 17 00:00:00 2001 From: FacuM Date: Tue, 17 Nov 2026 13:20:21 -0300 Subject: [PATCH 5/7] Take a reference sample when streaming starts The first streaming poll never sampled the screen, because the frame counter has no previous value yet. The first update then became the reference instead of being measured against the picture before it. Sample on the first streaming poll after the change detector is reset, and once more on the next poll, without counting frame reception as activity. --- android/AGENTS.md | 3 ++- .../kotlin/com/librestatic/ezdisplay/MainActivity.kt | 11 +++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/android/AGENTS.md b/android/AGENTS.md index f2e0435..32aae3c 100644 --- a/android/AGENTS.md +++ b/android/AGENTS.md @@ -38,7 +38,8 @@ Repository-wide rules (languages and localization, naming) are in the root `AGEN Kotlin motion model: Drift or Bounce, speed level 1..10 at 10 dp/s each, rare steps with reduced motion) and `ScreensaverPrefs`. `IdleTracker` rules: new frames are not activity; `MainActivity` samples the stream surface with `PixelCopy` (96x54) on each frame increase, and once more on the stats poll after the last increase because a frame - is counted before it is decoded and shown (a request made during a copy runs when the copy ends), and + is counted before it is decoded and shown (a request made during a copy runs when the copy ends), plus on the + first streaming poll after the detector is reset so that there is a reference before the first update, and `ScreenChangeDetector` (pure Kotlin, tolerance 24/255 per channel, reference = screen at the last content activity) gives the changed fraction, which wakes only at `wakePct` (setting "wake threshold", default 50, 5..100 step 5). A PC cursor appearing or moving inside the tablet screen always wakes diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt index b958ebe..4561fe8 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt @@ -199,6 +199,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. private var sampling = false private var samplePending = false // a sample was asked for while a copy was under way private var settleSample = false // the last poll saw new frames: sample once more when they stop + private var needReference = true // the change detector was reset: the first streaming poll samples private var rebaseSample = false // the next sample becomes the reference (the screensaver just started) private var samplingFailureLogged = false private var hostCursorInside = false @@ -444,6 +445,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. shift.onHover(false, now) if (shift.setConfig(PixelShiftPrefs.read(this), now)) applyShift() changeDetector.reset() + needReference = true applyInputConfig() updateDiscovery() checkAccessory() @@ -665,6 +667,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. samplePending = false settleSample = false changeDetector.reset() + needReference = true rebaseSample = false lastInputNote = "" keysHintShown = false @@ -928,8 +931,12 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. // A received frame is decoded and shown a little later, so the poll after the last new frame samples // once more: otherwise a single large update would be measured on the picture before it. val grew = idle.onFramesReceived(j.optLong("frames_received"), now) - if (grew || settleSample) sampleScreen() - settleSample = grew + // Without a reference the first update would become it instead of being measured against the + // picture before it, so the first streaming poll samples too (and settles like a new frame). + val first = needReference && idleConfig.enabled + needReference = false + if (grew || settleSample || first) sampleScreen() + settleSample = grew || first } else { settleSample = false } From a887264a3228ab28e6b2c3bdcc67c210887c18ba Mon Sep 17 00:00:00 2001 From: FacuM Date: Tue, 17 Nov 2026 13:31:31 -0300 Subject: [PATCH 6/7] Retry the reference sample until a copy succeeds A failed PixelCopy on the first streaming poll left the change detector without a reference until the next frame. Keep asking on every streaming poll and clear the flag only when a copy succeeds. --- android/AGENTS.md | 5 +++-- .../main/kotlin/com/librestatic/ezdisplay/MainActivity.kt | 7 ++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/android/AGENTS.md b/android/AGENTS.md index 32aae3c..451fe89 100644 --- a/android/AGENTS.md +++ b/android/AGENTS.md @@ -38,8 +38,9 @@ Repository-wide rules (languages and localization, naming) are in the root `AGEN Kotlin motion model: Drift or Bounce, speed level 1..10 at 10 dp/s each, rare steps with reduced motion) and `ScreensaverPrefs`. `IdleTracker` rules: new frames are not activity; `MainActivity` samples the stream surface with `PixelCopy` (96x54) on each frame increase, and once more on the stats poll after the last increase because a frame - is counted before it is decoded and shown (a request made during a copy runs when the copy ends), plus on the - first streaming poll after the detector is reset so that there is a reference before the first update, and + is counted before it is decoded and shown (a request made during a copy runs when the copy ends), plus on + every streaming poll after the detector is reset until one copy succeeds, so that there is a reference before the + first update, and `ScreenChangeDetector` (pure Kotlin, tolerance 24/255 per channel, reference = screen at the last content activity) gives the changed fraction, which wakes only at `wakePct` (setting "wake threshold", default 50, 5..100 step 5). A PC cursor appearing or moving inside the tablet screen always wakes diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt index 4561fe8..71cfc3f 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt @@ -199,7 +199,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. private var sampling = false private var samplePending = false // a sample was asked for while a copy was under way private var settleSample = false // the last poll saw new frames: sample once more when they stop - private var needReference = true // the change detector was reset: the first streaming poll samples + private var needReference = true // the change detector was reset: streaming polls sample until one copy works private var rebaseSample = false // the next sample becomes the reference (the screensaver just started) private var samplingFailureLogged = false private var hostCursorInside = false @@ -845,6 +845,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. return } if (!started || !sessionActive) return + needReference = false sampleBitmap.getPixels(samplePixels, 0, SAMPLE_W, 0, 0, SAMPLE_W, SAMPLE_H) if (rebaseSample) { rebaseSample = false @@ -932,9 +933,9 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. // once more: otherwise a single large update would be measured on the picture before it. val grew = idle.onFramesReceived(j.optLong("frames_received"), now) // Without a reference the first update would become it instead of being measured against the - // picture before it, so the first streaming poll samples too (and settles like a new frame). + // picture before it, so streaming polls sample until one copy succeeds (and then settle like a new + // frame). `onScreenSample` clears the flag, so a failed copy is tried again on the next poll. val first = needReference && idleConfig.enabled - needReference = false if (grew || settleSample || first) sampleScreen() settleSample = grew || first } else { From 4312a517fb354d6180773ca961753ecd35eca3d0 Mon Sep 17 00:00:00 2001 From: FacuM Date: Tue, 17 Nov 2026 13:41:44 -0300 Subject: [PATCH 7/7] Drop a screen copy that was asked for before a reset A PixelCopy still under way when a session started or the activity resumed could finish afterwards and become the reference of the new session. Tag each request with an epoch that changes with every detector reset, ignore results from an older epoch and sample again instead. --- .../main/kotlin/com/librestatic/ezdisplay/MainActivity.kt | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt index 71cfc3f..646ff97 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt @@ -200,6 +200,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. private var samplePending = false // a sample was asked for while a copy was under way private var settleSample = false // the last poll saw new frames: sample once more when they stop private var needReference = true // the change detector was reset: streaming polls sample until one copy works + private var sampleEpoch = 0 // bumped with each detector reset: a copy asked for before it is dropped private var rebaseSample = false // the next sample becomes the reference (the screensaver just started) private var samplingFailureLogged = false private var hostCursorInside = false @@ -445,6 +446,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. shift.onHover(false, now) if (shift.setConfig(PixelShiftPrefs.read(this), now)) applyShift() changeDetector.reset() + sampleEpoch++ needReference = true applyInputConfig() updateDiscovery() @@ -667,6 +669,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. samplePending = false settleSample = false changeDetector.reset() + sampleEpoch++ needReference = true rebaseSample = false lastInputNote = "" @@ -823,10 +826,12 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. return } sampling = true + val epoch = sampleEpoch try { PixelCopy.request(surfaceView, sampleBitmap, { result -> sampling = false - onScreenSample(result) + // A copy from before the reset shows the previous session or the screen before a pause. + if (epoch == sampleEpoch) onScreenSample(result) else samplePending = true if (samplePending) { samplePending = false sampleScreen()