mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Show recent photos in place of the keyboard when attaching to the agent (#3702)
* Show recent photos in place of the keyboard in the agent composer The attach button opens a tray, at the keyboard's height, of the device's recent pictures; a tap attaches or detaches one. The tray also opens the system file picker and asks for photo access when the app has none. * Agent instructions: manifest needs an APK; the agent resumes after a Lab build restart * Skip the tray's back handler where the host has no back dispatcher * Offer the photo tray in windows that cannot open pickers, such as the floating pet * Fix the tray's permission request for windows without a registry * Move the game screenshot button into the photo tray * Name only the model in the agent's compact chip * Keep the session drawer open while the tray's picker or photo permission prompt is up * Address review: tray height on short screens, denied photo access, kept photo marks, tile labels, Lab build refusals * Keep tray photos being copied across the tray closing * Let a tray photo copy clear only its own in-progress marker * Review: one attachment file per copy, photo tile labels, superseded copies attach nothing * Drop tray photo copies still running when the message is sent
This commit is contained in:
1 parent
de3ed8b986
commit
77fffa7592
38 files changed
+526
-61
No files matched your search
@@ -22,6 +22,12 @@ object AgentAttachments {
|
||||
/** True while the file picker is open over a session: it answers the drawer's agent page, so the drawer must stay. */
|
||||
@Volatile var picking = false
|
||||
|
||||
/** Launches a system screen that answers the agent page, keeping the drawer for it; the result callback clears [picking]. */
|
||||
fun pick(launch: () -> Unit) {
|
||||
picking = true
|
||||
if (runCatching(launch).isFailure) picking = false
|
||||
}
|
||||
|
||||
private const val NEW = "new"
|
||||
private const val GUEST_DIR = "/root/.cache/droiddeck/attachments"
|
||||
private val IMAGE = setOf("png", "jpg", "jpeg", "webp", "gif", "bmp")
|
||||
@@ -38,14 +44,17 @@ object AgentAttachments {
|
||||
val folder = chat ?: NEW
|
||||
val dir = File(hostDir(app), folder).apply { mkdirs() }
|
||||
return uris.mapNotNull { uri ->
|
||||
var target: File? = null
|
||||
runCatching {
|
||||
val name = displayName(app, uri).replace(Regex("[^A-Za-z0-9._-]"), "_").ifEmpty { "file" }
|
||||
var target = File(dir, name)
|
||||
var candidate = File(dir, name)
|
||||
var n = 1
|
||||
while (target.exists()) target = File(dir, "${name.substringBeforeLast('.')}-${n++}${name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }}")
|
||||
app.contentResolver.openInputStream(uri)!!.use { input -> target.outputStream().use { input.copyTo(it) } }
|
||||
"$GUEST_DIR/$folder/${target.name}"
|
||||
}.getOrNull()
|
||||
// Created atomically, so copies running side by side never pick the same name.
|
||||
while (!candidate.createNewFile()) candidate = File(dir, "${name.substringBeforeLast('.')}-${n++}${name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }}")
|
||||
target = candidate
|
||||
app.contentResolver.openInputStream(uri)!!.use { input -> candidate.outputStream().use { input.copyTo(it) } }
|
||||
"$GUEST_DIR/$folder/${candidate.name}"
|
||||
}.onFailure { target?.delete() }.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,9 @@ import android.content.ContextWrapper
|
||||
import android.os.Build
|
||||
import android.view.KeyEvent
|
||||
import android.view.WindowManager
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.LocalActivityResultRegistryOwner
|
||||
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.animation.expandVertically
|
||||
@@ -50,12 +52,12 @@ import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.outlined.Send
|
||||
import androidx.compose.material.icons.outlined.Extension
|
||||
import androidx.compose.material.icons.outlined.PhotoCamera
|
||||
import androidx.compose.material.icons.outlined.MicOff
|
||||
import androidx.compose.material.icons.outlined.Mic
|
||||
import androidx.compose.material.icons.outlined.Add
|
||||
import androidx.compose.material.icons.outlined.ArrowDownward
|
||||
import androidx.compose.material.icons.outlined.AttachFile
|
||||
import androidx.compose.material.icons.outlined.Keyboard
|
||||
import androidx.compose.material.icons.outlined.Terminal
|
||||
import androidx.compose.material.icons.outlined.Build
|
||||
import androidx.compose.material.icons.outlined.Close
|
||||
@@ -79,6 +81,7 @@ import androidx.compose.runtime.MutableState
|
||||
import androidx.compose.runtime.Stable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
@@ -108,6 +111,7 @@ import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.platform.testTag
|
||||
@@ -301,7 +305,7 @@ private fun AgentPageContent(
|
||||
readingBack = false
|
||||
scope.launch { list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2) }
|
||||
}
|
||||
val hidden = !composer.focused && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() &&
|
||||
val hidden = !composer.focused && !composer.tray && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() &&
|
||||
AgentHost.approvals.isEmpty()
|
||||
var listHeight by remember { mutableIntStateOf(0) }
|
||||
Box(
|
||||
@@ -319,6 +323,7 @@ private fun AgentPageContent(
|
||||
awaitEachGesture {
|
||||
awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
|
||||
if (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE) panel = AgentPanel.NONE
|
||||
composer.tray = false
|
||||
// Forced: the unforced path walks the focus chain and throws ("ActiveParent with no focused child") when a tap lands while focus is moving.
|
||||
if (composer.focused) focusManager.clearFocus(force = true)
|
||||
}
|
||||
@@ -344,6 +349,12 @@ private fun AgentPageContent(
|
||||
@Stable
|
||||
private class ComposerState {
|
||||
var focused by mutableStateOf(false)
|
||||
/** The photo tray stands in for the keyboard, at the height the keyboard last had. */
|
||||
var tray by mutableStateOf(false)
|
||||
var keyboardHeight by mutableStateOf(0.dp)
|
||||
/** Tray photos copied, or being copied, for this conversation, so reopening the tray keeps their marks and copies nothing twice. */
|
||||
val photoCopies = mutableStateMapOf<android.net.Uri, String>()
|
||||
val photosCopying = mutableStateMapOf<android.net.Uri, Any>()
|
||||
var focusRequests by mutableIntStateOf(0)
|
||||
private set
|
||||
private var consumedFocusRequests by mutableIntStateOf(0)
|
||||
@@ -390,7 +401,7 @@ private fun ModelChip(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstCon
|
||||
.clickable { onPanel(AgentPanel.MODEL) }.padding(horizontal = 8.dp).testTag("agent-model"),
|
||||
) {
|
||||
val mode = AgentHost.harness.permissions.drop(1).firstOrNull { it.id == AgentHost.permission }?.let { stringResource(it.label) }
|
||||
val parts = if (compact) listOfNotNull(mode ?: model)
|
||||
val parts = if (compact) listOf(model)
|
||||
else listOfNotNull(
|
||||
AgentHost.harness.name, model, AgentHost.effort, mode,
|
||||
stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans },
|
||||
@@ -748,6 +759,8 @@ private fun AgentComposer(
|
||||
if (text.isEmpty() && AgentAttachments.pending.isEmpty()) return@send
|
||||
AgentHost.send(context, text, AgentAttachments.pending.toList())
|
||||
AgentAttachments.pending.clear()
|
||||
composer.photosCopying.clear()
|
||||
composer.tray = false
|
||||
onSent()
|
||||
}
|
||||
}
|
||||
@@ -813,7 +826,34 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
val field = remember { FocusRequester() }
|
||||
LaunchedEffect(composer.focusRequests) { if (composer.hasUnconsumedFocusRequest()) runCatching { field.requestFocus() } }
|
||||
val attach = LocalActivityResultRegistryOwner.current != null
|
||||
val picks = LocalActivityResultRegistryOwner.current != null
|
||||
val density = LocalDensity.current
|
||||
val imeHeight = WindowInsets.ime.getBottom(density)
|
||||
LaunchedEffect(imeHeight) {
|
||||
val height = with(density) { imeHeight.toDp() }
|
||||
if (height > composer.keyboardHeight) composer.keyboardHeight = height
|
||||
}
|
||||
LaunchedEffect(hideAttach) { if (hideAttach) composer.tray = false }
|
||||
LaunchedEffect(AgentHost.chat) {
|
||||
composer.photoCopies.clear()
|
||||
composer.photosCopying.clear()
|
||||
}
|
||||
// BackHandler throws where the host provides no back dispatcher: the front end and the floating pet.
|
||||
if (LocalOnBackPressedDispatcherOwner.current != null) BackHandler(composer.tray) { composer.tray = false }
|
||||
val focusManager = LocalFocusManager.current
|
||||
val files = if (picks) rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) {
|
||||
AgentAttachments.picking = false
|
||||
attachUris(context, it)
|
||||
} else null
|
||||
val toggleTray = {
|
||||
if (composer.tray) {
|
||||
composer.tray = false
|
||||
composer.open()
|
||||
} else {
|
||||
focusManager.clearFocus(force = true)
|
||||
composer.tray = true
|
||||
}
|
||||
}
|
||||
BoxWithConstraints(
|
||||
Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape16).background(colors.surface)
|
||||
.border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16).padding(6.dp),
|
||||
@@ -841,6 +881,7 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
|
||||
Modifier.fillMaxWidth().focusRequester(field).onFocusChanged {
|
||||
focused = it.isFocused
|
||||
composer.focused = it.isFocused
|
||||
if (it.isFocused) composer.tray = false
|
||||
if (it.isFocused) composer.consumeFocusRequest()
|
||||
}.testTag("agent-input"),
|
||||
textStyle = TextStyle(fontSize = 16.sp, color = colors.onSurface),
|
||||
@@ -866,19 +907,22 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
|
||||
if (stacked) Column {
|
||||
text(Modifier.fillMaxWidth())
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
|
||||
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() }
|
||||
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() }
|
||||
AnimatedVisibility(!hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton(composer.tray, toggleTray) }
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp).horizontalScroll(rememberScrollState(), reverseScrolling = true)) { if (controls != null && !focused) controls() }
|
||||
actions()
|
||||
}
|
||||
} else Row(verticalAlignment = Alignment.Bottom) {
|
||||
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() }
|
||||
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() }
|
||||
AnimatedVisibility(!hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton(composer.tray, toggleTray) }
|
||||
text(Modifier.weight(1f))
|
||||
if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() }
|
||||
actions()
|
||||
}
|
||||
}
|
||||
AnimatedVisibility(composer.tray, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
|
||||
val most = LocalConfiguration.current.screenHeightDp.dp * 0.45f
|
||||
val height = (if (composer.keyboardHeight > 0.dp) composer.keyboardHeight else 280.dp).coerceAtLeast(160.dp).coerceAtMost(most)
|
||||
AgentPhotoTray(height, composer.photoCopies, composer.photosCopying, files?.let { { AgentAttachments.pick { it.launch(arrayOf("*/*")) } } })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -974,53 +1018,15 @@ private fun VoiceButton(voice: AgentVoice, onStart: () -> Unit, onSend: () -> Un
|
||||
}
|
||||
}
|
||||
|
||||
/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */
|
||||
/** Opens the photo tray in place of the keyboard; while it is open, brings the keyboard back. */
|
||||
@Composable
|
||||
private fun GameFrameButton() {
|
||||
val context = LocalContext.current
|
||||
private fun AttachButton(trayOpen: Boolean, onClick: () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
RoundButton(Icons.Outlined.PhotoCamera, stringResource(R.string.agent_attach_game), pal.surfaceVariant, pal.onBackground, "agent-game-frame") {
|
||||
val grab = AgentAttachments.gameFrame ?: return@RoundButton
|
||||
val chat = AgentHost.chat
|
||||
grab frame@{ frame ->
|
||||
if (frame == null) {
|
||||
android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return@frame
|
||||
}
|
||||
Thread({
|
||||
val path = AgentAttachments.saveFrame(context, chat, frame)
|
||||
frame.recycle()
|
||||
android.os.Handler(android.os.Looper.getMainLooper()).post {
|
||||
when {
|
||||
path == null -> android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show()
|
||||
AgentHost.chat == chat -> AgentAttachments.pending.add(path)
|
||||
else -> AgentAttachments.discard(context, listOf(path))
|
||||
}
|
||||
}
|
||||
}, "agent-game-frame").start()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AttachButton() {
|
||||
val context = LocalContext.current
|
||||
val pal = LocalPalette.current
|
||||
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
|
||||
AgentAttachments.picking = false
|
||||
if (uris.isEmpty()) return@rememberLauncherForActivityResult
|
||||
val chat = AgentHost.chat
|
||||
Thread({
|
||||
val paths = AgentAttachments.copy(context, chat, uris)
|
||||
android.os.Handler(android.os.Looper.getMainLooper()).post {
|
||||
if (AgentHost.chat == chat) AgentAttachments.pending.addAll(paths) else AgentAttachments.discard(context, paths)
|
||||
}
|
||||
}, "agent-attach").start()
|
||||
}
|
||||
RoundButton(Icons.Outlined.AttachFile, stringResource(R.string.agent_attach), pal.surfaceVariant, pal.onBackground, "agent-attach") {
|
||||
AgentAttachments.picking = true
|
||||
if (runCatching { picker.launch(arrayOf("*/*")) }.isFailure) AgentAttachments.picking = false
|
||||
}
|
||||
RoundButton(
|
||||
if (trayOpen) Icons.Outlined.Keyboard else Icons.Outlined.AttachFile,
|
||||
stringResource(if (trayOpen) R.string.agent_keyboard else R.string.agent_attach),
|
||||
if (trayOpen) pal.primary else pal.surfaceVariant, if (trayOpen) pal.onPrimary else pal.onBackground, "agent-attach", onClick = onClick,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.Manifest
|
||||
import android.content.ContentUris
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.MediaStore
|
||||
import android.provider.Settings
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.LocalActivityResultRegistryOwner
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
import androidx.compose.foundation.lazy.grid.GridItemSpan
|
||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||
import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Check
|
||||
import androidx.compose.material.icons.outlined.FolderOpen
|
||||
import androidx.compose.material.icons.outlined.PhotoCamera
|
||||
import androidx.compose.material.icons.outlined.PhotoLibrary
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshots.SnapshotStateMap
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalLifecycleOwner
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.selected
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import coil.compose.AsyncImage
|
||||
import coil.request.ImageRequest
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.agent.AgentAttachments
|
||||
import com.droiddeck.launcher.agent.AgentHost
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** The device's photos, newest first, as MediaStore lets the app see them. */
|
||||
internal object AgentPhotos {
|
||||
enum class Access { NONE, SELECTED, ALL }
|
||||
|
||||
/** Android stops showing the request after repeated denials and answers it at once, so a denied request sends later ones to Settings. */
|
||||
var refused = false
|
||||
|
||||
fun permissions(sdk: Int = Build.VERSION.SDK_INT): Array<String> = when {
|
||||
sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE -> arrayOf(Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED)
|
||||
sdk >= Build.VERSION_CODES.TIRAMISU -> arrayOf(Manifest.permission.READ_MEDIA_IMAGES)
|
||||
else -> arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
|
||||
}
|
||||
|
||||
fun access(context: Context): Access {
|
||||
fun granted(permission: String) = context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
|
||||
val all = permissions().first()
|
||||
return when {
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && Environment.isExternalStorageManager() -> Access.ALL
|
||||
granted(all) -> Access.ALL
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && granted(Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED) -> Access.SELECTED
|
||||
else -> Access.NONE
|
||||
}
|
||||
}
|
||||
|
||||
class Photo(val uri: Uri, val name: String)
|
||||
|
||||
fun recent(context: Context, limit: Int = 300): List<Photo> = runCatching {
|
||||
val images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
|
||||
context.contentResolver.query(
|
||||
images, arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME), null, null, "${MediaStore.Images.Media.DATE_ADDED} DESC",
|
||||
)?.use { c ->
|
||||
buildList {
|
||||
while (size < limit && c.moveToNext()) add(Photo(ContentUris.withAppendedId(images, c.getLong(0)), c.getString(1).orEmpty()))
|
||||
}
|
||||
}.orEmpty()
|
||||
}.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies [uris] into the conversation's attachments off the main thread, then hands [onCopied] what was attached: nothing if the
|
||||
* conversation changed meanwhile or [current] says the copy was superseded.
|
||||
*/
|
||||
internal fun attachUris(context: Context, uris: List<Uri>, current: () -> Boolean = { true }, onCopied: (List<Pair<Uri, String>>) -> Unit = {}) {
|
||||
if (uris.isEmpty()) return
|
||||
val chat = AgentHost.chat
|
||||
Thread({
|
||||
val copied = uris.mapNotNull { uri -> AgentAttachments.copy(context, chat, listOf(uri)).firstOrNull()?.let { uri to it } }
|
||||
android.os.Handler(android.os.Looper.getMainLooper()).post {
|
||||
val paths = copied.map { it.second }
|
||||
if (AgentHost.chat == chat && current()) {
|
||||
AgentAttachments.pending.addAll(paths)
|
||||
onCopied(copied)
|
||||
} else {
|
||||
AgentAttachments.discard(context, paths)
|
||||
onCopied(emptyList())
|
||||
}
|
||||
}
|
||||
}, "agent-attach").start()
|
||||
}
|
||||
|
||||
/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */
|
||||
private fun attachGameFrame(context: Context) {
|
||||
val grab = AgentAttachments.gameFrame ?: return
|
||||
val chat = AgentHost.chat
|
||||
grab frame@{ frame ->
|
||||
if (frame == null) {
|
||||
Toast.makeText(context, R.string.agent_attach_game_failed, Toast.LENGTH_SHORT).show()
|
||||
return@frame
|
||||
}
|
||||
Thread({
|
||||
val path = AgentAttachments.saveFrame(context, chat, frame)
|
||||
frame.recycle()
|
||||
android.os.Handler(android.os.Looper.getMainLooper()).post {
|
||||
when {
|
||||
path == null -> Toast.makeText(context, R.string.agent_attach_game_failed, Toast.LENGTH_SHORT).show()
|
||||
AgentHost.chat == chat -> AgentAttachments.pending.add(path)
|
||||
else -> AgentAttachments.discard(context, listOf(path))
|
||||
}
|
||||
}
|
||||
}, "agent-game-frame").start()
|
||||
}
|
||||
}
|
||||
|
||||
/** Shown in place of the keyboard: recent photos to tap onto the message, and the system picker for anything else. */
|
||||
@Composable
|
||||
internal fun AgentPhotoTray(height: Dp, copies: SnapshotStateMap<Uri, String>, copying: SnapshotStateMap<Uri, Any>, onFiles: (() -> Unit)?) {
|
||||
val context = LocalContext.current
|
||||
val pal = LocalPalette.current
|
||||
var access by remember { mutableStateOf(AgentPhotos.access(context)) }
|
||||
var photos by remember { mutableStateOf<List<AgentPhotos.Photo>?>(null) }
|
||||
var reloads by remember { mutableStateOf(0) }
|
||||
// A window no activity owns (the floating pet's chat) cannot ask for a permission, so it sends the user to the app's settings.
|
||||
val launcher = if (LocalActivityResultRegistryOwner.current != null) {
|
||||
rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
|
||||
AgentAttachments.picking = false
|
||||
access = AgentPhotos.access(context)
|
||||
if (access == AgentPhotos.Access.NONE) AgentPhotos.refused = true
|
||||
reloads++
|
||||
}
|
||||
} else null
|
||||
val request = {
|
||||
if (launcher != null && !AgentPhotos.refused) {
|
||||
AgentAttachments.pick { launcher.launch(AgentPhotos.permissions()) }
|
||||
} else {
|
||||
val details = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + context.packageName)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(details) }
|
||||
}
|
||||
Unit
|
||||
}
|
||||
// Access can change in Settings, and new pictures arrive, while the app is in the background.
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
DisposableEffect(lifecycle) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME) {
|
||||
access = AgentPhotos.access(context)
|
||||
reloads++
|
||||
}
|
||||
}
|
||||
lifecycle.addObserver(observer)
|
||||
onDispose { lifecycle.removeObserver(observer) }
|
||||
}
|
||||
LaunchedEffect(access, reloads) {
|
||||
photos = if (access == AgentPhotos.Access.NONE) emptyList() else withContext(Dispatchers.IO) { AgentPhotos.recent(context) }
|
||||
}
|
||||
LazyVerticalGrid(
|
||||
GridCells.Adaptive(96.dp),
|
||||
Modifier.fillMaxWidth().height(height).padding(top = 8.dp).testTag("agent-photo-tray"),
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
if (AgentAttachments.gameFrame != null) item {
|
||||
TrayTile(Icons.Outlined.PhotoCamera, stringResource(R.string.agent_attach_game), "agent-game-frame") { attachGameFrame(context) }
|
||||
}
|
||||
if (onFiles != null) item { TrayTile(Icons.Outlined.FolderOpen, stringResource(R.string.agent_attach_files), "agent-attach-files", onFiles) }
|
||||
if (access != AgentPhotos.Access.ALL) item {
|
||||
TrayTile(
|
||||
Icons.Outlined.PhotoLibrary,
|
||||
stringResource(if (access == AgentPhotos.Access.NONE) R.string.agent_photos_allow else R.string.agent_photos_more),
|
||||
"agent-photos-allow",
|
||||
onClick = request,
|
||||
)
|
||||
}
|
||||
val list = photos
|
||||
if (list != null && list.isEmpty() && access != AgentPhotos.Access.NONE) item(span = { GridItemSpan(maxLineSpan) }) {
|
||||
Text(
|
||||
stringResource(R.string.agent_photos_empty), fontSize = 13.sp, color = pal.onSurfaceVariant, textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||
)
|
||||
}
|
||||
items(list.orEmpty(), key = { it.uri.toString() }) { photo ->
|
||||
val uri = photo.uri
|
||||
val path = copies[uri]
|
||||
val selected = path != null && path in AgentAttachments.pending
|
||||
Box(
|
||||
Modifier.aspectRatio(1f).clip(Shape12).background(pal.surfaceVariant)
|
||||
.then(if (selected) Modifier.border(3.dp, pal.primary, Shape12) else Modifier)
|
||||
.clickable {
|
||||
when {
|
||||
selected -> AgentAttachments.pending.remove(path)
|
||||
path != null && AgentAttachments.host(context, path).exists() -> AgentAttachments.pending.add(path)
|
||||
uri in copying -> Unit
|
||||
else -> {
|
||||
// Leaving the conversation clears the markers, so a copy started before that is no longer current even back in it.
|
||||
val copy = Any()
|
||||
copying[uri] = copy
|
||||
attachUris(context, listOf(uri), current = { copying[uri] === copy }) { copied ->
|
||||
copied.forEach { (u, p) -> copies[u] = p }
|
||||
if (copying[uri] === copy) copying.remove(uri)
|
||||
}
|
||||
}
|
||||
}
|
||||
}.semantics {
|
||||
contentDescription = photo.name
|
||||
this.selected = selected
|
||||
}.testTag("agent-photo"),
|
||||
) {
|
||||
AsyncImage(
|
||||
model = ImageRequest.Builder(context).data(uri).size(320).build(), contentDescription = null,
|
||||
contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
if (selected) Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.align(Alignment.TopEnd).padding(6.dp).size(22.dp).clip(CircleShape).background(pal.primary),
|
||||
) {
|
||||
Icon(Icons.Outlined.Check, null, tint = pal.onPrimary, modifier = Modifier.size(16.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TrayTile(icon: ImageVector, label: String, tag: String, onClick: () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center,
|
||||
modifier = Modifier.aspectRatio(1f).clip(Shape12).background(pal.surfaceVariant).clickable(onClick = onClick).padding(8.dp).testTag(tag),
|
||||
) {
|
||||
Icon(icon, null, tint = pal.onBackground, modifier = Modifier.size(26.dp))
|
||||
Text(
|
||||
label, fontSize = 12.sp, color = pal.onBackground, textAlign = TextAlign.Center, maxLines = 3, overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.padding(top = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user