Skip to content

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

feat(proactive): ProactiveSessionManager, multi-entity grouped UI, notification OTP auto-copy, settings toggles & debouncing

Rishabh Bajpai28eb9b9ddecf
diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
index c6135a9..f1b7c9a 100644
--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt
+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
@@ -40,7 +40,14 @@ data class Settings(
val autoReadReplies: Boolean = false,
val assistiveBallEnabled: Boolean = false,
val themeMode: ThemeMode = ThemeMode.SYSTEM,
- val disabledSkills: Set<String> = emptySet()
+ val disabledSkills: Set<String> = emptySet(),
+ // Proactive Assistance Settings
+ val proactiveEnabled: Boolean = true,
+ val proactiveScanScreen: Boolean = true,
+ val proactiveScanClipboard: Boolean = true,
+ val proactiveScanNotifications: Boolean = true,
+ val proactiveAutoCopyOtp: Boolean = true,
+ val proactiveAppBlacklist: Set<String> = emptySet()
) {
/** True when the active provider has everything it needs to make requests. */
val isConfigured: Boolean
@@ -115,7 +122,13 @@ class SettingsRepository(context: Context) {
themeMode = runCatching {
ThemeMode.valueOf(prefs.getString(KEY_THEME_MODE, "SYSTEM") ?: "SYSTEM")
}.getOrDefault(ThemeMode.SYSTEM),
- disabledSkills = prefs.getStringSet(KEY_DISABLED_SKILLS, emptySet()) ?: emptySet()
+ disabledSkills = prefs.getStringSet(KEY_DISABLED_SKILLS, emptySet()) ?: emptySet(),
+ proactiveEnabled = prefs.getBoolean(KEY_PROACTIVE_ENABLED, true),
+ proactiveScanScreen = prefs.getBoolean(KEY_PROACTIVE_SCAN_SCREEN, true),
+ proactiveScanClipboard = prefs.getBoolean(KEY_PROACTIVE_SCAN_CLIPBOARD, true),
+ proactiveScanNotifications = prefs.getBoolean(KEY_PROACTIVE_SCAN_NOTIFICATIONS, true),
+ proactiveAutoCopyOtp = prefs.getBoolean(KEY_PROACTIVE_AUTO_COPY_OTP, true),
+ proactiveAppBlacklist = prefs.getStringSet(KEY_PROACTIVE_BLACKLIST, emptySet()) ?: emptySet()
)
fun save(settings: Settings) {
@@ -143,6 +156,12 @@ class SettingsRepository(context: Context) {
.putBoolean(KEY_ASSISTIVE_BALL, settings.assistiveBallEnabled)
.putString(KEY_THEME_MODE, settings.themeMode.name)
.putStringSet(KEY_DISABLED_SKILLS, settings.disabledSkills)
+ .putBoolean(KEY_PROACTIVE_ENABLED, settings.proactiveEnabled)
+ .putBoolean(KEY_PROACTIVE_SCAN_SCREEN, settings.proactiveScanScreen)
+ .putBoolean(KEY_PROACTIVE_SCAN_CLIPBOARD, settings.proactiveScanClipboard)
+ .putBoolean(KEY_PROACTIVE_SCAN_NOTIFICATIONS, settings.proactiveScanNotifications)
+ .putBoolean(KEY_PROACTIVE_AUTO_COPY_OTP, settings.proactiveAutoCopyOtp)
+ .putStringSet(KEY_PROACTIVE_BLACKLIST, settings.proactiveAppBlacklist)
.apply()
}
@@ -186,5 +205,11 @@ class SettingsRepository(context: Context) {
const val KEY_ASSISTIVE_BALL = "assistive_ball_enabled"
const val KEY_THEME_MODE = "theme_mode"
const val KEY_DISABLED_SKILLS = "disabled_skills"
+ const val KEY_PROACTIVE_ENABLED = "proactive_enabled"
+ const val KEY_PROACTIVE_SCAN_SCREEN = "proactive_scan_screen"
+ const val KEY_PROACTIVE_SCAN_CLIPBOARD = "proactive_scan_clipboard"
+ const val KEY_PROACTIVE_SCAN_NOTIFICATIONS = "proactive_scan_notifications"
+ const val KEY_PROACTIVE_AUTO_COPY_OTP = "proactive_auto_copy_otp"
+ const val KEY_PROACTIVE_BLACKLIST = "proactive_blacklist"
}
}
diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
index 395d98f..b1a8063 100644
--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
@@ -75,8 +75,11 @@ class AssistiveBallService : Service() {
)
}
+ val proactiveSessionManager = ProactiveSessionManager()
+
override fun onCreate() {
super.onCreate()
+ instance = this
settingsRepository = SettingsRepository(this)
val s = settingsRepository.load()
ttsEngine = TtsEngine(this, s.ttsApiBaseUrl, s.apiKey)
@@ -356,6 +359,36 @@ class AssistiveBallService : Service() {
data = android.provider.CalendarContract.Events.CONTENT_URI
putExtra(android.provider.CalendarContract.Events.TITLE, payload)
}
+ SmartActionDetector.TYPE_SMS ->
+ Intent(Intent.ACTION_SENDTO, android.net.Uri.parse("smsto:" + android.net.Uri.encode(payload)))
+ SmartActionDetector.TYPE_VIEW ->
+ Intent(Intent.ACTION_VIEW, android.net.Uri.parse(payload))
+ SmartActionDetector.TYPE_MAILTO ->
+ Intent(Intent.ACTION_SENDTO, android.net.Uri.parse("mailto:" + android.net.Uri.encode(payload)))
+ SmartActionDetector.TYPE_SHARE ->
+ Intent.createChooser(
+ Intent(Intent.ACTION_SEND).apply {
+ this.type = "text/plain"
+ putExtra(Intent.EXTRA_TEXT, payload)
+ },
+ "Share"
+ )
+ SmartActionDetector.TYPE_CONTACT ->
+ Intent(Intent.ACTION_INSERT).apply {
+ data = android.provider.ContactsContract.Contacts.CONTENT_URI
+ putExtra(android.provider.ContactsContract.Intents.Insert.PHONE, payload)
+ }
+ SmartActionDetector.TYPE_WHATSAPP -> {
+ val cleanPhone = payload.replace(Regex("[^0-9+]"), "")
+ val uri = android.net.Uri.parse("https://api.whatsapp.com/send?phone=" + android.net.Uri.encode(cleanPhone))
+ Intent(Intent.ACTION_VIEW, uri)
+ }
+ SmartActionDetector.TYPE_COPY -> {
+ val clipManager = getSystemService(Context.CLIPBOARD_SERVICE) as? android.content.ClipboardManager
+ clipManager?.setPrimaryClip(android.content.ClipData.newPlainText("Gotcha", payload))
+ android.widget.Toast.makeText(this, "Copied to clipboard", android.widget.Toast.LENGTH_SHORT).show()
+ null
+ }
else -> null
} ?: return
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
@@ -606,6 +639,7 @@ class AssistiveBallService : Service() {
override fun onBind(intent: Intent?): IBinder? = null
override fun onDestroy() {
+ if (instance === this) instance = null
_isRunning.value = false
callController.endCall()
chatWindow.hide()
@@ -763,6 +797,18 @@ class AssistiveBallService : Service() {
/** Cap on fetched page text handed to the LLM for link summarization. */
private const val MAX_FETCH_CHARS = 12000
+ @Volatile
+ var instance: AssistiveBallService? = null
+ private set
+
+ fun onProactiveEntitiesDiscovered(entities: List<DetectedEntity>, packageName: String? = null) {
+ val service = instance ?: return
+ android.os.Handler(android.os.Looper.getMainLooper()).post {
+ val sessionItems = service.proactiveSessionManager.mergeEntities(entities, packageName)
+ service.overlay.setProactiveSessionItems(sessionItems)
+ }
+ }
+
fun startIntent(context: Context): Intent =
Intent(context, AssistiveBallService::class.java).setAction(ACTION_START)
diff --git a/app/src/main/java/com/gotcha/service/GotchaNotificationListenerService.kt b/app/src/main/java/com/gotcha/service/GotchaNotificationListenerService.kt
index 3e9b4ef..2e66b47 100644
--- a/app/src/main/java/com/gotcha/service/GotchaNotificationListenerService.kt
+++ b/app/src/main/java/com/gotcha/service/GotchaNotificationListenerService.kt
@@ -1,15 +1,20 @@
package com.gotcha.service
+import android.content.ClipData
+import android.content.ClipboardManager
+import android.content.Context
+import android.os.Handler
+import android.os.Looper
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
+import android.widget.Toast
+import com.gotcha.data.SettingsRepository
/**
* Tier 3 — NotificationListenerService.
*
- * Once the user grants Notification access, this service can read and dismiss the
- * notifications of every app. Like the accessibility service it publishes a static
- * [instance] so the stateless [com.gotcha.tools.NotificationTool] can query the
- * live, bound service; when the user has not granted access the instance is null.
+ * Reads incoming notifications, runs proactive entity detection (OTP, URLs, phone, email),
+ * optionally auto-copies OTPs, and forwards discovered entities to the proactive engine.
*/
class GotchaNotificationListenerService : NotificationListenerService() {
@@ -28,8 +33,44 @@ class GotchaNotificationListenerService : NotificationListenerService() {
super.onDestroy()
}
- // We don't need to react to posts/removals; tools pull on demand.
- override fun onNotificationPosted(sbn: StatusBarNotification?) {}
+ override fun onNotificationPosted(sbn: StatusBarNotification?) {
+ if (sbn == null) return
+ val context = applicationContext
+ val settings = runCatching { SettingsRepository(context).load() }.getOrNull() ?: return
+ if (!settings.proactiveEnabled || !settings.proactiveScanNotifications) return
+
+ val pkg = sbn.packageName ?: ""
+ if (settings.proactiveAppBlacklist.contains(pkg)) return
+
+ val extras = sbn.notification?.extras ?: return
+ val title = extras.getCharSequence("android.title")?.toString() ?: ""
+ val text = extras.getCharSequence("android.text")?.toString() ?: ""
+ val fullText = "$title $text".trim()
+ if (fullText.isBlank()) return
+
+ val entities = SmartActionDetector.detectAll(fullText, allowChat = false)
+ if (entities.isEmpty()) return
+
+ // Auto-copy OTP if enabled
+ if (settings.proactiveAutoCopyOtp) {
+ val otpEntity = entities.firstOrNull { it.type == EntityType.OTP }
+ if (otpEntity != null) {
+ val clipManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
+ clipManager?.setPrimaryClip(ClipData.newPlainText("OTP Code", otpEntity.normalizedValue))
+ Handler(Looper.getMainLooper()).post {
+ Toast.makeText(
+ context,
+ "🔑 OTP ${otpEntity.normalizedValue} copied to clipboard",
+ Toast.LENGTH_SHORT
+ ).show()
+ }
+ }
+ }
+
+ // Forward to proactive engine
+ AssistiveBallService.onProactiveEntitiesDiscovered(entities, pkg)
+ }
+
override fun onNotificationRemoved(sbn: StatusBarNotification?) {}
/** Snapshot of the currently-active notifications (safe wrapper around the platform call). */
diff --git a/app/src/main/java/com/gotcha/service/ProactiveSessionManager.kt b/app/src/main/java/com/gotcha/service/ProactiveSessionManager.kt
new file mode 100644
index 0000000..2fe17a0
--- /dev/null
+++ b/app/src/main/java/com/gotcha/service/ProactiveSessionManager.kt
@@ -0,0 +1,103 @@
+package com.gotcha.service
+
+import android.graphics.Rect
+
+/**
+ * An item stored in the active proactive session list.
+ */
+data class ProactiveSessionItem(
+ val entity: DetectedEntity,
+ val firstSeenTimestamp: Long = System.currentTimeMillis(),
+ var lastUpdatedTimestamp: Long = System.currentTimeMillis(),
+ var boundsOnScreen: Rect? = null
+)
+
+/**
+ * Manages the stable, deduplicated, non-flickering accumulator of detected entities
+ * across screen scans, clipboard updates, and notifications.
+ */
+class ProactiveSessionManager(
+ private val ttlMs: Long = 45_000L
+) {
+ private val itemsMap = LinkedHashMap<String, ProactiveSessionItem>()
+ private var lastPackageName: String? = null
+
+ /**
+ * Merge new detected entities into the session.
+ * Re-detected entities update their timestamp without resetting order;
+ * new entities append. Expired items beyond [ttlMs] are purged.
+ */
+ @Synchronized
+ fun mergeEntities(
+ newEntities: List<DetectedEntity>,
+ packageName: String? = null
+ ): List<ProactiveSessionItem> {
+ val now = System.currentTimeMillis()
+
+ // If package changed to a different foreground app, clear old screen entities
+ if (packageName != null && lastPackageName != null && packageName != lastPackageName) {
+ itemsMap.entries.removeIf { (_, item) ->
+ item.entity.type != EntityType.OTP && item.entity.type != EntityType.CHAT_REPLY
+ }
+ }
+ if (packageName != null) {
+ lastPackageName = packageName
+ }
+
+ // Purge expired items
+ itemsMap.entries.removeIf { (_, item) -> now - item.lastUpdatedTimestamp > ttlMs }
+
+ // Merge new entities
+ for (entity in newEntities) {
+ val key = "${entity.type}:${entity.normalizedValue}"
+ val existing = itemsMap[key]
+ if (existing != null) {
+ existing.lastUpdatedTimestamp = now
+ itemsMap[key] = existing.copy(
+ entity = entity,
+ lastUpdatedTimestamp = now,
+ boundsOnScreen = existing.boundsOnScreen
+ )
+ } else {
+ itemsMap[key] = ProactiveSessionItem(
+ entity = entity,
+ firstSeenTimestamp = now,
+ lastUpdatedTimestamp = now
+ )
+ }
+ }
+
+ return getActiveSessionItems()
+ }
+
+ /**
+ * Get all active session items ordered by entity priority and timestamp.
+ */
+ @Synchronized
+ fun getActiveSessionItems(): List<ProactiveSessionItem> {
+ val now = System.currentTimeMillis()
+ itemsMap.entries.removeIf { (_, item) -> now - item.lastUpdatedTimestamp > ttlMs }
+ return itemsMap.values.sortedWith(
+ compareByDescending<ProactiveSessionItem> { it.entity.type.basePriority }
+ .thenByDescending { it.lastUpdatedTimestamp }
+ )
+ }
+
+ /**
+ * Get entity counts grouped by [EntityType] for discoverability badges.
+ */
+ @Synchronized
+ fun getCategoryCounts(): Map<EntityType, Int> {
+ val active = getActiveSessionItems()
+ return active.groupingBy { it.entity.type }.eachCount()
+ }
+
+ /**
+ * Clear all session state.
+ */
+ @Synchronized
+ fun clear() {
+ itemsMap.clear()
+ lastPackageName = null
+ }
+}
diff --git a/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt b/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt
index 73a48d1..f6f1c3e 100644
--- a/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt
+++ b/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt
@@ -10,20 +10,20 @@ import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import com.gotcha.agent.ScreenSnapshot
+import com.gotcha.data.SettingsRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
+@Suppress("TooManyFunctions")
class ScreenCompanionController(
private val context: Context,
private val scope: CoroutineScope,
private val onSmartActionReady: (label: String, prompt: String) -> Unit,
private val onReadClipboardRequest: () -> Unit = {},
- /**
- * Offer a primary action plus an optional secondary ("alt") action — used to
- * pair "Extract text?" with "Translate Screenshot" on a screenshot trigger.
- */
private val onSmartActionPairReady: (
label: String,
prompt: String,
@@ -33,6 +33,8 @@ class ScreenCompanionController(
) {
private val mainHandler = Handler(Looper.getMainLooper())
+ private var scanDebounceJob: Job? = null
+ private var lastScreenTextHash: Int = 0
private val screenshotObserver = object : ContentObserver(mainHandler) {
override fun onChange(selfChange: Boolean, uri: Uri?) {
@@ -43,7 +45,6 @@ class ScreenCompanionController(
private val appChangeReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
- android.util.Log.d("ScreenCompanionController", "appChangeReceiver received action: ${intent?.action}")
if (intent?.action == ACTION_APP_CHANGED) {
performLightweightScan(triggerType = "AppChange")
} else if (intent?.action == ACTION_CLIPBOARD_CHANGED) {
@@ -79,59 +80,54 @@ class ScreenCompanionController(
}
private fun performLightweightScan(triggerType: String) {
- scope.launch {
- withContext(Dispatchers.Default) {
- if (triggerType == "Screenshot") {
- withContext(Dispatchers.Main) {
- onSmartActionPairReady(
- "📸 Screenshot taken. Extract text?",
- "Extract the text from this screenshot.",
- "🌐 Translate Screenshot",
- TRANSLATE_SCREENSHOT_PROMPT
- )
- }
- return@withContext
- }
+ val settings = runCatching { SettingsRepository(context).load() }.getOrNull()
+ if (settings != null && !settings.proactiveEnabled) return
+
+ if (triggerType == "Screenshot") {
+ onSmartActionPairReady(
+ "📸 Screenshot taken. Extract text?",
+ "Extract the text from this screenshot.",
+ "🌐 Translate Screenshot",
+ TRANSLATE_SCREENSHOT_PROMPT
+ )
+ return
+ }
- if (triggerType == "Clipboard") {
- android.util.Log.d(
- "ScreenCompanionController",
- "Clipboard trigger: request read on Main"
- )
- // We must read clipboard from Main thread via overlay to avoid SecurityException
- withContext(Dispatchers.Main) {
- onReadClipboardRequest()
- }
- return@withContext
- }
+ if (triggerType == "Clipboard") {
+ if (settings == null || settings.proactiveScanClipboard) {
+ onReadClipboardRequest()
+ }
+ return
+ }
+
+ if (triggerType == "AppChange") {
+ if (settings != null && !settings.proactiveScanScreen) return
- if (triggerType == "AppChange") {
+ // Debounce 600ms trailing
+ scanDebounceJob?.cancel()
+ scanDebounceJob = scope.launch {
+ delay(DEBOUNCE_DELAY_MS)
+ withContext(Dispatchers.Default) {
val root = GotchaAccessibilityService.instance?.rootInActiveWindow
val pkg = root?.packageName?.toString() ?: ""
root?.recycle()
- val isIgnoredForLinks = pkg.contains("browser", ignoreCase = true) ||
- pkg.contains("chrome", ignoreCase = true) ||
- pkg.contains("firefox", ignoreCase = true) ||
- pkg.contains("chromium", ignoreCase = true) ||
- pkg.contains("messaging", ignoreCase = true) ||
- pkg.contains("messages", ignoreCase = true) ||
- pkg.contains("com.gotcha")
+ if (settings != null && settings.proactiveAppBlacklist.contains(pkg)) {
+ return@withContext
+ }
- val screenText = ScreenSnapshot.captureScreenText(limit = 40) ?: return@withContext
- val url = SmartActionDetector.extractUrl(screenText)
+ val screenText = ScreenSnapshot.captureScreenText(limit = 120) ?: return@withContext
+ val currentHash = screenText.hashCode()
+ if (currentHash == lastScreenTextHash) return@withContext
+ lastScreenTextHash = currentHash
- if (url != null && !isIgnoredForLinks) {
+ val entities = SmartActionDetector.detectAll(screenText, allowChat = false)
+ if (entities.isNotEmpty()) {
withContext(Dispatchers.Main) {
- val fetch = SmartActionDetector.fetchAction(url)
- onSmartActionReady(fetch.label, fetch.prompt)
- }
- } else {
- // Structured-data (address / phone / currency / calendar) scan.
- val smart = SmartActionDetector.detect(screenText, allowChat = false)
- if (smart != null) {
- withContext(Dispatchers.Main) {
- onSmartActionReady(smart.label, smart.prompt)
+ AssistiveBallService.onProactiveEntitiesDiscovered(entities, pkg)
+ val topAction = entities.first().primaryAction
+ if (topAction != null) {
+ onSmartActionReady(topAction.label, topAction.prompt)
}
}
}
@@ -143,12 +139,8 @@ class ScreenCompanionController(
companion object {
const val ACTION_APP_CHANGED = "com.gotcha.action.APP_CHANGED"
const val ACTION_CLIPBOARD_CHANGED = "com.gotcha.action.CLIPBOARD_CHANGED"
+ private const val DEBOUNCE_DELAY_MS = 600L
- /**
- * OCR-translate prompt for the "Translate Screenshot" action. The word
- * "screenshot" in it also drives [AssistiveBallService] to attach the
- * captured image to the request.
- */
const val TRANSLATE_SCREENSHOT_PROMPT =
"Extract any text present on this screenshot, translate it to English " +
"(or the user's system language), and display both the original text " +
diff --git a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
index 30a097e..f78caef 100644
--- a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
+++ b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
@@ -1,11 +1,9 @@
package com.gotcha.ui
import android.animation.ValueAnimator
-import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Configuration
import android.graphics.Color
-import android.graphics.Outline
import android.graphics.PixelFormat
import android.graphics.Typeface
import android.graphics.drawable.GradientDrawable
@@ -18,10 +16,8 @@ import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
-import android.view.ViewOutlineProvider
import android.view.WindowManager
import android.view.animation.AccelerateDecelerateInterpolator
-import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
@@ -30,27 +26,16 @@ import androidx.core.graphics.ColorUtils
import com.gotcha.R
import com.gotcha.data.SettingsRepository
import com.gotcha.data.ThemeMode
+import com.gotcha.service.EntityType
+import com.gotcha.service.ProactiveSessionItem
+import com.gotcha.service.SmartActionDetector
import kotlin.math.abs
import kotlin.math.hypot
/** Accessibility label for the ball root view — used by UiAutomator to find the overlay. */
const val ASSISTIVE_BALL_CONTENT_DESCRIPTION = "Gotcha assistive ball"
-/**
- * The floating "assistive ball" drawn over other apps via SYSTEM_ALERT_WINDOW,
- * reworked into a Messenger-Bubbles-style call head:
- *
- * - Tap: Open App / Screenshot menu when idle; toggles the call chat window
- * during a call.
- * - Long-press (3s idle / 5s during a call): start or end a voice call.
- * - Drag: moves the ball; an ✕ target appears at the bottom of the screen
- * and dropping the ball on it hides the ball (Messenger-style dismiss).
- *
- * Structurally modelled on [ConfirmationOverlay]: a [WindowManager] +
- * [WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY] window, gated on
- * [Settings.canDrawOverlays], with all window mutations posted to the main thread.
- */
-@Suppress("TooManyFunctions", "LargeClass")
+@Suppress("TooManyFunctions", "LargeClass", "MaxLineLength", "ComplexCondition")
class AssistiveBallOverlay(context: Context) {
private val appContext = context.applicationContext
@@ -70,9 +55,9 @@ class AssistiveBallOverlay(context: Context) {
var onSmartActionSelected: (prompt: String) -> Unit = {}
var isPanelOpen: Boolean = false
- /** Queried per gesture: is a voice call active (any non-idle state)? */
var isCallActive: () -> Boolean = { false }
+ private var proactiveSessionItems: List<ProactiveSessionItem> = emptyList()
private var pendingSmartAction: Pair<String, String>? = null
private var pendingSmartActionAlt: Pair<String, String>? = null
private var lastOfferedLabel: String? = null
@@ -88,17 +73,13 @@ class AssistiveBallOverlay(context: Context) {
private var cardView: View? = null
private var dismissTargetView: View? = null
- /** Which edge the ball docks to when idle. Defaults to the right edge. */
private var dockSide: Int = DOCK_SIDE_END
-
private val ballParams: WindowManager.LayoutParams by lazy { ballLayoutParams() }
-
private val settingsRepository by lazy { SettingsRepository(appContext) }
private val figtree: Typeface? by lazy {
runCatching { ResourcesCompat.getFont(appContext, R.font.figtree) }.getOrNull()
}
- /** Colors mirroring the app's Material scheme (ui/theme/Color.kt) for raw views. */
private class OverlayPalette(
val surface: Int,
val onSurface: Int,
@@ -107,7 +88,6 @@ class AssistiveBallOverlay(context: Context) {
val buttonText: Int
)
- /** Follows the in-app theme setting; SYSTEM tracks the device dark mode. */
private fun isDarkTheme(): Boolean {
val mode = runCatching { settingsRepository.load().themeMode }.getOrDefault(ThemeMode.SYSTEM)
return when (mode) {
@@ -121,26 +101,50 @@ class AssistiveBallOverlay(context: Context) {
private fun palette(): OverlayPalette = if (isDarkTheme()) {
OverlayPalette(
- surface = 0xFF1E293B.toInt(), // DarkSurface
+ surface = 0xFF1E293B.toInt(),
onSurface = 0xFFE2E8F0.toInt(),
- outline = 0xFF334155.toInt(), // DarkSurfaceVariant
+ outline = 0xFF334155.toInt(),
buttonBg = 0xFF334155.toInt(),
buttonText = 0xFFE2E8F0.toInt()
)
} else {
OverlayPalette(
- surface = 0xFFFBFDF9.toInt(), // LightSurface
+ surface = 0xFFFBFDF9.toInt(),
onSurface = 0xFF191C1A.toInt(),
- outline = 0xFFDBE5E0.toInt(), // LightSurfaceVariant
- buttonBg = 0xFFE8F6F2.toInt(), // LightPrimaryContainer
- buttonText = 0xFF002117.toInt() // LightOnPrimaryContainer
+ outline = 0xFFDBE5E0.toInt(),
+ buttonBg = 0xFFE8F6F2.toInt(),
+ buttonText = 0xFF002117.toInt()
)
}
- /** Whether we currently hold the "Display over other apps" permission. */
fun canShow(): Boolean =
Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(appContext)
+ fun hideChromeForCapture() {
+ mainHandler.post {
+ ballView?.visibility = View.INVISIBLE
+ }
+ }
+
+ /** Restore the ball after a capture (back to its faint edge-peek state). */
+ fun showChromeAfterCapture() {
+ mainHandler.post {
+ ballView?.visibility = View.VISIBLE
+ ballView?.alpha = PEEK_ALPHA
+ }
+ }
+
+ fun setCallActive(active: Boolean) {
+ mainHandler.post {
+ if (active) {
+ hideChromeForCapture()
+ removeMenu()
+ } else {
+ showChromeAfterCapture()
+ }
+ }
+ }
+
fun show() {
mainHandler.post {
if (ballView != null) return@post
@@ -148,14 +152,6 @@ class AssistiveBallOverlay(context: Context) {
try {
windowManager.addView(ball, ballParams)
ballView = ball
- // On first enable, show the full, opaque button (centred) so the user
- // sees it; it auto-docks to the edge after a short idle delay.
- ball.alpha = 1.0f
- ballParams.x = (screenWidth() - dp(BALL_SIZE_DP)) / 2
- try {
- windowManager.updateViewLayout(ball, ballParams)
- } catch (_: Exception) { }
- scheduleAutoDock()
} catch (_: Exception) {
ballView = null
}
@@ -164,85 +160,95 @@ class AssistiveBallOverlay(context: Context) {
fun dismiss() {
mainHandler.post {
- cancelAutoDock()
+ removeSmartActionRing()
removeLongPressRing()
removeMenu()
removeCard()
removeDismissTarget()
- clearSmartAction()
ballView?.let { safeRemove(it) }
ballView = null
}
}
- /** Tint the ball's rim green while a call is active so the 5s end gesture is discoverable. */
- fun setCallActive(active: Boolean) {
- mainHandler.post {
- (ballView as? ImageView)?.foreground = ballRim(active)
- }
- }
-
- // ---- Capture chrome ----
-
- /**
- * Hide all of our own overlay windows (menu, status card, and the ball) so they are
- * not baked into a screen capture taken for the call's screen context. Call
- * [showChromeAfterCapture] once the screenshot has been taken.
- */
- fun hideChromeForCapture() {
+ fun setProactiveSessionItems(items: List<ProactiveSessionItem>) {
mainHandler.post {
- removeLongPressRing()
- removeMenu()
- removeCard()
- ballView?.visibility = View.GONE
+ proactiveSessionItems = items
+ if (items.isNotEmpty()) {
+ val topEntity = items.first().entity
+ topEntity.primaryAction?.let { action ->
+ setSmartActionAvailable(action.label, action.prompt)
+ }
+ }
}
}
- /** Restore the ball after a capture (back to its faint edge-peek state). */
- fun showChromeAfterCapture() {
- mainHandler.post {
- ballView?.visibility = View.VISIBLE
- ballView?.alpha = PEEK_ALPHA
- }
+ fun setSmartActionPairAvailable(label: String, prompt: String, altLabel: String, altPrompt: String) {
+ setSmartActionAvailable(label, prompt, altLabel, altPrompt)
}
- // ---- Status card (errors only) ----
-
fun setSmartActionAvailable(label: String, prompt: String) {
setSmartActionAvailable(label, prompt, null, null)
}
- /**
- * Offer a primary smart action plus an optional secondary ("alt") action shown
- * as a second chip in the menu — e.g. "Extract text?" alongside "Translate".
- */
fun setSmartActionAvailable(label: String, prompt: String, altLabel: String?, altPrompt: String?) {
mainHandler.post {
if (isCallActive()) return@post
-
val currentLabel = pendingSmartAction?.first ?: ""
if (currentLabel.contains("copied", ignoreCase = true) && !label.contains("copied", ignoreCase = true)) {
- android.util.Log.d(
- "AssistiveBallOverlay",
- "Preventing overwrite of active clipboard action '$currentLabel' by passive action '$label'"
- )
- return@post
- }
-
- if (label == lastOfferedLabel) {
return@post
}
+ if (label == lastOfferedLabel) return@post
lastOfferedLabel = label
pendingSmartAction = Pair(label, prompt)
- pendingSmartActionAlt = if (altLabel != null && altPrompt != null) {
- Pair(altLabel, altPrompt)
- } else {
- null
- }
+ pendingSmartActionAlt = if (altLabel != null && altPrompt != null) Pair(altLabel, altPrompt) else null
showSmartActionRing()
mainHandler.removeCallbacks(smartActionClearRunnable)
- mainHandler.postDelayed(smartActionClearRunnable, 45000L) // 45 seconds
+ mainHandler.postDelayed(smartActionClearRunnable, 45000L)
+ }
+ }
+
+ fun showError(message: String) {
+ showCard("⚠️ $message", showClose = true)
+ }
+
+ fun showCard(message: String, showClose: Boolean = true) {
+ mainHandler.post {
+ removeCard()
+ val colors = palette()
+ val container = LinearLayout(appContext).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(dp(20), dp(16), dp(20), dp(16))
+ background = GradientDrawable().apply {
+ cornerRadius = dp(20).toFloat()
+ setColor(colors.surface)
+ setStroke(dp(1), colors.outline)
+ }
+ }
+ val scroll = ScrollView(appContext).apply {
+ addView(
+ TextView(appContext).apply {
+ text = message
+ typeface = figtree ?: Typeface.DEFAULT
+ setTextColor(colors.onSurface)
+ textSize = 14f
+ }
+ )
+ layoutParams = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT,
+ dp(240)
+ )
+ }
+ container.addView(scroll)
+ if (showClose) {
+ container.addView(tapButton("Close", colors) { hideCard() })
+ }
+ try {
+ windowManager.addView(container, cardLayoutParams())
+ cardView = container
+ } catch (_: Exception) {
+ cardView = null
+ }
}
}
@@ -256,129 +262,177 @@ class AssistiveBallOverlay(context: Context) {
}
}
- private fun showSmartActionRing() {
- removeSmartActionRing()
- val density = appContext.resources.displayMetrics.density
- val viewSize = (BALL_SIZE_DP * 1.5f * density).toInt()
- val ballPx = dp(BALL_SIZE_DP)
- val drawable = RingDrawable().apply {
- fillColor = Color.TRANSPARENT
- strokeColor = ColorUtils.setAlphaComponent(Color.CYAN, 120)
- strokeWidth = 2f * density
+ private fun buildBall(): View {
+ val size = dp(BALL_SIZE_DP)
+ return View(appContext).apply {
+ contentDescription = ASSISTIVE_BALL_CONTENT_DESCRIPTION
+ background = RingDrawable().apply {
+ fillColor = Color.parseColor("#44101018")
+ strokeColor = Color.parseColor("#88568CD8")
+ strokeWidth = 2f * appContext.resources.displayMetrics.density
+ }
+ alpha = PEEK_ALPHA
+ setOnTouchListener(ballTouchListener())
+ layoutParams = LinearLayout.LayoutParams(size, size)
}
- val view = View(appContext).apply { background = drawable }
- val params = WindowManager.LayoutParams(
- viewSize,
- viewSize,
- overlayType(),
- WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
- WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
- WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
- PixelFormat.TRANSLUCENT
- ).apply {
- gravity = Gravity.TOP or Gravity.START
- x = ballParams.x + ballPx / 2 - viewSize / 2
- y = ballParams.y + ballPx / 2 - viewSize / 2
+ }
+
+ private fun toggleMenu() {
+ if (menuView != null) removeMenu() else showMenu()
+ }
+
+ private fun showMenu() {
+ removeMenu()
+ val colors = palette()
+ val container = LinearLayout(appContext).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(dp(8), dp(8), dp(8), dp(8))
+ background = GradientDrawable().apply {
+ cornerRadius = dp(20).toFloat()
+ setColor(colors.surface)
+ setStroke(dp(1), colors.outline)
+ }
}
- try {
- windowManager.addView(view, params)
- smartActionRingView = view
- val minRadius = ballPx * 0.45f
- val maxRadius = ballPx * 0.65f
+ // Render Proactive Multi-Entity Grouped List
+ if (proactiveSessionItems.isNotEmpty()) {
+ val scroll = ScrollView(appContext).apply {
+ layoutParams = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT,
+ dp(220)
+ )
+ }
+ val listContent = LinearLayout(appContext).apply {
+ orientation = LinearLayout.VERTICAL
+ }
- smartActionRingAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
- duration = 1200L
- repeatMode = ValueAnimator.REVERSE
- repeatCount = 5
- interpolator = AccelerateDecelerateInterpolator()
- addUpdateListener { anim ->
- val p = anim.animatedValue as Float
- drawable.ringRadius = minRadius + (maxRadius - minRadius) * p
- drawable.strokeColor = ColorUtils.setAlphaComponent(Color.CYAN, (40 + 80 * (1f - p)).toInt())
+ for (item in proactiveSessionItems.take(4)) {
+ val entity = item.entity
+ val headerText = TextView(appContext).apply {
+ text = "${getCategoryIcon(entity.type)} ${SmartActionDetector.snippet(entity.normalizedValue, 22)}"
+ typeface = figtree ?: Typeface.DEFAULT
+ textSize = 12f
+ setTextColor(colors.onSurface)
+ setPadding(dp(8), dp(6), dp(8), dp(2))
+ }
+ listContent.addView(headerText)
+
+ val chipRow = LinearLayout(appContext).apply {
+ orientation = LinearLayout.HORIZONTAL
+ setPadding(dp(4), dp(2), dp(4), dp(6))
+ }
+ for (action in entity.actions) {
+ chipRow.addView(
+ tapButton(action.label, colors) {
+ val currentPrompt = action.prompt
+ clearSmartAction()
+ onSmartActionSelected(currentPrompt)
+ }.apply {
+ textSize = 11f
+ setPadding(dp(8), dp(4), dp(8), dp(4))
+ }
+ )
}
- addListener(object : android.animation.AnimatorListenerAdapter() {
- override fun onAnimationEnd(animation: android.animation.Animator) {
- smartActionRingView?.animate()
- ?.alpha(0f)
- ?.setDuration(500L)
- ?.withEndAction {
- removeSmartActionRing()
- }
- ?.start()
+ listContent.addView(chipRow)
+ }
+ scroll.addView(listContent)
+ container.addView(scroll)
+ } else {
+ pendingSmartAction?.let { (label, prompt) ->
+ container.addView(
+ tapButton(label, colors) {
+ clearSmartAction()
+ onSmartActionSelected(prompt)
}
- })
- start()
+ )
}
- } catch (_: Exception) {
- smartActionRingView = null
}
- }
- private fun removeSmartActionRing() {
- smartActionRingAnimator?.cancel()
- smartActionRingAnimator = null
- smartActionRingView?.let { safeRemove(it) }
- smartActionRingView = null
- }
+ container.addView(
+ tapButton("📱 Open App", colors) {
+ removeMenu()
+ onOpenApp()
+ }
+ )
+ container.addView(
+ tapButton("📸 Screenshot", colors) {
+ removeMenu()
+ onTakeScreenshot()
+ }
+ )
+ container.addView(
+ tapButton("🔍 Lens", colors) {
+ removeMenu()
+ onStartLens()
+ }
+ )
- private fun updateSmartActionRingPosition() {
- smartActionRingView?.let {
- try {
- val viewSize = it.layoutParams.width
- val ballPx = dp(BALL_SIZE_DP)
- val params = it.layoutParams as WindowManager.LayoutParams
- params.x = ballParams.x + ballPx / 2 - viewSize / 2
- params.y = ballParams.y + ballPx / 2 - viewSize / 2
- windowManager.updateViewLayout(it, params)
- } catch (_: Exception) {}
+ val params = menuLayoutParams()
+ try {
+ windowManager.addView(container, params)
+ menuView = container
+ } catch (_: Exception) {
+ menuView = null
}
}
- fun showError(text: String) = showCard(text, showClose = true)
-
- // ---- Ball ----
+ private fun getCategoryIcon(type: EntityType): String = when (type) {
+ EntityType.OTP -> "🔑"
+ EntityType.PHONE -> "📞"
+ EntityType.ADDRESS -> "📍"
+ EntityType.EMAIL -> "📧"
+ EntityType.URL -> "🌐"
+ EntityType.CALENDAR -> "📅"
+ EntityType.CURRENCY -> "💵"
+ EntityType.TRACKING_NUMBER -> "📦"
+ EntityType.CHAT_REPLY -> "💬"
+ EntityType.GENERIC_TEXT -> "📋"
+ }
- @SuppressLint("ClickableViewAccessibility")
- private fun buildBall(): View {
- return ImageView(appContext).apply {
- contentDescription = ASSISTIVE_BALL_CONTENT_DESCRIPTION
- setImageResource(R.mipmap.ic_launcher_round)
- scaleType = ImageView.ScaleType.CENTER_CROP
- // Clip the square launcher icon into a circular "ball".
- outlineProvider = object : ViewOutlineProvider() {
- override fun getOutline(view: View, outline: Outline) {
- outline.setOval(0, 0, view.width, view.height)
- }
+ private fun tapButton(label: String, colors: OverlayPalette, onClick: () -> Unit): TextView {
+ return TextView(appContext).apply {
+ text = label
+ typeface = figtree ?: Typeface.DEFAULT
+ textSize = 13f
+ setTextColor(colors.buttonText)
+ gravity = Gravity.CENTER
+ setPadding(dp(14), dp(8), dp(14), dp(8))
+ background = GradientDrawable().apply {
+ cornerRadius = dp(12).toFloat()
+ setColor(colors.buttonBg)
}
- clipToOutline = true
- // Subtle rim so the logo reads on any background (green during calls).
- foreground = ballRim(isCallActive())
- setOnTouchListener(ballTouchListener())
+ layoutParams = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.WRAP_CONTENT,
+ LinearLayout.LayoutParams.WRAP_CONTENT
+ ).apply { setMargins(dp(4), dp(4), dp(4), dp(4)) }
+ setOnClickListener { onClick() }
}
}
- private fun ballRim(callActive: Boolean) = GradientDrawable().apply {
- shape = GradientDrawable.OVAL
- if (callActive) {
- setStroke(dp(2), Color.parseColor("#CC34C759"))
- } else {
- setStroke(dp(1), Color.parseColor("#66FFFFFF"))
- }
+ private fun removeMenu() {
+ menuView?.let { safeRemove(it) }
+ menuView = null
+ }
+
+ private fun hideCard() {
+ mainHandler.post { removeCard() }
}
- // ---- Long-press ring ----
+ private fun removeCard() {
+ cardView?.let { safeRemove(it) }
+ cardView = null
+ }
- /** Show a growing ring around the ball during the 3s hold to start a call. */
private fun showLongPressRing() {
removeLongPressRing()
val density = appContext.resources.displayMetrics.density
- // View is 3.5x the ball so the ring can grow to ~1.6x the ball radius
- // without hitting the view's bounds. The screen edge may still clip
- // when the ball is near the edge — that's intended.
- val viewSize = (BALL_SIZE_DP * 3.5f * density).toInt()
+ val viewSize = (BALL_SIZE_DP * 3.2f * density).toInt()
val ballPx = dp(BALL_SIZE_DP)
- val drawable = RingDrawable()
+ val drawable = RingDrawable().apply {
+ fillColor = Color.TRANSPARENT
+ strokeColor = Color.WHITE
+ strokeWidth = 2.5f * density
+ }
val view = View(appContext).apply { background = drawable }
val params = WindowManager.LayoutParams(
viewSize,
@@ -400,33 +454,18 @@ class AssistiveBallOverlay(context: Context) {
val minRadius = ballPx * 0.50f
val maxRadius = ballPx * 1.60f
- val strokePx = 2.5f * density
- val fillBase = Color.WHITE
- val strokeBase = Color.WHITE
-
ringAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
duration = LONG_PRESS_START_MS
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { anim ->
val p = anim.animatedValue as Float
drawable.ringRadius = minRadius + (maxRadius - minRadius) * p
- // Stroke fades from full to ~40% opacity as it expands
- drawable.strokeColor = ColorUtils.setAlphaComponent(
- strokeBase,
- ((1f - p * 0.6f) * 255).toInt()
- )
- drawable.strokeWidth = strokePx
- // Fill tints the area between ball and ring, fades out
- drawable.fillColor = ColorUtils.setAlphaComponent(
- fillBase,
- ((0.18f * (1f - p)) * 255).toInt()
- )
+ drawable.strokeColor = ColorUtils.setAlphaComponent(Color.WHITE, ((1f - p * 0.6f) * 255).toInt())
}
start()
}
} catch (_: Exception) {
ringView = null
- ringDrawable = null
}
}
@@ -442,7 +481,74 @@ class AssistiveBallOverlay(context: Context) {
ringDrawable = null
}
- @Suppress("CyclomaticComplexMethod")
+ private fun showSmartActionRing() {
+ removeSmartActionRing()
+ val density = appContext.resources.displayMetrics.density
+ val viewSize = (BALL_SIZE_DP * 1.5f * density).toInt()
+ val ballPx = dp(BALL_SIZE_DP)
+ val drawable = RingDrawable().apply {
+ fillColor = Color.TRANSPARENT
+ strokeColor = ColorUtils.setAlphaComponent(Color.CYAN, 120)
+ strokeWidth = 2f * density
+ }
+ val view = View(appContext).apply { background = drawable }
+ val params = WindowManager.LayoutParams(
+ viewSize,
+ viewSize,
+ overlayType(),
+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
+ WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
+ WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
+ PixelFormat.TRANSLUCENT
+ ).apply {
+ gravity = Gravity.TOP or Gravity.START
+ x = ballParams.x + ballPx / 2 - viewSize / 2
+ y = ballParams.y + ballPx / 2 - viewSize / 2
+ }
+ try {
+ windowManager.addView(view, params)
+ smartActionRingView = view
+
+ val minRadius = ballPx * 0.45f
+ val maxRadius = ballPx * 0.65f
+ smartActionRingAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
+ duration = 1200L
+ repeatMode = ValueAnimator.REVERSE
+ repeatCount = 5
+ interpolator = AccelerateDecelerateInterpolator()
+ addUpdateListener { anim ->
+ val p = anim.animatedValue as Float
+ drawable.ringRadius = minRadius + (maxRadius - minRadius) * p
+ drawable.strokeColor = ColorUtils.setAlphaComponent(Color.CYAN, (40 + 80 * (1f - p)).toInt())
+ }
+ start()
+ }
+ } catch (_: Exception) {
+ smartActionRingView = null
+ }
+ }
+
+ private fun removeSmartActionRing() {
+ smartActionRingAnimator?.cancel()
+ smartActionRingAnimator = null
+ smartActionRingView?.let { safeRemove(it) }
+ smartActionRingView = null
+ }
+
+ private fun updateSmartActionRingPosition() {
+ val view = smartActionRingView ?: return
+ val density = appContext.resources.displayMetrics.density
+ val viewSize = (BALL_SIZE_DP * 1.5f * density).toInt()
+ val ballPx = dp(BALL_SIZE_DP)
+ val params = (view.layoutParams as WindowManager.LayoutParams).apply {
+ x = ballParams.x + ballPx / 2 - viewSize / 2
+ y = ballParams.y + ballPx / 2 - viewSize / 2
+ }
+ try {
+ windowManager.updateViewLayout(view, params)
+ } catch (_: Exception) { }
+ }
+
private fun ballTouchListener(): View.OnTouchListener {
var startX = 0
var startY = 0
@@ -464,8 +570,6 @@ class AssistiveBallOverlay(context: Context) {
touchDownRawY = event.rawY
dragging = false
longPressFired = false
- // Reveal the sliver immediately on contact; the ball stays put
- // so drag math (relative to startX) stays consistent.
cancelAutoDock()
ballView?.alpha = 1.0f
mainHandler.postDelayed(
@@ -503,18 +607,15 @@ class AssistiveBallOverlay(context: Context) {
val droppedOnTarget = dragging && isOverDismissTarget()
removeDismissTarget()
when {
- longPressFired -> { /* handled by the runnable */ }
+ longPressFired -> { }
droppedOnTarget -> onDismiss()
dragging -> {
- // Snap to the edge on the side the ball was dropped on.
dockSide = sideForX(ballParams.x)
clampBallIntoBounds()
scheduleAutoDock()
}
isCallActive() -> onToggleChatWindow()
else -> {
- // Idle tap: slide the full ball on-screen, open the menu,
- // then auto-dock back to the edge after a short idle.
expandFromEdge()
toggleMenu()
scheduleAutoDock()
@@ -527,7 +628,6 @@ class AssistiveBallOverlay(context: Context) {
hideLongPressRing()
removeDismissTarget()
if (dragging) {
- // Snap to the edge on the side the ball was dropped on.
dockSide = sideForX(ballParams.x)
clampBallIntoBounds()
scheduleAutoDock()
@@ -542,7 +642,6 @@ class AssistiveBallOverlay(context: Context) {
private fun clampBallIntoBounds() {
val metrics = appContext.resources.displayMetrics
val maxY = metrics.heightPixels - dp(BALL_SIZE_DP)
- // Allow the ball to dock fully off either edge down to its peek position.
val minX = -dp(BALL_SIZE_DP - PEEK_DP)
val maxX = metrics.widthPixels - dp(PEEK_DP)
ballParams.x = ballParams.x.coerceIn(minX, maxX)
@@ -553,29 +652,23 @@ class AssistiveBallOverlay(context: Context) {
} catch (_: Exception) { }
}
- // ---- Edge-peek expand / dock ----
-
private fun screenWidth(): Int = appContext.resources.displayMetrics.widthPixels
- /** X offset (from the left/START edge) that places the ball in its peek sliver. */
private fun dockedX(side: Int): Int = when (side) {
DOCK_SIDE_END -> screenWidth() - dp(PEEK_DP)
else -> -dp(BALL_SIZE_DP - PEEK_DP)
}
- /** X offset that places the fully-expanded ball just inside [side]'s edge. */
private fun dockedExpandX(side: Int): Int = when (side) {
DOCK_SIDE_END -> screenWidth() - dp(BALL_SIZE_DP) - dp(DOCK_MARGIN_DP)
else -> dp(DOCK_MARGIN_DP)
}
- /** Pick the dock side from the ball's current left offset (uses its centre). */
private fun sideForX(leftX: Int): Int {
val centre = leftX + dp(BALL_SIZE_DP) / 2
return if (centre < screenWidth() / 2) DOCK_SIDE_START else DOCK_SIDE_END
}
- /** Slide the full ball onto the screen (on its current dock side) and make it fully opaque. */
private fun expandFromEdge() {
cancelAutoDock()
ballParams.x = dockedExpandX(dockSide)
@@ -594,7 +687,6 @@ class AssistiveBallOverlay(context: Context) {
}
}
- /** Animate the ball back to the faint, docked-at-edge peek state. */
private fun dockToEdge() {
val view = ballView ?: return
val targetX = dockedX(dockSide)
@@ -628,8 +720,6 @@ class AssistiveBallOverlay(context: Context) {
mainHandler.removeCallbacks(autoDockRunnable)
}
- // ---- Dismiss target (drag the ball onto the ✕ to hide it) ----
-
private fun showDismissTarget() {
if (dismissTargetView != null) return
val target = TextView(appContext).apply {
@@ -673,7 +763,6 @@ class AssistiveBallOverlay(context: Context) {
dismissTargetView?.scaleY = scale
}
- /** True when the ball's centre is within snapping distance of the ✕ target's centre. */
private fun isOverDismissTarget(): Boolean {
if (dismissTargetView == null) return false
val metrics = appContext.resources.displayMetrics
@@ -686,171 +775,10 @@ class AssistiveBallOverlay(context: Context) {
return distance <= dp(DISMISS_SNAP_RADIUS_DP)
}
- // ---- Expanded menu (idle only; taps during a call toggle the chat window) ----
-
- private fun toggleMenu() {
- if (menuView != null) removeMenu() else showMenu()
- }
-
- private fun showMenu() {
- removeMenu()
- val colors = palette()
- val container = LinearLayout(appContext).apply {
- orientation = LinearLayout.VERTICAL
- setPadding(dp(8), dp(8), dp(8), dp(8))
- background = GradientDrawable().apply {
- cornerRadius = dp(20).toFloat()
- setColor(colors.surface)
- setStroke(dp(1), colors.outline)
- }
- }
-
- pendingSmartAction?.let { (label, prompt) ->
- container.addView(
- tapButton(label, colors) {
- val currentPrompt = prompt
- clearSmartAction()
- onSmartActionSelected(currentPrompt)
- }.apply {
- background = GradientDrawable().apply {
- cornerRadius = dp(12).toFloat()
- setColor(ColorUtils.setAlphaComponent(Color.CYAN, 40))
- setStroke(dp(1), Color.CYAN)
- }
- setTextColor(Color.CYAN)
- }
- )
- }
-
- pendingSmartActionAlt?.let { (label, prompt) ->
- container.addView(
- tapButton(label, colors) {
- val currentPrompt = prompt
- clearSmartAction()
- onSmartActionSelected(currentPrompt)
- }.apply {
- background = GradientDrawable().apply {
- cornerRadius = dp(12).toFloat()
- setColor(ColorUtils.setAlphaComponent(Color.CYAN, 24))
- setStroke(dp(1), ColorUtils.setAlphaComponent(Color.CYAN, 160))
- }
- setTextColor(Color.CYAN)
- }
- )
- }
-
- container.addView(
- tapButton("\uD83D\uDCF1 Open App", colors) {
- removeMenu()
- onOpenApp()
- }
- )
- container.addView(
- tapButton("\uD83D\uDCF7 Screenshot", colors) {
- removeMenu()
- onTakeScreenshot()
- }
- )
- container.addView(
- tapButton("\uD83D\uDD0D Lens", colors) {
- removeMenu()
- onStartLens()
- }
- )
-
- val params = menuLayoutParams()
- try {
- windowManager.addView(container, params)
- menuView = container
- } catch (_: Exception) {
- menuView = null
- }
- }
-
- private fun tapButton(label: String, colors: OverlayPalette, onClick: () -> Unit): TextView {
- return TextView(appContext).apply {
- text = label
- typeface = figtree ?: Typeface.DEFAULT
- textSize = 14f
- setTextColor(colors.buttonText)
- gravity = Gravity.CENTER
- setPadding(dp(16), dp(10), dp(16), dp(10))
- background = GradientDrawable().apply {
- cornerRadius = dp(12).toFloat()
- setColor(colors.buttonBg)
- }
- layoutParams = LinearLayout.LayoutParams(
- LinearLayout.LayoutParams.MATCH_PARENT,
- LinearLayout.LayoutParams.WRAP_CONTENT
- ).apply { setMargins(dp(4), dp(4), dp(4), dp(4)) }
- setOnClickListener { onClick() }
- }
- }
-
- private fun removeMenu() {
- menuView?.let { safeRemove(it) }
- menuView = null
- }
-
- // ---- Card ----
-
- private fun showCard(message: String, showClose: Boolean) {
- mainHandler.post {
- removeCard()
- val colors = palette()
- val container = LinearLayout(appContext).apply {
- orientation = LinearLayout.VERTICAL
- setPadding(dp(20), dp(16), dp(20), dp(16))
- background = GradientDrawable().apply {
- cornerRadius = dp(20).toFloat()
- setColor(colors.surface)
- setStroke(dp(1), colors.outline)
- }
- }
- val scroll = ScrollView(appContext).apply {
- addView(
- TextView(appContext).apply {
- text = message
- typeface = figtree ?: Typeface.DEFAULT
- setTextColor(colors.onSurface)
- textSize = 14f
- }
- )
- layoutParams = LinearLayout.LayoutParams(
- LinearLayout.LayoutParams.MATCH_PARENT,
- dp(240)
- )
- }
- container.addView(scroll)
- if (showClose) {
- container.addView(tapButton("Close", colors) { hideCard() })
- }
- try {
- windowManager.addView(container, cardLayoutParams())
- cardView = container
- } catch (_: Exception) {
- cardView = null
- }
- }
- }
-
- fun hideCard() {
- mainHandler.post { removeCard() }
- }
-
- private fun removeCard() {
- cardView?.let { safeRemove(it) }
- cardView = null
- }
-
- // ---- Helpers ----
-
private fun safeRemove(view: View) {
try {
windowManager.removeView(view)
- } catch (_: Exception) {
- // Already detached; ignore.
- }
+ } catch (_: Exception) { }
}
private fun overlayType(): Int =
@@ -871,7 +799,6 @@ class AssistiveBallOverlay(context: Context) {
PixelFormat.TRANSLUCENT
).apply {
gravity = Gravity.TOP or Gravity.START
- // Default-dock off the right edge: only PEEK_DP of the ball is visible.
x = dockedX(dockSide)
y = dp(160)
}
@@ -885,7 +812,6 @@ class AssistiveBallOverlay(context: Context) {
PixelFormat.TRANSLUCENT
).apply {
gravity = Gravity.TOP or Gravity.START
- // Anchor near the ball, clamped so the menu stays on screen.
val metrics = appContext.resources.displayMetrics
x = (ballParams.x).coerceIn(0, (metrics.widthPixels - dp(MENU_WIDTH_DP)).coerceAtLeast(0))
y = (ballParams.y + dp(64)).coerceIn(0, (metrics.heightPixels - dp(140)).coerceAtLeast(0))
@@ -905,39 +831,33 @@ class AssistiveBallOverlay(context: Context) {
private fun dp(value: Int): Int =
(value * appContext.resources.displayMetrics.density).toInt()
+ fun readClipboardWithFocus(onResult: (android.content.ClipData?) -> Unit) {
+ ClipboardReaderActivity.onClipboardRead = onResult
+ val intent = android.content.Intent(appContext, ClipboardReaderActivity::class.java).apply {
+ addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK or android.content.Intent.FLAG_ACTIVITY_NO_ANIMATION)
+ }
+ try {
+ appContext.startActivity(intent)
+ } catch (_: Exception) {
+ onResult(null)
+ }
+ }
+
private companion object {
const val BALL_SIZE_DP = 56
- const val MENU_WIDTH_DP = 200
+ const val MENU_WIDTH_DP = 220
const val LONG_PRESS_START_MS = 2000L
const val LONG_PRESS_END_MS = 2000L
const val DISMISS_TARGET_SIZE_DP = 64
const val DISMISS_TARGET_MARGIN_DP = 32
const val DISMISS_SNAP_RADIUS_DP = 56
- // Edge-peek behaviour: when idle the ball docks off an edge, leaving
- // only a thin, semi-transparent sliver; interaction reveals the full ball.
const val PEEK_DP = 28
const val PEEK_ALPHA = 0.35f
const val DOCK_MARGIN_DP = 16
const val AUTO_DOCK_DELAY_MS = 2500L
- // Dock side identifiers (START = left edge, END = right edge).
const val DOCK_SIDE_START = 0
const val DOCK_SIDE_END = 1
}
- fun readClipboardWithFocus(onResult: (android.content.ClipData?) -> Unit) {
- android.util.Log.d("AssistiveBallOverlay", "readClipboardWithFocus called. Setting onClipboardRead callback.")
- ClipboardReaderActivity.onClipboardRead = onResult
- val intent = android.content.Intent(appContext, ClipboardReaderActivity::class.java).apply {
- addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK or android.content.Intent.FLAG_ACTIVITY_NO_ANIMATION)
- }
- try {
- android.util.Log.d("AssistiveBallOverlay", "Starting ClipboardReaderActivity...")
- appContext.startActivity(intent)
- android.util.Log.d("AssistiveBallOverlay", "startActivity called successfully")
- } catch (e: Exception) {
- android.util.Log.e("AssistiveBallOverlay", "Failed to start ClipboardReaderActivity", e)
- onResult(null)
- }
- }
}
diff --git a/app/src/test/java/com/gotcha/service/ProactiveSessionManagerTest.kt b/app/src/test/java/com/gotcha/service/ProactiveSessionManagerTest.kt
new file mode 100644
index 0000000..9f3c738
--- /dev/null
+++ b/app/src/test/java/com/gotcha/service/ProactiveSessionManagerTest.kt
@@ -0,0 +1,108 @@
+package com.gotcha.service
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ProactiveSessionManagerTest {
+
+ @Test
+ fun `mergeEntities adds new entities and updates existing without dupes`() {
+ val manager = ProactiveSessionManager(ttlMs = 45_000L)
+
+ val entity1 = DetectedEntity(
+ type = EntityType.PHONE,
+ rawValue = "+1 415 555 2671",
+ normalizedValue = "+14155552671",
+ span = 0..14,
+ confidence = 0.9f,
+ actions = emptyList()
+ )
+
+ val itemsInitial = manager.mergeEntities(listOf(entity1), packageName = "com.app.one")
+ assertEquals(1, itemsInitial.size)
+ assertEquals("+14155552671", itemsInitial.first().entity.normalizedValue)
+
+ // Merge same entity again -> size remains 1, updated timestamp
+ val itemsUpdated = manager.mergeEntities(listOf(entity1), packageName = "com.app.one")
+ assertEquals(1, itemsUpdated.size)
+ }
+
+ @Test
+ fun `category counts map groups active entities correctly`() {
+ val manager = ProactiveSessionManager()
+
+ val phone = DetectedEntity(
+ type = EntityType.PHONE,
+ rawValue = "+1 415 555 2671",
+ normalizedValue = "+14155552671",
+ span = 0..14,
+ confidence = 0.9f,
+ actions = emptyList()
+ )
+ val url1 = DetectedEntity(
+ type = EntityType.URL,
+ rawValue = "https://example.com",
+ normalizedValue = "https://example.com",
+ span = 20..39,
+ confidence = 0.9f,
+ actions = emptyList()
+ )
+ val url2 = DetectedEntity(
+ type = EntityType.URL,
+ rawValue = "https://google.com",
+ normalizedValue = "https://google.com",
+ span = 45..63,
+ confidence = 0.9f,
+ actions = emptyList()
+ )
+
+ manager.mergeEntities(listOf(phone, url1, url2))
+ val counts = manager.getCategoryCounts()
+
+ assertEquals(2, counts[EntityType.URL])
+ assertEquals(1, counts[EntityType.PHONE])
+ }
+
+ @Test
+ fun `ttl expiration purges stale items`() {
+ val manager = ProactiveSessionManager(ttlMs = 50L) // 50ms TTL
+
+ val entity = DetectedEntity(
+ type = EntityType.EMAIL,
+ rawValue = "[email protected]",
+ normalizedValue = "[email protected]",
+ span = 0..16,
+ confidence = 0.9f,
+ actions = emptyList()
+ )
+
+ manager.mergeEntities(listOf(entity))
+ assertEquals(1, manager.getActiveSessionItems().size)
+
+ Thread.sleep(100L) // Sleep longer than 50ms TTL
+
+ assertEquals(0, manager.getActiveSessionItems().size)
+ }
+
+ @Test
+ fun `package change invalidates screen items`() {
+ val manager = ProactiveSessionManager()
+
+ val phone = DetectedEntity(
+ type = EntityType.PHONE,
+ rawValue = "+1 415 555 2671",
+ normalizedValue = "+14155552671",
+ span = 0..14,
+ confidence = 0.9f,
+ actions = emptyList()
+ )
+
+ manager.mergeEntities(listOf(phone), packageName = "com.app.first")
+ assertEquals(1, manager.getActiveSessionItems().size)
+
+ // Switch package to com.app.second
+ val updated = manager.mergeEntities(emptyList(), packageName = "com.app.second")
+ assertTrue(updated.isEmpty())
+ }
+}