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: integrate ML Kit barcode scanning to support QR and barcode detection with context-aware actions
Rishabh Bajpai60b129b58b10
diff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex ba15cee..1dee571 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -218,8 +218,10 @@ dependencies {exclude(group = "com.atlassian.commonmark", module = "commonmark")}- // ML Kit on-device text recognition (for Lens mode OCR)+ // ML Kit on-device text recognition (for Lens mode OCR) and barcode scanningimplementation("com.google.mlkit:text-recognition:16.0.1")+ implementation("com.google.mlkit:barcode-scanning:17.3.0")+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.7.3")// CameraX for automated photo captureval cameraxVersion = "1.4.0"diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.ktindex a8654bd..77f67f0 100644--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt@@ -129,7 +129,10 @@ class AssistiveBallService : Service() {onSmartActionSelected = { prompt ->handleSmartActionSelected(prompt, activeCompanionHistory)}- onRequestClipboardCheck = { handleClipboardRead() }+ onRequestClipboardCheck = {+ handleClipboardRead()+ screenCompanionController.triggerScan(force = true)+ }isCallActive = { callController.isActive() }}diff --git a/app/src/main/java/com/gotcha/service/ProactiveSessionManager.kt b/app/src/main/java/com/gotcha/service/ProactiveSessionManager.ktindex d04f69b..0d4d374 100644--- a/app/src/main/java/com/gotcha/service/ProactiveSessionManager.kt+++ b/app/src/main/java/com/gotcha/service/ProactiveSessionManager.kt@@ -47,6 +47,14 @@ class ProactiveSessionManager(// Purge expired itemsitemsMap.entries.removeIf { (_, item) -> now - item.lastUpdatedTimestamp > ttlMs }+ // When new QR_CODE or BARCODE entities are discovered, clear older ones+ val hasNewQrOrBarcode = newEntities.any { it.type == EntityType.QR_CODE || it.type == EntityType.BARCODE }+ if (hasNewQrOrBarcode) {+ itemsMap.entries.removeIf { (_, item) ->+ item.entity.type == EntityType.QR_CODE || item.entity.type == EntityType.BARCODE+ }+ }+// Merge new entitiesfor (entity in newEntities) {val key = "${entity.type}:${entity.normalizedValue}"diff --git a/app/src/main/java/com/gotcha/service/QrCodeScanner.kt b/app/src/main/java/com/gotcha/service/QrCodeScanner.ktnew file mode 100644index 0000000..171e23c--- /dev/null+++ b/app/src/main/java/com/gotcha/service/QrCodeScanner.kt@@ -0,0 +1,177 @@+package com.gotcha.service++import android.graphics.Bitmap+import com.google.mlkit.vision.barcode.BarcodeScannerOptions+import com.google.mlkit.vision.barcode.BarcodeScanning+import com.google.mlkit.vision.barcode.common.Barcode+import com.google.mlkit.vision.common.InputImage+import kotlinx.coroutines.tasks.await++/**+ * On-device ML Kit visual QR code and barcode detector for screen snapshots.+ */+object QrCodeScanner {++ private val scanner by lazy {+ val options = BarcodeScannerOptions.Builder()+ .setBarcodeFormats(Barcode.FORMAT_ALL_FORMATS)+ .build()+ BarcodeScanning.getClient(options)+ }++ /**+ * Scans [bitmap] for QR codes and 1D/2D barcodes using ML Kit on-device recognition.+ */+ suspend fun scanBitmap(bitmap: Bitmap): List<DetectedEntity> {+ return try {+ val image = InputImage.fromBitmap(bitmap, 0)+ val barcodes = scanner.process(image).await()+ barcodes.mapNotNull { barcodeToEntity(it) }+ } catch (_: Throwable) {+ emptyList()+ }+ }++ @Suppress("LongMethod", "CyclomaticComplexMethod")+ fun barcodeToEntity(barcode: Barcode): DetectedEntity? {+ val rawValue = barcode.rawValue ?: return null+ if (rawValue.isBlank()) return null++ val isQr = barcode.format == Barcode.FORMAT_QR_CODE+ val type = if (isQr) EntityType.QR_CODE else EntityType.BARCODE+ val actions = mutableListOf<SmartAction>()++ val displayTitle = when (barcode.valueType) {+ Barcode.TYPE_URL -> {+ val url = barcode.url?.url ?: rawValue+ val domain = runCatching { android.net.Uri.parse(url).host }.getOrNull()+ ?: SmartActionDetector.snippet(url, 20)+ actions.add(+ SmartAction(+ label = "🌐 Open QR Link: $domain",+ prompt = SmartActionDetector.encode(SmartActionDetector.TYPE_VIEW, url),+ actionType = ActionType.NATIVE_BROWSE,+ isPrimary = true+ )+ )+ actions.add(+ SmartAction(+ label = "📝 Summarize",+ prompt = SmartActionDetector.encode(SmartActionDetector.TYPE_FETCH, url),+ actionType = ActionType.LLM_SUMMARIZE+ )+ )+ actions.add(+ SmartAction(+ label = "📋 Copy URL",+ prompt = SmartActionDetector.encode(SmartActionDetector.TYPE_COPY, url),+ actionType = ActionType.NATIVE_COPY+ )+ )+ "QR Link: $domain"+ }+ Barcode.TYPE_WIFI -> {+ val ssid = barcode.wifi?.ssid ?: "Wi-Fi"+ val pwd = barcode.wifi?.password ?: ""+ val info = "SSID: $ssid, Password: $pwd"+ actions.add(+ SmartAction(+ label = "📶 Wi-Fi: $ssid",+ prompt = SmartActionDetector.encode(SmartActionDetector.TYPE_COPY, info),+ actionType = ActionType.NATIVE_COPY,+ isPrimary = true+ )+ )+ "Wi-Fi QR: $ssid"+ }+ Barcode.TYPE_PHONE -> {+ val phone = barcode.phone?.number ?: rawValue+ actions.add(+ SmartAction(+ label = "📞 Call: ${SmartActionDetector.snippet(phone, 15)}",+ prompt = SmartActionDetector.encode(SmartActionDetector.TYPE_DIAL, phone),+ actionType = ActionType.NATIVE_DIAL,+ isPrimary = true+ )+ )+ "QR Phone: $phone"+ }+ else -> {+ if (rawValue.startsWith("http://", ignoreCase = true) ||+ rawValue.startsWith("https://", ignoreCase = true)+ ) {+ val domain = runCatching { android.net.Uri.parse(rawValue).host }.getOrNull()+ ?: SmartActionDetector.snippet(rawValue, 20)+ actions.add(+ SmartAction(+ label = "🌐 Open QR Link: $domain",+ prompt = SmartActionDetector.encode(SmartActionDetector.TYPE_VIEW, rawValue),+ actionType = ActionType.NATIVE_BROWSE,+ isPrimary = true+ )+ )+ actions.add(+ SmartAction(+ label = "📝 Summarize",+ prompt = SmartActionDetector.encode(SmartActionDetector.TYPE_FETCH, rawValue),+ actionType = ActionType.LLM_SUMMARIZE+ )+ )+ actions.add(+ SmartAction(+ label = "📋 Copy Link",+ prompt = SmartActionDetector.encode(SmartActionDetector.TYPE_COPY, rawValue),+ actionType = ActionType.NATIVE_COPY+ )+ )+ "QR Link: $domain"+ } else if (!isQr) {+ val searchUrl = "https://www.google.com/search?q=${android.net.Uri.encode(rawValue)}"+ actions.add(+ SmartAction(+ label = "🔍 Search Barcode: ${SmartActionDetector.snippet(rawValue, 16)}",+ prompt = SmartActionDetector.encode(SmartActionDetector.TYPE_VIEW, searchUrl),+ actionType = ActionType.NATIVE_BROWSE,+ isPrimary = true+ )+ )+ actions.add(+ SmartAction(+ label = "📋 Copy Barcode",+ prompt = SmartActionDetector.encode(SmartActionDetector.TYPE_COPY, rawValue),+ actionType = ActionType.NATIVE_COPY+ )+ )+ "Barcode: ${SmartActionDetector.snippet(rawValue, 20)}"+ } else {+ actions.add(+ SmartAction(+ label = "📷 QR: ${SmartActionDetector.snippet(rawValue, 20)}",+ prompt = "Here is the content of a QR code detected on screen:\n\n$rawValue\n\n" ++ "Please process or act on this QR code content.",+ actionType = ActionType.LLM_GENERAL,+ isPrimary = true+ )+ )+ actions.add(+ SmartAction(+ label = "📋 Copy QR Content",+ prompt = SmartActionDetector.encode(SmartActionDetector.TYPE_COPY, rawValue),+ actionType = ActionType.NATIVE_COPY+ )+ )+ "QR: ${SmartActionDetector.snippet(rawValue, 20)}"+ }+ }+ }++ return DetectedEntity(+ type = type,+ rawValue = rawValue,+ normalizedValue = displayTitle,+ span = 0..rawValue.length,+ confidence = 0.98f,+ actions = actions+ )+ }+}diff --git a/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt b/app/src/main/java/com/gotcha/service/ScreenCompanionController.ktindex 854d279..83fa334 100644--- a/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt+++ b/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt@@ -79,6 +79,12 @@ class ScreenCompanionController(} catch (_: Exception) {}}+ fun triggerScan(force: Boolean = true) {+ if (force) lastScreenTextHash = 0+ performLightweightScan(triggerType = "AppChange")+ }++ @Suppress("CyclomaticComplexMethod")private fun performLightweightScan(triggerType: String) {val settings = runCatching { SettingsRepository(context).load() }.getOrNull()if (settings != null && !settings.proactiveEnabled) return@@ -119,13 +125,36 @@ class ScreenCompanionController(return@withContext}- val screenText = ScreenSnapshot.captureScreenText(limit = 120) ?: return@withContext+ val screenText = ScreenSnapshot.captureScreenText(limit = 120) ?: ""val currentHash = screenText.hashCode()- if (currentHash == lastScreenTextHash) return@withContext- lastScreenTextHash = currentHash+ if (screenText.isNotEmpty() && currentHash == lastScreenTextHash) return@withContext+ if (screenText.isNotEmpty()) lastScreenTextHash = currentHash++ val visualQrEntities = try {+ val bitmap = GotchaAccessibilityService.instance?.takeScreenshotBitmap()+ if (bitmap != null) {+ val scanned = QrCodeScanner.scanBitmap(bitmap)+ bitmap.recycle()+ scanned+ } else {+ emptyList()+ }+ } catch (_: Throwable) {+ emptyList()+ }val prefCurrency = effectiveSettings?.preferredCurrency ?: "USD"- val allEntities = SmartActionDetector.detectAll(screenText, allowChat = false, targetCurrency = prefCurrency)+ val textEntities = if (screenText.isNotEmpty()) {+ SmartActionDetector.detectAll(screenText, allowChat = false, targetCurrency = prefCurrency)+ } else {+ emptyList()+ }++ val allEntities = (visualQrEntities + textEntities).sortedWith(+ compareByDescending<DetectedEntity> { it.type.basePriority }+ .thenByDescending { it.confidence }+ )+val actionableEntities = allEntities.filter { item ->item.confidence >= 0.85f &&item.type != com.gotcha.service.EntityType.CHAT_REPLY &&diff --git a/app/src/main/java/com/gotcha/service/SmartActionDetector.kt b/app/src/main/java/com/gotcha/service/SmartActionDetector.ktindex b257ed3..9cf431c 100644--- a/app/src/main/java/com/gotcha/service/SmartActionDetector.kt+++ b/app/src/main/java/com/gotcha/service/SmartActionDetector.kt@@ -6,6 +6,8 @@ import java.util.regex.Pattern* High-level entity types recognized by [SmartActionDetector], ordered by default priority.*/enum class EntityType(val basePriority: Int) {+ QR_CODE(200),+ BARCODE(190),OTP(100),PHONE(80),ADDRESS(80),@@ -183,6 +185,9 @@ object SmartActionDetector {val rawEntities = mutableListOf<DetectedEntity>()+ // 0. QR & Barcode patterns in text+ detectQrAndBarcodes(text, rawEntities)+// 1. OTPdetectOtps(text, rawEntities)@@ -651,9 +656,38 @@ object SmartActionDetector {return hasSpeakerPrefix || looksConversational || isForeignScript}- private fun encode(type: String, payload: String): String =+ fun encode(type: String, payload: String): String ="$ACTION_PREFIX$type$PAYLOAD_SEP$payload"+ private fun detectQrAndBarcodes(text: String, out: MutableList<DetectedEntity>) {+ if (text.isBlank()) return+ val wifiPattern = Pattern.compile("WIFI:S:([^;]+);(?:T:([^;]+);)?(?:P:([^;]+);)?", Pattern.CASE_INSENSITIVE)+ val mWifi = wifiPattern.matcher(text)+ while (mWifi.find()) {+ val ssid = mWifi.group(1) ?: "Wi-Fi"+ val pass = mWifi.group(3) ?: ""+ val fullMatch = mWifi.group(0) ?: text+ val actions = listOf(+ SmartAction(+ label = "📶 Connect Wi-Fi: $ssid",+ prompt = encode(TYPE_COPY, "SSID: $ssid, Password: $pass"),+ actionType = ActionType.NATIVE_COPY,+ isPrimary = true+ )+ )+ out.add(+ DetectedEntity(+ type = EntityType.QR_CODE,+ rawValue = fullMatch,+ normalizedValue = "Wi-Fi QR: $ssid",+ span = mWifi.start()..mWifi.end(),+ confidence = 0.95f,+ actions = actions+ )+ )+ }+ }+/** Build a native "fetch this URL and summarize" action. */fun fetchAction(url: String): SmartAction =SmartAction(diff --git a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.ktindex fa9601d..a3b3eec 100644--- a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt+++ b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt@@ -443,6 +443,8 @@ class AssistiveBallOverlay(context: Context) {}private fun getCategoryIcon(type: EntityType): String = when (type) {+ EntityType.QR_CODE -> "📷"+ EntityType.BARCODE -> "📊"EntityType.OTP -> "🔑"EntityType.PHONE -> "📞"EntityType.ADDRESS -> "📍"diff --git a/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt b/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.ktindex 6b9e483..5f26700 100644--- a/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt+++ b/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt@@ -310,4 +310,13 @@ class SmartActionDetectorTest {fun `decode returns null for non-native prompts`() {assertNull(SmartActionDetector.decode("Just a normal prompt"))}++ @Test+ fun `qr code and barcode entities have highest priority over OTP and phone`() {+ val text = "Your OTP is 123456. Connect to WIFI:S:HomeNet;P:secret123;T:WPA;;"+ val entities = SmartActionDetector.detectAll(text)+ assertTrue(entities.isNotEmpty())+ assertEquals(EntityType.QR_CODE, entities.first().type)+ assertTrue(entities.first().normalizedValue.contains("HomeNet"))+ }}