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.

refactor: single top-bar share menu, extract SharePosterState, guard poster screenshot decode

Rishabh Bajpaie75010a5dfe0
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 814ebfb..02c24a5 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -41,7 +41,6 @@ import com.gotcha.audio.ModelCategory
import com.gotcha.auth.SamosaAuthManager
import com.gotcha.auth.SamosaSignInResult
import com.gotcha.data.LEGAL_VERSION
-import com.gotcha.data.RunSummary
import com.gotcha.data.Settings
import com.gotcha.data.SettingsRepository
import com.gotcha.llm.ChatMessage
@@ -60,6 +59,7 @@ import com.gotcha.ui.NotificationDetailDialog
import com.gotcha.ui.SettingsPage
import com.gotcha.ui.SettingsScreen
import com.gotcha.ui.SharePosterSheet
+import com.gotcha.ui.SharePosterState
import com.gotcha.ui.theme.GotchaTheme
import com.gotcha.ui.theme.SkinBackdrop
import com.gotcha.ui.theme.Skins
@@ -104,7 +104,7 @@ private fun routeForTourPlace(place: TourPlace): Pair<Route, SettingsPage?> = wh
TourPlace.PERSONAL_INFO -> Route.SETTINGS to SettingsPage.PERSONAL_INFO
}
-@Suppress("LargeClass", "TooManyFunctions")
+@Suppress("LargeClass")
class MainActivity : ComponentActivity() {
private val chatViewModel: ChatViewModel by viewModels()
@@ -124,12 +124,7 @@ class MainActivity : ComponentActivity() {
private var appearance by mutableStateOf(Appearance())
// ---- "Share your Gotcha moment" poster state ----
- /** Runs the poster is being built from (null = sheet closed). */
- private var shareRuns by mutableStateOf<List<RunSummary>?>(null)
- private var shareLoading by mutableStateOf(false)
- private var sharePreview by mutableStateOf<android.graphics.Bitmap?>(null)
- private var shareError by mutableStateOf<String?>(null)
- private var shareIncludeScreenshot by mutableStateOf(false)
+ private val sharePoster: SharePosterState by lazy { SharePosterState(this, chatViewModel) }
/**
* ETag-style version of the legal bundle the user has accepted. Empty until
@@ -769,11 +764,11 @@ class MainActivity : ComponentActivity() {
},
onShareMessage = { message ->
chatViewModel.activeSessionRunSummaries().lastOrNull()?.let {
- openShareSheet(listOf(it))
+ sharePoster.open(listOf(it))
}
},
onCreateShareCard = {
- openShareSheet(chatViewModel.activeSessionRunSummaries())
+ sharePoster.open(chatViewModel.activeSessionRunSummaries())
}
)
}
@@ -799,28 +794,17 @@ class MainActivity : ComponentActivity() {
)
}
- shareRuns?.let { runs ->
+ sharePoster.runs?.let { runs ->
SharePosterSheet(
runs = runs,
- loading = shareLoading,
- preview = sharePreview,
- error = shareError,
- onGenerate = { includeScreenshot ->
- shareIncludeScreenshot = includeScreenshot
- generateSharePoster(includeScreenshot)
- },
- onShare = { sharePreview?.let { sharePoster(it) } },
- onSave = { sharePreview?.let { savePoster(it) } },
- onRegenerate = { includeScreenshot ->
- shareIncludeScreenshot = includeScreenshot
- generateSharePoster(includeScreenshot)
- },
- onDismiss = {
- shareRuns = null
- shareLoading = false
- sharePreview = null
- shareError = null
- }
+ loading = sharePoster.loading,
+ preview = sharePoster.preview,
+ error = sharePoster.error,
+ onGenerate = sharePoster::generate,
+ onShare = { sharePoster.preview?.let { sharePoster.share(it) } },
+ onSave = { sharePoster.preview?.let { sharePoster.save(it) } },
+ onRegenerate = sharePoster::generate,
+ onDismiss = sharePoster::dismiss
)
}
@@ -898,74 +882,4 @@ class MainActivity : ComponentActivity() {
}
firstLaunchLauncher.launch(perms.toTypedArray())
}
-
- // ---- "Share your Gotcha moment" poster flow ----
-
- /** Opens the poster sheet for [runs] (single latest run or whole chat). */
- private fun openShareSheet(runs: List<RunSummary>) {
- if (runs.isEmpty()) {
- Toast.makeText(this, "Nothing to share yet.", Toast.LENGTH_SHORT).show()
- return
- }
- shareRuns = runs
- shareLoading = false
- sharePreview = null
- shareError = null
- }
-
- /** Generates the poster (one LLM call + render). */
- private fun generateSharePoster(includeScreenshot: Boolean) {
- val runs = shareRuns ?: return
- shareLoading = true
- sharePreview = null
- shareError = null
- lifecycleScope.launch {
- val result = chatViewModel.generateShareCard(runs, includeScreenshot)
- shareLoading = false
- result.fold(
- onSuccess = { sharePreview = it },
- onFailure = { e ->
- shareError = e.message ?: "Could not generate the poster."
- }
- )
- }
- }
-
- /** Shares the generated poster via the Android share sheet (FileProvider). */
- private fun sharePoster(bitmap: android.graphics.Bitmap) {
- try {
- val dir = java.io.File(cacheDir, "poster")
- dir.mkdirs()
- val file = java.io.File(dir, "gotcha_moment_${System.currentTimeMillis()}.png")
- file.outputStream().use { out -> bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, out) }
- val uri = androidx.core.content.FileProvider.getUriForFile(
- this,
- "$packageName.fileprovider",
- file
- )
- val intent = Intent(Intent.ACTION_SEND).apply {
- type = "image/png"
- putExtra(Intent.EXTRA_STREAM, uri)
- putExtra(Intent.EXTRA_SUBJECT, "Gotcha just did this for me")
- addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
- }
- startActivity(Intent.createChooser(intent, "Share your Gotcha moment"))
- } catch (e: Exception) {
- Toast.makeText(this, "Could not share: ${e.message}", Toast.LENGTH_SHORT).show()
- }
- }
-
- /** Saves the generated poster to the device gallery. */
- private fun savePoster(bitmap: android.graphics.Bitmap) {
- try {
- val location = com.gotcha.data.GotchaStorage.saveScreenshot(
- this,
- "gotcha_moment_${System.currentTimeMillis()}.png",
- bitmap
- )
- Toast.makeText(this, "Saved to $location", Toast.LENGTH_SHORT).show()
- } catch (e: Exception) {
- Toast.makeText(this, "Could not save: ${e.message}", Toast.LENGTH_SHORT).show()
- }
- }
}
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index c25673c..608304a 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -1096,6 +1096,11 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
/**
* Best-effort screenshot for the poster thumbnail: the newest PNG in the
* engine session's working dir, else a fresh screen capture, else null.
+ *
+ * Guarded so a huge or malformed PNG can't OOM the decode: files over
+ * [MAX_SHARE_SCREENSHOT_BYTES] are skipped, and anything larger than
+ * [MAX_SHARE_SCREENSHOT_DIM] on either side is downsampled before decoding
+ * (the poster draws the thumbnail at 460×345, so full-res is wasteful).
*/
private fun loadShareScreenshot(): Bitmap? {
val dir = com.gotcha.data.GotchaStorage.subdir(
@@ -1106,7 +1111,19 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
?.maxByOrNull { it.lastModified() }
if (newest != null) {
return try {
- BitmapFactory.decodeFile(newest.absolutePath)
+ if (newest.length() > MAX_SHARE_SCREENSHOT_BYTES) return null
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ BitmapFactory.decodeFile(newest.absolutePath, bounds)
+ val w = bounds.outWidth
+ val h = bounds.outHeight
+ if (w <= 0 || h <= 0) return null
+ val options = BitmapFactory.Options().apply {
+ inSampleSize = when {
+ w <= MAX_SHARE_SCREENSHOT_DIM && h <= MAX_SHARE_SCREENSHOT_DIM -> 1
+ else -> maxOf(w, h) / MAX_SHARE_SCREENSHOT_DIM
+ }
+ }
+ BitmapFactory.decodeFile(newest.absolutePath, options)
} catch (_: Exception) {
null
}
@@ -1153,5 +1170,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
private companion object {
const val GATE_TIMEOUT_MS = 120_000L
const val MIGRATED_CHAT_DIRS_KEY = "migrated_chat_dirs_v1"
+
+ /** Poster-thumbnail screenshot guards (see [loadShareScreenshot]). */
+ const val MAX_SHARE_SCREENSHOT_BYTES = 50L * 1024 * 1024
+ const val MAX_SHARE_SCREENSHOT_DIM = 2048
}
}
diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
index 482bc9e..40ebf3f 100644
--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
@@ -30,7 +30,6 @@ import androidx.compose.material.icons.automirrored.rounded.VolumeUp
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Mic
-import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Send
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.Stop
@@ -224,10 +223,7 @@ fun ChatScreen(
)
}
}
- IconButton(onClick = onExportChat, enabled = !state.isBusy) {
- Icon(Icons.Default.Share, contentDescription = "Export chat")
- }
- ShareCardMenu(
+ ChatShareMenu(
onExportChat = onExportChat,
onCreateShareCard = onCreateShareCard,
enabled = !state.isBusy
@@ -661,11 +657,12 @@ fun ChatScreen(
}
/**
- * Overflow menu in the chat top bar: chat export plus the "Create share card"
- * (whole-chat aggregation) entry point for the marketing poster.
+ * Share menu in the chat top bar, reached from a single share icon: the
+ * markdown chat export plus the "Create share card" (whole-chat aggregation)
+ * entry point for the marketing poster.
*/
@Composable
-private fun ShareCardMenu(
+private fun ChatShareMenu(
onExportChat: () -> Unit,
onCreateShareCard: () -> Unit,
enabled: Boolean
@@ -673,7 +670,7 @@ private fun ShareCardMenu(
var expanded by remember { mutableStateOf(false) }
Box {
IconButton(onClick = { expanded = true }, enabled = enabled) {
- Icon(Icons.Default.MoreVert, contentDescription = "More options")
+ Icon(Icons.Default.Share, contentDescription = "Share chat")
}
DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
DropdownMenuItem(
diff --git a/app/src/main/java/com/gotcha/ui/SharePosterState.kt b/app/src/main/java/com/gotcha/ui/SharePosterState.kt
new file mode 100644
index 0000000..c9ed133
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/SharePosterState.kt
@@ -0,0 +1,111 @@
+package com.gotcha.ui
+
+import android.content.Context
+import android.content.Intent
+import android.graphics.Bitmap
+import android.widget.Toast
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import androidx.core.content.FileProvider
+import androidx.lifecycle.viewModelScope
+import com.gotcha.agent.ChatViewModel
+import com.gotcha.data.GotchaStorage
+import com.gotcha.data.RunSummary
+import kotlinx.coroutines.launch
+
+/**
+ * State + flow for the "Share your Gotcha moment" poster sheet.
+ *
+ * Owns the sheet's open/loading/preview/error state and the generate/share/save
+ * actions so [android.app.Activity] hosts stay thin. The LLM copy call runs on
+ * [ChatViewModel.viewModelScope]; the render hops to the main thread inside
+ * [ChatViewModel.generateShareCard].
+ */
+class SharePosterState(
+ private val context: Context,
+ private val viewModel: ChatViewModel
+) {
+ /** Runs the poster is being built from (null = sheet closed). */
+ var runs by mutableStateOf<List<RunSummary>?>(null)
+ private set
+ var loading by mutableStateOf(false)
+ private set
+ var preview by mutableStateOf<Bitmap?>(null)
+ private set
+ var error by mutableStateOf<String?>(null)
+ private set
+
+ /** Opens the poster sheet for [runs] (single latest run or whole chat). */
+ fun open(runs: List<RunSummary>) {
+ if (runs.isEmpty()) {
+ Toast.makeText(context, "Nothing to share yet.", Toast.LENGTH_SHORT).show()
+ return
+ }
+ this.runs = runs
+ loading = false
+ preview = null
+ error = null
+ }
+
+ /** Generates the poster (one LLM call + render) for the sheet's [runs]. */
+ fun generate(includeScreenshot: Boolean) {
+ val runs = this.runs ?: return
+ loading = true
+ preview = null
+ error = null
+ viewModel.viewModelScope.launch {
+ val result = viewModel.generateShareCard(runs, includeScreenshot)
+ loading = false
+ result.fold(
+ onSuccess = { preview = it },
+ onFailure = { e ->
+ error = e.message ?: "Could not generate the poster."
+ }
+ )
+ }
+ }
+
+ /** Shares the generated poster via the Android share sheet (FileProvider). */
+ fun share(bitmap: Bitmap) {
+ try {
+ val dir = java.io.File(context.cacheDir, "poster")
+ dir.mkdirs()
+ val file = java.io.File(dir, "gotcha_moment_${System.currentTimeMillis()}.png")
+ file.outputStream().use { out -> bitmap.compress(Bitmap.CompressFormat.PNG, 100, out) }
+ val uri = FileProvider.getUriForFile(
+ context,
+ "${context.packageName}.fileprovider",
+ file
+ )
+ val intent = Intent(Intent.ACTION_SEND).apply {
+ type = "image/png"
+ putExtra(Intent.EXTRA_STREAM, uri)
+ putExtra(Intent.EXTRA_SUBJECT, "Gotcha just did this for me")
+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ }
+ context.startActivity(Intent.createChooser(intent, "Share your Gotcha moment"))
+ } catch (e: Exception) {
+ Toast.makeText(context, "Could not share: ${e.message}", Toast.LENGTH_SHORT).show()
+ }
+ }
+
+ /** Saves the generated poster to the device gallery. */
+ fun save(bitmap: Bitmap) {
+ try {
+ val location = GotchaStorage.saveScreenshot(
+ context,
+ "gotcha_moment_${System.currentTimeMillis()}.png",
+ bitmap
+ )
+ Toast.makeText(context, "Saved to $location", Toast.LENGTH_SHORT).show()
+ } catch (e: Exception) {
+ Toast.makeText(context, "Could not save: ${e.message}", Toast.LENGTH_SHORT).show()
+ }
+ }
+
+ /** Closes the sheet. */
+ fun dismiss() {
+ runs = null
+ }
+}