Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
feat: implement OverlayRotationWatcher to manage overlay positioning during screen rotations
Durganshu Mishra1fcfbc2838b0
diff --git a/app/src/main/java/com/gotcha/service/ScreenLensController.kt b/app/src/main/java/com/gotcha/service/ScreenLensController.ktindex 5ec32d3..8178e6e 100644--- a/app/src/main/java/com/gotcha/service/ScreenLensController.kt+++ b/app/src/main/java/com/gotcha/service/ScreenLensController.kt@@ -48,6 +48,19 @@ class ScreenLensController(private val windowManager = appContext.getSystemService(Context.WINDOW_SERVICE) as WindowManagerprivate val mainHandler = Handler(Looper.getMainLooper())+ /**+ * Lens does not survive a rotation, and should not pretend to.+ *+ * Everything the session is holding — the crop rectangle, the accessibility+ * bounds the annotations are drawn at, the chip bar's placement, the crop+ * bitmap already taken — is in the pixels of the screen it started on. When+ * the device rotates, the app underneath re-lays itself out, so those+ * coordinates no longer point at the thing the user was selecting. Closing+ * is the only honest answer; re-placing the chrome would leave a selection+ * that looks right and means nothing.+ */+ private val rotationWatcher = com.gotcha.ui.OverlayRotationWatcher(context) { _, _ -> cancel() }+private var cropOverlay: View? = nullprivate var actionMenu: View? = nullprivate var textChips: View? = null@@ -98,6 +111,7 @@ class ScreenLensController(try {windowManager.addView(overlay, params)cropOverlay = overlay+ rotationWatcher.start()} catch (_: Exception) {cropOverlay = nullonError("Couldn't start Lens mode")@@ -107,6 +121,7 @@ class ScreenLensController(fun cancel() {mainHandler.post {+ rotationWatcher.stop()removeCropOverlay()removeActionMenu()removeTextChips()diff --git a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.ktindex df20520..27b4a8a 100644--- a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt+++ b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt@@ -1,10 +1,8 @@package com.gotcha.uiimport android.animation.ValueAnimator-import android.content.ComponentCallbacksimport android.content.Contextimport android.content.SharedPreferences-import android.content.res.Configurationimport android.graphics.Colorimport android.graphics.PixelFormatimport android.graphics.Typeface@@ -12,6 +10,7 @@ import android.graphics.drawable.GradientDrawableimport android.os.Handlerimport android.os.Looperimport android.provider.Settings+import android.util.Sizeimport android.view.Gravityimport android.view.HapticFeedbackConstantsimport android.view.MotionEvent@@ -124,16 +123,9 @@ class AssistiveBallOverlay(context: Context) {/** Held so a rotation mid-glide cannot finish it against the old screen. */private var dockAnimator: ValueAnimator? = null- /**- * The screen [ballParams] was last positioned against.- *- * The window position is in pixels and nothing moves it when the device- * rotates, so the ball has to be put back itself. Keeping the old size is- * what makes that possible: without it there is no way to tell where down- * the screen the ball used to be.- */- private var lastScreenWidth: Int = 0- private var lastScreenHeight: Int = 0+ private val rotationWatcher = OverlayRotationWatcher(context) { previous, current ->+ handleScreenChanged(previous, current)+ }private val ballParams: WindowManager.LayoutParams by lazy { ballLayoutParams() }private val settingsRepository by lazy { SettingsRepository(appContext) }@@ -165,33 +157,9 @@ class AssistiveBallOverlay(context: Context) {mainHandler.post { restyleIfSkinChanged() }}- /**- * Put the ball back on screen after the device rotates.- *- * An overlay window is positioned in raw pixels and nobody re-lays it out- * for us: a ball docked to the right edge in landscape is sitting at- * roughly x=2200, and in portrait that is a few hundred pixels past the- * right of a 1080px display. With FLAG_LAYOUT_NO_LIMITS there is nothing to- * clamp it either, so the ball simply vanished — it was never gone, just- * parked off the side of the screen.- */- private val configWatcher = object : ComponentCallbacks {- override fun onConfigurationChanged(newConfig: Configuration) {- // Posted rather than handled inline: the callback can arrive on the- // same pass that updates the app's resources, and every measurement- // below reads displayMetrics.- mainHandler.post { handleScreenChanged() }- }-- override fun onLowMemory() { }- }-- private fun handleScreenChanged() {+ /** Put the ball back on screen after the display changes shape. */+ private fun handleScreenChanged(previous: Size, current: Size) {if (ballView == null) return- val metrics = appContext.resources.displayMetrics- val width = metrics.widthPixels- val height = metrics.heightPixels- if (width == lastScreenWidth && height == lastScreenHeight) return// The menu is measured and placed once, against the screen it opened// on, and the dismiss target only exists mid-drag. Neither survives a@@ -205,16 +173,14 @@ class AssistiveBallOverlay(context: Context) {if (isDocked) ballView?.alpha = PEEK_ALPHA// Keep the ball as far down the screen as it was, and put it back on- // its edge. A ball the user dragged somewhere gets carried across- // proportionally instead, which is the closest thing to "where I left- // it" that survives the screen changing shape.- val xFraction = if (lastScreenWidth > 0) ballParams.x.toFloat() / lastScreenWidth else 0f- val yFraction = if (lastScreenHeight > 0) ballParams.y.toFloat() / lastScreenHeight else 0f- lastScreenWidth = width- lastScreenHeight = height-- ballParams.x = if (isDocked) dockedX(dockSide) else (xFraction * width).toInt()- ballParams.y = (yFraction * height).toInt()+ // its edge — the docked x is a function of the screen width, so it is+ // the one position that has to be recomputed rather than carried over.+ ballParams.x = if (isDocked) {+ dockedX(dockSide)+ } else {+ remapAcrossScreen(ballParams.x, previous.width, current.width)+ }+ ballParams.y = remapAcrossScreen(ballParams.y, previous.height, current.height)clampBallIntoBounds()}@@ -295,13 +261,10 @@ class AssistiveBallOverlay(context: Context) {if (ballView != null) return@postval ball = buildBall()try {- val metrics = appContext.resources.displayMetrics- lastScreenWidth = metrics.widthPixels- lastScreenHeight = metrics.heightPixelswindowManager.addView(ball, ballParams)ballView = ballrefreshStatusRing()- appContext.registerComponentCallbacks(configWatcher)+ rotationWatcher.start()// SharedPreferences keeps only a weak reference to a listener;// [skinWatcher] is a field of this object, which the service// holds, so it survives as long as the ball does.@@ -321,7 +284,7 @@ class AssistiveBallOverlay(context: Context) {settingsChangeNotifier(appContext).unregisterOnSharedPreferenceChangeListener(skinWatcher)}- runCatching { appContext.unregisterComponentCallbacks(configWatcher) }+ rotationWatcher.stop()dockAnimator?.cancel()dockAnimator = nullremoveLongPressRing()diff --git a/app/src/main/java/com/gotcha/ui/CallChatWindow.kt b/app/src/main/java/com/gotcha/ui/CallChatWindow.ktindex b69294d..884508b 100644--- a/app/src/main/java/com/gotcha/ui/CallChatWindow.kt+++ b/app/src/main/java/com/gotcha/ui/CallChatWindow.kt@@ -9,6 +9,7 @@ import android.graphics.PixelFormatimport android.graphics.drawable.GradientDrawableimport android.os.Handlerimport android.os.Looper+import android.util.Sizeimport android.view.Gravityimport android.view.MotionEventimport android.view.View@@ -47,6 +48,10 @@ class CallChatWindow(context: Context) {var onInterrupt: () -> Unit = {}var onEndCall: () -> Unit = {}+ private val rotationWatcher = OverlayRotationWatcher(context) { previous, current ->+ handleScreenChanged(previous, current)+ }+private var rootView: View? = nullprivate var rootParams: WindowManager.LayoutParams? = nullprivate var actionBtn: View? = null@@ -100,6 +105,7 @@ class CallChatWindow(context: Context) {windowManager.addView(root, params)rootView = rootrootParams = params+ rotationWatcher.start()renderButtons()} catch (_: Exception) {rootView = null@@ -111,6 +117,7 @@ class CallChatWindow(context: Context) {fun hide() {mainHandler.post {mainHandler.removeCallbacks(endLongPressRunnable)+ rotationWatcher.stop()stopBreathe()swapAnimator?.cancel()swapAnimator = null@@ -723,13 +730,28 @@ class CallChatWindow(context: Context) {windowManager.updateViewLayout(rootView, p)} catch (_: Exception) { }}+ // The ring is its own window and does not come along.+ followRootWithActionRing()}true}MotionEvent.ACTION_UP -> {mainHandler.removeCallbacks(endLongPressRunnable)removeRingOverlay()- if (!dragging && !longPressFired) {+ if (dragging) {+ // Nothing else stops a drag from parking the end-call+ // button past the edge of the display, which during a call+ // is the one control that has to stay reachable.+ rootParams?.let { p ->+ rootView?.let { v ->+ clampIntoBounds(p, v)+ try {+ windowManager.updateViewLayout(v, p)+ } catch (_: Exception) { }+ }+ }+ followRootWithActionRing()+ } else if (!longPressFired) {handleActionUp(event.x, event.y)}longPressFired = false@@ -746,6 +768,66 @@ class CallChatWindow(context: Context) {// ---- Layout ----+ /**+ * Put the buttons back on screen after the display changes shape.+ *+ * They open anchored to the bottom-right corner and can be dragged+ * anywhere from there, all in raw pixels against the display. Rotating+ * leaves both cases stranded: the resting position alone is roughly+ * (width - 120dp, height - 120dp), which in the other orientation is well+ * past two of the four edges.+ */+ private fun handleScreenChanged(previous: Size, current: Size) {+ val view = rootView ?: return+ val params = rootParams ?: return++ // Mid-press ring: the finger that started it is on an edge that moved.+ removeRingOverlay()++ params.x = remapAcrossScreen(params.x, previous.width, current.width)+ params.y = remapAcrossScreen(params.y, previous.height, current.height)+ clampIntoBounds(params, view)+ try {+ windowManager.updateViewLayout(view, params)+ } catch (_: Exception) { }+ followRootWithActionRing()+ }++ /**+ * Keep the whole control on the display.+ *+ * FLAG_LAYOUT_NO_LIMITS lets the window sit off the edge, which is what+ * makes the ring overlays possible; it also means nothing stops the+ * buttons from ending up somewhere unreachable.+ */+ private fun clampIntoBounds(params: WindowManager.LayoutParams, view: View) {+ val metrics = appContext.resources.displayMetrics+ // A window added this frame has not been measured yet; the resting+ // size is a good enough floor to clamp against until it has.+ val width = if (view.width > 0) view.width else dp(BTN_SIZE_DP * 2f + 32f)+ val height = if (view.height > 0) view.height else dp(BTN_SIZE_DP.toFloat())+ params.x = params.x.coerceIn(0, (metrics.widthPixels - width).coerceAtLeast(0))+ params.y = params.y.coerceIn(0, (metrics.heightPixels - height).coerceAtLeast(0))+ }++ /**+ * Move the action ring back onto the button it belongs to. It is its own+ * window — sized for an aura that a button-sized window would clip — so it+ * does not travel with the root on its own.+ */+ private fun followRootWithActionRing() {+ val view = actionRingOverlayView ?: return+ val params = view.layoutParams as? WindowManager.LayoutParams ?: return+ val density = appContext.resources.displayMetrics.density+ val paddingPx = (8 * density).toInt()+ val btnPx = (BTN_SIZE_DP * density).toInt()+ params.x = (rootParams?.x ?: 0) + paddingPx + btnPx / 2 - params.width / 2+ params.y = (rootParams?.y ?: 0) + btnPx / 2 - params.height / 2+ try {+ windowManager.updateViewLayout(view, params)+ } catch (_: Exception) { }+ }+private fun layoutParams(): WindowManager.LayoutParams {val type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAYval metrics = appContext.resources.displayMetricsdiff --git a/app/src/main/java/com/gotcha/ui/OverlayRotationWatcher.kt b/app/src/main/java/com/gotcha/ui/OverlayRotationWatcher.ktnew file mode 100644index 0000000..bd1cad7--- /dev/null+++ b/app/src/main/java/com/gotcha/ui/OverlayRotationWatcher.kt@@ -0,0 +1,92 @@+package com.gotcha.ui++import android.content.ComponentCallbacks+import android.content.Context+import android.content.res.Configuration+import android.os.Handler+import android.os.Looper+import android.util.Size++/**+ * Tells an overlay when the screen it is pinned to changes shape.+ *+ * An overlay window is positioned in raw pixels against the display and+ * nothing re-lays it out when the device rotates. A control docked to the+ * right edge in landscape is sitting at roughly x=2300, and in portrait that+ * is several hundred pixels past the side of a 1080px screen; with+ * FLAG_LAYOUT_NO_LIMITS there is nothing to clamp it either. The window is+ * still there — just parked off the display, which is indistinguishable from+ * it having vanished.+ *+ * Every overlay that pins itself to an edge, carries a dragged position, or+ * sizes itself against the screen owns one of these and puts itself back.+ * Overlays laid out purely by gravity (a centred card, say) do not need one:+ * WindowManager re-centres those on its own.+ */+class OverlayRotationWatcher(+ context: Context,+ private val onScreenChanged: (previous: Size, current: Size) -> Unit+) {++ private val appContext = context.applicationContext+ private val mainHandler = Handler(Looper.getMainLooper())+ private var registered = false+ private var lastSize = Size(0, 0)++ private val callbacks = object : ComponentCallbacks {+ override fun onConfigurationChanged(newConfig: Configuration) {+ // Posted rather than handled inline: the callback can arrive on the+ // same pass that updates the app's resources, and everything the+ // overlays measure against reads displayMetrics.+ mainHandler.post { dispatch() }+ }++ override fun onLowMemory() { }+ }++ /** The display's size right now, in pixels. */+ fun screenSize(): Size {+ val metrics = appContext.resources.displayMetrics+ return Size(metrics.widthPixels, metrics.heightPixels)+ }++ /**+ * Start watching, taking the current screen as the baseline. Call once the+ * overlay's window is actually up; calling again while running only+ * re-baselines, which is what a window being re-added wants.+ */+ fun start() {+ lastSize = screenSize()+ if (registered) return+ appContext.registerComponentCallbacks(callbacks)+ registered = true+ }++ /** Stop watching. Safe to call when never started. */+ fun stop() {+ if (!registered) return+ runCatching { appContext.unregisterComponentCallbacks(callbacks) }+ registered = false+ }++ private fun dispatch() {+ if (!registered) return+ val current = screenSize()+ // Configuration changes fire for font scale, locale, dark mode and a+ // dozen other things. Only a screen that actually changed size moved+ // anybody's window.+ if (current == lastSize) return+ val previous = lastSize+ lastSize = current+ onScreenChanged(previous, current)+ }+}++/**+ * Where [value] sat along a [from]-long axis, moved to a [to]-long one.+ *+ * The closest thing to "where I left it" that survives the screen changing+ * shape, for positions the user chose rather than ones we compute.+ */+fun remapAcrossScreen(value: Int, from: Int, to: Int): Int =+ if (from <= 0) value else (value.toFloat() / from * to).toInt()diff --git a/app/src/main/java/com/gotcha/ui/ScreenCompanionPanelOverlay.kt b/app/src/main/java/com/gotcha/ui/ScreenCompanionPanelOverlay.ktindex 71b7155..80ece78 100644--- a/app/src/main/java/com/gotcha/ui/ScreenCompanionPanelOverlay.kt+++ b/app/src/main/java/com/gotcha/ui/ScreenCompanionPanelOverlay.kt@@ -30,7 +30,11 @@ class ScreenCompanionPanelOverlay(private val context: Context) {private val mainHandler = Handler(Looper.getMainLooper())private val markwon = Markwon.create(appContext)+ private val rotationWatcher = OverlayRotationWatcher(context) { _, _ -> handleScreenChanged() }+private var panelView: View? = null+ private var panelParams: WindowManager.LayoutParams? = null+ private var panelShadowPad: Int = 0private var responseTextView: TextView? = nullprivate var inputEditText: EditText? = nullprivate var micButton: TextView? = null@@ -264,8 +268,8 @@ class ScreenCompanionPanelOverlay(private val context: Context) {// Sized to the card plus the room its shadow needs, so the shadow is not// clipped to the window's square edge.val params = WindowManager.LayoutParams(- dp(320) + shadowPad * 2,- dp(400) + shadowPad * 2,+ 0,+ 0,WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE orWindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,@@ -273,6 +277,8 @@ class ScreenCompanionPanelOverlay(private val context: Context) {).apply {gravity = Gravity.CENTER}+ panelShadowPad = shadowPad+ applyPanelSize(params)editText.setOnTouchListener { _, event ->if (event.action == MotionEvent.ACTION_DOWN) {@@ -309,6 +315,34 @@ class ScreenCompanionPanelOverlay(private val context: Context) {try {windowManager.addView(container, params)panelView = container+ panelParams = params+ rotationWatcher.start()+ } catch (_: Exception) {}+ }++ /**+ * Size the panel to the card it wants to be, or to the screen if that is+ * smaller.+ *+ * The panel is centred, so rotating never strands it — but it asked for a+ * flat 400dp of height, and a phone in landscape is only about 410dp tall.+ * The card overflowed top and bottom, taking the close button and the+ * input row off screen with it.+ */+ private fun applyPanelSize(params: WindowManager.LayoutParams) {+ val metrics = appContext.resources.displayMetrics+ val maxWidth = metrics.widthPixels - dp(SCREEN_MARGIN_DP) * 2+ val maxHeight = metrics.heightPixels - dp(SCREEN_MARGIN_DP) * 2+ params.width = (dp(PANEL_WIDTH_DP) + panelShadowPad * 2).coerceAtMost(maxWidth)+ params.height = (dp(PANEL_HEIGHT_DP) + panelShadowPad * 2).coerceAtMost(maxHeight)+ }++ private fun handleScreenChanged() {+ val view = panelView ?: return+ val params = panelParams ?: return+ applyPanelSize(params)+ try {+ windowManager.updateViewLayout(view, params)} catch (_: Exception) {}}@@ -386,12 +420,14 @@ class ScreenCompanionPanelOverlay(private val context: Context) {fun dismiss() {mainHandler.post {+ rotationWatcher.stop()panelView?.let {try {windowManager.removeView(it)} catch (_: Exception) {}}panelView = null+ panelParams = nullinputEditText = nullmicButton = nullspeakerButton = null@@ -405,5 +441,11 @@ class ScreenCompanionPanelOverlay(private val context: Context) {private companion object {/** Semantic, not thematic: an open microphone is red in every skin. */val RECORDING_RED = Color.parseColor("#E23B3B")++ const val PANEL_WIDTH_DP = 320+ const val PANEL_HEIGHT_DP = 400++ /** Breathing room so the card never runs into the display edge. */+ const val SCREEN_MARGIN_DP = 16}}