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 MediaProjectionService for screen capture and update AccessibilityTool for improved gesture handling and service state management

Rishabh Bajpai500003452744
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index c7cded9..19fb83b 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -48,6 +48,7 @@
android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
<!-- Assistive ball: records audio (STT) from the foreground service and runs as a
floating overlay assistant. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
@@ -126,6 +127,12 @@
android:value="floating_assistant_overlay" />
</service>
+ <!-- Screenshot capture via MediaProjection (foreground service, one-shot). -->
+ <service
+ android:name=".service.MediaProjectionService"
+ android:exported="false"
+ android:foregroundServiceType="mediaProjection" />
+
<!-- Tier 3: NotificationListenerService — reads/dismisses notifications, media control. -->
<service
android:name=".service.GotchaNotificationListenerService"
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 1e369b3..bd38962 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -40,6 +40,7 @@ import com.gotcha.llm.LLMClient
import kotlinx.serialization.json.JsonPrimitive
import com.gotcha.service.AssistiveBallService
import com.gotcha.service.GotchaDeviceAdminReceiver
+import com.gotcha.tools.ScreenPerception
import com.gotcha.tools.ToolResult
import com.gotcha.ui.ChatScreen
import com.gotcha.ui.SessionsScreen
@@ -68,6 +69,19 @@ class MainActivity : ComponentActivity() {
).show()
}
+ /** MediaProjection consent result — stores intent for screenshot capture. */
+ private val mediaProjectionLauncher =
+ registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
+ android.util.Log.d("ScreenCapture", "mediaProjectionLauncher: resultCode=${result.resultCode}, data=${result.data != null}")
+ if (result.resultCode == RESULT_OK && result.data != null) {
+ ScreenPerception.mediaProjectionResultData = result.data
+ Toast.makeText(this, "Screenshot permission granted.", Toast.LENGTH_SHORT).show()
+ android.util.Log.d("ScreenCapture", "mediaProjectionLauncher: consent stored successfully")
+ } else {
+ android.util.Log.w("ScreenCapture", "mediaProjectionLauncher: consent denied or data null")
+ }
+ }
+
/** Requests all runtime permissions at once on first launch. */
private val firstLaunchLauncher =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { _ ->
@@ -134,6 +148,12 @@ class MainActivity : ComponentActivity() {
"VPN already authorized — ask the assistant again.",
Toast.LENGTH_SHORT
).show()
+ "special:screenshot_consent" -> {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ val mpManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as android.media.projection.MediaProjectionManager
+ mediaProjectionLauncher.launch(mpManager.createScreenCaptureIntent())
+ }
+ }
// Runtime permissions are mapped in Settings → Permissions; skip here.
}
}
@@ -158,6 +178,14 @@ class MainActivity : ComponentActivity() {
requestAllRuntimePermissions()
prefs.edit().putBoolean(KEY_FIRST_LAUNCH_DONE, true).apply()
}
+ // Request MediaProjection consent for screenshot capture
+ // Always request if not granted in this process session (cleared on process kill)
+ if (ScreenPerception.mediaProjectionResultData == null) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ val mpManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as android.media.projection.MediaProjectionManager
+ mediaProjectionLauncher.launch(mpManager.createScreenCaptureIntent())
+ }
+ }
}
setContent {
@@ -368,7 +396,7 @@ class MainActivity : ComponentActivity() {
messages = listOf(ChatMessage(role = "user", content = JsonPrimitive("Reply with the single word: pong"))),
temperature = 0f
)
- response.choices.firstOrNull()?.message?.textContent?.take(60) ?: "empty response"
+ response.choices.firstOrNull()?.message?.textContent?. take(60) ?: "empty response"
}
companion object {
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index ff2eb2c..67b255b 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -153,6 +153,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
val exportContent: SharedFlow<String> = _exportContent.asSharedFlow()
init {
+ ScreenPerception.appContext = application
toolExecutor = ToolExecutor(
application,
onTask = { description, prompt ->
@@ -710,27 +711,48 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
// contract and inject them as a vision user message so the LLM
// can "see" the screen alongside structured element data.
if (result.success && call.function.name == "read_screen") {
+ android.util.Log.d("ScreenCapture", "read_screen auto-injection: calling captureCompressedScreenshot()")
val screenshot = captureCompressedScreenshot()
+ android.util.Log.d("ScreenCapture", "read_screen auto-injection: screenshot=${screenshot != null}")
if (screenshot != null) {
val uiTree = ScreenPerception.buildUiHierarchyText()
val observationText = ScreenPerception.buildObservationText(screenshot, uiTree)
val visionMsg = visionUserMessage(observationText, screenshot.base64, "jpeg")
llmHistory.add(visionMsg)
appendUi(MessageKind.ASSISTANT, "[Screenshot captured for visual context]")
+ android.util.Log.d("ScreenCapture", "read_screen auto-injection: vision message added, base64 length=${screenshot.base64.length}")
+ } else {
+ android.util.Log.e("ScreenCapture", "read_screen auto-injection: screenshot was null — no vision message added")
+ // If MediaProjection consent hasn't been granted, request it
+ if (ScreenPerception.mediaProjectionResultData == null) {
+ _permissionRequests.tryEmit("special:screenshot_consent")
+ }
}
}
// read_screen_raw: full-resolution PNG screenshot for visual detail.
+ // Also saves the raw bytes to the working directory as a file.
if (result.success && call.function.name == "read_screen_raw") {
val screenshot = captureFullResScreenshot()
if (screenshot != null) {
val screenText = result.message.removePrefix("read_screen_raw:").take(500)
+ // Save screenshot to working directory
+ val savedPath = try {
+ val ts = java.text.SimpleDateFormat("yyyyMMdd_HHmmss", java.util.Locale.US).format(java.util.Date())
+ val dir = java.io.File(com.gotcha.tools.FileResolver.WORKING_DIR_BASE)
+ if (!dir.exists()) dir.mkdirs()
+ val file = java.io.File(dir, "screenshot_$ts.png")
+ val rawBytes = android.util.Base64.decode(screenshot.base64, android.util.Base64.DEFAULT)
+ file.writeBytes(rawBytes)
+ file.absolutePath
+ } catch (_: Exception) { null }
+ val pathNote = if (savedPath != null) "\n\nSaved to: $savedPath" else ""
val visionMsg = visionUserMessage(
"Screen text:\n$screenText\n\nThe assistant captured a " +
- "full-resolution screenshot for visual detail.",
+ "full-resolution screenshot for visual detail.$pathNote",
screenshot.base64, screenshot.format
)
llmHistory.add(visionMsg)
- appendUi(MessageKind.ASSISTANT, "[Full-resolution screenshot captured]")
+ appendUi(MessageKind.ASSISTANT, "[Full-resolution screenshot captured]${if (savedPath != null) " → $savedPath" else ""}")
}
}
// Special-access markers: emit and continue (no wait needed since they open Settings)
diff --git a/app/src/main/java/com/gotcha/service/MediaProjectionService.kt b/app/src/main/java/com/gotcha/service/MediaProjectionService.kt
new file mode 100644
index 0000000..2953172
--- /dev/null
+++ b/app/src/main/java/com/gotcha/service/MediaProjectionService.kt
@@ -0,0 +1,254 @@
+package com.gotcha.service
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.Service
+import android.content.Context
+import android.content.Intent
+import android.graphics.Bitmap
+import android.graphics.PixelFormat
+import android.hardware.display.DisplayManager
+import android.hardware.display.VirtualDisplay
+import android.media.ImageReader
+import android.media.projection.MediaProjection
+import android.media.projection.MediaProjectionManager
+import android.os.Build
+import android.os.IBinder
+import android.util.DisplayMetrics
+import android.util.Log
+import android.view.WindowManager
+import java.io.ByteArrayOutputStream
+import java.io.File
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
+
+/**
+ * One-shot foreground service that captures a single screenshot via MediaProjection.
+ * Writes PNG bytes to a temp file and signals completion via [resultReady].
+ */
+class MediaProjectionService : Service() {
+
+ companion object {
+ private const val CHANNEL_ID = "screenshot_capture"
+ private const val NOTIFICATION_ID = 9999
+ private const val RESULT_FILE = "media_projection_capture.png"
+
+ /** Set by caller before starting the service. */
+ var resultData: Intent? = null
+
+ /** Latch that callers can await; countDown() fires when PNG is written. */
+ var resultReady = CountDownLatch(1)
+
+ /** Path to the captured PNG file after [resultReady] fires. */
+ var resultFilePath: String? = null
+ private set
+
+ fun capture(context: Context, resultIntent: Intent, timeoutMs: Long = 5000): ByteArray? {
+ Log.d("ScreenCapture", "MediaProjectionService.capture() called")
+ resultData = resultIntent
+ resultReady = CountDownLatch(1)
+ resultFilePath = null
+
+ val serviceIntent = Intent(context, MediaProjectionService::class.java)
+ try {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ context.startForegroundService(serviceIntent)
+ } else {
+ context.startService(serviceIntent)
+ }
+ Log.d("ScreenCapture", "MediaProjectionService started")
+ } catch (e: Exception) {
+ Log.e("ScreenCapture", "Failed to start MediaProjectionService: ${e.message}")
+ return null
+ }
+
+ val completed = resultReady.await(timeoutMs, TimeUnit.MILLISECONDS)
+ Log.d("ScreenCapture", "MediaProjectionService latch completed=$completed, resultFilePath=$resultFilePath")
+
+ val path = resultFilePath ?: return null
+ val file = File(path)
+ if (!file.exists()) {
+ Log.e("ScreenCapture", "Result file does not exist: $path")
+ return null
+ }
+ val bytes = file.readBytes()
+ file.delete()
+ Log.d("ScreenCapture", "MediaProjectionService returning ${bytes.size} bytes")
+ return bytes
+ }
+ }
+
+ private var projection: MediaProjection? = null
+ private var virtualDisplay: VirtualDisplay? = null
+ private var imageReader: ImageReader? = null
+
+ override fun onBind(intent: Intent?): IBinder? = null
+
+ override fun onCreate() {
+ super.onCreate()
+ createNotificationChannel()
+ startForeground(NOTIFICATION_ID, buildNotification())
+ }
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ val data = resultData
+ Log.d("ScreenCapture", "MediaProjectionService.onStartCommand: data=${data != null}")
+ if (data == null) {
+ resultFilePath = null
+ resultReady.countDown()
+ stopSelf()
+ return START_NOT_STICKY
+ }
+
+ Thread {
+ try {
+ captureScreenshot(data)
+ } catch (e: Exception) {
+ Log.e("ScreenCapture", "MediaProjectionService captureScreenshot exception: ${e.message}")
+ resultFilePath = null
+ resultReady.countDown()
+ stopSelf()
+ }
+ }.start()
+
+ return START_NOT_STICKY
+ }
+
+ private fun captureScreenshot(data: Intent) {
+ Log.d("ScreenCapture", "captureScreenshot: starting")
+ val mpManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
+ projection = mpManager.getMediaProjection(-1, data)
+ Log.d("ScreenCapture", "captureScreenshot: projection=${projection != null}")
+ if (projection == null) {
+ Log.e("ScreenCapture", "captureScreenshot: getMediaProjection returned null — consent data may be stale")
+ resultFilePath = null
+ resultReady.countDown()
+ stopSelf()
+ return
+ }
+
+ val wm = getSystemService(Context.WINDOW_SERVICE) as WindowManager
+ val metrics = DisplayMetrics()
+ wm.defaultDisplay.getRealMetrics(metrics)
+
+ val screenWidth = metrics.widthPixels
+ val screenHeight = metrics.heightPixels
+ val screenDpi = metrics.densityDpi
+ Log.d("ScreenCapture", "captureScreenshot: screen ${screenWidth}x${screenHeight} dpi=$screenDpi")
+
+ imageReader = ImageReader.newInstance(
+ screenWidth, screenHeight,
+ PixelFormat.RGBA_8888, 2
+ )
+
+ virtualDisplay = projection!!.createVirtualDisplay(
+ "ScreenCapture",
+ screenWidth, screenHeight, screenDpi,
+ DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
+ imageReader!!.surface,
+ null, null
+ )
+ Log.d("ScreenCapture", "captureScreenshot: virtualDisplay=${virtualDisplay != null}")
+
+ Thread.sleep(500)
+
+ Log.d("ScreenCapture", "captureScreenshot: acquiring image from ImageReader")
+ val image = imageReader!!.acquireLatestImage()
+ Log.d("ScreenCapture", "captureScreenshot: image=${image != null}")
+ if (image != null) {
+ try {
+ val bitmap = try {
+ val plane = image.planes[0]
+ val buffer = plane.buffer
+ val pixelStride = plane.pixelStride
+ val rowStride = plane.rowStride
+ val w = screenWidth
+ val h = screenHeight
+ val srcBytes = ByteArray(buffer.remaining())
+ buffer.get(srcBytes)
+ // Create tightly-packed output (no row padding) with RGBA→ARGB swap
+ val packedBytes = ByteArray(w * h * 4)
+ for (row in 0 until h) {
+ val srcRow = row * rowStride
+ val dstRow = row * w * 4
+ for (col in 0 until w) {
+ val sp = srcRow + col * pixelStride
+ val dp = dstRow + col * 4
+ packedBytes[dp + 0] = srcBytes[sp + 2] // B ← R
+ packedBytes[dp + 1] = srcBytes[sp + 1] // G
+ packedBytes[dp + 2] = srcBytes[sp + 0] // R ← B
+ packedBytes[dp + 3] = srcBytes[sp + 3] // A
+ }
+ }
+ val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
+ bmp.copyPixelsFromBuffer(java.nio.ByteBuffer.wrap(packedBytes))
+ Log.d("ScreenCapture", "captureScreenshot: bitmap=${bmp.width}x${bmp.height} (stride=$rowStride, pxStride=$pixelStride)")
+ bmp
+ } catch (e: Exception) {
+ Log.e("ScreenCapture", "captureScreenshot: bitmap creation failed: ${e.message}")
+ null
+ }
+
+ if (bitmap != null) {
+ val stream = ByteArrayOutputStream()
+ bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
+ bitmap.recycle()
+ val pngBytes = stream.toByteArray()
+ Log.d("ScreenCapture", "captureScreenshot: PNG compressed ${pngBytes.size} bytes")
+ if (pngBytes.isNotEmpty()) {
+ val outPath = File(cacheDir, RESULT_FILE).absolutePath
+ File(outPath).writeBytes(pngBytes)
+ resultFilePath = outPath
+ Log.d("ScreenCapture", "captureScreenshot: saved to $outPath")
+ } else {
+ Log.e("ScreenCapture", "captureScreenshot: PNG compression produced 0 bytes")
+ resultFilePath = null
+ }
+ } else {
+ Log.e("ScreenCapture", "captureScreenshot: bitmap was null")
+ resultFilePath = null
+ }
+ } finally {
+ image.close()
+ }
+ } else {
+ Log.e("ScreenCapture", "captureScreenshot: acquireLatestImage returned null")
+ resultFilePath = null
+ }
+
+ resultReady.countDown()
+
+ virtualDisplay?.release()
+ imageReader?.close()
+ projection?.stop()
+ stopSelf()
+ }
+
+ private fun createNotificationChannel() {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ val channel = NotificationChannel(
+ CHANNEL_ID,
+ "Screenshot Capture",
+ NotificationManager.IMPORTANCE_LOW
+ ).apply { description = "One-shot screen capture" }
+ val nm = getSystemService(NotificationManager::class.java)
+ nm.createNotificationChannel(channel)
+ }
+ }
+
+ private fun buildNotification(): Notification {
+ return Notification.Builder(this, CHANNEL_ID)
+ .setContentTitle("Gotcha")
+ .setContentText("Capturing screenshot…")
+ .setSmallIcon(android.R.drawable.ic_menu_camera)
+ .build()
+ }
+
+ override fun onDestroy() {
+ virtualDisplay?.release()
+ imageReader?.close()
+ projection?.stop()
+ super.onDestroy()
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
index 238b316..70993e6 100644
--- a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
+++ b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
@@ -17,7 +17,8 @@ class AccessibilityTool(private val context: Context) {
/** Read the visible on-screen text of whatever app is in the foreground. */
fun readScreen(): ToolResult {
- val service = requireService() ?: return notEnabled()
+ val service = GotchaAccessibilityService.instance
+ if (service == null) return if (isEnabled()) serviceNotRunning() else notEnabled()
val lines = service.dumpScreenText()
return if (lines.isEmpty()) {
ToolResult.ok("No readable text is on screen right now.")
@@ -28,7 +29,8 @@ class AccessibilityTool(private val context: Context) {
/** Read screen text AND flag for full-resolution screenshot capture. */
fun readScreenRaw(): ToolResult {
- val service = requireService() ?: return notEnabled()
+ val service = GotchaAccessibilityService.instance
+ if (service == null) return if (isEnabled()) serviceNotRunning() else notEnabled()
val lines = service.dumpScreenText()
val text = if (lines.isEmpty()) "No readable text is on screen right now."
else lines.joinToString("\n") { "- $it" }
@@ -37,7 +39,7 @@ class AccessibilityTool(private val context: Context) {
/** Tap either an on-screen element matching [text], or absolute coordinates. */
fun tap(text: String?, x: Int?, y: Int?): ToolResult {
- val service = requireService() ?: return notEnabled()
+ val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()
return when {
!text.isNullOrBlank() ->
if (service.tapByText(text)) ToolResult.ok("Tapped an element matching \"$text\".")
@@ -51,7 +53,7 @@ class AccessibilityTool(private val context: Context) {
/** Swipe in a named direction, or between explicit coordinates. */
fun swipe(direction: String?, x1: Int?, y1: Int?, x2: Int?, y2: Int?, normalized: Boolean = false, distance: Int? = null): ToolResult {
- val service = requireService() ?: return notEnabled()
+ val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()
if (x1 != null && y1 != null && x2 != null && y2 != null) {
val (sx, sy, ex, ey) = if (normalized) {
val (w, h) = ScreenPerception.getScreenDimensions()
@@ -68,30 +70,30 @@ class AccessibilityTool(private val context: Context) {
val metrics = context.resources.displayMetrics
val w = metrics.widthPixels.toFloat()
val h = metrics.heightPixels.toFloat()
- val scrollPx = distance?.toFloat()?.takeIf { it > 0f } ?: (h * 0.4f)
+ val scrollPx = distance?.toFloat()?.takeIf { it > 0f } ?: (h * 0.6f)
val (sx, sy, ex, ey) = when (direction?.lowercase()?.trim()) {
- "up" -> listOf(w / 2, h * 0.6f, w / 2, h * 0.6f - scrollPx)
- "down" -> listOf(w / 2, h * 0.4f, w / 2, h * 0.4f + scrollPx)
- "left" -> listOf(w * 0.6f, h / 2, w * 0.6f - scrollPx, h / 2)
- "right" -> listOf(w * 0.4f, h / 2, w * 0.4f + scrollPx, h / 2)
+ "up" -> listOf(w / 2, h * 0.2f, w / 2, h * 0.2f + scrollPx)
+ "down" -> listOf(w / 2, h * 0.8f, w / 2, h * 0.8f - scrollPx)
+ "left" -> listOf(w * 0.2f, h / 2, w * 0.2f + scrollPx, h / 2)
+ "right" -> listOf(w * 0.8f, h / 2, w * 0.8f - scrollPx, h / 2)
else -> return ToolResult.error(
"Provide a direction (up/down/left/right) or explicit x1,y1,x2,y2 coordinates."
)
}
- return if (service.swipe(sx, sy, ex, ey)) ToolResult.ok("Swiped $direction.")
+ return if (service.swipe(sx, sy, ex, ey, 500)) ToolResult.ok("Swiped $direction.")
else ToolResult.error("Could not dispatch the swipe gesture.")
}
/** Type text into the currently focused input field. */
fun inputText(text: String): ToolResult {
- val service = requireService() ?: return notEnabled()
+ val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()
return if (service.typeText(text)) ToolResult.ok("Typed \"$text\" into the focused field.")
else ToolResult.error("No editable field is focused. Tap a text field first, then input text.")
}
/** Perform a device-wide navigation gesture via the accessibility service (back/home/recents/...). */
fun globalAction(action: String): ToolResult {
- val service = requireService() ?: return notEnabled()
+ val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()
return if (service.performGlobal(action)) ToolResult.ok("Performed global action: $action.")
else ToolResult.error(
"Unknown or unsupported global action '$action'. " +
@@ -101,7 +103,7 @@ class AccessibilityTool(private val context: Context) {
/** Tap a UI element by its index from the numbered elements list. */
fun tapByIndex(index: Int): ToolResult {
- val service = requireService() ?: return notEnabled()
+ val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()
val element = ScreenPerception.resolveElementByIndex(index)
?: return ToolResult.error("No UI element with index $index found on screen.")
val parts = element.bounds.split(",").map { it.trim().toIntOrNull() }
@@ -124,7 +126,7 @@ class AccessibilityTool(private val context: Context) {
val globalKeys = setOf("back", "home", "recents", "notifications", "quick_settings", "lock_screen")
if (k in globalKeys) return globalAction(k)
if (k == "enter") {
- val service = requireService() ?: return notEnabled()
+ val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()
try {
val root = service.rootInActiveWindow
val result = try {
@@ -143,7 +145,9 @@ class AccessibilityTool(private val context: Context) {
}
private fun requireService(): GotchaAccessibilityService? =
- if (isEnabled()) GotchaAccessibilityService.instance else null
+ GotchaAccessibilityService.instance ?: run {
+ if (isEnabled()) null else null // both cases return null, but error differs
+ }
private fun notEnabled() = ToolResult.permissionNeeded(
ToolResult.ACCESSIBILITY_ACCESS,
@@ -151,16 +155,28 @@ class AccessibilityTool(private val context: Context) {
"settings — please enable Gotcha there and ask again."
)
+ private fun serviceNotRunning() = ToolResult.error(
+ "The Gotcha accessibility service is enabled but not running. " +
+ "This can happen after an app restart. Please toggle it off and on in " +
+ "Settings → Accessibility, or force-stop and reopen the app."
+ )
+
/** True when this app's service is listed in the system's enabled-accessibility-services setting. */
private fun isEnabled(): Boolean {
- val expected = "${context.packageName}/${GotchaAccessibilityService::class.java.name}"
val enabled = Settings.Secure.getString(
context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
) ?: return false
+ val pkg = context.packageName
+ val cls = GotchaAccessibilityService::class.java.name
val splitter = TextUtils.SimpleStringSplitter(':')
splitter.setString(enabled)
while (splitter.hasNext()) {
- if (splitter.next().equals(expected, ignoreCase = true)) return true
+ val entry = splitter.next()
+ // Check long form (com.gotcha/com.gotcha.service.GotchaAccessibilityService)
+ if (entry.equals("$pkg/$cls", ignoreCase = true)) return true
+ // Check short form (com.gotcha/.service.GotchaAccessibilityService)
+ if (entry.equals("$pkg/.${cls.substringAfter(pkg)}", ignoreCase = true)) return true
+ if (entry.startsWith("$pkg/", ignoreCase = true) && entry.endsWith(cls.substringAfterLast('.'), ignoreCase = true)) return true
}
return false
}
diff --git a/app/src/main/java/com/gotcha/tools/ScreenPerception.kt b/app/src/main/java/com/gotcha/tools/ScreenPerception.kt
index d3d82cb..f0f0e16 100644
--- a/app/src/main/java/com/gotcha/tools/ScreenPerception.kt
+++ b/app/src/main/java/com/gotcha/tools/ScreenPerception.kt
@@ -8,14 +8,25 @@ import android.graphics.Paint
import android.graphics.Rect
import android.os.Build
import android.util.Base64
+import android.util.Log
import android.view.accessibility.AccessibilityNodeInfo
import com.gotcha.service.GotchaAccessibilityService
+import com.gotcha.service.MediaProjectionService
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
object ScreenPerception {
+ /** Set by MainActivity after the user grants MediaProjection consent. */
+ @Volatile
+ var mediaProjectionResultData: android.content.Intent? = null
+
+ /** Application context — set by ChatViewModel.init(). Used by captureRawBytes. */
+ @Volatile
+ var appContext: android.content.Context? = null
+
data class CompressedScreenshot(
val base64: String,
val width: Int,
@@ -41,11 +52,24 @@ object ScreenPerception {
quality: Int = 50,
drawGrid: Boolean = false
): CompressedScreenshot? {
- val bytes = captureRawBytes() ?: return null
+ Log.d("ScreenCapture", "compressScreenshot: starting capture...")
+ val bytes = captureRawBytes()
+ if (bytes == null) {
+ Log.e("ScreenCapture", "compressScreenshot: captureRawBytes returned null — all paths failed")
+ return null
+ }
+ Log.d("ScreenCapture", "compressScreenshot: got ${bytes.size} raw bytes")
val originalSize = bytes.size.toLong()
- val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return null
+ val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
+ if (bitmap == null) {
+ Log.e("ScreenCapture", "compressScreenshot: BitmapFactory.decodeByteArray returned null — invalid image data")
+ return null
+ }
+ Log.d("ScreenCapture", "compressScreenshot: decoded bitmap ${bitmap.width}x${bitmap.height}")
val scaled = if (maxDimension > 0) downscale(bitmap, maxDimension) else bitmap
if (scaled != bitmap) bitmap.recycle()
+ val sw = scaled.width
+ val sh = scaled.height
val (forEncoding, recycleForEncoding) = if (drawGrid) {
drawCoordinateGrid(scaled) to true
} else {
@@ -63,7 +87,7 @@ object ScreenPerception {
Bitmap.CompressFormat.WEBP_LOSSLESS -> "webp"
else -> "jpeg"
}
- return CompressedScreenshot(base64, scaled.width, scaled.height, fmtName, originalSize)
+ return CompressedScreenshot(base64, sw, sh, fmtName, originalSize)
}
fun buildUiHierarchyText(maxElements: Int = 100): String {
@@ -186,15 +210,60 @@ object ScreenPerception {
return result
}
+ /** Public entry point: capture raw screenshot PNG bytes. */
+ suspend fun captureRawScreenshotBytes(): ByteArray? = captureRawBytes()
+
private suspend fun captureRawBytes(): ByteArray? {
+ // Path 1: AccessibilityService.takeScreenshot() — API 30+, no special perms.
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ val service = GotchaAccessibilityService.instance
+ Log.d("ScreenCapture", "Path1: API>=30, service=${service != null}")
+ if (service != null) {
+ for (attempt in 1..2) {
+ Log.d("ScreenCapture", "Path1: takeScreenshotBitmap attempt $attempt")
+ val bitmap = service.takeScreenshotBitmap()
+ Log.d("ScreenCapture", "Path1: takeScreenshotBitmap returned ${bitmap != null}")
+ if (bitmap != null) {
+ val bytes = withContext(Dispatchers.Default) {
+ val stream = ByteArrayOutputStream()
+ bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
+ bitmap.recycle()
+ stream.toByteArray()
+ }
+ Log.d("ScreenCapture", "Path1: compressed to ${bytes.size} bytes")
+ if (bytes.isNotEmpty()) return bytes
+ }
+ if (attempt < 2) delay(1100)
+ }
+ Log.w("ScreenCapture", "Path1: both attempts failed")
+ }
+ }
+ // Path 2: MediaProjection — works on all devices if user granted consent.
+ val projectionData = mediaProjectionResultData
+ val ctx = appContext ?: GotchaAccessibilityService.instance?.applicationContext
+ Log.d("ScreenCapture", "Path2: projectionData=${projectionData != null}, ctx=${ctx != null}, appContext=${appContext != null}")
+ if (projectionData != null && ctx != null) {
+ Log.d("ScreenCapture", "Path2: calling MediaProjectionService.capture()")
+ val bytes = withContext(Dispatchers.IO) {
+ MediaProjectionService.capture(ctx, projectionData)
+ }
+ Log.d("ScreenCapture", "Path2: MediaProjectionService.capture returned ${bytes?.size ?: "null"} bytes")
+ if (bytes != null && bytes.isNotEmpty()) return bytes
+ }
+ // Path 3: screencap via shell (works on rooted devices / emulators).
+ Log.d("ScreenCapture", "Path3: trying screencap -p")
return try {
withContext(Dispatchers.IO) {
val process = Runtime.getRuntime().exec("screencap -p")
val bytes = process.inputStream.use { it.readBytes() }
process.waitFor()
+ Log.d("ScreenCapture", "Path3: screencap returned ${bytes.size} bytes, exit=${process.exitValue()}")
if (bytes.isEmpty()) null else bytes
}
- } catch (_: Exception) { null }
+ } catch (e: Exception) {
+ Log.e("ScreenCapture", "Path3: screencap failed: ${e.message}")
+ null
+ }
}
private fun downscale(bitmap: Bitmap, maxDim: Int): Bitmap {
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index e9f0e88..f5de64b 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -1286,10 +1286,6 @@ object ToolDefinitions {
put("type", "boolean")
put("description", "If true, coordinate params are in [0, 1000] normalized space. Default false.")
}
- putJsonObject("distance") {
- put("type", "integer")
- put("description", "Scroll distance in pixels. Default 0 = full screen (70% of dimension). Ignored when using explicit coordinates.")
- }
}
}
)
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index 067cdbd..112ccac 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -360,8 +360,7 @@ class ToolExecutor(
direction = args.requireString("direction"),
x1 = args.requireInt("x1"), y1 = args.requireInt("y1"),
x2 = args.requireInt("x2"), y2 = args.requireInt("y2"),
- normalized = args.requireBoolean("normalized") ?: false,
- distance = args.requireInt("distance")
+ normalized = args.requireBoolean("normalized") ?: false
)
"tap_index" -> {
val index = args.requireInt("index") ?: return missing("index")
diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
index f0fcf60..733dfa4 100644
--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
@@ -80,18 +80,13 @@ object ToolRegistry {
}
)),
"swipe" to ToolDefinition(function = FunctionDefinition("swipe",
- "Swipe a direction (up/down/left/right) or between coordinates.",
+ "Scroll the screen in a direction. Each swipe scrolls about half the screen.",
buildJsonObject {
put("type", "object")
putJsonObject("properties") {
- putJsonObject("direction") { put("type", "string"); put("description", "up/down/left/right") }
- putJsonObject("x1") { put("type", "integer"); put("description", "Start X") }
- putJsonObject("y1") { put("type", "integer"); put("description", "Start Y") }
- putJsonObject("x2") { put("type", "integer"); put("description", "End X") }
- putJsonObject("y2") { put("type", "integer"); put("description", "End Y") }
- putJsonObject("normalized") { put("type", "boolean"); put("description", "Coords in [0,1000]") }
- putJsonObject("distance") { put("type", "integer"); put("description", "Pixels to scroll") }
+ putJsonObject("direction") { put("type", "string"); put("description", "up, down, left, or right") }
}
+ putJsonArray("required") { add("direction") }
}
)),
"input_text" to ToolDefinition(function = FunctionDefinition("input_text",