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: add OCR-to-clipboard and image-prompt capability to screen crop overlay via LLM vision
Rishabh Bajpaief939a6a6cc1
diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.ktindex f1f0d4f..0192373 100644--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt@@ -40,7 +40,7 @@ import java.io.File** Started/stopped from the in-app toggle via [ACTION_START] / [ACTION_STOP].*/-@Suppress("TooManyFunctions")+@Suppress("TooManyFunctions", "LargeClass")class AssistiveBallService : Service() {private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)@@ -294,6 +294,12 @@ class AssistiveBallService : Service() {onContextualAction = { prompt ->handleSmartActionSelected(prompt, activeCompanionHistory)},+ onImagePrompt = { base64, prompt ->+ openCompanionWithImageAndQuery(base64, prompt)+ },+ onOcrToClipboard = { base64 ->+ ocrCropToClipboard(base64)+ },onError = { overlay.showError(it) })}@@ -401,6 +407,69 @@ class AssistiveBallService : Service() {screenCompanionPanel.updateResponse("Ask me anything about the selected region.")}+ /**+ * Open the panel with a Lens crop attached AND immediately query the LLM with+ * [prompt] (used by the inline "Translate" chip on image regions).+ */+ private fun openCompanionWithImageAndQuery(base64Jpeg: String, prompt: String) {+ activeCompanionHistory.clear()+ activeCompanionHistory.add(+ com.gotcha.llm.ChatMessage(+ "system",+ kotlinx.serialization.json.JsonPrimitive(+ "You are Screen Companion. The user has attached a captured screen region."+ )+ )+ )+ activeCompanionHistory.add(com.gotcha.llm.visionUserMessage(prompt, base64Jpeg, "jpeg"))+ overlay.isPanelOpen = true+ screenCompanionPanel.show("📸 Region attached")+ screenCompanionPanel.updateResponse("Thinking...")+ val currentHistory = activeCompanionHistory.toList()+ scope.launch {+ try {+ val response = llmClient.chat(currentHistory)+ val replyText = response.choices.firstOrNull()?.message?.textContent ?: "No response"+ activeCompanionHistory.add(+ com.gotcha.llm.ChatMessage("assistant", kotlinx.serialization.json.JsonPrimitive(replyText))+ )+ screenCompanionPanel.updateResponse(replyText)+ } catch (e: Exception) {+ screenCompanionPanel.updateResponse("Error: ${e.message}")+ }+ }+ }++ /** OCR a Lens crop via the LLM and copy the recognized text to the clipboard. */+ private fun ocrCropToClipboard(base64Jpeg: String) {+ overlay.showError("Reading text…")+ val history = listOf(+ com.gotcha.llm.ChatMessage(+ "system",+ kotlinx.serialization.json.JsonPrimitive(+ "You are an OCR engine. Return ONLY the exact text visible in the image, " ++ "with no commentary, labels, or quotes. If there is no text, return an empty string."+ )+ ),+ com.gotcha.llm.visionUserMessage("Extract all text from this image.", base64Jpeg, "jpeg")+ )+ scope.launch {+ try {+ val response = llmClient.chat(history)+ val text = response.choices.firstOrNull()?.message?.textContent?.trim().orEmpty()+ if (text.isBlank()) {+ overlay.showError("No text found in selection")+ } else {+ val clipboard = getSystemService(CLIPBOARD_SERVICE) as android.content.ClipboardManager+ clipboard.setPrimaryClip(android.content.ClipData.newPlainText("Lens text", text))+ overlay.showError("Text copied")+ }+ } catch (e: Exception) {+ overlay.showError("Couldn't read text: ${e.message}")+ }+ }+ }+private fun setupScreenCompanionPanel() {screenCompanionPanel = com.gotcha.ui.ScreenCompanionPanelOverlay(this).apply {onDismiss = {diff --git a/app/src/main/java/com/gotcha/service/ScreenLensController.kt b/app/src/main/java/com/gotcha/service/ScreenLensController.ktindex ee07932..751c04b 100644--- a/app/src/main/java/com/gotcha/service/ScreenLensController.kt+++ b/app/src/main/java/com/gotcha/service/ScreenLensController.kt@@ -50,6 +50,10 @@ class ScreenLensController(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: (base64Jpeg: String) -> Unit,private val onError: (String) -> Unit) {private val appContext = context.applicationContext@@ -79,7 +83,14 @@ class ScreenLensController(val overlay = ScreenCropOverlayView(appContext,onSelection = { rect -> onRegionSelected(rect) },- onCancel = { cancel() }+ 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()+ })val params = WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT,@@ -214,12 +225,12 @@ class ScreenLensController(/*** 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. Only shown when the selection contains text.+ * 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?) {removeTextChips()- val text = regionText?.trim()- if (text.isNullOrBlank()) return+ val text = regionText?.trim()?.takeIf { it.isNotBlank() }val row = LinearLayout(appContext).apply {orientation = LinearLayout.HORIZONTAL@@ -232,17 +243,40 @@ class ScreenLensController(}row.addView(smallChip("📝 Copy text") {- copyTextToClipboard(text)- finishMenu(recycle = true)+ if (text != null) {+ copyTextToClipboard(text)+ finishMenu(recycle = true)+ } else {+ // No accessibility text — OCR the crop, then copy the result.+ val base64 = pendingCrop?.let { encodeJpeg(it) }+ finishMenu(recycle = true)+ if (base64 != null) onOcrToClipboard(base64) else onError("Couldn't read selection")+ }})row.addView(smallChip("🌐 Translate") {- 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"- )+ 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")+ }+ }})diff --git a/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt b/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.ktindex c17d8ec..7f3e15c 100644--- a/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt+++ b/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt@@ -37,7 +37,10 @@ import kotlin.random.Randomclass ScreenCropOverlayView(context: Context,private val onSelection: (Rect) -> Unit,- private val onCancel: () -> 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 = {}) : View(context) {private val density = resources.displayMetrics.density@@ -275,10 +278,16 @@ 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+ // While a screenshot is being captured, ignore touches.+ if (captureMode) return falsewhen (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()+ }drawing = truemoved = falsepath.reset()