Skip to content

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

fix(ui,lens): fix ball opacity, outside-click menu dismiss, menu layout, passive offer filters, and Lens auto-annotation bounding boxes

Rishabh Bajpai0d093a80bc13
diff --git a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
index 2e5eb2b..067bba5 100644
--- a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
+++ b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
@@ -26,6 +26,8 @@ import kotlin.coroutines.resume
* for null and returns a permission hint otherwise.
*/
// One function per accessibility capability (tap, swipe, type, …) by design; size is inherent.
+data class ScreenNodeText(val text: String, val bounds: android.graphics.Rect)
+
@Suppress("TooManyFunctions")
class GotchaAccessibilityService : AccessibilityService() {
@@ -302,6 +304,33 @@ class GotchaAccessibilityService : AccessibilityService() {
return performed
}
+ /** Traverses active window nodes and extracts visible text along with screen bounds. */
+ fun extractScreenNodeTexts(): List<ScreenNodeText> {
+ val root = rootInActiveWindow ?: return emptyList()
+ val results = mutableListOf<ScreenNodeText>()
+
+ fun walk(node: AccessibilityNodeInfo?) {
+ if (node == null) return
+ if (node.isVisibleToUser) {
+ val txt = (node.text?.toString() ?: node.contentDescription?.toString())?.trim()
+ if (!txt.isNullOrBlank() && txt.length >= 3) {
+ val rect = android.graphics.Rect()
+ node.getBoundsInScreen(rect)
+ if (rect.width() > 10 && rect.height() > 10) {
+ results.add(ScreenNodeText(txt, rect))
+ }
+ }
+ }
+ for (i in 0 until node.childCount) {
+ walk(node.getChild(i))
+ }
+ }
+
+ walk(root)
+ root.recycle()
+ return results
+ }
+
fun longPressByText(query: String): Boolean {
val root = rootInActiveWindow ?: return false
val match = findClickable(root, query.lowercase())
diff --git a/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt b/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt
index f6f1c3e..c0221be 100644
--- a/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt
+++ b/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt
@@ -121,14 +121,21 @@ class ScreenCompanionController(
if (currentHash == lastScreenTextHash) return@withContext
lastScreenTextHash = currentHash
- val entities = SmartActionDetector.detectAll(screenText, allowChat = false)
- if (entities.isNotEmpty()) {
- withContext(Dispatchers.Main) {
- AssistiveBallService.onProactiveEntitiesDiscovered(entities, pkg)
- val topAction = entities.first().primaryAction
+ val allEntities = SmartActionDetector.detectAll(screenText, allowChat = false)
+ val actionableEntities = allEntities.filter { item ->
+ item.confidence >= 0.85f &&
+ item.type != com.gotcha.service.EntityType.CHAT_REPLY &&
+ item.type != com.gotcha.service.EntityType.GENERIC_TEXT
+ }
+ withContext(Dispatchers.Main) {
+ if (actionableEntities.isNotEmpty()) {
+ AssistiveBallService.onProactiveEntitiesDiscovered(actionableEntities, pkg)
+ val topAction = actionableEntities.first().primaryAction
if (topAction != null) {
onSmartActionReady(topAction.label, topAction.prompt)
}
+ } else {
+ AssistiveBallService.onProactiveEntitiesDiscovered(emptyList(), pkg)
}
}
}
diff --git a/app/src/main/java/com/gotcha/service/ScreenLensController.kt b/app/src/main/java/com/gotcha/service/ScreenLensController.kt
index 9149bf5..e843983 100644
--- a/app/src/main/java/com/gotcha/service/ScreenLensController.kt
+++ b/app/src/main/java/com/gotcha/service/ScreenLensController.kt
@@ -3,74 +3,41 @@ package com.gotcha.service
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
-import android.graphics.Color
import android.graphics.PixelFormat
import android.graphics.Rect
-import android.graphics.drawable.GradientDrawable
import android.os.Build
-import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.View
import android.view.WindowManager
-import android.widget.LinearLayout
import android.widget.TextView
import com.gotcha.ui.ScreenCropOverlayView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
-import java.io.File
-import java.io.FileOutputStream
-
-/**
- * Drives "Lens" mode: the user draws a free-form shape over the screen; its
- * bounding rectangle is cropped from a fresh accessibility screenshot. The crop
- * can then be:
- * - opened in the Screen Companion panel as an attached image, so the user can
- * ask their own question about it (NOT auto-explained),
- * - copied to the clipboard,
- * - saved to the public Downloads folder, or
- * - acted on contextually (convert currency / add to calendar / dial / navigate)
- * when structured data is detected inside the selection.
- *
- * Bitmap lifecycle: the controller owns exactly one [pendingCrop] at a time and is
- * the ONLY place that recycles it. Menu actions read it, then recycle happens once
- * the action's (possibly async) work has finished — this avoids the earlier
- * "can't compress a recycled bitmap" race.
- *
- * All window mutations are posted to the main thread.
- */
+
@Suppress("TooManyFunctions")
class ScreenLensController(
private val context: Context,
private val scope: CoroutineScope,
- /** Open the companion panel with the crop attached; the user asks their own question. */
private val onAskAboutCrop: (base64Jpeg: String) -> Unit,
- /** Route a detected structured action (native intent or LLM prompt) to the host. */
private val onContextualAction: (prompt: String) -> Unit,
- /** Open the companion panel with the crop attached AND auto-send [prompt] (OCR/translate). */
private val onImagePrompt: (base64Jpeg: String, prompt: String) -> Unit,
- /** OCR the crop and copy the recognized text to the clipboard (async). */
private val onOcrToClipboard: (crop: Bitmap) -> Unit,
private val onError: (String) -> Unit
) {
private val appContext = context.applicationContext
private val windowManager = appContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
private val mainHandler = Handler(Looper.getMainLooper())
- private val dragSlop = android.view.ViewConfiguration.get(appContext).scaledTouchSlop
private var cropOverlay: View? = null
private var actionMenu: View? = null
-
- /** Small floating "Copy text" / "Translate" chips anchored above the rectangle. */
private var textChips: View? = null
-
- /** The current cropped bitmap; owned and recycled only by this controller. */
private var pendingCrop: Bitmap? = null
- /** Begin a Lens capture: add the full-screen crop overlay. */
+ /** Begin a Lens capture: add the full-screen crop overlay and auto-annotate UI elements. */
fun start() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
onError("Lens mode requires Android 11+")
@@ -80,18 +47,33 @@ class ScreenLensController(
removeActionMenu()
removeCropOverlay()
recyclePendingCrop()
+
+ val service = GotchaAccessibilityService.instance
+ val nodeTexts = service?.extractScreenNodeTexts() ?: emptyList()
+ val annotatedEntities = mutableListOf<AnnotatedEntity>()
+ for (nodeText in nodeTexts) {
+ val entities = SmartActionDetector.detectAll(nodeText.text, allowChat = false)
+ for (entity in entities) {
+ annotatedEntities.add(AnnotatedEntity(entity, nodeText.bounds))
+ }
+ }
+
val overlay = ScreenCropOverlayView(
appContext,
onSelection = { rect -> onRegionSelected(rect) },
onCancel = { cancel() },
- // Redrawing after the menu showed: drop the menu/chips + stale crop
- // and let the user re-select. The overlay itself stays up.
onReselectStart = {
removeActionMenu()
removeTextChips()
recyclePendingCrop()
+ },
+ onAnnotatedEntitySelected = { prompt ->
+ cancel()
+ onContextualAction(prompt)
}
)
+ overlay.setAnnotatedEntities(annotatedEntities)
+
val params = WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
@@ -126,7 +108,6 @@ class ScreenLensController(
val viewW = overlay?.width ?: 0
val viewH = overlay?.height ?: 0
- // 1) Enforce a minimum size: a thin line/scribble becomes a usable band.
val minPx = (MIN_SELECTION_DP * appContext.resources.displayMetrics.density).toInt()
val padded = expandToMinimum(rectInView, minPx, viewW, viewH)
@@ -136,23 +117,16 @@ class ScreenLensController(
withContext(Dispatchers.Main) { onError("Accessibility service not available") }
return@launch
}
- // 2) Snap to UI elements the selection substantially overlaps, so drawing
- // around ~most of a control captures the whole control.
val snapped = service.snapRegionToElements(padded).also {
it.intersect(0, 0, viewW.coerceAtLeast(1), viewH.coerceAtLeast(1))
}
val finalRect = if (snapped.width() >= minPx && snapped.height() >= minPx) snapped else padded
- // Freeze the selection on the overlay so it stays visible (with the live
- // particle animation) while the action menu is up.
withContext(Dispatchers.Main) { overlay?.freezeSelection(finalRect) }
- // Detect structured data inside the selection via accessibility text.
val regionText = service.dumpTextInRegion(finalRect)
val contextualActions = regionText?.let { SmartActionDetector.detectContextual(it) } ?: emptyList()
- // Hide the overlay's chrome only for the capture instant so it isn't
- // baked into the screenshot, then restore it behind the menu.
withContext(Dispatchers.Main) { overlay?.setCaptureMode(true) }
kotlinx.coroutines.delay(80)
var full = service.takeScreenshotBitmap()
@@ -185,7 +159,6 @@ class ScreenLensController(
}
}
- /** Grow [rect] so each side is at least [minPx], clamped to the view bounds. */
private fun expandToMinimum(rect: Rect, minPx: Int, viewW: Int, viewH: Int): Rect {
val out = Rect(rect)
if (out.width() < minPx) {
@@ -198,103 +171,71 @@ class ScreenLensController(
out.top = cy - minPx / 2
out.bottom = cy + minPx / 2
}
- if (viewW > 0 && viewH > 0) out.intersect(0, 0, viewW, viewH)
+ out.intersect(0, 0, viewW, viewH)
return out
}
- /**
- * Map the selection from view coordinates onto the (possibly higher-res)
- * screenshot bitmap and crop it, clamping to the bitmap bounds.
- */
- private fun cropToSelection(full: Bitmap, rect: Rect, viewW: Int, viewH: Int): Bitmap? {
- val scaleX = if (viewW > 0) full.width.toFloat() / viewW else 1f
- val scaleY = if (viewH > 0) full.height.toFloat() / viewH else 1f
- val left = (rect.left * scaleX).toInt().coerceIn(0, full.width - 1)
- val top = (rect.top * scaleY).toInt().coerceIn(0, full.height - 1)
- val right = (rect.right * scaleX).toInt().coerceIn(left + 1, full.width)
- val bottom = (rect.bottom * scaleY).toInt().coerceIn(top + 1, full.height)
- val w = right - left
- val h = bottom - top
- if (w <= 0 || h <= 0) return null
- return try {
- Bitmap.createBitmap(full, left, top, w, h)
- } catch (_: Exception) {
- null
- }
+ private fun cropToSelection(src: Bitmap, rectInView: Rect, viewW: Int, viewH: Int): Bitmap? {
+ if (src.isRecycled || viewW <= 0 || viewH <= 0) return null
+ val scaleX = src.width.toFloat() / viewW.toFloat()
+ val scaleY = src.height.toFloat() / viewH.toFloat()
+ val cropX = (rectInView.left * scaleX).toInt().coerceIn(0, src.width - 1)
+ val cropY = (rectInView.top * scaleY).toInt().coerceIn(0, src.height - 1)
+ val cropW = (rectInView.width() * scaleX).toInt().coerceIn(1, src.width - cropX)
+ val cropH = (rectInView.height() * scaleY).toInt().coerceIn(1, src.height - cropY)
+ return runCatching { Bitmap.createBitmap(src, cropX, cropY, cropW, cropH) }.getOrNull()
}
- /**
- * Float small "Copy text" / "Translate" chips just above the selection
- * rectangle, so the user can act on the selection's text directly without
- * opening the full menu. Always shown: if the region has accessibility text we
- * act on it directly; otherwise we fall back to OCR via the crop image (LLM).
- */
- private fun showTextChips(rectInView: Rect, regionText: String?) {
+ private fun showTextChips(finalRect: Rect, regionText: String?) {
removeTextChips()
- val text = regionText?.trim()?.takeIf { it.isNotBlank() }
-
- val row = LinearLayout(appContext).apply {
- orientation = LinearLayout.HORIZONTAL
- setPadding(dp(4), dp(4), dp(4), dp(4))
- background = GradientDrawable().apply {
- cornerRadius = dp(18).toFloat()
- setColor(Color.parseColor("#F21E1E1E"))
- setStroke(dp(1), Color.parseColor("#66568CD8"))
+ val overlay = cropOverlay ?: return
+ val density = appContext.resources.displayMetrics.density
+ val cleanText = regionText?.replace(Regex("\\s+"), " ")?.trim()
+
+ val chipsLayout = android.widget.LinearLayout(appContext).apply {
+ orientation = android.widget.LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER
+ setPadding((6 * density).toInt(), (4 * density).toInt(), (6 * density).toInt(), (4 * density).toInt())
+ background = android.graphics.drawable.GradientDrawable().apply {
+ cornerRadius = 14f * density
+ setColor(android.graphics.Color.parseColor("#EE101018"))
+ setStroke((1 * density).toInt(), android.graphics.Color.parseColor("#44568CD8"))
}
}
- row.addView(
- smallChip("📝 Copy text") {
- if (text != null) {
- copyTextToClipboard(text)
- finishMenu(recycle = true)
- } else {
- // No accessibility text — OCR the crop, then copy the result.
- val crop = pendingCrop?.let { it.copy(android.graphics.Bitmap.Config.ARGB_8888, false) }
- finishMenu(recycle = true)
- if (crop != null) onOcrToClipboard(crop) else onError("Couldn't read selection")
+
+ val hasText = !cleanText.isNullOrBlank()
+ if (hasText) {
+ chipsLayout.addView(
+ chipButton("📋 Copy text") {
+ val crop = pendingCrop
+ if (crop != null && !crop.isRecycled) {
+ onOcrToClipboard(crop)
+ }
+ cancel()
}
- }
- )
- row.addView(
- smallChip("🌐 Translate") {
- if (text != null) {
- finishMenu(recycle = true)
- onContextualAction(
- "Translate the following text to English (or the user's system " +
- "language if it is already English). Show only the translation:\n\n$text"
- )
- } else {
- // No accessibility text — attach the crop and translate via vision.
- val base64 = pendingCrop?.let { encodeJpeg(it) }
- finishMenu(recycle = true)
- if (base64 != null) {
- onImagePrompt(
- base64,
- "Read the text in this image and translate it to English (or the " +
- "user's system language if it is already English). Show the " +
- "original text and its translation."
- )
- } else {
- onError("Couldn't read selection")
+ )
+ chipsLayout.addView(
+ chipButton("🌐 Translate") {
+ val crop = pendingCrop
+ if (crop != null && !crop.isRecycled) {
+ val base64 = bitmapToBase64(crop)
+ onImagePrompt(base64, ScreenCompanionController.TRANSLATE_SCREENSHOT_PROMPT)
+ cancel()
}
}
- }
- )
+ )
+ }
- // Measure so we can centre the row over the rectangle and place it above it.
- row.measure(
- View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
- View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
+ chipsLayout.addView(
+ chipButton("❓ Ask about this") {
+ val crop = pendingCrop
+ if (crop != null && !crop.isRecycled) {
+ val base64 = bitmapToBase64(crop)
+ onAskAboutCrop(base64)
+ cancel()
+ }
+ }
)
- val rowW = row.measuredWidth.coerceAtLeast(dp(160))
- val rowH = row.measuredHeight.coerceAtLeast(dp(40))
- val metrics = appContext.resources.displayMetrics
-
- var x = rectInView.centerX() - rowW / 2
- x = x.coerceIn(dp(8), (metrics.widthPixels - rowW - dp(8)).coerceAtLeast(dp(8)))
- // Prefer just above the rectangle; if there's no room, place just below it.
- var y = rectInView.top - rowH - dp(8)
- if (y < dp(8)) y = (rectInView.bottom + dp(8)).coerceAtMost(metrics.heightPixels - rowH - dp(8))
val params = WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
@@ -304,316 +245,105 @@ class ScreenLensController(
PixelFormat.TRANSLUCENT
).apply {
gravity = Gravity.TOP or Gravity.START
- this.x = x
- this.y = y
+ x = (finalRect.centerX() - (120 * density)).toInt().coerceIn(0, overlay.width - 240)
+ y = (finalRect.top - (48 * density)).toInt().coerceAtLeast((16 * density).toInt())
}
+
try {
- windowManager.addView(row, params)
- textChips = row
+ windowManager.addView(chipsLayout, params)
+ textChips = chipsLayout
} catch (_: Exception) {
textChips = null
}
}
- private fun smallChip(label: String, onClick: () -> Unit): TextView = TextView(appContext).apply {
- text = label
- setTextColor(Color.WHITE)
- textSize = 13f
- gravity = Gravity.CENTER
- setPadding(dp(14), dp(8), dp(14), dp(8))
- background = GradientDrawable().apply {
- cornerRadius = dp(14).toFloat()
- setColor(Color.parseColor("#33568CD8"))
- setStroke(dp(1), Color.parseColor("#66B06FD0"))
+ private fun chipButton(label: String, onClick: () -> Unit): TextView {
+ val density = appContext.resources.displayMetrics.density
+ return TextView(appContext).apply {
+ text = label
+ textSize = 12f
+ setTextColor(android.graphics.Color.WHITE)
+ setPadding((10 * density).toInt(), (6 * density).toInt(), (10 * density).toInt(), (6 * density).toInt())
+ setOnClickListener { onClick() }
}
- layoutParams = LinearLayout.LayoutParams(
- LinearLayout.LayoutParams.WRAP_CONTENT,
- LinearLayout.LayoutParams.WRAP_CONTENT
- ).apply { setMargins(dp(3), dp(3), dp(3), dp(3)) }
- setOnClickListener { onClick() }
}
- private fun showActionMenu(contextualActions: List<SmartAction>) {
+ private fun showActionMenu(actions: List<SmartAction>) {
removeActionMenu()
- 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(Color.parseColor("#F21E1E1E"))
- setStroke(dp(1), Color.parseColor("#66568CD8"))
+ if (actions.isEmpty()) return
+
+ val density = appContext.resources.displayMetrics.density
+ val menuLayout = android.widget.LinearLayout(appContext).apply {
+ orientation = android.widget.LinearLayout.VERTICAL
+ setPadding((8 * density).toInt(), (8 * density).toInt(), (8 * density).toInt(), (8 * density).toInt())
+ background = android.graphics.drawable.GradientDrawable().apply {
+ cornerRadius = 16f * density
+ setColor(android.graphics.Color.parseColor("#F51E293B"))
+ setStroke((1 * density).toInt(), android.graphics.Color.parseColor("#334155"))
}
}
- // Draggable handle: grab this bar to move the menu over the selection.
- container.addView(dragHandle("⠿ Lens selection · drag to move"))
-
- // Contextual actions detected inside the selection come first.
- contextualActions.forEach { action ->
- container.addView(
- menuButton(action.label, highlight = true) {
- finishMenu(recycle = true)
- onContextualAction(action.prompt)
- }
- )
- }
- // (Text ops — Copy text / Translate — live as inline chips on the rectangle.)
-
- container.addView(
- menuButton("🔍 Ask about this") {
- val base64 = pendingCrop?.let { encodeJpeg(it) }
- finishMenu(recycle = true)
- if (base64 != null) {
- onAskAboutCrop(base64)
- } else {
- onError("Couldn't encode selection")
+ for (action in actions) {
+ val btn = TextView(appContext).apply {
+ text = action.label
+ textSize = 13f
+ setTextColor(android.graphics.Color.parseColor("#E2E8F0"))
+ setPadding((14 * density).toInt(), (8 * density).toInt(), (14 * density).toInt(), (8 * density).toInt())
+ background = android.graphics.drawable.GradientDrawable().apply {
+ cornerRadius = 10f * density
+ setColor(android.graphics.Color.parseColor("#334155"))
+ }
+ layoutParams = android.widget.LinearLayout.LayoutParams(
+ android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
+ android.widget.LinearLayout.LayoutParams.WRAP_CONTENT
+ ).apply { setMargins(0, (4 * density).toInt(), 0, (4 * density).toInt()) }
+ setOnClickListener {
+ val prompt = action.prompt
+ cancel()
+ onContextualAction(prompt)
}
}
- )
- container.addView(
- menuButton("📋 Copy Image") {
- pendingCrop?.let { copyImageToClipboard(it) }
- finishMenu(recycle = true)
- }
- )
- container.addView(
- menuButton("💾 Save to Downloads") {
- val bmp = pendingCrop
- // Hand ownership to the async saver, which recycles when done.
- pendingCrop = null
- removeActionMenu()
- removeCropOverlay()
- if (bmp != null) saveToDownloads(bmp) else onError("Nothing to save")
- }
- )
- container.addView(
- menuButton("✕ Cancel") {
- finishMenu(recycle = true)
- }
- )
+ menuLayout.addView(btn)
+ }
val params = WindowManager.LayoutParams(
- dp(280),
+ (240 * density).toInt(),
WindowManager.LayoutParams.WRAP_CONTENT,
overlayType(),
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT
).apply {
- gravity = Gravity.TOP or Gravity.START
- // Start centred; the user can drag it anywhere via the handle.
- val metrics = appContext.resources.displayMetrics
- x = (metrics.widthPixels - dp(280)) / 2
- y = (metrics.heightPixels / 3)
- }
- attachDragToMenu(container, params)
- try {
- windowManager.addView(container, params)
- actionMenu = container
- } catch (_: Exception) {
- actionMenu = null
- }
- }
-
- /** Make the menu window draggable by touching its handle row. */
- @SuppressLint("ClickableViewAccessibility")
- private fun attachDragToMenu(container: View, params: WindowManager.LayoutParams) {
- var downRawX = 0f
- var downRawY = 0f
- var startX = 0
- var startY = 0
- container.setOnTouchListener { _, event ->
- when (event.action) {
- android.view.MotionEvent.ACTION_DOWN -> {
- downRawX = event.rawX
- downRawY = event.rawY
- startX = params.x
- startY = params.y
- false // let child buttons still receive the tap
- }
- android.view.MotionEvent.ACTION_MOVE -> {
- val dx = (event.rawX - downRawX).toInt()
- val dy = (event.rawY - downRawY).toInt()
- if (kotlin.math.abs(dx) > dragSlop || kotlin.math.abs(dy) > dragSlop) {
- params.x = startX + dx
- params.y = startY + dy
- try {
- windowManager.updateViewLayout(container, params)
- } catch (_: Exception) {}
- true
- } else {
- false
- }
- }
- else -> false
- }
- }
- }
-
- private fun dragHandle(label: String): TextView = TextView(appContext).apply {
- text = label
- setTextColor(Color.parseColor("#9FB6E0"))
- textSize = 12f
- gravity = Gravity.CENTER
- setPadding(dp(12), dp(8), dp(12), dp(10))
- }
-
- /**
- * Dismiss the menu AND the (now-persisted) selection overlay, and optionally
- * recycle the crop the menu was acting on.
- */
- private fun finishMenu(recycle: Boolean) {
- removeActionMenu()
- removeTextChips()
- removeCropOverlay()
- if (recycle) recyclePendingCrop()
- }
-
- private fun copyTextToClipboard(text: String) {
- try {
- val clipboard = appContext.getSystemService(Context.CLIPBOARD_SERVICE)
- as android.content.ClipboardManager
- clipboard.setPrimaryClip(android.content.ClipData.newPlainText("Lens text", text))
- toast("Text copied")
- } catch (e: Exception) {
- onError("Copy failed: ${e.message}")
+ gravity = Gravity.CENTER
}
- }
- private fun copyImageToClipboard(bitmap: Bitmap) {
try {
- val uri = writeToCache(bitmap) ?: run {
- onError("Couldn't copy image")
- return
- }
- val clipboard = appContext.getSystemService(Context.CLIPBOARD_SERVICE)
- as android.content.ClipboardManager
- val clip = android.content.ClipData.newUri(
- appContext.contentResolver,
- "Cropped Image",
- uri
- )
- clipboard.setPrimaryClip(clip)
- toast("Image copied")
- } catch (e: Exception) {
- onError("Copy failed: ${e.message}")
- }
- }
-
- /** Write to a FileProvider-shared cache file so a content:// URI can be clipped. */
- private fun writeToCache(bitmap: Bitmap): android.net.Uri? {
- return try {
- val dir = File(appContext.cacheDir, "lens").apply { mkdirs() }
- val file = File(dir, "lens_${System.currentTimeMillis()}.png")
- FileOutputStream(file).use { out -> bitmap.compress(Bitmap.CompressFormat.PNG, 100, out) }
- androidx.core.content.FileProvider.getUriForFile(
- appContext,
- "${appContext.packageName}.fileprovider",
- file
- )
+ windowManager.addView(menuLayout, params)
+ actionMenu = menuLayout
} catch (_: Exception) {
- null
- }
- }
-
- /** Saves [bitmap] on IO, then recycles it — takes ownership from the caller. */
- private fun saveToDownloads(bitmap: Bitmap) {
- scope.launch(Dispatchers.IO) {
- try {
- val filename = "Gotcha_Crop_${System.currentTimeMillis()}.png"
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
- val values = android.content.ContentValues().apply {
- put(android.provider.MediaStore.Downloads.DISPLAY_NAME, filename)
- put(android.provider.MediaStore.Downloads.MIME_TYPE, "image/png")
- put(
- android.provider.MediaStore.Downloads.RELATIVE_PATH,
- Environment.DIRECTORY_DOWNLOADS + "/Gotcha"
- )
- }
- val uri = appContext.contentResolver.insert(
- android.provider.MediaStore.Downloads.EXTERNAL_CONTENT_URI,
- values
- )
- if (uri != null) {
- appContext.contentResolver.openOutputStream(uri)?.use { out ->
- bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
- }
- withContext(Dispatchers.Main) { toast("Saved to Downloads/Gotcha") }
- } else {
- withContext(Dispatchers.Main) { onError("Save failed") }
- }
- } else {
- @Suppress("DEPRECATION")
- val directory = File(
- Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
- "Gotcha"
- )
- if (!directory.exists()) directory.mkdirs()
- val file = File(directory, filename)
- FileOutputStream(file).use { out ->
- bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
- }
- withContext(Dispatchers.Main) { toast("Saved: ${file.absolutePath}") }
- }
- } catch (e: Exception) {
- withContext(Dispatchers.Main) { onError("Save failed: ${e.message}") }
- } finally {
- bitmap.recycle()
- }
+ actionMenu = null
}
}
- private fun encodeJpeg(bitmap: Bitmap): String? {
- return com.gotcha.tools.ScreenPerception.compressBitmap(
- bitmap = bitmap,
- maxDimension = 1024,
- quality = 85,
- format = Bitmap.CompressFormat.JPEG,
- recycleInput = false
- )
- }
-
- private fun recyclePendingCrop() {
- pendingCrop?.let { if (!it.isRecycled) it.recycle() }
- pendingCrop = null
- }
-
- private fun toast(msg: String) {
- android.widget.Toast.makeText(appContext, msg, android.widget.Toast.LENGTH_SHORT).show()
- }
-
- private fun menuButton(label: String, highlight: Boolean = false, onClick: () -> Unit): TextView =
- TextView(appContext).apply {
- text = label
- setTextColor(if (highlight) Color.parseColor("#E081C0") else Color.WHITE)
- textSize = 15f
- gravity = Gravity.CENTER_VERTICAL
- setPadding(dp(16), dp(12), dp(16), dp(12))
- background = GradientDrawable().apply {
- cornerRadius = dp(12).toFloat()
- setColor(Color.parseColor(if (highlight) "#332C6BE0" else "#33FFFFFF"))
- if (highlight) setStroke(dp(1), Color.parseColor("#66E081C0"))
- }
- 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 removeCropOverlay() {
- removeTextChips()
cropOverlay?.let { safeRemove(it) }
cropOverlay = null
}
+ private fun removeActionMenu() {
+ actionMenu?.let { safeRemove(it) }
+ actionMenu = null
+ }
+
private fun removeTextChips() {
textChips?.let { safeRemove(it) }
textChips = null
}
- private fun removeActionMenu() {
- actionMenu?.let { safeRemove(it) }
- actionMenu = null
+ private fun recyclePendingCrop() {
+ pendingCrop?.let {
+ if (!it.isRecycled) it.recycle()
+ }
+ pendingCrop = null
}
private fun safeRemove(view: View) {
@@ -622,6 +352,12 @@ class ScreenLensController(
} catch (_: Exception) {}
}
+ private fun bitmapToBase64(bitmap: Bitmap): String {
+ val baos = java.io.ByteArrayOutputStream()
+ bitmap.compress(Bitmap.CompressFormat.JPEG, 85, baos)
+ return android.util.Base64.encodeToString(baos.toByteArray(), android.util.Base64.NO_WRAP)
+ }
+
private fun overlayType(): Int =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
@@ -630,11 +366,7 @@ class ScreenLensController(
WindowManager.LayoutParams.TYPE_PHONE
}
- private fun dp(value: Int): Int =
- (value * appContext.resources.displayMetrics.density).toInt()
-
private companion object {
- /** Minimum side length of a Lens selection, so a thin line still captures a band. */
- const val MIN_SELECTION_DP = 44
+ const val MIN_SELECTION_DP = 24
}
}
diff --git a/app/src/main/java/com/gotcha/service/SmartActionDetector.kt b/app/src/main/java/com/gotcha/service/SmartActionDetector.kt
index eb6e032..2e7e18f 100644
--- a/app/src/main/java/com/gotcha/service/SmartActionDetector.kt
+++ b/app/src/main/java/com/gotcha/service/SmartActionDetector.kt
@@ -65,6 +65,14 @@ data class DetectedEntity(
val primaryAction: SmartAction? get() = actions.firstOrNull { it.isPrimary } ?: actions.firstOrNull()
}
+/**
+ * An entity mapped to absolute screen bounds for the Lens auto-annotate overlay.
+ */
+data class AnnotatedEntity(
+ val entity: DetectedEntity,
+ val boundsOnScreen: android.graphics.Rect
+)
+
/**
* Lightweight text scanner that recognises structured data types — physical
* addresses, phone numbers, foreign-currency prices, calendar events, URLs, emails,
diff --git a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
index f78caef..8ce929a 100644
--- a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
+++ b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
@@ -18,6 +18,7 @@ import android.view.View
import android.view.ViewConfiguration
import android.view.WindowManager
import android.view.animation.AccelerateDecelerateInterpolator
+import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
@@ -61,8 +62,6 @@ class AssistiveBallOverlay(context: Context) {
private var pendingSmartAction: Pair<String, String>? = null
private var pendingSmartActionAlt: Pair<String, String>? = null
private var lastOfferedLabel: String? = null
- private var smartActionRingView: View? = null
- private var smartActionRingAnimator: ValueAnimator? = null
private val smartActionClearRunnable = Runnable { clearSmartAction() }
private var ballView: View? = null
@@ -126,7 +125,6 @@ class AssistiveBallOverlay(context: Context) {
}
}
- /** Restore the ball after a capture (back to its faint edge-peek state). */
fun showChromeAfterCapture() {
mainHandler.post {
ballView?.visibility = View.VISIBLE
@@ -160,7 +158,6 @@ class AssistiveBallOverlay(context: Context) {
fun dismiss() {
mainHandler.post {
- removeSmartActionRing()
removeLongPressRing()
removeMenu()
removeCard()
@@ -178,6 +175,8 @@ class AssistiveBallOverlay(context: Context) {
topEntity.primaryAction?.let { action ->
setSmartActionAvailable(action.label, action.prompt)
}
+ } else {
+ clearSmartAction()
}
}
}
@@ -202,7 +201,6 @@ class AssistiveBallOverlay(context: Context) {
lastOfferedLabel = label
pendingSmartAction = Pair(label, prompt)
pendingSmartActionAlt = if (altLabel != null && altPrompt != null) Pair(altLabel, altPrompt) else null
- showSmartActionRing()
mainHandler.removeCallbacks(smartActionClearRunnable)
mainHandler.postDelayed(smartActionClearRunnable, 45000L)
}
@@ -257,19 +255,19 @@ class AssistiveBallOverlay(context: Context) {
pendingSmartAction = null
pendingSmartActionAlt = null
lastOfferedLabel = null
- removeSmartActionRing()
removeMenu()
}
}
private fun buildBall(): View {
val size = dp(BALL_SIZE_DP)
+ val colors = palette()
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
+ fillColor = colors.surface
+ strokeColor = Color.parseColor("#FF3E7BFF")
+ strokeWidth = 2.5f * appContext.resources.displayMetrics.density
}
alpha = PEEK_ALPHA
setOnTouchListener(ballTouchListener())
@@ -284,22 +282,76 @@ class AssistiveBallOverlay(context: Context) {
private fun showMenu() {
removeMenu()
val colors = palette()
- val container = LinearLayout(appContext).apply {
+
+ // Full-screen transparent root overlay that closes the menu on outside clicks
+ val rootLayout = FrameLayout(appContext).apply {
+ setOnClickListener {
+ removeMenu()
+ }
+ }
+
+ val menuCard = LinearLayout(appContext).apply {
orientation = LinearLayout.VERTICAL
- setPadding(dp(8), dp(8), dp(8), dp(8))
+ setPadding(dp(10), dp(10), dp(10), dp(10))
background = GradientDrawable().apply {
- cornerRadius = dp(20).toFloat()
+ cornerRadius = dp(18).toFloat()
setColor(colors.surface)
setStroke(dp(1), colors.outline)
}
+ // Stop clicks inside the card from closing the menu
+ setOnClickListener { }
+ }
+
+ buildProactiveMenuContent(menuCard, colors)
+
+ val appNavRow = LinearLayout(appContext).apply {
+ orientation = LinearLayout.VERTICAL
+ }
+ appNavRow.addView(
+ tapButton("📱 Open App", colors) {
+ removeMenu()
+ onOpenApp()
+ }
+ )
+ appNavRow.addView(
+ tapButton("📸 Screenshot", colors) {
+ removeMenu()
+ onTakeScreenshot()
+ }
+ )
+ appNavRow.addView(
+ tapButton("🔍 Lens", colors) {
+ removeMenu()
+ onStartLens()
+ }
+ )
+ menuCard.addView(appNavRow)
+
+ val cardParams = FrameLayout.LayoutParams(
+ dp(MENU_WIDTH_DP),
+ FrameLayout.LayoutParams.WRAP_CONTENT
+ ).apply {
+ val metrics = appContext.resources.displayMetrics
+ leftMargin = (ballParams.x).coerceIn(0, (metrics.widthPixels - dp(MENU_WIDTH_DP)).coerceAtLeast(0))
+ topMargin = (ballParams.y + dp(64)).coerceIn(0, (metrics.heightPixels - dp(280)).coerceAtLeast(0))
+ }
+ rootLayout.addView(menuCard, cardParams)
+
+ val params = fullScreenMenuLayoutParams()
+ try {
+ windowManager.addView(rootLayout, params)
+ menuView = rootLayout
+ } catch (_: Exception) {
+ menuView = null
}
+ }
- // Render Proactive Multi-Entity Grouped List
+ private fun buildProactiveMenuContent(menuCard: LinearLayout, colors: OverlayPalette) {
if (proactiveSessionItems.isNotEmpty()) {
val scroll = ScrollView(appContext).apply {
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
- dp(220)
+ dp(240)
)
}
val listContent = LinearLayout(appContext).apply {
@@ -309,71 +361,57 @@ class AssistiveBallOverlay(context: Context) {
for (item in proactiveSessionItems.take(4)) {
val entity = item.entity
val headerText = TextView(appContext).apply {
- text = "${getCategoryIcon(entity.type)} ${SmartActionDetector.snippet(entity.normalizedValue, 22)}"
+ text = "${getCategoryIcon(entity.type)} ${SmartActionDetector.snippet(entity.normalizedValue, 24)}"
typeface = figtree ?: Typeface.DEFAULT
textSize = 12f
setTextColor(colors.onSurface)
- setPadding(dp(8), dp(6), dp(8), dp(2))
+ setPadding(dp(6), dp(6), dp(6), dp(4))
}
listContent.addView(headerText)
val chipRow = LinearLayout(appContext).apply {
orientation = LinearLayout.HORIZONTAL
- setPadding(dp(4), dp(2), dp(4), dp(6))
+ setPadding(dp(2), dp(2), dp(2), dp(8))
}
for (action in entity.actions) {
- chipRow.addView(
- tapButton(action.label, colors) {
+ val chipBtn = TextView(appContext).apply {
+ text = action.label
+ typeface = figtree ?: Typeface.DEFAULT
+ textSize = 12f
+ setTextColor(colors.buttonText)
+ gravity = Gravity.CENTER
+ setPadding(dp(10), dp(6), dp(10), dp(6))
+ background = GradientDrawable().apply {
+ cornerRadius = dp(10).toFloat()
+ setColor(colors.buttonBg)
+ }
+ layoutParams = LinearLayout.LayoutParams(
+ 0,
+ LinearLayout.LayoutParams.WRAP_CONTENT,
+ 1f
+ ).apply { setMargins(dp(2), dp(2), dp(2), dp(2)) }
+ setOnClickListener {
val currentPrompt = action.prompt
- clearSmartAction()
+ removeMenu()
onSmartActionSelected(currentPrompt)
- }.apply {
- textSize = 11f
- setPadding(dp(8), dp(4), dp(8), dp(4))
}
- )
+ }
+ chipRow.addView(chipBtn)
}
listContent.addView(chipRow)
}
scroll.addView(listContent)
- container.addView(scroll)
+ menuCard.addView(scroll)
} else {
pendingSmartAction?.let { (label, prompt) ->
- container.addView(
+ menuCard.addView(
tapButton(label, colors) {
- clearSmartAction()
+ removeMenu()
onSmartActionSelected(prompt)
}
)
}
}
-
- container.addView(
- tapButton("📱 Open App", colors) {
- removeMenu()
- onOpenApp()
- }
- )
- container.addView(
- tapButton("📸 Screenshot", colors) {
- removeMenu()
- onTakeScreenshot()
- }
- )
- container.addView(
- tapButton("🔍 Lens", colors) {
- removeMenu()
- onStartLens()
- }
- )
-
- val params = menuLayoutParams()
- try {
- windowManager.addView(container, params)
- menuView = container
- } catch (_: Exception) {
- menuView = null
- }
}
private fun getCategoryIcon(type: EntityType): String = when (type) {
@@ -402,9 +440,9 @@ class AssistiveBallOverlay(context: Context) {
setColor(colors.buttonBg)
}
layoutParams = LinearLayout.LayoutParams(
- LinearLayout.LayoutParams.WRAP_CONTENT,
+ LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
- ).apply { setMargins(dp(4), dp(4), dp(4), dp(4)) }
+ ).apply { setMargins(dp(4), dp(3), dp(4), dp(3)) }
setOnClickListener { onClick() }
}
}
@@ -481,74 +519,6 @@ class AssistiveBallOverlay(context: Context) {
ringDrawable = null
}
- 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
@@ -595,7 +565,6 @@ class AssistiveBallOverlay(context: Context) {
try {
windowManager.updateViewLayout(ballView, ballParams)
ballView?.requestFocus()
- updateSmartActionRingPosition()
} catch (_: Exception) { }
updateDismissTargetHighlight(isOverDismissTarget())
}
@@ -648,7 +617,6 @@ class AssistiveBallOverlay(context: Context) {
ballParams.y = ballParams.y.coerceIn(0, maxY.coerceAtLeast(0))
try {
windowManager.updateViewLayout(ballView, ballParams)
- updateSmartActionRingPosition()
} catch (_: Exception) { }
}
@@ -675,7 +643,6 @@ class AssistiveBallOverlay(context: Context) {
val view = ballView ?: return
try {
windowManager.updateViewLayout(view, ballParams)
- updateSmartActionRingPosition()
} catch (_: Exception) { }
ValueAnimator.ofFloat(view.alpha, 1.0f).apply {
duration = 180L
@@ -700,7 +667,6 @@ class AssistiveBallOverlay(context: Context) {
ballParams.x = (startX + (targetX - startX) * p).toInt()
try {
windowManager.updateViewLayout(view, ballParams)
- updateSmartActionRingPosition()
} catch (_: Exception) { }
view.alpha = startAlpha + (PEEK_ALPHA - startAlpha) * p
}
@@ -803,18 +769,15 @@ class AssistiveBallOverlay(context: Context) {
y = dp(160)
}
- private fun menuLayoutParams(): WindowManager.LayoutParams =
+ private fun fullScreenMenuLayoutParams(): WindowManager.LayoutParams =
WindowManager.LayoutParams(
- dp(MENU_WIDTH_DP),
- WindowManager.LayoutParams.WRAP_CONTENT,
+ WindowManager.LayoutParams.MATCH_PARENT,
+ WindowManager.LayoutParams.MATCH_PARENT,
overlayType(),
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT
).apply {
gravity = Gravity.TOP or Gravity.START
- 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))
}
private fun cardLayoutParams(): WindowManager.LayoutParams =
@@ -845,15 +808,15 @@ class AssistiveBallOverlay(context: Context) {
private companion object {
const val BALL_SIZE_DP = 56
- const val MENU_WIDTH_DP = 220
+ const val MENU_WIDTH_DP = 290
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
- const val PEEK_DP = 28
- const val PEEK_ALPHA = 0.35f
+ const val PEEK_DP = 36
+ const val PEEK_ALPHA = 0.85f
const val DOCK_MARGIN_DP = 16
const val AUTO_DOCK_DELAY_MS = 2500L
diff --git a/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt b/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt
index 7f3e15c..48dc8c8 100644
--- a/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt
+++ b/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt
@@ -13,39 +13,23 @@ import android.graphics.RectF
import android.graphics.Shader
import android.view.MotionEvent
import android.view.View
+import com.gotcha.service.AnnotatedEntity
import kotlin.math.max
import kotlin.math.min
import kotlin.random.Random
-/**
- * Full-screen premium "Lens" overlay. The user draws ANY free-form shape; on
- * release its bounding rectangle (max width/height of the drawn path) becomes the
- * selection. [onSelection] fires with that [Rect] in view pixels; a tap (no real
- * drag) calls [onCancel].
- *
- * Visual treatment (matches the app logo's pink/blue theme):
- * - a soft pink glow bleeding in from all four screen edges,
- * - drifting glowing particles (pink + blue) whose density is higher near the
- * edges and sparse in the centre,
- * - while drawing, the traced path is stroked in a pink→blue gradient and its
- * live bounding box is outlined.
- *
- * The particle field animates via [postInvalidateOnAnimation]; it is deterministic
- * only in look, not in exact positions (seeded from the view size).
- */
@SuppressLint("ViewConstructor")
+@Suppress("TooManyFunctions", "LargeClass", "MaxLineLength")
class ScreenCropOverlayView(
context: Context,
private val onSelection: (Rect) -> Unit,
private val onCancel: () -> Unit,
- /** Fired when the user starts drawing again after a selection was frozen, so the
- * host can tear down the menu/chips and let the user re-select from scratch. */
- private val onReselectStart: () -> Unit = {}
+ private val onReselectStart: () -> Unit = {},
+ private val onAnnotatedEntitySelected: (prompt: String) -> Unit = {}
) : View(context) {
private val density = resources.displayMetrics.density
- // ---- Free-form drawing state ----
private val path = Path()
private var minX = 0f
private var minY = 0f
@@ -54,16 +38,11 @@ class ScreenCropOverlayView(
private var drawing = false
private var moved = false
- /** A finalized selection to keep drawn while the action menu is shown. */
private var frozenRect: RectF? = null
-
- /**
- * When true, all overlay chrome (scrim, glow, particles, selection) is hidden
- * so a screenshot taken behind us does not capture it. Restored right after.
- */
private var captureMode = false
- // ---- Paints ----
+ private var annotatedEntities: List<AnnotatedEntity> = emptyList()
+
private val dimPaint = Paint().apply { color = Color.parseColor("#66101018") }
private val edgeGlowPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val pathPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
@@ -73,7 +52,6 @@ class ScreenCropOverlayView(
strokeJoin = Paint.Join.ROUND
}
- /** Thin premium pinkish-blue glowing border around the whole screen edge. */
private val screenBorderPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeWidth = 3f * density
@@ -86,7 +64,6 @@ class ScreenCropOverlayView(
maskFilter = android.graphics.BlurMaskFilter(14f * density, android.graphics.BlurMaskFilter.Blur.NORMAL)
}
- /** Selection-rectangle border: premium pinkish-blue, glowing. */
private val boxPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeWidth = 3f * density
@@ -99,6 +76,22 @@ class ScreenCropOverlayView(
color = Color.parseColor("#55568CD8")
maskFilter = android.graphics.BlurMaskFilter(12f * density, android.graphics.BlurMaskFilter.Blur.NORMAL)
}
+
+ private val entityBoxPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ strokeWidth = 2.5f * density
+ color = Color.parseColor("#FF00E5FF")
+ }
+ private val entityChipBgPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.FILL
+ color = Color.parseColor("#EE1E293B")
+ }
+ private val entityChipTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ color = Color.WHITE
+ textSize = 12f * density
+ textAlign = Paint.Align.LEFT
+ }
+
private val particlePaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val hintPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.WHITE
@@ -112,10 +105,14 @@ class ScreenCropOverlayView(
init {
isFocusableInTouchMode = true
- // Software layer keeps radial/linear gradient + shadow rendering correct.
setLayerType(LAYER_TYPE_SOFTWARE, null)
}
+ fun setAnnotatedEntities(entities: List<AnnotatedEntity>) {
+ this.annotatedEntities = entities
+ postInvalidateOnAnimation()
+ }
+
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
buildEdgeGlow(w, h)
@@ -123,8 +120,6 @@ class ScreenCropOverlayView(
}
private fun buildEdgeGlow(w: Int, h: Int) {
- // A large radial gradient that is transparent in the centre and pink at the
- // rim, giving an edge-vignette wash.
val cx = w / 2f
val cy = h / 2f
val radius = max(w, h) * 0.75f
@@ -146,7 +141,6 @@ class ScreenCropOverlayView(
particles.clear()
if (w == 0 || h == 0) return
val rnd = Random(w * 31L + h)
- // Density scales with screen area; edge-biased placement via rejection.
val target = ((w * h) / (26000f * density)).toInt().coerceIn(40, 220)
var placed = 0
var guard = 0
@@ -154,11 +148,9 @@ class ScreenCropOverlayView(
guard++
val x = rnd.nextFloat() * w
val y = rnd.nextFloat() * h
- // edgeScore ~1 at edges, ~0 at centre.
val ex = 1f - (2f * x / w - 1f).let { it * it }
val ey = 1f - (2f * y / h - 1f).let { it * it }
- val centreness = (1f - ex) * (1f - ey) // ~1 at centre corners... invert below
- // Keep more particles near edges: accept with prob higher when centreness low.
+ val centreness = (1f - ex) * (1f - ey)
val keepProb = 0.15f + 0.85f * (1f - centreness)
if (rnd.nextFloat() > keepProb) continue
particles.add(
@@ -180,8 +172,6 @@ class ScreenCropOverlayView(
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (captureMode) {
- // Draw nothing this frame so a screenshot behind us stays clean, but
- // keep animating so we resume smoothly.
postInvalidateOnAnimation()
return
}
@@ -189,13 +179,14 @@ class ScreenCropOverlayView(
canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), edgeGlowPaint)
stepAndDrawParticles(canvas)
-
drawScreenBorder(canvas)
+ // Draw Auto-Annotated Bounding Boxes & Action Chips
+ drawAnnotatedEntities(canvas)
+
val frozen = frozenRect
when {
drawing && moved -> {
- // Gradient stroke for the traced path.
pathPaint.shader = LinearGradient(
minX, minY, maxX, maxY,
Color.parseColor("#FF6FC0"), Color.parseColor("#5B8CFF"),
@@ -205,17 +196,44 @@ class ScreenCropOverlayView(
drawSelectionBox(canvas, RectF(minX, minY, maxX, maxY))
}
frozen != null -> drawSelectionBox(canvas, frozen)
- else -> canvas.drawText(
- "Draw around anything • tap to cancel",
- width / 2f,
- height * 0.12f,
- hintPaint
- )
+ else -> if (annotatedEntities.isEmpty()) {
+ canvas.drawText(
+ "Draw around anything • tap to cancel",
+ width / 2f,
+ height * 0.12f,
+ hintPaint
+ )
+ }
}
postInvalidateOnAnimation()
}
- /** A thin, premium pinkish-blue glowing frame just inside the screen edges. */
+ private fun drawAnnotatedEntities(canvas: Canvas) {
+ for (item in annotatedEntities) {
+ val bounds = item.boundsOnScreen
+ val rectF = RectF(bounds)
+
+ // Draw bounding box
+ val radius = 8f * density
+ canvas.drawRoundRect(rectF, radius, radius, entityBoxPaint)
+
+ // Draw primary action chip pill anchored above the box
+ val action = item.entity.primaryAction ?: continue
+ val labelStr = action.label
+ val textWidth = entityChipTextPaint.measureText(labelStr)
+ val chipW = textWidth + 16f * density
+ val chipH = 24f * density
+
+ val chipLeft = (rectF.left).coerceIn(8f * density, width - chipW - 8f * density)
+ val chipTop = (rectF.top - chipH - 4f * density).coerceAtLeast(8f * density)
+ val chipRect = RectF(chipLeft, chipTop, chipLeft + chipW, chipTop + chipH)
+
+ canvas.drawRoundRect(chipRect, 12f * density, 12f * density, entityChipBgPaint)
+ canvas.drawRoundRect(chipRect, 12f * density, 12f * density, entityBoxPaint)
+ canvas.drawText(labelStr, chipLeft + 8f * density, chipTop + 16f * density, entityChipTextPaint)
+ }
+ }
+
private fun drawScreenBorder(canvas: Canvas) {
val inset = screenBorderGlowPaint.strokeWidth / 2f + 1f
val r = RectF(inset, inset, width - inset, height - inset)
@@ -230,14 +248,12 @@ class ScreenCropOverlayView(
canvas.drawRoundRect(rect, radius, radius, boxPaint)
}
- /** Freeze [rect] (view px) so it stays drawn while the action menu is shown. */
fun freezeSelection(rect: Rect) {
frozenRect = RectF(rect)
drawing = false
postInvalidateOnAnimation()
}
- /** Toggle capture mode: when true the overlay draws nothing (see [onDraw]). */
fun setCaptureMode(enabled: Boolean) {
captureMode = enabled
postInvalidateOnAnimation()
@@ -253,7 +269,6 @@ class ScreenCropOverlayView(
for (p in particles) {
p.x += p.vx * dt
p.y += p.vy * dt
- // Wrap around edges so the field stays populated.
if (p.x < -p.radius) p.x = w + p.radius
if (p.x > w + p.radius) p.x = -p.radius
if (p.y < -p.radius) p.y = h + p.radius
@@ -262,7 +277,6 @@ class ScreenCropOverlayView(
val glowAlpha = (0.35f + 0.65f * (0.5f + 0.5f * kotlin.math.sin(t * p.twinkle + p.phase)))
val core = if (p.pink) 0xFF5FBF else 0x5B8CFF
val a = (glowAlpha * 255).toInt().coerceIn(0, 255)
- // Outer glow.
particlePaint.shader = RadialGradient(
p.x, p.y, p.radius * 3.2f,
Color.argb((a * 0.5f).toInt(), (core shr 16) and 0xFF, (core shr 8) and 0xFF, core and 0xFF),
@@ -270,7 +284,6 @@ class ScreenCropOverlayView(
Shader.TileMode.CLAMP
)
canvas.drawCircle(p.x, p.y, p.radius * 3.2f, particlePaint)
- // Bright core.
particlePaint.shader = null
particlePaint.color = Color.argb(a, 255, 255, 255)
canvas.drawCircle(p.x, p.y, p.radius * 0.6f, particlePaint)
@@ -278,12 +291,33 @@ class ScreenCropOverlayView(
}
override fun onTouchEvent(event: MotionEvent): Boolean {
- // While a screenshot is being captured, ignore touches.
if (captureMode) return false
+
+ // Check if touch hits an annotated entity box/chip
+ if (event.action == MotionEvent.ACTION_UP && !moved) {
+ val touchX = event.x
+ val touchY = event.y
+ for (item in annotatedEntities) {
+ val bounds = RectF(item.boundsOnScreen)
+ val chipH = 24f * density
+ val expandedBounds = RectF(
+ bounds.left - 16f,
+ bounds.top - chipH - 16f,
+ bounds.right + 16f,
+ bounds.bottom + 16f
+ )
+ if (expandedBounds.contains(touchX, touchY)) {
+ val prompt = item.entity.primaryAction?.prompt
+ if (prompt != null) {
+ onAnnotatedEntitySelected(prompt)
+ return true
+ }
+ }
+ }
+ }
+
when (event.action) {
MotionEvent.ACTION_DOWN -> {
- // A new drag after a frozen selection restarts the selection: clear
- // the old rect and ask the host to tear down the menu/chips.
if (frozenRect != null) {
frozenRect = null
onReselectStart()
@@ -308,8 +342,6 @@ class ScreenCropOverlayView(
MotionEvent.ACTION_UP -> {
drawing = false
val rect = Rect(minX.toInt(), minY.toInt(), maxX.toInt(), maxY.toInt())
- // Accept any real drag (even a thin line — the controller expands it
- // to a minimum band). A tap with no movement cancels.
if (moved && max(rect.width(), rect.height()) > MIN_SIZE_PX) {
onSelection(rect)
} else {