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: enhance lens selection with smart sizing, UI-element snapping, persistent overlays, and draggable menus with data-prefixed labels.

Rishabh Bajpai5937e57997b6
diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
index 8a775f9..9c8babc 100644
--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
@@ -170,12 +170,9 @@ class AssistiveBallService : Service() {
}
return
}
- // Only these explicitly-visual actions attach a screenshot. (A generic
- // prompt that merely mentions "screen" must NOT pull in an image.)
- val attachScreenshot = prompt.contains("screenshot", ignoreCase = true) ||
- prompt.contains("webpage shown", ignoreCase = true) ||
- prompt.contains("shown on screen", ignoreCase = true) ||
- prompt.contains("shown on the screen", ignoreCase = true)
+ // Only an explicit screenshot action attaches an image. (A generic prompt
+ // that merely mentions "screen" must NOT pull one in.)
+ val attachScreenshot = prompt.contains("screenshot", ignoreCase = true)
screenCompanionPanel.show(prompt)
overlay.isPanelOpen = true
scope.launch {
@@ -344,7 +341,7 @@ class AssistiveBallService : Service() {
} else {
android.util.Log.d("AssistiveBallService", "Setting smart action: Text copied. Translate?")
overlay.setSmartActionAvailable(
- "📋 Text copied. Translate?",
+ "📋 Translate: ${SmartActionDetector.snippet(clipText, 24)}",
"Translate the copied text to English if it is not, otherwise summarize it:\n\n$clipText"
)
}
diff --git a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
index 3e9cf01..f7ac35d 100644
--- a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
+++ b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
@@ -241,6 +241,58 @@ class GotchaAccessibilityService : AccessibilityService() {
}
}
+ /**
+ * Grow [region] (screen pixels) to include any UI element it substantially
+ * overlaps, so a selection drawn around ~most of a control snaps to the whole
+ * control. An element is included when the intersection covers at least
+ * [coverage] of EITHER the element's area or the drawn region's area (the
+ * latter lets a small scribble inside a big element still snap to it). Returns
+ * the unioned rectangle, or the original [region] when nothing qualifies.
+ */
+ fun snapRegionToElements(
+ region: android.graphics.Rect,
+ coverage: Float = 0.6f
+ ): android.graphics.Rect {
+ val root = rootInActiveWindow ?: return region
+ val result = android.graphics.Rect(region)
+ val regionArea = region.width().toLong() * region.height().toLong()
+ accumulateSnap(root, region, regionArea, coverage, result)
+ root.recycle()
+ return result
+ }
+
+ private fun accumulateSnap(
+ node: AccessibilityNodeInfo?,
+ region: android.graphics.Rect,
+ regionArea: Long,
+ coverage: Float,
+ acc: android.graphics.Rect
+ ) {
+ if (node == null) return
+ val bounds = android.graphics.Rect()
+ node.getBoundsInScreen(bounds)
+ if (!bounds.isEmpty && android.graphics.Rect.intersects(bounds, region)) {
+ val inter = android.graphics.Rect(bounds)
+ if (inter.intersect(region)) {
+ val interArea = inter.width().toLong() * inter.height().toLong()
+ val nodeArea = bounds.width().toLong() * bounds.height().toLong()
+ val coversNode = nodeArea > 0 && interArea >= coverage * nodeArea
+ val coversRegion = regionArea > 0 && interArea >= coverage * regionArea
+ // Skip full-screen containers/root so we snap to actual controls,
+ // not the window that swallows everything.
+ val metrics = resources.displayMetrics
+ val screenArea = metrics.widthPixels.toLong() * metrics.heightPixels.toLong()
+ val sane = nodeArea in 1 until (screenArea * 8 / 10)
+ if ((coversNode || coversRegion) && sane) {
+ acc.union(bounds)
+ }
+ }
+ }
+ for (i in 0 until node.childCount) {
+ accumulateSnap(node.getChild(i), region, regionArea, coverage, acc)
+ }
+ }
+
/** Tap the first clickable node whose text/description contains [query] (case-insensitive). */
fun tapByText(query: String): Boolean {
val root = rootInActiveWindow ?: return false
diff --git a/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt b/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt
index 2dc09ff..f336d3b 100644
--- a/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt
+++ b/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt
@@ -125,13 +125,6 @@ class ScreenCompanionController(
val fetch = SmartActionDetector.fetchAction(url)
onSmartActionReady(fetch.label, fetch.prompt)
}
- } else if (screenText.contains("Exception") || screenText.contains("Error", ignoreCase = true)) {
- withContext(Dispatchers.Main) {
- onSmartActionReady(
- "⚠️ Error detected. Explain?",
- "Explain the error code or stack trace shown on the screen."
- )
- }
} else {
// Structured-data (address / phone / currency / calendar) scan.
val smart = SmartActionDetector.detect(screenText, allowChat = false)
diff --git a/app/src/main/java/com/gotcha/service/ScreenLensController.kt b/app/src/main/java/com/gotcha/service/ScreenLensController.kt
index 1a1fbdf..12bec8a 100644
--- a/app/src/main/java/com/gotcha/service/ScreenLensController.kt
+++ b/app/src/main/java/com/gotcha/service/ScreenLensController.kt
@@ -1,5 +1,6 @@
package com.gotcha.service
+import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
@@ -41,6 +42,7 @@ import java.io.FileOutputStream
*
* All window mutations are posted to the main thread.
*/
+@Suppress("TooManyFunctions")
class ScreenLensController(
private val context: Context,
private val scope: CoroutineScope,
@@ -53,6 +55,7 @@ class ScreenLensController(
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
@@ -104,46 +107,85 @@ class ScreenLensController(
}
private fun onRegionSelected(rectInView: Rect) {
- val overlay = cropOverlay
+ val overlay = cropOverlay as? ScreenCropOverlayView
val viewW = overlay?.width ?: 0
val viewH = overlay?.height ?: 0
- // Hide the scrim overlay before capturing so it isn't baked into the shot.
- removeCropOverlay()
+
+ // 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)
+
scope.launch {
val service = GotchaAccessibilityService.instance
if (service == null) {
withContext(Dispatchers.Main) { onError("Accessibility service not available") }
return@launch
}
- // Detect structured data inside the selection via accessibility text
- // (full-screen overlay ⇒ view coords are screen coords).
- val regionText = service.dumpTextInRegion(rectInView)
+ // 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()
- // Small delay so the removed overlay is gone from the real display.
- kotlinx.coroutines.delay(120)
+ // 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()
if (full == null) {
- kotlinx.coroutines.delay(500)
+ kotlinx.coroutines.delay(400)
full = service.takeScreenshotBitmap()
}
+ withContext(Dispatchers.Main) { overlay?.setCaptureMode(false) }
if (full == null) {
- withContext(Dispatchers.Main) { onError("Screenshot failed — try again") }
+ withContext(Dispatchers.Main) {
+ removeCropOverlay()
+ onError("Screenshot failed — try again")
+ }
return@launch
}
- val cropped = cropToSelection(full, rectInView, viewW, viewH)
+ val cropped = cropToSelection(full, finalRect, viewW, viewH)
full.recycle()
if (cropped == null) {
- withContext(Dispatchers.Main) { onError("Selection was empty") }
+ withContext(Dispatchers.Main) {
+ removeCropOverlay()
+ onError("Selection was empty")
+ }
return@launch
}
withContext(Dispatchers.Main) {
pendingCrop = cropped
- showActionMenu(contextualActions)
+ showActionMenu(contextualActions, regionText)
}
}
}
+ /** 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) {
+ val cx = out.centerX()
+ out.left = cx - minPx / 2
+ out.right = cx + minPx / 2
+ }
+ if (out.height() < minPx) {
+ val cy = out.centerY()
+ out.top = cy - minPx / 2
+ out.bottom = cy + minPx / 2
+ }
+ if (viewW > 0 && viewH > 0) 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.
@@ -165,7 +207,7 @@ class ScreenLensController(
}
}
- private fun showActionMenu(contextualActions: List<SmartAction>) {
+ private fun showActionMenu(contextualActions: List<SmartAction>, regionText: String?) {
removeActionMenu()
val container = LinearLayout(appContext).apply {
orientation = LinearLayout.VERTICAL
@@ -173,10 +215,11 @@ class ScreenLensController(
background = GradientDrawable().apply {
cornerRadius = dp(20).toFloat()
setColor(Color.parseColor("#F21E1E1E"))
- setStroke(dp(1), Color.parseColor("#66E081C0"))
+ setStroke(dp(1), Color.parseColor("#66568CD8"))
}
}
- container.addView(menuTitle("Lens selection"))
+ // 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 ->
@@ -188,6 +231,17 @@ class ScreenLensController(
)
}
+ // "Copy text" when the selection contains readable text.
+ val selectedText = regionText?.trim()
+ if (!selectedText.isNullOrBlank()) {
+ container.addView(
+ menuButton("📝 Copy text") {
+ copyTextToClipboard(selectedText)
+ finishMenu(recycle = true)
+ }
+ )
+ }
+
container.addView(
menuButton("🔍 Ask about this") {
val base64 = pendingCrop?.let { encodeJpeg(it) }
@@ -211,6 +265,7 @@ class ScreenLensController(
// Hand ownership to the async saver, which recycles when done.
pendingCrop = null
removeActionMenu()
+ removeCropOverlay()
if (bmp != null) saveToDownloads(bmp) else onError("Nothing to save")
}
)
@@ -227,8 +282,13 @@ class ScreenLensController(
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT
).apply {
- gravity = Gravity.CENTER
+ 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
@@ -237,12 +297,70 @@ class ScreenLensController(
}
}
- /** Dismiss the menu and optionally recycle the crop the menu was acting on. */
+ /** 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()
+ 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}")
+ }
+ }
+
private fun copyImageToClipboard(bitmap: Bitmap) {
try {
val uri = writeToCache(bitmap) ?: run {
@@ -354,13 +472,6 @@ class ScreenLensController(
android.widget.Toast.makeText(appContext, msg, android.widget.Toast.LENGTH_SHORT).show()
}
- private fun menuTitle(text: String): TextView = TextView(appContext).apply {
- this.text = text
- setTextColor(Color.parseColor("#E081C0"))
- textSize = 13f
- setPadding(dp(12), dp(6), dp(12), dp(10))
- }
-
private fun menuButton(label: String, highlight: Boolean = false, onClick: () -> Unit): TextView =
TextView(appContext).apply {
text = label
@@ -406,4 +517,9 @@ class ScreenLensController(
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
+ }
}
diff --git a/app/src/main/java/com/gotcha/service/SmartActionDetector.kt b/app/src/main/java/com/gotcha/service/SmartActionDetector.kt
index 39102f9..afea129 100644
--- a/app/src/main/java/com/gotcha/service/SmartActionDetector.kt
+++ b/app/src/main/java/com/gotcha/service/SmartActionDetector.kt
@@ -46,8 +46,19 @@ object SmartActionDetector {
/** Separator between the encoded action type and its payload. */
const val PAYLOAD_SEP = "|"
+ /**
+ * Street addresses: a house number, a street name, and a street-type suffix
+ * (optionally followed by a unit and/or a ", City, ST 12345" tail). The suffix
+ * list is broadened and an optional trailing punctuation-mark allowance makes
+ * everyday addresses match more reliably.
+ */
private val addressPattern: Pattern = Pattern.compile(
- "\\d+\\s+[a-zA-Z0-9\\s,]+ (Street|St|Avenue|Ave|Road|Rd|Drive|Dr|Lane|Ln|Boulevard|Blvd|Way)\\b",
+ "\\b\\d{1,6}\\s+[A-Za-z0-9.'\\-]+(?:\\s+[A-Za-z0-9.'\\-]+){0,5}\\s+" +
+ "(Street|St|Avenue|Ave|Road|Rd|Drive|Dr|Lane|Ln|Boulevard|Blvd|Way|" +
+ "Court|Ct|Place|Pl|Terrace|Ter|Circle|Cir|Highway|Hwy|Parkway|Pkwy|" +
+ "Square|Sq|Trail|Trl|Close|Crescent|Cres)\\b\\.?" +
+ "(?:\\s*(?:#|Apt\\.?|Suite|Ste\\.?|Unit)\\s*\\w+)?" +
+ "(?:,\\s*[A-Za-z .'\\-]+(?:,\\s*[A-Z]{2})?(?:\\s*\\d{5}(?:-\\d{4})?)?)?",
Pattern.CASE_INSENSITIVE
)
@@ -72,11 +83,23 @@ object SmartActionDetector {
"([¥€£$])\\s?\\d{1,5}(\\.\\d{2})?"
)
+ /**
+ * Calendar events. Matches any of:
+ * - a keyword ("meeting"/"call"/…) near a weekday,
+ * - a weekday/relative-day followed by a clock time,
+ * - a month name + day (+ optional year) optionally with a clock time —
+ * e.g. "July 20 at 9:10 a.m.", "Dec 3", "Jan 5 2027 3pm",
+ * - a bare clock time with an am/pm marker (with or without dots).
+ */
private val calendarPattern: Pattern = Pattern.compile(
- "\\b(meeting|appointment|event|call|lunch|dinner)\\b.{0,40}?" +
+ "\\b(meeting|appointment|event|call|lunch|dinner|reminder|deadline)\\b.{0,40}?" +
"\\b(today|tomorrow|mon(day)?|tue(sday)?|wed(nesday)?|thu(rsday)?|fri(day)?|sat(urday)?|sun(day)?)\\b" +
"|\\b(today|tomorrow|mon(day)?|tue(sday)?|wed(nesday)?|thu(rsday)?|fri(day)?|sat(urday)?|sun(day)?)\\b" +
- "\\s+at\\s+\\d{1,2}(:\\d{2})?\\s?(am|pm)",
+ "\\s+(at\\s+)?\\d{1,2}(:\\d{2})?\\s?([ap])\\.?\\s?m\\.?" +
+ "|\\b(jan(uary)?|feb(ruary)?|mar(ch)?|apr(il)?|may|jun(e)?|jul(y)?|aug(ust)?|" +
+ "sep(t)?(ember)?|oct(ober)?|nov(ember)?|dec(ember)?)\\s+\\d{1,2}(st|nd|rd|th)?" +
+ "(,?\\s+\\d{4})?(\\s+(at\\s+)?\\d{1,2}(:\\d{2})?\\s?([ap])\\.?\\s?m\\.?)?" +
+ "|\\b\\d{1,2}(:\\d{2})?\\s?([ap])\\.?\\s?m\\.?",
Pattern.CASE_INSENSITIVE
)
@@ -102,7 +125,7 @@ object SmartActionDetector {
if (allowChat && looksLikeChatMessage(text)) {
return SmartAction(
- label = "💬 Message copied. Draft reply?",
+ label = "💬 Draft reply: ${snippet(text.trim(), 24)}",
prompt = "Draft a short, friendly reply to this message. Return only the " +
"reply text:\n\n$text"
)
@@ -131,7 +154,7 @@ object SmartActionDetector {
if (!m.find()) return null
val number = m.group().trim()
return SmartAction(
- label = "📞 Dial $number?",
+ label = "📞 Dial ${snippet(number, 20)}",
prompt = encode(TYPE_DIAL, number)
)
}
@@ -139,9 +162,9 @@ object SmartActionDetector {
private fun detectAddress(text: String): SmartAction? {
val m = addressPattern.matcher(text)
if (!m.find()) return null
- val address = m.group().trim()
+ val address = m.group().trim().trimEnd(',')
return SmartAction(
- label = "📍 Navigate to address?",
+ label = "📍 Navigate: ${snippet(address, 28)}",
prompt = encode(TYPE_NAVIGATE, address)
)
}
@@ -151,7 +174,7 @@ object SmartActionDetector {
if (!m.find()) return null
val price = m.group().trim()
return SmartAction(
- label = "💵 Convert $price?",
+ label = "💵 Convert ${snippet(price, 16)}",
prompt = "Convert the price \"$price\" to USD and to common major " +
"currencies (EUR, GBP, INR). Show the approximate exchange rate " +
"you used. Keep it brief."
@@ -163,7 +186,7 @@ object SmartActionDetector {
if (!m.find()) return null
val event = m.group().trim()
return SmartAction(
- label = "📅 Add \"$event\" to calendar?",
+ label = "📅 Add to calendar: ${snippet(event, 26)}",
prompt = encode(TYPE_CALENDAR, event)
)
}
@@ -188,7 +211,23 @@ object SmartActionDetector {
/** Build a native "fetch this URL and summarize" action. */
fun fetchAction(url: String): SmartAction =
- SmartAction(label = "🔗 Summarize link?", prompt = encode(TYPE_FETCH, url.trim()))
+ SmartAction(label = "🔗 Summarize: ${snippet(prettyUrl(url), 30)}", prompt = encode(TYPE_FETCH, url.trim()))
+
+ /** Strip scheme/`www.` for a friendlier label (keeps the full URL in the payload). */
+ private fun prettyUrl(url: String): String =
+ url.trim()
+ .replace(Regex("^https?://", RegexOption.IGNORE_CASE), "")
+ .removePrefix("www.")
+
+ /**
+ * A short preview of detected data for action labels: up to [max] chars, then
+ * an ellipsis, so the user can see WHAT was detected before acting. Collapses
+ * internal whitespace/newlines to single spaces.
+ */
+ fun snippet(value: String, max: Int = 24): String {
+ val clean = value.replace(Regex("\\s+"), " ").trim()
+ return if (clean.length <= max) clean else clean.take(max).trimEnd() + "…"
+ }
/**
* Extract the first http(s) URL from [text], normalising a bare `www.`/domain
diff --git a/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt b/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt
index 63de815..c17d8ec 100644
--- a/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt
+++ b/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt
@@ -51,6 +51,15 @@ 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 val dimPaint = Paint().apply { color = Color.parseColor("#66101018") }
private val edgeGlowPaint = Paint(Paint.ANTI_ALIAS_FLAG)
@@ -60,11 +69,32 @@ class ScreenCropOverlayView(
strokeCap = Paint.Cap.ROUND
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
+ color = Color.parseColor("#B0568CD8")
+ }
+ private val screenBorderGlowPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ strokeWidth = 8f * density
+ color = Color.parseColor("#55A0459E")
+ 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 = 1.5f * density
- color = Color.parseColor("#CCE081C0")
- pathEffect = android.graphics.DashPathEffect(floatArrayOf(12f * density, 8f * density), 0f)
+ strokeWidth = 3f * density
+ color = Color.parseColor("#D0B06FD0")
+ pathEffect = android.graphics.DashPathEffect(floatArrayOf(14f * density, 8f * density), 0f)
+ }
+ private val boxGlowPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ strokeWidth = 7f * density
+ color = Color.parseColor("#55568CD8")
+ maskFilter = android.graphics.BlurMaskFilter(12f * density, android.graphics.BlurMaskFilter.Blur.NORMAL)
}
private val particlePaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val hintPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
@@ -146,22 +176,33 @@ 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
+ }
canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), dimPaint)
canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), edgeGlowPaint)
stepAndDrawParticles(canvas)
- if (drawing && moved) {
- // Gradient stroke for the traced path.
- pathPaint.shader = LinearGradient(
- minX, minY, maxX, maxY,
- Color.parseColor("#FF6FC0"), Color.parseColor("#5B8CFF"),
- Shader.TileMode.CLAMP
- )
- canvas.drawPath(path, pathPaint)
- canvas.drawRect(RectF(minX, minY, maxX, maxY), boxPaint)
- } else if (!drawing) {
- canvas.drawText(
+ drawScreenBorder(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"),
+ Shader.TileMode.CLAMP
+ )
+ canvas.drawPath(path, pathPaint)
+ 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,
@@ -171,6 +212,34 @@ class ScreenCropOverlayView(
postInvalidateOnAnimation()
}
+ /** A thin, premium pinkish-blue glowing frame just inside the screen edges. */
+ private fun drawScreenBorder(canvas: Canvas) {
+ val inset = screenBorderGlowPaint.strokeWidth / 2f + 1f
+ val r = RectF(inset, inset, width - inset, height - inset)
+ val radius = 24f * density
+ canvas.drawRoundRect(r, radius, radius, screenBorderGlowPaint)
+ canvas.drawRoundRect(r, radius, radius, screenBorderPaint)
+ }
+
+ private fun drawSelectionBox(canvas: Canvas, rect: RectF) {
+ val radius = 10f * density
+ canvas.drawRoundRect(rect, radius, radius, boxGlowPaint)
+ 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()
+ }
+
private fun stepAndDrawParticles(canvas: Canvas) {
val now = System.nanoTime()
val dt = if (lastFrameNs == 0L) 0.016f else ((now - lastFrameNs) / 1_000_000_000f).coerceIn(0f, 0.05f)
@@ -206,6 +275,8 @@ class ScreenCropOverlayView(
}
override fun onTouchEvent(event: MotionEvent): Boolean {
+ // Once a selection is frozen (menu shown) or during capture, ignore touches.
+ if (frozenRect != null || captureMode) return false
when (event.action) {
MotionEvent.ACTION_DOWN -> {
drawing = true
@@ -228,7 +299,9 @@ class ScreenCropOverlayView(
MotionEvent.ACTION_UP -> {
drawing = false
val rect = Rect(minX.toInt(), minY.toInt(), maxX.toInt(), maxY.toInt())
- if (moved && rect.width() > MIN_SIZE_PX && rect.height() > MIN_SIZE_PX) {
+ // 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 {
onCancel()
diff --git a/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt b/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt
index 6c39be6..e6f1699 100644
--- a/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt
+++ b/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt
@@ -72,7 +72,7 @@ class SmartActionDetectorTest {
assertNull(SmartActionDetector.detect(text, allowChat = false))
val action = SmartActionDetector.detect(text, allowChat = true)
assertNotNull(action)
- assertTrue(action!!.label.contains("Message"))
+ assertTrue(action!!.label.contains("Draft reply"))
}
@Test
@@ -104,11 +104,48 @@ class SmartActionDetectorTest {
assertEquals(SmartActionDetector.TYPE_CALENDAR, SmartActionDetector.decode(cal!!.prompt)!!.first)
}
+ @Test
+ fun `contextual detection finds month-day time event`() {
+ // Regression: "July 20 at 9:10 a.m." was previously missed.
+ val actions = SmartActionDetector.detectContextual("Flight on July 20 at 9:10 a.m.")
+ val cal = actions.firstOrNull { it.label.contains("calendar") }
+ assertNotNull(cal)
+ assertEquals(SmartActionDetector.TYPE_CALENDAR, SmartActionDetector.decode(cal!!.prompt)!!.first)
+ }
+
+ @Test
+ fun `contextual detection finds address with city and zip`() {
+ val actions = SmartActionDetector.detectContextual("Ship to 350 5th Ave, New York, NY 10118")
+ val addr = actions.firstOrNull { it.label.contains("Navigate") }
+ assertNotNull(addr)
+ assertEquals(SmartActionDetector.TYPE_NAVIGATE, SmartActionDetector.decode(addr!!.prompt)!!.first)
+ }
+
@Test
fun `contextual detection returns empty for plain prose`() {
assertTrue(SmartActionDetector.detectContextual("just some words here").isEmpty())
}
+ // ---- Snippets in labels ----
+
+ @Test
+ fun `snippet truncates long values with an ellipsis`() {
+ assertEquals("hello", SmartActionDetector.snippet("hello", 10))
+ assertEquals("hello…", SmartActionDetector.snippet("hello world", 5))
+ assertEquals("a b c", SmartActionDetector.snippet("a b\nc", 10))
+ }
+
+ @Test
+ fun `fetch action label shows a url snippet`() {
+ val action = SmartActionDetector.fetchAction("https://www.example.com/very/long/path/here")
+ assertTrue(action.label.contains("example.com"))
+ // The full URL is preserved in the payload.
+ assertEquals(
+ "https://www.example.com/very/long/path/here",
+ SmartActionDetector.decode(action.prompt)!!.second
+ )
+ }
+
@Test
fun `decode returns null for non-native prompts`() {
assertNull(SmartActionDetector.decode("Just a normal prompt"))