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: implement SmartActionDetector for semantic text handling and add ScreenLensController for region-based image interaction

Rishabh Bajpai985877aa3b29
diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
index 831f007..f99d6b6 100644
--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
@@ -39,6 +39,7 @@ import java.io.File
*
* Started/stopped from the in-app toggle via [ACTION_START] / [ACTION_STOP].
*/
+@Suppress("TooManyFunctions")
class AssistiveBallService : Service() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
@@ -52,6 +53,7 @@ class AssistiveBallService : Service() {
private lateinit var callController: CallSessionController
private lateinit var screenCompanionController: ScreenCompanionController
private lateinit var screenCompanionPanel: com.gotcha.ui.ScreenCompanionPanelOverlay
+ private lateinit var screenLensController: ScreenLensController
private val llmClient by lazy {
val s = settingsRepository.load()
com.gotcha.llm.LLMClient(
@@ -86,43 +88,11 @@ class AssistiveBallService : Service() {
setupScreenCompanionPanel()
+ // Lens mode: interactive crop selection + capture.
+ setupScreenLensController()
+
// Screen Companion Controller
- screenCompanionController = ScreenCompanionController(
- context = this,
- scope = scope,
- onSmartActionReady = { label, prompt ->
- overlay.setSmartActionAvailable(label, prompt)
- },
- onReadClipboardRequest = {
- android.util.Log.d("AssistiveBallService", "onReadClipboardRequest called")
- overlay.readClipboardWithFocus { clip ->
- android.util.Log.d(
- "AssistiveBallService",
- "readClipboardWithFocus: null=${clip == null}, count=${clip?.itemCount ?: 0}"
- )
- com.gotcha.service.GotchaAccessibilityService.lastClipboardData = clip
- val clipText = clip?.getItemAt(0)?.text?.toString()
- android.util.Log.d("AssistiveBallService", "clipText = $clipText")
- if (!clipText.isNullOrBlank()) {
- if (android.util.Patterns.WEB_URL.matcher(clipText).find()) {
- android.util.Log.d("AssistiveBallService", "Setting smart action: Link copied. Summarize?")
- overlay.setSmartActionAvailable(
- "🔗 Link copied. Summarize?",
- "Summarize the content of the copied URL: $clipText"
- )
- } else {
- android.util.Log.d("AssistiveBallService", "Setting smart action: Text copied. Translate?")
- overlay.setSmartActionAvailable(
- "📋 Text copied. Translate?",
- "Translate the copied text to English if it is not, otherwise summarize it:\n\n$clipText"
- )
- }
- } else {
- android.util.Log.d("AssistiveBallService", "clipText is null or blank, not setting smart action")
- }
- }
- }
- )
+ setupScreenCompanionController()
screenCompanionController.start()
// Assistive ball (shown when idle, hidden during a call)
@@ -138,6 +108,7 @@ class AssistiveBallService : Service() {
startActivity(intent)
}
onTakeScreenshot = { takeScreenshot() }
+ onStartLens = { screenLensController.start() }
onStartCall = { callController.startCall() }
onEndCall = { callController.endCall() }
onToggleChatWindow = { } // no-op during calls (ball is hidden)
@@ -179,6 +150,12 @@ class AssistiveBallService : Service() {
}
private fun handleSmartActionSelected(prompt: String, history: MutableList<com.gotcha.llm.ChatMessage>) {
+ // Native structured actions (dial / navigate / schedule) fire an Android
+ // intent instead of querying the LLM.
+ if (SmartActionDetector.isNativeAction(prompt)) {
+ handleNativeAction(prompt)
+ return
+ }
val attachScreenshot = prompt.contains("screenshot", ignoreCase = true) ||
prompt.contains("screen", ignoreCase = true) ||
prompt.contains("webpage", ignoreCase = true)
@@ -242,12 +219,147 @@ class AssistiveBallService : Service() {
}
}
+ private fun setupScreenLensController() {
+ screenLensController = ScreenLensController(
+ context = this,
+ scope = scope,
+ onAskAboutCrop = { prompt, base64 ->
+ handleCropQuery(prompt, base64)
+ },
+ onError = { overlay.showError(it) }
+ )
+ }
+
+ private fun setupScreenCompanionController() {
+ screenCompanionController = ScreenCompanionController(
+ context = this,
+ scope = scope,
+ onSmartActionReady = { label, prompt ->
+ overlay.setSmartActionAvailable(label, prompt)
+ },
+ onSmartActionPairReady = { label, prompt, altLabel, altPrompt ->
+ overlay.setSmartActionAvailable(label, prompt, altLabel, altPrompt)
+ },
+ onReadClipboardRequest = { handleClipboardRead() }
+ )
+ }
+
+ /** Read the clipboard (via a focus-stealing activity) and offer a smart action. */
+ private fun handleClipboardRead() {
+ android.util.Log.d("AssistiveBallService", "onReadClipboardRequest called")
+ overlay.readClipboardWithFocus { clip ->
+ android.util.Log.d(
+ "AssistiveBallService",
+ "readClipboardWithFocus: null=${clip == null}, count=${clip?.itemCount ?: 0}"
+ )
+ com.gotcha.service.GotchaAccessibilityService.lastClipboardData = clip
+ val clipText = clip?.getItemAt(0)?.text?.toString()
+ android.util.Log.d("AssistiveBallService", "clipText = $clipText")
+ if (clipText.isNullOrBlank()) {
+ android.util.Log.d("AssistiveBallService", "clipText is null or blank, not setting smart action")
+ return@readClipboardWithFocus
+ }
+ if (android.util.Patterns.WEB_URL.matcher(clipText).find()) {
+ android.util.Log.d("AssistiveBallService", "Setting smart action: Link copied. Summarize?")
+ overlay.setSmartActionAvailable(
+ "🔗 Link copied. Summarize?",
+ "Summarize the content of the copied URL: $clipText"
+ )
+ return@readClipboardWithFocus
+ }
+ // Prefer a structured action (dial / navigate / convert / schedule / reply)
+ // when the copied text carries recognisable data; otherwise fall back to
+ // the generic translate/summarize offer.
+ val smart = SmartActionDetector.detect(clipText, allowChat = true)
+ if (smart != null) {
+ android.util.Log.d("AssistiveBallService", "Setting smart action: ${smart.label}")
+ overlay.setSmartActionAvailable(smart.label, smart.prompt)
+ } else {
+ android.util.Log.d("AssistiveBallService", "Setting smart action: Text copied. Translate?")
+ overlay.setSmartActionAvailable(
+ "📋 Text copied. Translate?",
+ "Translate the copied text to English if it is not, otherwise summarize it:\n\n$clipText"
+ )
+ }
+ }
+ }
+
+ /**
+ * Resolve a native structured action (encoded by [SmartActionDetector]) into
+ * an Android system intent — navigate on a map, open the dialer, or create a
+ * calendar event. Failures are surfaced on the ball's error card.
+ */
+ private fun handleNativeAction(prompt: String) {
+ val decoded = SmartActionDetector.decode(prompt) ?: return
+ val (type, payload) = decoded
+ try {
+ val intent = when (type) {
+ SmartActionDetector.TYPE_NAVIGATE ->
+ Intent(Intent.ACTION_VIEW, android.net.Uri.parse("geo:0,0?q=" + android.net.Uri.encode(payload)))
+ SmartActionDetector.TYPE_DIAL ->
+ Intent(Intent.ACTION_DIAL, android.net.Uri.parse("tel:" + android.net.Uri.encode(payload)))
+ SmartActionDetector.TYPE_CALENDAR ->
+ Intent(Intent.ACTION_INSERT).apply {
+ data = android.provider.CalendarContract.Events.CONTENT_URI
+ putExtra(android.provider.CalendarContract.Events.TITLE, payload)
+ }
+ else -> null
+ } ?: return
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ startActivity(intent)
+ } catch (e: Exception) {
+ overlay.showError("Couldn't open action: ${e.message}")
+ }
+ }
+
+ /**
+ * Send a Lens-cropped image (base64 JPEG) to the LLM with [prompt] and stream
+ * the answer into the Screen Companion panel.
+ */
+ private fun handleCropQuery(prompt: String, base64Jpeg: String) {
+ val history = activeCompanionHistory
+ screenCompanionPanel.show(prompt)
+ overlay.isPanelOpen = true
+ scope.launch {
+ try {
+ history.clear()
+ history.add(
+ com.gotcha.llm.ChatMessage(
+ "system",
+ kotlinx.serialization.json.JsonPrimitive(
+ "You are Screen Companion. Provide a short, precise answer."
+ )
+ )
+ )
+ history.add(com.gotcha.llm.visionUserMessage(prompt, base64Jpeg, "jpeg"))
+ val response = llmClient.chat(history.toList())
+ val replyText = response.choices.firstOrNull()?.message?.textContent ?: "No response"
+ history.add(
+ com.gotcha.llm.ChatMessage(
+ "assistant",
+ kotlinx.serialization.json.JsonPrimitive(replyText)
+ )
+ )
+ screenCompanionPanel.updateResponse(replyText)
+ } catch (e: Exception) {
+ screenCompanionPanel.updateResponse("Error: ${e.message}")
+ }
+ }
+ }
+
private fun setupScreenCompanionPanel() {
screenCompanionPanel = com.gotcha.ui.ScreenCompanionPanelOverlay(this).apply {
onDismiss = {
overlay.isPanelOpen = false
activeCompanionHistory.clear()
+ // Stop any in-flight voice I/O so nothing keeps the mic/TTS alive.
+ stopPanelVoiceInput()
+ ttsEngine.stop()
}
+ onStartVoiceInput = { startPanelVoiceInput() }
+ onStopVoiceInput = { stopPanelVoiceInput() }
+ onReadAloud = { text -> readPanelResponseAloud(text) }
+ onStopReadAloud = { ttsEngine.stop() }
onSendInput = { input ->
activeCompanionHistory.add(com.gotcha.llm.ChatMessage("user", kotlinx.serialization.json.JsonPrimitive(input)))
val currentHistory = activeCompanionHistory.toList()
@@ -271,6 +383,89 @@ class AssistiveBallService : Service() {
}
}
+ // ---- Screen Companion panel voice I/O (STT / TTS) ----
+
+ /** Start voice typing in the panel using the configured STT provider. */
+ private fun startPanelVoiceInput() {
+ val s = settingsRepository.load()
+ when (s.sttProvider) {
+ com.gotcha.audio.AudioProvider.ANDROID -> {
+ if (!hasMicPermission()) {
+ overlay.showError("Microphone permission not granted.")
+ screenCompanionPanel.setListening(false)
+ return
+ }
+ if (!sttEngine.startAndroidListening()) {
+ overlay.showError("Failed to start speech recognition.")
+ screenCompanionPanel.setListening(false)
+ }
+ }
+ com.gotcha.audio.AudioProvider.API -> {
+ if (s.sttApiBaseUrl.isBlank() || s.sttApiModel.isBlank()) {
+ overlay.showError("Configure an STT API URL and model in settings.")
+ screenCompanionPanel.setListening(false)
+ return
+ }
+ if (!hasMicPermission()) {
+ overlay.showError("Microphone permission not granted.")
+ screenCompanionPanel.setListening(false)
+ return
+ }
+ if (!sttEngine.startRecording()) {
+ overlay.showError("Failed to start recording.")
+ screenCompanionPanel.setListening(false)
+ }
+ }
+ com.gotcha.audio.AudioProvider.NONE -> {
+ overlay.showError("No STT provider configured. Enable one in settings.")
+ screenCompanionPanel.setListening(false)
+ }
+ }
+ }
+
+ /** Stop voice typing, transcribe, and append the result to the panel input. */
+ private fun stopPanelVoiceInput() {
+ val s = settingsRepository.load()
+ val provider = s.sttProvider
+ if (provider == com.gotcha.audio.AudioProvider.NONE) {
+ screenCompanionPanel.setListening(false)
+ return
+ }
+ scope.launch {
+ val result = sttEngine.stopListeningAndTranscribe(provider, s.sttApiModel)
+ screenCompanionPanel.setListening(false)
+ result
+ .onSuccess { text -> if (text.isNotBlank()) screenCompanionPanel.appendVoiceInput(text) }
+ .onFailure { e -> overlay.showError("Transcription failed: ${e.message}") }
+ }
+ }
+
+ /** Read the panel's current response aloud using the configured TTS provider. */
+ private fun readPanelResponseAloud(text: String) {
+ val s = settingsRepository.load()
+ if (s.ttsProvider == com.gotcha.audio.AudioProvider.NONE) {
+ overlay.showError("No TTS provider configured. Enable one in settings.")
+ screenCompanionPanel.setSpeaking(false)
+ return
+ }
+ scope.launch {
+ ttsEngine.speak(
+ text = text,
+ provider = s.ttsProvider,
+ apiModel = s.ttsApiModel,
+ voice = ""
+ )
+ // Playback completed (or was stopped) — reset the speaker icon.
+ screenCompanionPanel.setSpeaking(false)
+ }
+ }
+
+ private fun hasMicPermission(): Boolean =
+ androidx.core.content.ContextCompat.checkSelfPermission(
+ this,
+ android.Manifest.permission.RECORD_AUDIO
+ ) == android.content.pm.PackageManager.PERMISSION_GRANTED
+
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
ACTION_STOP -> {
@@ -295,6 +490,7 @@ class AssistiveBallService : Service() {
screenCompanionPanel.dismiss()
overlay.dismiss()
screenCompanionController.stop()
+ screenLensController.cancel()
ttsEngine.shutdown()
scope.cancel()
super.onDestroy()
diff --git a/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt b/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt
index cafbbef..7808f56 100644
--- a/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt
+++ b/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt
@@ -20,7 +20,17 @@ class ScreenCompanionController(
private val context: Context,
private val scope: CoroutineScope,
private val onSmartActionReady: (label: String, prompt: String) -> Unit,
- private val onReadClipboardRequest: () -> 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,
+ altLabel: String,
+ altPrompt: String
+ ) -> Unit = { l, p, _, _ -> onSmartActionReady(l, p) }
) {
private val mainHandler = Handler(Looper.getMainLooper())
@@ -73,9 +83,11 @@ class ScreenCompanionController(
withContext(Dispatchers.Default) {
if (triggerType == "Screenshot") {
withContext(Dispatchers.Main) {
- onSmartActionReady(
+ onSmartActionPairReady(
"📸 Screenshot taken. Extract text?",
- "Extract the text from this screenshot."
+ "Extract the text from this screenshot.",
+ "🌐 Translate Screenshot",
+ TRANSLATE_SCREENSHOT_PROMPT
)
}
return@withContext
@@ -123,6 +135,14 @@ class ScreenCompanionController(
"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)
+ if (smart != null) {
+ withContext(Dispatchers.Main) {
+ onSmartActionReady(smart.label, smart.prompt)
+ }
+ }
}
}
}
@@ -132,5 +152,15 @@ class ScreenCompanionController(
companion object {
const val ACTION_APP_CHANGED = "com.gotcha.action.APP_CHANGED"
const val ACTION_CLIPBOARD_CHANGED = "com.gotcha.action.CLIPBOARD_CHANGED"
+
+ /**
+ * 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 " +
+ "and its translation side-by-side using a markdown table."
}
}
diff --git a/app/src/main/java/com/gotcha/service/ScreenLensController.kt b/app/src/main/java/com/gotcha/service/ScreenLensController.kt
new file mode 100644
index 0000000..f05d149
--- /dev/null
+++ b/app/src/main/java/com/gotcha/service/ScreenLensController.kt
@@ -0,0 +1,363 @@
+package com.gotcha.service
+
+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 drags a bounding box over the screen, and the
+ * selected region is cropped from a fresh accessibility screenshot. The crop can
+ * then be sent to the LLM (explain / translate), copied to the clipboard, or
+ * saved to the public Downloads folder.
+ *
+ * All window mutations are posted to the main thread. The controller owns exactly
+ * one crop overlay and one action menu at a time.
+ */
+class ScreenLensController(
+ private val context: Context,
+ private val scope: CoroutineScope,
+ /** Show the companion panel with a prompt and stream the LLM reply into it. */
+ private val onAskAboutCrop: (prompt: String, base64Jpeg: String) -> 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 var cropOverlay: View? = null
+ private var actionMenu: View? = null
+
+ /** Begin a Lens capture: add the full-screen crop overlay. */
+ fun start() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ onError("Lens mode requires Android 11+")
+ return
+ }
+ mainHandler.post {
+ removeActionMenu()
+ removeCropOverlay()
+ val overlay = ScreenCropOverlayView(
+ appContext,
+ onSelection = { rect -> onRegionSelected(rect) },
+ onCancel = { cancel() }
+ )
+ val params = WindowManager.LayoutParams(
+ WindowManager.LayoutParams.MATCH_PARENT,
+ WindowManager.LayoutParams.MATCH_PARENT,
+ overlayType(),
+ WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
+ WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
+ PixelFormat.TRANSLUCENT
+ ).apply {
+ gravity = Gravity.TOP or Gravity.START
+ }
+ try {
+ windowManager.addView(overlay, params)
+ cropOverlay = overlay
+ } catch (_: Exception) {
+ cropOverlay = null
+ onError("Couldn't start Lens mode")
+ }
+ }
+ }
+
+ fun cancel() {
+ mainHandler.post {
+ removeCropOverlay()
+ removeActionMenu()
+ }
+ }
+
+ private fun onRegionSelected(rectInView: Rect) {
+ val overlay = cropOverlay
+ 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()
+ scope.launch {
+ val service = GotchaAccessibilityService.instance
+ if (service == null) {
+ withContext(Dispatchers.Main) { onError("Accessibility service not available") }
+ return@launch
+ }
+ // Small delay so the removed overlay is gone from the real display.
+ kotlinx.coroutines.delay(120)
+ var full = service.takeScreenshotBitmap()
+ if (full == null) {
+ kotlinx.coroutines.delay(500)
+ full = service.takeScreenshotBitmap()
+ }
+ if (full == null) {
+ withContext(Dispatchers.Main) { onError("Screenshot failed — try again") }
+ return@launch
+ }
+ val cropped = cropToSelection(full, rectInView, viewW, viewH)
+ full.recycle()
+ if (cropped == null) {
+ withContext(Dispatchers.Main) { onError("Selection was empty") }
+ return@launch
+ }
+ withContext(Dispatchers.Main) { showActionMenu(cropped) }
+ }
+ }
+
+ /**
+ * 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 showActionMenu(cropped: Bitmap) {
+ 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("#66FFFFFF"))
+ }
+ }
+ container.addView(menuTitle("Lens selection"))
+ container.addView(
+ menuButton("🔍 Ask / Explain") {
+ removeActionMenu()
+ val base64 = encodeJpeg(cropped)
+ cropped.recycle()
+ if (base64 != null) {
+ onAskAboutCrop(
+ "Explain what is shown in this cropped screen region. If it " +
+ "contains text in another language, translate it to English.",
+ base64
+ )
+ } else {
+ onError("Couldn't encode selection")
+ }
+ }
+ )
+ container.addView(
+ menuButton("📋 Copy Image") {
+ removeActionMenu()
+ copyImageToClipboard(cropped)
+ cropped.recycle()
+ }
+ )
+ container.addView(
+ menuButton("💾 Save to Downloads") {
+ removeActionMenu()
+ saveToDownloads(cropped)
+ cropped.recycle()
+ }
+ )
+ container.addView(
+ menuButton("✕ Cancel") {
+ removeActionMenu()
+ cropped.recycle()
+ }
+ )
+
+ val params = WindowManager.LayoutParams(
+ dp(260),
+ WindowManager.LayoutParams.WRAP_CONTENT,
+ overlayType(),
+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
+ PixelFormat.TRANSLUCENT
+ ).apply {
+ gravity = Gravity.CENTER
+ }
+ try {
+ windowManager.addView(container, params)
+ actionMenu = container
+ } catch (_: Exception) {
+ actionMenu = null
+ }
+ }
+
+ 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
+ )
+ } catch (_: Exception) {
+ null
+ }
+ }
+
+ 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}") }
+ }
+ }
+ }
+
+ private fun encodeJpeg(bitmap: Bitmap): String? {
+ return try {
+ val (w, h) = if (bitmap.width > 1024 || bitmap.height > 1024) {
+ val ratio = minOf(1024f / bitmap.width, 1024f / bitmap.height)
+ (bitmap.width * ratio).toInt().coerceAtLeast(1) to
+ (bitmap.height * ratio).toInt().coerceAtLeast(1)
+ } else {
+ bitmap.width to bitmap.height
+ }
+ val scaled = Bitmap.createScaledBitmap(bitmap, w, h, true)
+ val output = java.io.ByteArrayOutputStream()
+ scaled.compress(Bitmap.CompressFormat.JPEG, 85, output)
+ if (scaled != bitmap) scaled.recycle()
+ android.util.Base64.encodeToString(output.toByteArray(), android.util.Base64.NO_WRAP)
+ } catch (_: Exception) {
+ null
+ }
+ }
+
+ private fun toast(msg: String) {
+ 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.CYAN)
+ textSize = 13f
+ setPadding(dp(12), dp(6), dp(12), dp(10))
+ }
+
+ private fun menuButton(label: String, onClick: () -> Unit): TextView = TextView(appContext).apply {
+ text = label
+ setTextColor(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("#33FFFFFF"))
+ }
+ 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() {
+ cropOverlay?.let { safeRemove(it) }
+ cropOverlay = null
+ }
+
+ private fun removeActionMenu() {
+ actionMenu?.let { safeRemove(it) }
+ actionMenu = null
+ }
+
+ private fun safeRemove(view: View) {
+ try {
+ windowManager.removeView(view)
+ } catch (_: Exception) {}
+ }
+
+ private fun overlayType(): Int =
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
+ } else {
+ @Suppress("DEPRECATION")
+ WindowManager.LayoutParams.TYPE_PHONE
+ }
+
+ private fun dp(value: Int): Int =
+ (value * appContext.resources.displayMetrics.density).toInt()
+}
diff --git a/app/src/main/java/com/gotcha/service/SmartActionDetector.kt b/app/src/main/java/com/gotcha/service/SmartActionDetector.kt
new file mode 100644
index 0000000..9a33a1d
--- /dev/null
+++ b/app/src/main/java/com/gotcha/service/SmartActionDetector.kt
@@ -0,0 +1,148 @@
+package com.gotcha.service
+
+import java.util.regex.Pattern
+
+/**
+ * A structured, semantic action surfaced in the assistive-ball menu.
+ *
+ * [prompt] is either a plain LLM prompt (currency conversion, chat reply) or a
+ * native-intent directive encoded with [SmartActionDetector.ACTION_PREFIX]. The
+ * host service decodes the prefixed form and fires an Android intent instead of
+ * querying the LLM.
+ */
+data class SmartAction(val label: String, val prompt: String)
+
+/**
+ * Lightweight text scanner that recognises structured data types — physical
+ * addresses, phone numbers, foreign-currency prices, calendar events, and chat
+ * messages — and turns the first match into a specialised [SmartAction].
+ *
+ * Detection order is most-specific first so a phone number is not mistaken for a
+ * street address and vice-versa. Chat detection is opt-in (clipboard only) since
+ * its heuristic is intentionally loose.
+ */
+object SmartActionDetector {
+
+ /** Marker prefix identifying a native-intent action (vs. a plain LLM prompt). */
+ const val ACTION_PREFIX = "@@SMART:"
+ const val TYPE_NAVIGATE = "NAVIGATE"
+ const val TYPE_DIAL = "DIAL"
+ const val TYPE_CALENDAR = "CALENDAR"
+
+ /** Separator between the encoded action type and its payload. */
+ const val PAYLOAD_SEP = "|"
+
+ 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",
+ Pattern.CASE_INSENSITIVE
+ )
+
+ private val phonePattern: Pattern = Pattern.compile(
+ "(\\+\\d{1,2}\\s)?\\(?\\d{3}\\)?[\\s.-]?\\d{3}[\\s.-]?\\d{4}"
+ )
+
+ private val currencyPattern: Pattern = Pattern.compile(
+ "([¥€£$])\\s?\\d{1,5}(\\.\\d{2})?"
+ )
+
+ private val calendarPattern: Pattern = Pattern.compile(
+ "\\b(meeting|appointment|event|call|lunch|dinner)\\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)",
+ Pattern.CASE_INSENSITIVE
+ )
+
+ /**
+ * Return the first structured [SmartAction] found in [text], or null if none
+ * apply. Set [allowChat] for clipboard text so the loose chat-reply heuristic
+ * can fire (it is suppressed for passive screen scans to avoid noise).
+ */
+ fun detect(text: String, allowChat: Boolean = false): SmartAction? {
+ if (text.isBlank()) return null
+
+ phonePattern.matcher(text).let { m ->
+ if (m.find()) {
+ val number = m.group().trim()
+ // Guard against matching a 10-digit run inside an address/id: require
+ // the match not be immediately embedded in a longer digit sequence.
+ return SmartAction(
+ label = "📞 Phone number detected. Dial?",
+ prompt = encode(TYPE_DIAL, number)
+ )
+ }
+ }
+
+ addressPattern.matcher(text).let { m ->
+ if (m.find()) {
+ val address = m.group().trim()
+ return SmartAction(
+ label = "📍 Address detected. Navigate?",
+ prompt = encode(TYPE_NAVIGATE, address)
+ )
+ }
+ }
+
+ currencyPattern.matcher(text).let { m ->
+ if (m.find()) {
+ val price = m.group().trim()
+ return SmartAction(
+ label = "💵 Currency detected. Convert?",
+ 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."
+ )
+ }
+ }
+
+ calendarPattern.matcher(text).let { m ->
+ if (m.find()) {
+ val event = m.group().trim()
+ return SmartAction(
+ label = "📅 Event detected. Schedule?",
+ prompt = encode(TYPE_CALENDAR, event)
+ )
+ }
+ }
+
+ if (allowChat && looksLikeChatMessage(text)) {
+ return SmartAction(
+ label = "💬 Message copied. Draft reply?",
+ prompt = "Draft a short, friendly reply to this message. Return only the " +
+ "reply text:\n\n$text"
+ )
+ }
+
+ return null
+ }
+
+ /**
+ * Loose heuristic for a copied chat bubble: short-ish, conversational text
+ * that either carries a "Sender: message" prefix or reads like a question/
+ * direct address. Kept conservative so it does not fire on arbitrary copies.
+ */
+ private fun looksLikeChatMessage(text: String): Boolean {
+ val trimmed = text.trim()
+ if (trimmed.length !in 2..300) return false
+ val hasSpeakerPrefix = Regex("^[A-Za-z][\\w .]{0,24}:\\s+\\S").containsMatchIn(trimmed)
+ val looksConversational = trimmed.endsWith("?") ||
+ Regex("\\b(hey|hi|hello|thanks|please|can you|are you|you free|lmk|wyd)\\b", RegexOption.IGNORE_CASE)
+ .containsMatchIn(trimmed)
+ return hasSpeakerPrefix || looksConversational
+ }
+
+ private fun encode(type: String, payload: String): String =
+ "$ACTION_PREFIX$type$PAYLOAD_SEP$payload"
+
+ /** True when [prompt] encodes a native intent (vs. a plain LLM prompt). */
+ fun isNativeAction(prompt: String): Boolean = prompt.startsWith(ACTION_PREFIX)
+
+ /** Decode a native-action prompt into (type, payload), or null if not one. */
+ fun decode(prompt: String): Pair<String, String>? {
+ if (!isNativeAction(prompt)) return null
+ val body = prompt.removePrefix(ACTION_PREFIX)
+ val sep = body.indexOf(PAYLOAD_SEP)
+ if (sep < 0) return null
+ return body.substring(0, sep) to body.substring(sep + PAYLOAD_SEP.length)
+ }
+}
diff --git a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
index e918e79..e173535 100644
--- a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
+++ b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
@@ -60,6 +60,7 @@ class AssistiveBallOverlay(context: Context) {
var onDismiss: () -> Unit = {}
var onOpenApp: () -> Unit = {}
var onTakeScreenshot: () -> Unit = {}
+ var onStartLens: () -> Unit = {}
var onStartCall: () -> Unit = {}
var onEndCall: () -> Unit = {}
var onToggleChatWindow: () -> Unit = {}
@@ -70,6 +71,7 @@ class AssistiveBallOverlay(context: Context) {
var isCallActive: () -> Boolean = { false }
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
@@ -204,6 +206,14 @@ class AssistiveBallOverlay(context: Context) {
// ---- 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
@@ -222,6 +232,11 @@ 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) // 45 seconds
@@ -231,6 +246,7 @@ class AssistiveBallOverlay(context: Context) {
private fun clearSmartAction() {
mainHandler.post {
pendingSmartAction = null
+ pendingSmartActionAlt = null
lastOfferedLabel = null
removeSmartActionRing()
removeMenu()
@@ -702,6 +718,23 @@ class AssistiveBallOverlay(context: Context) {
)
}
+ 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()
@@ -714,6 +747,12 @@ class AssistiveBallOverlay(context: Context) {
onTakeScreenshot()
}
)
+ container.addView(
+ tapButton("\uD83D\uDD0D Lens", colors) {
+ removeMenu()
+ onStartLens()
+ }
+ )
val params = menuLayoutParams()
try {
diff --git a/app/src/main/java/com/gotcha/ui/ScreenCompanionPanelOverlay.kt b/app/src/main/java/com/gotcha/ui/ScreenCompanionPanelOverlay.kt
index 210133a..2ecf4fd 100644
--- a/app/src/main/java/com/gotcha/ui/ScreenCompanionPanelOverlay.kt
+++ b/app/src/main/java/com/gotcha/ui/ScreenCompanionPanelOverlay.kt
@@ -29,10 +29,24 @@ class ScreenCompanionPanelOverlay(private val context: Context) {
private var panelView: View? = null
private var responseTextView: TextView? = null
+ private var inputEditText: EditText? = null
+ private var micButton: TextView? = null
+ private var speakerButton: TextView? = null
var onDismiss: () -> Unit = {}
var onSendInput: (text: String) -> Unit = {}
+ /** Voice typing (STT): toggled by the mic icon. Host starts/stops recognition. */
+ var onStartVoiceInput: () -> Unit = {}
+ var onStopVoiceInput: () -> Unit = {}
+
+ /** Read aloud (TTS): toggled by the speaker icon on the response block. */
+ var onReadAloud: (text: String) -> Unit = {}
+ var onStopReadAloud: () -> Unit = {}
+
+ private var isListening = false
+ private var isSpeaking = false
+
private fun dp(value: Int): Int = (value * appContext.resources.displayMetrics.density).toInt()
@Suppress("LongMethod", "CyclomaticComplexMethod")
@@ -67,6 +81,24 @@ class ScreenCompanionPanelOverlay(private val context: Context) {
typeface = Typeface.DEFAULT_BOLD
layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)
}
+ val speakerBtn = TextView(appContext).apply {
+ text = "🔊"
+ textSize = 18f
+ setPadding(dp(8), dp(8), dp(8), dp(8))
+ setOnClickListener {
+ if (isSpeaking) {
+ onStopReadAloud()
+ setSpeaking(false)
+ } else {
+ val text = responseTextView?.text?.toString()
+ if (!text.isNullOrBlank()) {
+ onReadAloud(text)
+ setSpeaking(true)
+ }
+ }
+ }
+ }
+ speakerButton = speakerBtn
val closeButton = TextView(appContext).apply {
text = "✕"
setTextColor(Color.LTGRAY)
@@ -75,6 +107,7 @@ class ScreenCompanionPanelOverlay(private val context: Context) {
setOnClickListener { dismiss() }
}
headerLayout.addView(titleText)
+ headerLayout.addView(speakerBtn)
headerLayout.addView(closeButton)
container.addView(headerLayout)
@@ -161,6 +194,23 @@ class ScreenCompanionPanelOverlay(private val context: Context) {
textSize = 14f
maxLines = 3
}
+ inputEditText = editText
+
+ val micBtn = TextView(appContext).apply {
+ text = "🎤"
+ textSize = 18f
+ setPadding(dp(8), dp(8), dp(8), dp(8))
+ setOnClickListener {
+ if (isListening) {
+ onStopVoiceInput()
+ setListening(false)
+ } else {
+ onStartVoiceInput()
+ setListening(true)
+ }
+ }
+ }
+ micButton = micBtn
val sendButton = Button(appContext).apply {
text = "Send"
@@ -175,6 +225,7 @@ class ScreenCompanionPanelOverlay(private val context: Context) {
}
}
inputLayout.addView(editText)
+ inputLayout.addView(micBtn)
inputLayout.addView(sendButton)
container.addView(inputLayout)
@@ -260,6 +311,41 @@ class ScreenCompanionPanelOverlay(private val context: Context) {
}
}
+ /** Append recognised speech to the follow-up input field (voice typing). */
+ fun appendVoiceInput(text: String) {
+ if (text.isBlank()) return
+ mainHandler.post {
+ inputEditText?.let { et ->
+ val existing = et.text?.toString().orEmpty()
+ val joined = if (existing.isBlank()) text else "$existing $text"
+ et.setText(joined)
+ et.setSelection(joined.length)
+ }
+ }
+ }
+
+ /** Reflect STT listening state on the mic icon (tinted while active). */
+ fun setListening(listening: Boolean) {
+ isListening = listening
+ mainHandler.post {
+ micButton?.apply {
+ text = if (listening) "⏺" else "🎤"
+ setTextColor(if (listening) Color.RED else Color.WHITE)
+ }
+ }
+ }
+
+ /** Reflect TTS playback state on the speaker icon (tinted while speaking). */
+ fun setSpeaking(speaking: Boolean) {
+ isSpeaking = speaking
+ mainHandler.post {
+ speakerButton?.apply {
+ text = if (speaking) "⏹" else "🔊"
+ setTextColor(if (speaking) Color.CYAN else Color.WHITE)
+ }
+ }
+ }
+
fun dismiss() {
mainHandler.post {
panelView?.let {
@@ -268,6 +354,11 @@ class ScreenCompanionPanelOverlay(private val context: Context) {
} catch (_: Exception) {}
}
panelView = null
+ inputEditText = null
+ micButton = null
+ speakerButton = null
+ isListening = false
+ isSpeaking = false
onDismiss()
}
}
diff --git a/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt b/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt
new file mode 100644
index 0000000..c88d70f
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt
@@ -0,0 +1,131 @@
+package com.gotcha.ui
+
+import android.annotation.SuppressLint
+import android.content.Context
+import android.graphics.Canvas
+import android.graphics.Color
+import android.graphics.Paint
+import android.graphics.PorterDuff
+import android.graphics.Rect
+import android.graphics.RectF
+import android.view.MotionEvent
+import android.view.View
+import kotlin.math.max
+import kotlin.math.min
+
+/**
+ * Full-screen, semi-transparent overlay that lets the user drag a bounding box
+ * to select a screen region ("Lens" mode). While dragging, the selected region
+ * is punched clear of the dim scrim so the user sees exactly what they're
+ * capturing. On release, [onSelection] fires with the selected [Rect] in view
+ * pixels (empty/degenerate selections are ignored).
+ *
+ * The view is added to the WindowManager by [ScreenLensController]; it is focusable
+ * and touchable so it intercepts the drag gesture.
+ */
+@SuppressLint("ViewConstructor")
+class ScreenCropOverlayView(
+ context: Context,
+ private val onSelection: (Rect) -> Unit,
+ private val onCancel: () -> Unit
+) : View(context) {
+
+ private var startX = 0f
+ private var startY = 0f
+ private var currentX = 0f
+ private var currentY = 0f
+ private var selecting = false
+
+ private val scrimPaint = Paint().apply {
+ color = Color.parseColor("#99000000")
+ }
+ private val clearPaint = Paint().apply {
+ xfermode = android.graphics.PorterDuffXfermode(PorterDuff.Mode.CLEAR)
+ }
+ private val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ color = Color.CYAN
+ strokeWidth = 2f * resources.displayMetrics.density
+ }
+ private val hintPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ color = Color.WHITE
+ textSize = 14f * resources.displayMetrics.density
+ textAlign = Paint.Align.CENTER
+ }
+
+ init {
+ // Enable an offscreen layer so PorterDuff.CLEAR punches through the scrim.
+ setLayerType(LAYER_TYPE_HARDWARE, null)
+ isFocusableInTouchMode = true
+ }
+
+ override fun onDraw(canvas: Canvas) {
+ super.onDraw(canvas)
+ canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), scrimPaint)
+ if (selecting) {
+ val r = currentRectF()
+ canvas.drawRect(r, clearPaint)
+ canvas.drawRect(r, borderPaint)
+ } else {
+ canvas.drawText(
+ "Drag to select a region • tap outside to cancel",
+ width / 2f,
+ height * 0.12f,
+ hintPaint
+ )
+ }
+ }
+
+ override fun onTouchEvent(event: MotionEvent): Boolean {
+ when (event.action) {
+ MotionEvent.ACTION_DOWN -> {
+ startX = event.x
+ startY = event.y
+ currentX = event.x
+ currentY = event.y
+ selecting = true
+ invalidate()
+ }
+ MotionEvent.ACTION_MOVE -> {
+ currentX = event.x
+ currentY = event.y
+ invalidate()
+ }
+ MotionEvent.ACTION_UP -> {
+ selecting = false
+ val rect = currentRect()
+ if (rect.width() > MIN_SIZE_PX && rect.height() > MIN_SIZE_PX) {
+ onSelection(rect)
+ } else {
+ // A tap (no real drag) cancels Lens mode.
+ onCancel()
+ }
+ invalidate()
+ }
+ MotionEvent.ACTION_CANCEL -> {
+ selecting = false
+ onCancel()
+ }
+ }
+ return true
+ }
+
+ private fun currentRectF(): RectF = RectF(
+ min(startX, currentX),
+ min(startY, currentY),
+ max(startX, currentX),
+ max(startY, currentY)
+ )
+
+ private fun currentRect(): Rect {
+ val l = min(startX, currentX).toInt()
+ val t = min(startY, currentY).toInt()
+ val r = max(startX, currentX).toInt()
+ val b = max(startY, currentY).toInt()
+ return Rect(l, t, r, b)
+ }
+
+ private companion object {
+ val MIN_SIZE_PX get() = 24
+ }
+}
diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xml
index b5760e4..a8caec5 100644
--- a/app/src/main/res/xml/file_paths.xml
+++ b/app/src/main/res/xml/file_paths.xml
@@ -2,4 +2,6 @@
<paths>
<!-- Captured photos live under getExternalFilesDir("Pictures"). -->
<external-files-path name="captures" path="." />
+ <!-- Lens-mode cropped images shared for "Copy Image" (content:// clip). -->
+ <cache-path name="lens" path="lens/" />
</paths>
diff --git a/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt b/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt
new file mode 100644
index 0000000..d73742c
--- /dev/null
+++ b/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt
@@ -0,0 +1,72 @@
+package com.gotcha.service
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class SmartActionDetectorTest {
+
+ @Test
+ fun `detects phone number and encodes a dial action`() {
+ val action = SmartActionDetector.detect("Call me at (415) 555-2671 tomorrow")
+ assertNotNull(action)
+ assertTrue(action!!.label.contains("Phone"))
+ assertTrue(SmartActionDetector.isNativeAction(action.prompt))
+ val (type, payload) = SmartActionDetector.decode(action.prompt)!!
+ assertEquals(SmartActionDetector.TYPE_DIAL, type)
+ assertTrue(payload.contains("555"))
+ }
+
+ @Test
+ fun `detects street address and encodes a navigate action`() {
+ val action = SmartActionDetector.detect("Meet at 1600 Amphitheatre Parkway Way for lunch")
+ assertNotNull(action)
+ assertTrue(action!!.label.contains("Address"))
+ val (type, _) = SmartActionDetector.decode(action.prompt)!!
+ assertEquals(SmartActionDetector.TYPE_NAVIGATE, type)
+ }
+
+ @Test
+ fun `detects foreign currency and returns a plain LLM prompt`() {
+ val action = SmartActionDetector.detect("The jacket costs €89.99 in Berlin")
+ assertNotNull(action)
+ assertTrue(action!!.label.contains("Currency"))
+ // Currency conversion is an LLM query, not a native intent.
+ assertTrue(!SmartActionDetector.isNativeAction(action.prompt))
+ }
+
+ @Test
+ fun `detects calendar event and encodes a calendar action`() {
+ val action = SmartActionDetector.detect("Let's schedule a meeting on Monday")
+ assertNotNull(action)
+ assertTrue(action!!.label.contains("Event"))
+ val (type, _) = SmartActionDetector.decode(action.prompt)!!
+ assertEquals(SmartActionDetector.TYPE_CALENDAR, type)
+ }
+
+ @Test
+ fun `chat reply only fires when allowChat is set`() {
+ val text = "Hey, are you free later?"
+ assertNull(SmartActionDetector.detect(text, allowChat = false))
+ val action = SmartActionDetector.detect(text, allowChat = true)
+ assertNotNull(action)
+ assertTrue(action!!.label.contains("Message"))
+ }
+
+ @Test
+ fun `plain prose returns no action`() {
+ assertNull(SmartActionDetector.detect("The quick brown fox jumps over the lazy dog."))
+ }
+
+ @Test
+ fun `blank input returns no action`() {
+ assertNull(SmartActionDetector.detect(" "))
+ }
+
+ @Test
+ fun `decode returns null for non-native prompts`() {
+ assertNull(SmartActionDetector.decode("Just a normal prompt"))
+ }
+}