What a model makes has a card in the chat, and a long generation is followed to its end
A tool call's `media` is a card in the reply: a picture drawn (from its attachment where the call has one, else from the file by its node id), a video or a track with Play, a 3D model or an unknown kind as what it is; each with Open in Files, Download (the system's "Save to" page), Share and Open with. The player is the platform's, over RemoteMedia: `/files/raw?node=` is read a piece at a time with the token in the header, as a file by its path is. A `media_job` is a card with what is made, its state, the time it has taken and Cancel. There is no stream frame for a job: the chat's jobs are read once when the chat comes to the front and the ones under way every three seconds while it stays there. A job that says the chat was told has left a reply this app did not start, so the transcript is read again and that reply followed. The cards are drawn only where a chat's own screen provides for them: the assistant's sheet, which may be over the lock screen, draws a picture as before and no card. Smaller: a new file is made with `create: true` and a taken name is said in the instance's sentence; attached sound and video are played (from a copy in the private cache: an attachment is answered whole); a version of a file can be saved to the phone; the folder picker makes a folder; a table can be shown as its text. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
29 files changed
+1325
-83
No files matched your search
@@ -4,6 +4,7 @@ import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
@@ -275,6 +276,7 @@ class MainActivity : ComponentActivity() {
|
||||
// The title of each report whose conversation was opened, by its chat: what that chat's bar says.
|
||||
val reportTitles = remember { mutableStateMapOf<String, String>() }
|
||||
val menu: () -> Unit = { scope.launch { drawer.open() } }
|
||||
val filesAt: (String) -> Unit = { folder -> over("files-at/" + Uri.encode(folder)) }
|
||||
ModalNavigationDrawer(
|
||||
drawerState = drawer,
|
||||
// The drawer opens by a swipe only from a chat: elsewhere the swipe is Back's.
|
||||
@@ -292,6 +294,7 @@ class MainActivity : ComponentActivity() {
|
||||
onNewChat = { top("new") },
|
||||
onLeave = { top("new") },
|
||||
onOpened = { id -> top("chat/$id") },
|
||||
onFiles = filesAt,
|
||||
)
|
||||
}
|
||||
composable("new-agent") {
|
||||
@@ -311,9 +314,12 @@ class MainActivity : ComponentActivity() {
|
||||
onMenu = menu,
|
||||
onNewChat = { top("new") },
|
||||
onLeave = { top("new") },
|
||||
onFiles = filesAt,
|
||||
)
|
||||
}
|
||||
composable("files") { FilesScreen(onBack = { nav.popBackStack() }) }
|
||||
// Files at a folder: where a generated file's "Open in Files" leads.
|
||||
composable("files-at/{at}") { e -> FilesScreen(onBack = { nav.popBackStack() }, start = e.arguments?.getString("at")) }
|
||||
composable("archived") {
|
||||
ArchivedScreen(onBack = { nav.popBackStack() }, onOpen = { top("chat/$it") }, onRestored = { chats.load() })
|
||||
}
|
||||
@@ -340,6 +346,7 @@ class MainActivity : ComponentActivity() {
|
||||
onNewChat = { top("new") },
|
||||
onLeave = { nav.popBackStack() },
|
||||
report = reportTitles[id].orEmpty(),
|
||||
onFiles = filesAt,
|
||||
)
|
||||
}
|
||||
composable("scheduled") {
|
||||
|
||||
@@ -37,6 +37,12 @@ data class GeneratedMedia(
|
||||
|
||||
/** What to call it: its name, else the last name of its path. */
|
||||
val title: String get() = name.ifBlank { FileKinds.name(path) }
|
||||
|
||||
/** Where its bytes are asked for: by its id, which outlives a rename or a move; by its path from a result without one. */
|
||||
val raw: Raw get() = if (nodeId.isNotBlank()) Raw.Node(nodeId) else Raw.Path(path)
|
||||
|
||||
/** The folder of the person's Files it was written to. */
|
||||
val folder: String get() = FileKinds.parent(path)
|
||||
}
|
||||
|
||||
/** What a generated file's card is: a picture drawn, a player, or (a 3D model, anything unknown) the file's details. */
|
||||
|
||||
@@ -94,14 +94,24 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Attachment
|
||||
import eu.llembas.android.api.Drawn
|
||||
import eu.llembas.android.api.GeneratedMedia
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.MediaView
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.api.ShowCard
|
||||
import eu.llembas.android.api.drawn
|
||||
import eu.llembas.android.ui.ModelAvatar
|
||||
import eu.llembas.android.ui.ProgressStatus
|
||||
import eu.llembas.android.ui.files.TransferHost
|
||||
import eu.llembas.android.ui.files.TransferViewModel
|
||||
import eu.llembas.android.ui.files.rememberSaver
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.viewer.FileViewer
|
||||
import eu.llembas.android.ui.viewer.PlayerDialog
|
||||
import eu.llembas.android.ui.viewer.Playing
|
||||
import kotlinx.coroutines.flow.drop
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@@ -121,6 +131,8 @@ fun ChatScreen(
|
||||
onKind: ((agent: Boolean) -> Unit)? = null,
|
||||
/** Entered from a report (its Reply): the bar says "Report: title" and has Back, to the report, where the menu is. */
|
||||
report: String? = null,
|
||||
/** Open the person's Files at a folder: where a generated file's "Open in Files" leads. */
|
||||
onFiles: (String) -> Unit = {},
|
||||
model: ChatViewModel = viewModel(key = chatId ?: if (agent) "new-agent" else "new"),
|
||||
) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
@@ -138,6 +150,11 @@ fun ChatScreen(
|
||||
LaunchedEffect(state.chat?.id) {
|
||||
if (state.chat?.id != null) lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { model.watchActivity() }
|
||||
}
|
||||
// The chat's long generations (a video, a track), read again every few seconds while the
|
||||
// screen is in front and not otherwise. An agent chat runs on a computer and makes none.
|
||||
LaunchedEffect(state.chat?.id) {
|
||||
if (state.chat?.id != null && !isAgent) lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { model.watchMedia() }
|
||||
}
|
||||
LaunchedEffect(state.error, state.notice) {
|
||||
(state.error ?: state.notice)?.let {
|
||||
snackbar.showSnackbar(it)
|
||||
@@ -145,6 +162,33 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// What a generated file's card does: the player over the chat, the folder in Files, and the
|
||||
// ways a file leaves the app. Its own transfers, as each screen that hands files out has.
|
||||
val transfers: TransferViewModel = viewModel(key = "chat-transfers")
|
||||
val saveTo = rememberSaver(transfers)
|
||||
var playing by remember { mutableStateOf<Playing?>(null) }
|
||||
val media = remember(model, transfers) {
|
||||
object : MediaActions {
|
||||
override fun play(media: GeneratedMedia) {
|
||||
playing = Playing(media.raw, media.title, media.size, video = media.view == MediaView.Video)
|
||||
}
|
||||
|
||||
override fun play(attachment: Attachment) {
|
||||
playing = Playing(Raw.Attached(attachment.id), attachment.name, attachment.size, video = attachment.kind == "video")
|
||||
}
|
||||
|
||||
override fun openInFiles(media: GeneratedMedia) = onFiles(media.folder)
|
||||
|
||||
override fun download(media: GeneratedMedia) = saveTo(media.raw, media.title, media.mime)
|
||||
|
||||
override fun share(media: GeneratedMedia) = transfers.share(media.raw, media.title, media.mime)
|
||||
|
||||
override fun openWith(media: GeneratedMedia) = transfers.openWith(media.raw, media.title, media.mime)
|
||||
|
||||
override fun cancel(job: MediaJob) = model.cancelJob(job)
|
||||
}
|
||||
}
|
||||
|
||||
// Read aloud on a reply, when the instance has a voice; it stops when the chat is left.
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
@@ -173,6 +217,7 @@ fun ChatScreen(
|
||||
onShow = { showing = it },
|
||||
onKind = onKind,
|
||||
report = report,
|
||||
media = media,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -183,6 +228,8 @@ fun ChatScreen(
|
||||
showing?.let { file ->
|
||||
state.chat?.id?.let { id -> FileViewer(id, file, onClose = { showing = null }) }
|
||||
}
|
||||
playing?.let { PlayerDialog(it, onClose = { playing = null }, gone = stringResource(R.string.media_gone)) }
|
||||
TransferHost(transfers)
|
||||
}
|
||||
|
||||
/** What the bar says of a chat entered from a report: "Report: title", or "Report" when the title is not known. */
|
||||
@@ -206,10 +253,13 @@ fun ChatContent(
|
||||
onShow: (ShowCard) -> Unit = {},
|
||||
onKind: ((agent: Boolean) -> Unit)? = null,
|
||||
report: String? = null,
|
||||
/** What the cards of generated media do; null draws none of them (a picture stays a picture). */
|
||||
media: MediaActions? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val chatMedia = remember(state.mediaJobs, media) { media?.let { ChatMedia(state.mediaJobs, it) } }
|
||||
// A chat opens at its end, where the conversation is, not at its first message.
|
||||
val list = rememberLazyListState(initialFirstVisibleItemIndex = maxOf(0, state.messages.size - 1 + if (state.more) 1 else 0))
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
@@ -270,7 +320,7 @@ fun ChatContent(
|
||||
snapshotFlow { list.layoutInfo.viewportSize.height }.drop(1).collect { if (following && !list.isScrollInProgress) yielding { list.toEnd() } }
|
||||
}
|
||||
|
||||
CompositionLocalProvider(LocalCopy provides copy) {
|
||||
CompositionLocalProvider(LocalCopy provides copy, LocalChatMedia provides chatMedia) {
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
snackbarHost = { SnackbarHost(snackbar) },
|
||||
|
||||
@@ -26,6 +26,7 @@ import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LinkedDevice
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.MediaFor
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.Mention
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.MessagePage
|
||||
@@ -102,6 +103,8 @@ data class ChatState(
|
||||
val lastSent: String? = null,
|
||||
/** The model picked for this open chat, by its ref: which of two models with one id the chat is on. */
|
||||
val picked: String? = null,
|
||||
/** The chat's long generations (a video, a track, a 3D model), by id, as each was last read. */
|
||||
val mediaJobs: Map<String, JobSeen> = emptyMap(),
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -655,6 +658,98 @@ class ChatViewModel(app: Application) :
|
||||
}
|
||||
}
|
||||
|
||||
// --- Generated media's jobs -----------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Follow the chat's long generations while the screen is in front: every job of the chat once
|
||||
* (a finished one's file is drawn on its card), then the ones under way every few seconds --
|
||||
* there is no stream frame for a job. One that ends by itself wakes the chat with a reply this
|
||||
* app did not start: when a job says the chat was told, the transcript is read again and that
|
||||
* reply followed. Runs until cancelled (the screen left, or no longer in front). An instance
|
||||
* without these routes has no jobs, and nothing is asked again.
|
||||
*/
|
||||
suspend fun watchMedia() {
|
||||
val chat = _state.value.chat ?: return
|
||||
val client = runCatching { api() }.getOrNull() ?: return
|
||||
try {
|
||||
val jobs = client.mediaJobs(chat.id)
|
||||
val before = _state.value.mediaJobs
|
||||
_state.update { it.withJobs(jobs, SystemClock.elapsedRealtime()) }
|
||||
// Away and back: a job that told the chat meanwhile left a reply this screen has not read.
|
||||
if (jobs.any { woke(before[it.id]?.job, it) }) rereadAndFollow()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
// An older instance, or one out of reach: the cards say what the calls said.
|
||||
}
|
||||
val waited = mutableMapOf<String, Int>()
|
||||
while (true) {
|
||||
delay(JOB_POLL_MS)
|
||||
val now = _state.value
|
||||
val telling = now.mediaJobs.values.filter { awaitsTelling(it.job) && it.at > 0 && (waited[it.job.id] ?: 0) < TELL_ROUNDS }.map { it.job.id }
|
||||
var woken = false
|
||||
for (id in (now.jobsToRead() + telling).distinct()) {
|
||||
val before = _state.value.mediaJobs[id]?.job
|
||||
val read = try {
|
||||
client.mediaJob(id)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: ApiException) {
|
||||
// Gone, or never this person's: the card says so in the instance's words and is not asked for again.
|
||||
if (e.status != 404) continue
|
||||
val ref = now.jobRefs.firstOrNull { it.id == id }
|
||||
MediaJob(id = id, kind = before?.kind ?: ref?.kind.orEmpty(), state = "expired", error = e.message.orEmpty(), told = true)
|
||||
} catch (_: Exception) {
|
||||
continue
|
||||
}
|
||||
if (awaitsTelling(read)) waited[id] = (waited[id] ?: 0) + 1
|
||||
_state.update { it.withJobs(listOf(read), SystemClock.elapsedRealtime()) }
|
||||
if (woke(before, read)) woken = true
|
||||
}
|
||||
if (woken) rereadAndFollow()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The chat was woken (a job ended): its transcript as the server has it now, and the reply
|
||||
* being written there followed. The telling is written a moment before the reply exists, so
|
||||
* where none is live yet the chat is read once more shortly after. While this screen follows
|
||||
* a reply of its own nothing is touched: the wake waits in the queue, and the stream's `next`
|
||||
* brings it.
|
||||
*/
|
||||
private suspend fun rereadAndFollow() {
|
||||
val chat = _state.value.chat ?: return
|
||||
repeat(2) { round ->
|
||||
if (_state.value.live != null) return
|
||||
val read = try {
|
||||
api().chat(chat.id)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
return
|
||||
}
|
||||
if (_state.value.live != null) return
|
||||
_state.update { it.copy(chat = read.chat, messages = read.messages, more = read.more) }
|
||||
read.live?.let {
|
||||
follow(it)
|
||||
return
|
||||
}
|
||||
if (round == 0) delay(WAKE_PAUSE_MS)
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop a generation: the job as it is after, in the card. One that has ended stays what it was. */
|
||||
fun cancelJob(job: MediaJob) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val after = api().cancelMediaJob(job.id)
|
||||
_state.update { it.withJobs(listOf(after), SystemClock.elapsedRealtime()) }
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var panelOpen = false
|
||||
|
||||
fun panel(open: Boolean) {
|
||||
@@ -833,5 +928,8 @@ class ChatViewModel(app: Application) :
|
||||
|
||||
private companion object {
|
||||
const val MENTION_PAUSE_MS = 250L
|
||||
|
||||
/** Between a job's "the chat was told" and the reply that telling starts. */
|
||||
const val WAKE_PAUSE_MS = 2000L
|
||||
}
|
||||
}
|
||||
@@ -11,12 +11,15 @@ import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -36,34 +39,52 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.GeneratedImage
|
||||
import eu.llembas.android.api.GeneratedMedia
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
/**
|
||||
* The pictures the instance made, fetched the one way the app fetches a chat's files: by
|
||||
* attachment id, from the instance it is signed in to, with its token. There is no URL to
|
||||
* follow -- a model's words can name an address, but never a picture this draws -- and nothing
|
||||
* bigger than [MAX_BYTES] is decoded.
|
||||
* The pictures the instance made, fetched the two ways the app fetches a chat's files: by
|
||||
* attachment id, or -- for a generated file with no attachment -- by its node id in the
|
||||
* person's Files; always from the instance it is signed in to, with its token. There is no URL
|
||||
* to follow -- a model's words can name an address, but never a picture this draws -- and
|
||||
* nothing bigger than [MAX_BYTES] is decoded.
|
||||
*/
|
||||
private object Pictures {
|
||||
/** Longest edge decoded: enough for a phone held either way, small enough to keep a few. */
|
||||
private const val EDGE = 1600
|
||||
private const val MAX_BYTES = 24 * 1024 * 1024
|
||||
const val MAX_BYTES = 24L * 1024 * 1024
|
||||
private val cache = LruCache<String, ImageBitmap>(8)
|
||||
private val failed = mutableSetOf<String>()
|
||||
private val gone = mutableSetOf<String>()
|
||||
|
||||
fun cached(id: String): ImageBitmap? = cache.get(id)
|
||||
fun cached(key: String): ImageBitmap? = cache.get(key)
|
||||
|
||||
suspend fun load(context: Context, id: String): ImageBitmap? {
|
||||
cache.get(id)?.let { return it }
|
||||
if (id.isBlank() || id in failed) return null
|
||||
/** Whether the instance said there is no such file (any more). */
|
||||
fun isGone(key: String): Boolean = key in gone
|
||||
|
||||
suspend fun load(context: Context, key: String, fetch: suspend (ApiClient) -> ByteArray): ImageBitmap? {
|
||||
cache.get(key)?.let { return it }
|
||||
if (key in failed) return null
|
||||
val api = context.lembas.instances.client() ?: return null
|
||||
val bytes = runCatching { api.attachmentBytes(id) }.getOrNull()?.takeIf { it.size <= MAX_BYTES }
|
||||
val bytes = try {
|
||||
fetch(api).takeIf { it.size <= MAX_BYTES }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
if (e is ApiException && e.status == 404) gone += key
|
||||
null
|
||||
}
|
||||
val image = bytes?.let { decode(it) }
|
||||
if (image == null) failed += id else cache.put(id, image)
|
||||
if (image == null) failed += key else cache.put(key, image)
|
||||
return image
|
||||
}
|
||||
|
||||
@@ -84,13 +105,42 @@ private object Pictures {
|
||||
*/
|
||||
@Composable
|
||||
fun GeneratedPicture(image: GeneratedImage, modifier: Modifier = Modifier) {
|
||||
if (image.id.isBlank()) return
|
||||
Picture("attachment:" + image.id, image.width, image.height, modifier) { api -> api.attachmentBytes(image.id) }
|
||||
}
|
||||
|
||||
/**
|
||||
* A generated picture that is a file of the person's Files and no attachment: fetched by its
|
||||
* node id from `/files/raw`, drawn the same way. One the person has since put in the trash
|
||||
* says that it is no longer there.
|
||||
*/
|
||||
@Composable
|
||||
fun GeneratedPicture(media: GeneratedMedia, modifier: Modifier = Modifier) {
|
||||
if (media.nodeId.isBlank()) return
|
||||
Picture("node:" + media.nodeId, media.width, media.height, modifier) { api ->
|
||||
// What the server says it weighs decides before a byte is asked for.
|
||||
if (media.size > Pictures.MAX_BYTES) throw ApiException(413, "")
|
||||
val held = ByteArrayOutputStream()
|
||||
api.download(api.raw(Raw.Node(media.nodeId), inline = true), held, most = Pictures.MAX_BYTES)
|
||||
held.toByteArray()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Picture(key: String, width: Int, height: Int, modifier: Modifier, fetch: suspend (ApiClient) -> ByteArray) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
val still = LocalInspectionMode.current
|
||||
var bitmap by remember(image.id) { mutableStateOf(Pictures.cached(image.id)) }
|
||||
var bitmap by remember(key) { mutableStateOf(Pictures.cached(key)) }
|
||||
var gone by remember(key) { mutableStateOf(Pictures.isGone(key)) }
|
||||
var whole by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(image.id) { if (bitmap == null && !still) bitmap = Pictures.load(context, image.id) }
|
||||
val ratio = if (image.width > 0 && image.height > 0) image.width.toFloat() / image.height else 1f
|
||||
LaunchedEffect(key) {
|
||||
if (bitmap == null && !still) {
|
||||
bitmap = Pictures.load(context, key, fetch)
|
||||
gone = Pictures.isGone(key)
|
||||
}
|
||||
}
|
||||
val ratio = if (width > 0 && height > 0) width.toFloat() / height else 1f
|
||||
val shape = RoundedCornerShape(16.dp)
|
||||
val described = stringResource(R.string.image_generated)
|
||||
Box(
|
||||
@@ -107,6 +157,8 @@ fun GeneratedPicture(image: GeneratedImage, modifier: Modifier = Modifier) {
|
||||
val shown = bitmap
|
||||
if (shown != null) {
|
||||
Image(shown, contentDescription = described, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
} else if (gone) {
|
||||
Text(stringResource(R.string.media_gone), color = palette.inkMuted, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(16.dp))
|
||||
} else {
|
||||
Icon(Icons.Filled.Image, contentDescription = described, tint = palette.inkFaint, modifier = Modifier.size(32.dp))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.os.SystemClock
|
||||
import android.text.format.Formatter
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.OpenInNew
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.ErrorOutline
|
||||
import androidx.compose.material.icons.filled.FolderOpen
|
||||
import androidx.compose.material.icons.filled.HourglassEmpty
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.Movie
|
||||
import androidx.compose.material.icons.filled.MusicNote
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.ViewInAr
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.FilledIconButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.IconButtonDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Attachment
|
||||
import eu.llembas.android.api.GeneratedImage
|
||||
import eu.llembas.android.api.GeneratedMedia
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.MediaView
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.viewer.playTime
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
// What a model made, in the reply: a card for a file (a picture drawn, a video or a track with
|
||||
// Play, a 3D model or anything else as what it is) and a card for a generation still under way.
|
||||
// The file is one of the person's Files, so each card leads there, and out of the app the ways
|
||||
// a file leaves it: saved where the person chooses, shared, or opened with another app. The
|
||||
// cards are drawn only where a chat provides [LocalChatMedia] -- the chat's own screen, which
|
||||
// is never over the lock screen; the assistant's sheet provides none and draws none.
|
||||
|
||||
/** What the media cards of a chat can do; nothing by default, for the screenshot tests. */
|
||||
interface MediaActions {
|
||||
/** Play a generated video or track, over the chat. */
|
||||
fun play(media: GeneratedMedia) {}
|
||||
|
||||
/** Play sound or video the person attached. */
|
||||
fun play(attachment: Attachment) {}
|
||||
|
||||
/** The folder of the person's Files the file is in. */
|
||||
fun openInFiles(media: GeneratedMedia) {}
|
||||
|
||||
/** Save it where the person chooses (the system's "Save to" page). */
|
||||
fun download(media: GeneratedMedia) {}
|
||||
|
||||
fun share(media: GeneratedMedia) {}
|
||||
|
||||
fun openWith(media: GeneratedMedia) {}
|
||||
|
||||
/** Stop a generation that is under way. */
|
||||
fun cancel(job: MediaJob) {}
|
||||
}
|
||||
|
||||
/** A chat's generated media as its cards need it: what is known of its jobs, and what a card can do. */
|
||||
class ChatMedia(val jobs: Map<String, JobSeen>, val actions: MediaActions)
|
||||
|
||||
/** Provided by the chat's screen; null anywhere else, and then no media card is drawn. */
|
||||
val LocalChatMedia = compositionLocalOf<ChatMedia?> { null }
|
||||
|
||||
private val CardShape = RoundedCornerShape(16.dp)
|
||||
|
||||
/** The word for what was asked for: a picture, a video, music, a 3D model; the server's own word for anything else. */
|
||||
@Composable
|
||||
internal fun mediaKind(kind: String): String = when (kind) {
|
||||
"image", "image_edit" -> stringResource(R.string.media_image)
|
||||
"video" -> stringResource(R.string.media_video)
|
||||
"music" -> stringResource(R.string.media_music)
|
||||
"model3d" -> stringResource(R.string.media_model)
|
||||
else -> kind
|
||||
}
|
||||
|
||||
private fun mediaIcon(kind: String): ImageVector = when (kind) {
|
||||
"image", "image_edit" -> Icons.Filled.Image
|
||||
"video" -> Icons.Filled.Movie
|
||||
"music" -> Icons.Filled.MusicNote
|
||||
else -> Icons.Filled.ViewInAr
|
||||
}
|
||||
|
||||
/** What is known of a file, in one line: what it is, how long, how large, its size in pixels. */
|
||||
@Composable
|
||||
internal fun mediaFacts(media: GeneratedMedia): String {
|
||||
val context = LocalContext.current
|
||||
return listOfNotNull(
|
||||
mediaKind(media.kind).ifBlank { null },
|
||||
media.seconds.takeIf { it > 0 }?.let { playTime((it * 1000).toInt()) },
|
||||
media.size.takeIf { it > 0 }?.let { Formatter.formatShortFileSize(context, it) },
|
||||
if (media.width > 0 && media.height > 0) "${media.width} × ${media.height}" else null,
|
||||
).joinToString(" · ")
|
||||
}
|
||||
|
||||
/**
|
||||
* A file a tool call made. A picture is drawn -- from its attachment where the call has one
|
||||
* ([image]), else from the file itself; a video or a track is its name with Play (48 dp), which
|
||||
* opens the player over the chat; a 3D model and anything this app does not know is what it is.
|
||||
* Under each, four buttons of one size: Open in Files, Download, Share, Open with.
|
||||
*/
|
||||
@Composable
|
||||
fun MediaCard(media: GeneratedMedia, image: GeneratedImage?, actions: MediaActions, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
Column(modifier.widthIn(max = 480.dp).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
when (media.view) {
|
||||
MediaView.Picture -> if (image != null && image.id.isNotBlank()) GeneratedPicture(image) else GeneratedPicture(media)
|
||||
|
||||
MediaView.Video, MediaView.Sound, MediaView.Details -> Row(
|
||||
Modifier.fillMaxWidth().border(1.dp, palette.border, CardShape).padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (media.view == MediaView.Details) {
|
||||
Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
|
||||
Icon(mediaIcon(media.kind), contentDescription = null, tint = palette.inkMuted)
|
||||
}
|
||||
} else {
|
||||
FilledIconButton(
|
||||
onClick = { actions.play(media) },
|
||||
colors = IconButtonDefaults.filledIconButtonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.size(48.dp),
|
||||
) { Icon(Icons.Filled.PlayArrow, contentDescription = stringResource(R.string.play)) }
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(media.title, style = MaterialTheme.typography.bodyLarge, color = palette.ink, maxLines = 1, overflow = TextOverflow.MiddleEllipsis)
|
||||
Text(
|
||||
mediaFacts(media),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Four buttons of 48 dp: nothing here depends on how long a word is in any language.
|
||||
Row {
|
||||
CardButton(Icons.Filled.FolderOpen, R.string.media_open_in_files) { actions.openInFiles(media) }
|
||||
CardButton(Icons.Filled.Download, R.string.download) { actions.download(media) }
|
||||
CardButton(Icons.Filled.Share, R.string.report_share) { actions.share(media) }
|
||||
CardButton(Icons.AutoMirrored.Filled.OpenInNew, R.string.files_open_with) { actions.openWith(media) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CardButton(icon: ImageVector, label: Int, onClick: () -> Unit) {
|
||||
IconButton(onClick = onClick) { Icon(icon, contentDescription = stringResource(label), tint = LocalPalette.current.inkMuted) }
|
||||
}
|
||||
|
||||
/** The word for where a job stands; a state this app does not know is said as the server says it. */
|
||||
@Composable
|
||||
internal fun jobState(state: String): String = when (state) {
|
||||
"queued" -> stringResource(R.string.job_queued)
|
||||
"running" -> stringResource(R.string.job_running)
|
||||
"done" -> stringResource(R.string.job_done)
|
||||
"failed" -> stringResource(R.string.job_failed)
|
||||
"cancelled" -> stringResource(R.string.job_cancelled)
|
||||
"expired" -> stringResource(R.string.job_expired)
|
||||
else -> state
|
||||
}
|
||||
|
||||
/**
|
||||
* A generation that takes minutes, on the card of the call that started it: what is being made,
|
||||
* where it stands and for how long, and Cancel while it is under way. One that ended without a
|
||||
* file says why in the server's own sentence. The mark keeps its 48 dp and Cancel its own width;
|
||||
* the words between them give.
|
||||
*/
|
||||
@Composable
|
||||
fun JobCard(seen: JobSeen, actions: MediaActions, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
val still = LocalInspectionMode.current
|
||||
val job = seen.job
|
||||
var now by remember { mutableLongStateOf(if (still) seen.at else SystemClock.elapsedRealtime()) }
|
||||
// The clock on the card runs on the phone between two reads of the job.
|
||||
LaunchedEffect(job.id, job.underWay) {
|
||||
while (job.underWay && !still) {
|
||||
now = SystemClock.elapsedRealtime()
|
||||
delay(1000)
|
||||
}
|
||||
}
|
||||
Row(
|
||||
modifier.widthIn(max = 480.dp).fillMaxWidth().border(1.dp, palette.border, CardShape).padding(start = 12.dp, end = 4.dp, top = 10.dp, bottom = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
|
||||
when {
|
||||
// A wheel that never ends never lets a screenshot be taken: a still mark there.
|
||||
job.underWay && !still -> CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(24.dp))
|
||||
|
||||
job.underWay -> Icon(Icons.Filled.HourglassEmpty, contentDescription = null, tint = palette.inkMuted)
|
||||
|
||||
job.unsuccessful -> Icon(
|
||||
Icons.Filled.ErrorOutline,
|
||||
contentDescription = null,
|
||||
tint = if (job.state ==
|
||||
"failed"
|
||||
) {
|
||||
palette.danger
|
||||
} else {
|
||||
palette.inkMuted
|
||||
},
|
||||
)
|
||||
|
||||
else -> Icon(mediaIcon(job.kind), contentDescription = null, tint = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
listOf(mediaKind(job.kind), jobState(job.state)).filter { it.isNotBlank() }.joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = palette.ink,
|
||||
)
|
||||
val elapsed = seen.elapsed(now)
|
||||
val facts = listOfNotNull(
|
||||
if (elapsed >
|
||||
0
|
||||
) {
|
||||
playTime((elapsed * 1000).coerceAtMost(Int.MAX_VALUE.toLong()).toInt())
|
||||
} else {
|
||||
null
|
||||
},
|
||||
job.source.ifBlank { null },
|
||||
)
|
||||
if (facts.isNotEmpty()) {
|
||||
Text(
|
||||
facts.joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
// Why it was not made, in the instance's words: a sentence for the person, shown whole.
|
||||
if (job.unsuccessful && job.error.isNotBlank()) {
|
||||
Text(
|
||||
job.error,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = if (job.state == "failed") palette.danger else palette.inkMuted,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (job.underWay) {
|
||||
TextButton(onClick = { actions.cancel(job) }) { Text(stringResource(R.string.cancel)) }
|
||||
} else {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What a call that made media leaves in the reply, always in view: its file's card; or its
|
||||
* job's card, which becomes the file's once the job is done.
|
||||
*/
|
||||
@Composable
|
||||
fun CallMedia(media: GeneratedMedia?, image: GeneratedImage?, job: JobSeen?, chat: ChatMedia) {
|
||||
if (media != null) MediaCard(media, image, chat.actions)
|
||||
if (job != null) {
|
||||
val result = job.job.result
|
||||
if (result != null && job.job.state == MediaJob.DONE) MediaCard(result, null, chat.actions) else JobCard(job, chat.actions)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.MediaJobRef
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.ToolCall
|
||||
|
||||
// A chat's long generations as the chat keeps them. There is no stream frame for a job -- a chat
|
||||
// has no stream while no reply is being written -- so the jobs under way are read again every few
|
||||
// seconds while the chat is in front, and the chat is read again when one of them has woken it.
|
||||
|
||||
/** A job as it was last read, and when ([at], the phone's uptime clock; 0: known only from the call). */
|
||||
data class JobSeen(val job: MediaJob, val at: Long = 0) {
|
||||
/** How long it has taken, in seconds, at [now]: counted on from the read while it is under way. */
|
||||
fun elapsed(now: Long): Long {
|
||||
val said = job.seconds.toLong().coerceAtLeast(0)
|
||||
return if (job.underWay && at > 0 && now > at) said + (now - at) / 1000 else said
|
||||
}
|
||||
}
|
||||
|
||||
/** How often jobs under way are read again. */
|
||||
const val JOB_POLL_MS = 3000L
|
||||
|
||||
/** How many more reads a job that has ended is given to say that the chat was told. */
|
||||
const val TELL_ROUNDS = 20
|
||||
|
||||
private fun calls(steps: List<Step>): Sequence<ToolCall> {
|
||||
fun all(call: ToolCall): Sequence<ToolCall> = sequenceOf(call) + call.children.orEmpty().asSequence().flatMap { all(it) }
|
||||
return steps.asSequence().flatMap { it.calls.asSequence() }.flatMap { all(it) }
|
||||
}
|
||||
|
||||
/** Every job the calls of these messages (and of the steps being written, [live]) started, each once, in the order the calls come. */
|
||||
fun jobRefsOf(messages: List<Message>, live: List<Step> = emptyList()): List<MediaJobRef> {
|
||||
val all = messages.asSequence().flatMap { calls(it.steps) } + calls(live)
|
||||
return all.mapNotNull { it.mediaJob?.takeIf { ref -> ref.id.isNotBlank() } }.distinctBy { it.id }.toList()
|
||||
}
|
||||
|
||||
/** The jobs this chat's calls started (the reply being written included). */
|
||||
val ChatState.jobRefs: List<MediaJobRef> get() = jobRefsOf(messages, live?.shown.orEmpty())
|
||||
|
||||
/**
|
||||
* A job that has ended and has not said yet that the chat was told: the reply about it is still
|
||||
* to come, so it is read a few more times. A cancelled job wakes nobody.
|
||||
*/
|
||||
fun awaitsTelling(job: MediaJob): Boolean = !job.underWay && !job.told && job.state != MediaJob.CANCELLED
|
||||
|
||||
/**
|
||||
* The jobs to read again: the ones a call names that were never read (the call's own word is
|
||||
* from the moment it returned), and the ones under way. A job that has ended is left alone.
|
||||
*/
|
||||
fun ChatState.jobsToRead(): List<String> {
|
||||
val named = jobRefs.map { it.id }.filter { mediaJobs[it]?.let { seen -> seen.at == 0L || seen.job.underWay } ?: true }
|
||||
val known = mediaJobs.values.filter { it.job.underWay }.map { it.job.id }
|
||||
return (named + known).distinct()
|
||||
}
|
||||
|
||||
/** [jobs], read at [at], among what the chat knows of its jobs. */
|
||||
fun ChatState.withJobs(jobs: List<MediaJob>, at: Long): ChatState =
|
||||
if (jobs.isEmpty()) this else copy(mediaJobs = mediaJobs + jobs.filter { it.id.isNotBlank() }.associate { it.id to JobSeen(it, at) })
|
||||
|
||||
/**
|
||||
* Whether a read says the chat was woken since the last one: the job was known and had not told
|
||||
* the chat, and now has. Then there is a reply this app did not start, and the transcript is
|
||||
* read again. A job first heard of already told is part of the transcript that was just read.
|
||||
*/
|
||||
fun woke(before: MediaJob?, after: MediaJob): Boolean = before != null && !before.told && after.told
|
||||
|
||||
/** What a call's job is drawn from: what was read of it, else the call's own word. */
|
||||
fun ChatMedia.job(ref: MediaJobRef): JobSeen = jobs[ref.id] ?: JobSeen(MediaJob.of(ref))
|
||||
@@ -13,6 +13,7 @@ import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -41,6 +42,8 @@ import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.Movie
|
||||
import androidx.compose.material.icons.filled.MusicNote
|
||||
import androidx.compose.material.icons.filled.Psychology
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.SelectAll
|
||||
@@ -593,9 +596,20 @@ private fun ToolsChip(step: Step, onShow: ((ShowCard) -> Unit)?) {
|
||||
}
|
||||
}
|
||||
shows.forEach { call -> ToolCallBlock(call, onShow = onShow) }
|
||||
// A picture the instance made stays in view, like a `show` card: it is the answer.
|
||||
step.calls.mapNotNull { call -> call.image?.takeIf { it.id.isNotBlank() && call.status != "error" && call.error.isNullOrEmpty() } }
|
||||
.forEach { GeneratedPicture(it) }
|
||||
// What the instance made stays in view, like a `show` card: it is the answer. A picture as
|
||||
// before; in a chat's own screen also the file's card (a player, the ways to the file) and
|
||||
// the card of a generation still under way. Elsewhere -- the assistant's sheet, which may be
|
||||
// over the lock screen -- only the picture, as before.
|
||||
val media = LocalChatMedia.current
|
||||
step.calls.filter { it.status != "error" && it.error.isNullOrEmpty() }.forEach { call ->
|
||||
val image = call.image?.takeIf { it.id.isNotBlank() }
|
||||
if (media == null) {
|
||||
image?.let { GeneratedPicture(it) }
|
||||
} else {
|
||||
if (call.media == null) image?.let { GeneratedPicture(it) }
|
||||
CallMedia(call.media, image, call.mediaJob?.takeIf { it.id.isNotBlank() }?.let { media.job(it) }, media)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -646,7 +660,17 @@ private object Thumbnails {
|
||||
fun AttachmentTile(attachment: Attachment, side: Dp, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
Box(modifier.size(side).clip(Block).background(palette.surfaceRaised).border(1.dp, palette.border, Block), contentAlignment = Alignment.Center) {
|
||||
// Sound and video the person attached are played, where a chat's screen has a player.
|
||||
val play = LocalChatMedia.current?.actions?.takeIf { attachment.kind == "audio" || attachment.kind == "video" }
|
||||
Box(
|
||||
modifier
|
||||
.size(side)
|
||||
.clip(Block)
|
||||
.background(palette.surfaceRaised)
|
||||
.border(1.dp, palette.border, Block)
|
||||
.then(if (play != null) Modifier.clickable(onClickLabel = stringResource(R.string.play)) { play.play(attachment) } else Modifier),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (attachment.image) {
|
||||
var image by remember(attachment.id) { mutableStateOf(Thumbnails.cached(attachment.id)) }
|
||||
val still = LocalInspectionMode.current
|
||||
@@ -659,7 +683,15 @@ fun AttachmentTile(attachment: Attachment, side: Dp, modifier: Modifier = Modifi
|
||||
}
|
||||
} else {
|
||||
Column(Modifier.padding(8.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Icon(Icons.Filled.Description, contentDescription = null, tint = palette.inkMuted)
|
||||
Icon(
|
||||
when (attachment.kind) {
|
||||
"audio" -> Icons.Filled.MusicNote
|
||||
"video" -> Icons.Filled.Movie
|
||||
else -> Icons.Filled.Description
|
||||
},
|
||||
contentDescription = null,
|
||||
tint = if (play != null) palette.accent else palette.inkMuted,
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
attachment.name,
|
||||
|
||||
@@ -16,8 +16,10 @@ import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.CreateNewFolder
|
||||
import androidx.compose.material.icons.filled.DeleteForever
|
||||
import androidx.compose.material.icons.filled.DeleteSweep
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.FolderShared
|
||||
import androidx.compose.material.icons.filled.RestoreFromTrash
|
||||
@@ -130,6 +132,9 @@ fun FolderPicker(title: String, confirm: String, start: String, onPick: (String)
|
||||
var state by remember { mutableStateOf(FolderPickState(path = start)) }
|
||||
var asked by remember { mutableStateOf(start) }
|
||||
var again by remember { mutableIntStateOf(0) }
|
||||
var naming by remember { mutableStateOf(false) }
|
||||
var said by remember { mutableStateOf<String?>(null) }
|
||||
val scope = rememberCoroutineScope()
|
||||
LaunchedEffect(asked, again) {
|
||||
state = state.copy(loading = true, error = null)
|
||||
state = try {
|
||||
@@ -147,8 +152,43 @@ fun FolderPicker(title: String, confirm: String, start: String, onPick: (String)
|
||||
if (parent != null) asked = parent else onDismiss()
|
||||
}
|
||||
Dialog(onDismissRequest = up, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
FolderPickContent(title, confirm, state, onOpen = { asked = it }, onUp = up, onPick = { onPick(state.path) }, onDismiss = onDismiss)
|
||||
FolderPickContent(
|
||||
title,
|
||||
confirm,
|
||||
state,
|
||||
onOpen = { asked = it },
|
||||
onUp = up,
|
||||
onPick = { onPick(state.path) },
|
||||
onDismiss = onDismiss,
|
||||
onNewFolder = { naming = true },
|
||||
)
|
||||
}
|
||||
if (naming) {
|
||||
NameDialog(
|
||||
stringResource(R.string.folder_new),
|
||||
stringResource(R.string.files_new_folder_ask),
|
||||
"",
|
||||
stringResource(R.string.save),
|
||||
onName = { name ->
|
||||
naming = false
|
||||
val dir = state.path
|
||||
scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
api.makeFolder(dir, name)
|
||||
// Made, and walked into: it is most likely where the thing is meant to go.
|
||||
if (asked == FileKinds.child(dir, name)) again++ else asked = FileKinds.child(dir, name)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
said = context.filesSay(e)
|
||||
}
|
||||
}
|
||||
},
|
||||
onDismiss = { naming = false },
|
||||
)
|
||||
}
|
||||
said?.let { SaidDialog(it, onClose = { said = null }) }
|
||||
}
|
||||
|
||||
/** The folder picker's page: where it is, that folder's folders, and the one button that chooses the folder shown. */
|
||||
@@ -161,11 +201,20 @@ fun FolderPickContent(
|
||||
onUp: () -> Unit = {},
|
||||
onPick: () -> Unit = {},
|
||||
onDismiss: () -> Unit = {},
|
||||
/** Make a folder in the one shown; null where the page cannot. */
|
||||
onNewFolder: (() -> Unit)? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
actions = {
|
||||
if (onNewFolder != null) {
|
||||
IconButton(onClick = onNewFolder, enabled = !state.loading && state.error == null) {
|
||||
Icon(Icons.Filled.CreateNewFolder, contentDescription = stringResource(R.string.folder_new))
|
||||
}
|
||||
}
|
||||
},
|
||||
navigationIcon = {
|
||||
IconButton(onClick = if (state.parent != null) onUp else onDismiss) {
|
||||
Icon(
|
||||
@@ -380,7 +429,7 @@ data class VersionsState(val versions: List<FileVersion> = emptyList(), val load
|
||||
|
||||
/** A file's versions, newest first; an older one can be made the file again, which adds a version and loses none. */
|
||||
@Composable
|
||||
fun VersionsDialog(path: String, onClose: () -> Unit, onRestored: () -> Unit) {
|
||||
fun VersionsDialog(path: String, onClose: () -> Unit, onRestored: () -> Unit, onDownload: ((FileVersion) -> Unit)? = null) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var state by remember(path) { mutableStateOf(VersionsState()) }
|
||||
@@ -396,7 +445,7 @@ fun VersionsDialog(path: String, onClose: () -> Unit, onRestored: () -> Unit) {
|
||||
}
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
VersionsContent(FileKinds.name(path), state, onRestore = { asking = it }, onClose = onClose)
|
||||
VersionsContent(FileKinds.name(path), state, onRestore = { asking = it }, onClose = onClose, onDownload = onDownload)
|
||||
}
|
||||
asking?.let { version ->
|
||||
ConfirmDialog(
|
||||
@@ -421,9 +470,19 @@ fun VersionsDialog(path: String, onClose: () -> Unit, onRestored: () -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
/** The versions' page: when, by whom and how large; the one the file holds now says so, the others can be restored. */
|
||||
/**
|
||||
* The versions' page: when, by whom and how large; the one the file holds now says so, the others
|
||||
* can be restored, and any of them saved to the phone as it was ([onDownload]; a 48 dp button
|
||||
* before the row's last part, so the buttons stand in one column whatever that part says).
|
||||
*/
|
||||
@Composable
|
||||
fun VersionsContent(name: String, state: VersionsState, onRestore: (FileVersion) -> Unit = {}, onClose: () -> Unit = {}) {
|
||||
fun VersionsContent(
|
||||
name: String,
|
||||
state: VersionsState,
|
||||
onRestore: (FileVersion) -> Unit = {},
|
||||
onClose: () -> Unit = {},
|
||||
onDownload: ((FileVersion) -> Unit)? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
Scaffold(
|
||||
@@ -447,12 +506,22 @@ fun VersionsContent(name: String, state: VersionsState, onRestore: (FileVersion)
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.versions, key = { it.id }) { version ->
|
||||
val download: (@Composable () -> Unit)? = if (onDownload != null) {
|
||||
{
|
||||
IconButton(onClick = { onDownload(version) }) {
|
||||
Icon(Icons.Filled.Download, contentDescription = stringResource(R.string.download))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
ListItem(
|
||||
headlineContent = { Text(ScheduleLogic.moment(version.at) ?: version.id, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = {
|
||||
val facts = listOfNotNull(version.by?.ifBlank { null }, Formatter.formatShortFileSize(context, version.size))
|
||||
Text(facts.joinToString(" · "), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
},
|
||||
leadingContent = download,
|
||||
trailingContent = {
|
||||
if (version.current) {
|
||||
Text(stringResource(R.string.version_current), style = MaterialTheme.typography.labelLarge, color = palette.inkMuted)
|
||||
|
||||
@@ -83,8 +83,10 @@ import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.BatchAnswer
|
||||
import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileExists
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileListing
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
@@ -138,9 +140,6 @@ data class FilesState(
|
||||
selected = if (same) selected intersect there else emptySet(),
|
||||
)
|
||||
}
|
||||
|
||||
/** Whether something here is already called [name]: a new file is never written over one. */
|
||||
fun taken(name: String): Boolean = entries.any { it.name == name.trim() }
|
||||
}
|
||||
|
||||
/** What a batch ended in: the server's sentences for what it refused, and the word for what it did. */
|
||||
@@ -270,19 +269,20 @@ class FilesViewModel(app: Application) : AndroidViewModel(app) {
|
||||
null
|
||||
}
|
||||
|
||||
/** A new, empty text file -- never over one that is there -- and [then] its path, to open it for writing. */
|
||||
fun newFile(name: String, then: (String) -> Unit) {
|
||||
val now = _state.value
|
||||
if (now.taken(name)) {
|
||||
_state.update { it.copy(said = app.getString(R.string.files_taken, name)) }
|
||||
return
|
||||
}
|
||||
write { api ->
|
||||
val path = FileKinds.child(now.path, name)
|
||||
api.saveFile(path, "")
|
||||
/**
|
||||
* A new, empty text file, and [then] its path, to open it for writing. The instance makes it
|
||||
* only where nothing is called that (`create`): otherwise nothing is written and its own
|
||||
* sentence says what is there.
|
||||
*/
|
||||
fun newFile(name: String, then: (String) -> Unit) = write { api ->
|
||||
val path = FileKinds.child(_state.value.path, name)
|
||||
try {
|
||||
api.saveFile(path, "", create = true)
|
||||
then(path)
|
||||
null
|
||||
} catch (e: FileExists) {
|
||||
_state.update { it.copy(said = e.message?.ifBlank { null } ?: app.getString(R.string.files_taken, name)) }
|
||||
}
|
||||
null
|
||||
}
|
||||
|
||||
fun rename(entry: FileEntry, name: String) = write { api ->
|
||||
@@ -352,14 +352,16 @@ class FilesViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun FilesScreen(onBack: () -> Unit, model: FilesViewModel = viewModel(), transfers: TransferViewModel = viewModel()) {
|
||||
fun FilesScreen(onBack: () -> Unit, start: String? = null, model: FilesViewModel = viewModel(), transfers: TransferViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
val context = LocalContext.current
|
||||
var viewing by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var writing by rememberSaveable { mutableStateOf(false) }
|
||||
var asked by remember { mutableStateOf<Ask?>(null) }
|
||||
var saving by remember { mutableStateOf<List<FileEntry>>(emptyList()) }
|
||||
LaunchedEffect(Unit) { if (state.entries.isEmpty() && state.error == null) model.open(state.path) }
|
||||
// Opened at a folder ([start]: where a generated file is) the first time; after that, where the person walked to.
|
||||
LaunchedEffect(Unit) { if (state.entries.isEmpty() && state.error == null) model.open(start?.ifBlank { null } ?: state.path) }
|
||||
val saveVersion = rememberSaver(transfers)
|
||||
LaunchedEffect(state.notice) {
|
||||
state.notice?.let {
|
||||
Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
|
||||
@@ -520,6 +522,7 @@ fun FilesScreen(onBack: () -> Unit, model: FilesViewModel = viewModel(), transfe
|
||||
|
||||
is Ask.Versions -> VersionsDialog(
|
||||
now.entry.path,
|
||||
onDownload = { version -> saveVersion(Raw.Path(now.entry.path, version.id), now.entry.name, now.entry.mime) },
|
||||
onClose = { asked = null },
|
||||
onRestored = {
|
||||
asked = null
|
||||
|
||||
@@ -7,6 +7,7 @@ import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.text.format.Formatter
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
@@ -18,6 +19,9 @@ import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
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.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
@@ -30,6 +34,7 @@ import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
@@ -71,12 +76,27 @@ class TransferViewModel(app: Application) : AndroidViewModel(app) {
|
||||
_state.update { it.copy(notice = app.getString(R.string.files_downloaded)) }
|
||||
}
|
||||
|
||||
fun openWith(path: String, name: String, mime: String) = start { api, progress ->
|
||||
/** One thing's bytes -- a version of a file, a generated file by its id, an attachment -- into the document [to]. */
|
||||
fun download(what: Raw, to: Uri) = start { api, progress ->
|
||||
api.downloadTo(app, api.raw(what), to, progress)
|
||||
_state.update { it.copy(notice = app.getString(R.string.files_downloaded)) }
|
||||
}
|
||||
|
||||
fun openWith(path: String, name: String, mime: String) = openWith(Raw.Path(path), name, mime)
|
||||
|
||||
fun openWith(what: Raw, name: String, mime: String) = start { api, progress ->
|
||||
FileCache.sweepShared(app)
|
||||
val copy = api.copyInto(api.rawFile(path), FileCache.shared(app, name), progress = progress)
|
||||
val copy = api.copyInto(api.raw(what), FileCache.shared(app, name), progress = progress)
|
||||
_state.update { it.copy(launch = Handover.view(app, copy, mime)) }
|
||||
}
|
||||
|
||||
/** One thing that is not named by a path (a generated file by its id), shared as itself. */
|
||||
fun share(what: Raw, name: String, mime: String) = start { api, progress ->
|
||||
FileCache.sweepShared(app)
|
||||
val copy = api.copyInto(api.raw(what), FileCache.shared(app, name), progress = progress)
|
||||
_state.update { it.copy(launch = Handover.share(app, listOf(copy), mime.ifBlank { "*/*" })) }
|
||||
}
|
||||
|
||||
/** A few files go as themselves; many, or any folder, as one zip the instance makes. */
|
||||
fun share(entries: List<FileEntry>) = start { api, progress ->
|
||||
if (entries.isEmpty()) return@start
|
||||
@@ -135,6 +155,24 @@ class TransferViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* "Save to" for one thing: the system's page for where it goes, and then the download into the
|
||||
* document chosen there. What is to be saved is kept while that page is open.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberSaver(transfers: TransferViewModel): (what: Raw, name: String, mime: String) -> Unit {
|
||||
var pending by remember { mutableStateOf<Raw?>(null) }
|
||||
val page = rememberLauncherForActivityResult(CreateFile()) { to ->
|
||||
val what = pending
|
||||
pending = null
|
||||
if (to != null && what != null) transfers.download(what, to)
|
||||
}
|
||||
return { what, name, mime ->
|
||||
pending = what
|
||||
page.launch(CreateFile.Ask(FileKinds.safeName(name), mime))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What a screen shows of its transfers: the one under way with Cancel, the other app once a
|
||||
* copy is ready, a failure in a dialog (it is a sentence to read), and a short word when one
|
||||
|
||||
@@ -24,11 +24,15 @@ import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.MusicNote
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
@@ -47,14 +51,18 @@ import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LifecycleEventEffect
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.RangeReader
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.api.sampleFor
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.files.FileCache
|
||||
@@ -271,10 +279,11 @@ private fun PdfPagesList(pages: PdfPages) {
|
||||
/**
|
||||
* A file on the instance as the platform's player reads it: piece by piece, each a `Range`
|
||||
* request made by the app's own HTTP client with the token in its header. The player is never
|
||||
* given an address, so the token is never in one.
|
||||
* given an address, so the token is never in one. [what] is a file by its path or by its node
|
||||
* id (what a generated file's result carries).
|
||||
*/
|
||||
class RemoteMedia(api: ApiClient, path: String, private val length: Long) : MediaDataSource() {
|
||||
private val reader = RangeReader(length) { from, to -> api.rawBytes(path, from, to) }
|
||||
class RemoteMedia(api: ApiClient, what: Raw, private val length: Long) : MediaDataSource() {
|
||||
private val reader = RangeReader(length) { from, to -> api.rawBytes(what, from, to) }
|
||||
|
||||
override fun readAt(position: Long, buffer: ByteArray, offset: Int, size: Int): Int = reader.read(position, buffer, offset, size)
|
||||
|
||||
@@ -283,32 +292,39 @@ class RemoteMedia(api: ApiClient, path: String, private val length: Long) : Medi
|
||||
override fun close() = reader.close()
|
||||
}
|
||||
|
||||
/** The most a chat's attachment may weigh to be copied for the player. */
|
||||
const val ATTACHED_MAX_BYTES = 512L * 1024 * 1024
|
||||
|
||||
/**
|
||||
* Sound or video of the tree, streamed: it starts before the file is there, and seeking asks
|
||||
* for the piece it lands in. Leaving the app pauses it; leaving the viewer lets go of it.
|
||||
* Sound or video, played by the platform's player. A file of the tree ([Raw.Path], [Raw.Node])
|
||||
* is streamed: it starts before the file is there, and seeking asks for the piece it lands in.
|
||||
* A chat's attachment ([Raw.Attached]) is answered whole by the instance, so it is copied into
|
||||
* the private cache first and played from there; the copy goes when the player does. Leaving
|
||||
* the app pauses it; leaving the viewer lets go of it.
|
||||
*/
|
||||
@Composable
|
||||
fun MediaBody(path: String, size: Long, video: Boolean, fallback: @Composable (String?) -> Unit) {
|
||||
fun MediaBody(what: Raw, size: Long, video: Boolean, fallback: @Composable (String?) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var ui by remember(path) { mutableStateOf(PlayerUi()) }
|
||||
var failed by remember(path) { mutableStateOf(false) }
|
||||
var player by remember(path) { mutableStateOf<MediaPlayer?>(null) }
|
||||
var surface by remember(path) { mutableStateOf<SurfaceHolder?>(null) }
|
||||
var ratio by remember(path) { mutableStateOf(16f / 9f) }
|
||||
var ui by remember(what) { mutableStateOf(PlayerUi()) }
|
||||
var failed by remember(what) { mutableStateOf(false) }
|
||||
var said by remember(what) { mutableStateOf<String?>(null) }
|
||||
var player by remember(what) { mutableStateOf<MediaPlayer?>(null) }
|
||||
var surface by remember(what) { mutableStateOf<SurfaceHolder?>(null) }
|
||||
var ratio by remember(what) { mutableStateOf(16f / 9f) }
|
||||
|
||||
DisposableEffect(path) {
|
||||
DisposableEffect(what) {
|
||||
var held: MediaPlayer? = null
|
||||
var source: RemoteMedia? = null
|
||||
var copy: File? = null
|
||||
val starting = scope.launch {
|
||||
val api = context.lembas.instances.client()
|
||||
if (api == null || size <= 0) {
|
||||
if (api == null || (size <= 0 && what !is Raw.Attached)) {
|
||||
failed = true
|
||||
return@launch
|
||||
}
|
||||
try {
|
||||
val media = RemoteMedia(api, path, size).also { source = it }
|
||||
val made = MediaPlayer().also { held = it }
|
||||
made.setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
@@ -316,7 +332,13 @@ fun MediaBody(path: String, size: Long, video: Boolean, fallback: @Composable (S
|
||||
.setContentType(if (video) AudioAttributes.CONTENT_TYPE_MOVIE else AudioAttributes.CONTENT_TYPE_MUSIC)
|
||||
.build(),
|
||||
)
|
||||
made.setDataSource(media)
|
||||
if (what is Raw.Attached) {
|
||||
val local = FileCache.viewing(context, "attachment").also { copy = it }
|
||||
api.copyInto(api.raw(what), local, ATTACHED_MAX_BYTES)
|
||||
made.setDataSource(local.path)
|
||||
} else {
|
||||
made.setDataSource(RemoteMedia(api, what, size).also { source = it })
|
||||
}
|
||||
made.setOnPreparedListener {
|
||||
ui = ui.copy(ready = true, durationMs = it.duration.coerceAtLeast(0))
|
||||
player = it
|
||||
@@ -328,7 +350,11 @@ fun MediaBody(path: String, size: Long, video: Boolean, fallback: @Composable (S
|
||||
}
|
||||
made.setOnVideoSizeChangedListener { _, w, h -> if (w > 0 && h > 0) ratio = (w.toFloat() / h).coerceIn(0.3f, 4f) }
|
||||
made.prepareAsync()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// The instance's refusal of a copy is a sentence to read; the player's own failure is not.
|
||||
said = if (e is ApiException || unreachable(e)) viewerSays(context, e) else null
|
||||
failed = true
|
||||
}
|
||||
}
|
||||
@@ -337,6 +363,7 @@ fun MediaBody(path: String, size: Long, video: Boolean, fallback: @Composable (S
|
||||
player = null
|
||||
held?.runCatching { release() }
|
||||
source?.runCatching { close() }
|
||||
copy?.runCatching { delete() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -354,7 +381,7 @@ fun MediaBody(path: String, size: Long, video: Boolean, fallback: @Composable (S
|
||||
}
|
||||
|
||||
if (failed) {
|
||||
fallback(null)
|
||||
fallback(said)
|
||||
return
|
||||
}
|
||||
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
@@ -405,3 +432,67 @@ fun MediaBody(path: String, size: Long, video: Boolean, fallback: @Composable (S
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** What a player opened over a chat plays: which bytes, what it is called, how large, and whether there is a picture. */
|
||||
data class Playing(val what: Raw, val title: String, val size: Long, val video: Boolean)
|
||||
|
||||
/** How a player's file was found before it was handed to the player. */
|
||||
private sealed interface Probed {
|
||||
data object Asking : Probed
|
||||
|
||||
data object There : Probed
|
||||
|
||||
data class Refused(val message: String?) : Probed
|
||||
}
|
||||
|
||||
/**
|
||||
* A player over the whole screen, for a file a chat names: a generated video or track (by its
|
||||
* node id) or an attachment. A file of the tree is asked for its first byte before the player
|
||||
* gets it, so one that is no longer there says so in a sentence rather than as a player that
|
||||
* does not start. Back or the cross closes it and lets go of the player.
|
||||
*/
|
||||
@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun PlayerDialog(playing: Playing, onClose: () -> Unit, gone: String) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val probed by produceState<Probed>(Probed.Asking, playing.what) {
|
||||
if (playing.what is Raw.Attached) {
|
||||
value = Probed.There
|
||||
return@produceState
|
||||
}
|
||||
value = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
withContext(Dispatchers.IO) { api.rawBytes(playing.what, 0, 0) }
|
||||
Probed.There
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// By its id the instance's own refusal names the id; "no longer there" is what a person reads.
|
||||
Probed.Refused(if (e is ApiException && e.status == 404) gone else viewerSays(context, e))
|
||||
}
|
||||
}
|
||||
val unplayable: @Composable (String?) -> Unit = { note ->
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(note ?: stringResource(R.string.files_not_shown), color = palette.inkMuted, modifier = Modifier.padding(32.dp))
|
||||
}
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = onClose) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = { Text(playing.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
when (val now = probed) {
|
||||
Probed.Asking -> Progress(Fetched.Loading())
|
||||
is Probed.Refused -> unplayable(now.message)
|
||||
Probed.There -> MediaBody(playing.what, playing.size, playing.video, unplayable)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,7 @@ import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileView
|
||||
import eu.llembas.android.api.Notebook
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.api.SaveConflict
|
||||
import eu.llembas.android.api.Table
|
||||
import eu.llembas.android.api.parseNotebook
|
||||
@@ -68,6 +69,7 @@ import eu.llembas.android.ui.files.TransferViewModel
|
||||
import eu.llembas.android.ui.files.VersionsDialog
|
||||
import eu.llembas.android.ui.files.filesSay
|
||||
import eu.llembas.android.ui.files.noSuchRoute
|
||||
import eu.llembas.android.ui.files.rememberSaver
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -148,6 +150,9 @@ fun TreeFileViewer(path: String, onClose: () -> Unit, startEditing: Boolean = fa
|
||||
var conflict by remember { mutableStateOf<String?>(null) }
|
||||
var said by remember { mutableStateOf<String?>(null) }
|
||||
var wantsEdit by remember(path) { mutableStateOf(startEditing) }
|
||||
// A table can be read as the text it is, as well as laid out.
|
||||
var tableAsText by remember(path) { mutableStateOf(false) }
|
||||
val saveVersion = rememberSaver(transfers)
|
||||
val name = FileKinds.name(path)
|
||||
|
||||
LaunchedEffect(path, reads) {
|
||||
@@ -255,6 +260,9 @@ fun TreeFileViewer(path: String, onClose: () -> Unit, startEditing: Boolean = fa
|
||||
}
|
||||
val text = file.text.takeIf { file.withheld == null && it.isNotEmpty() }
|
||||
if (text != null) MenuEntry(R.string.viewer_copy, then { copy(context, name, text) })
|
||||
if (text != null && FileKinds.viewer(file.fileKind) == FileView.Table) {
|
||||
MenuEntry(if (tableAsText) R.string.table_as_table else R.string.table_as_text, then { tableAsText = !tableAsText })
|
||||
}
|
||||
if (file.fileKind != null) {
|
||||
MenuEntry(R.string.download, then { actions.download() })
|
||||
MenuEntry(R.string.files_open_with, then { actions.openWith() })
|
||||
@@ -275,7 +283,7 @@ fun TreeFileViewer(path: String, onClose: () -> Unit, startEditing: Boolean = fa
|
||||
when (val now = opened) {
|
||||
Opened.Loading -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
is Opened.Failed -> Text(now.message, color = palette.inkMuted, modifier = Modifier.align(Alignment.Center).padding(32.dp))
|
||||
is Opened.Ready -> if (draft != null) EditorBody(draft, edit::type, enabled = !saving) else Shown(path, now.file, actions)
|
||||
is Opened.Ready -> if (draft != null) EditorBody(draft, edit::type, enabled = !saving) else Shown(path, now.file, actions, tableAsText)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -328,6 +336,7 @@ fun TreeFileViewer(path: String, onClose: () -> Unit, startEditing: Boolean = fa
|
||||
if (versions) {
|
||||
VersionsDialog(
|
||||
path,
|
||||
onDownload = { version -> saveVersion(Raw.Path(path, version.id), name, file?.mime.orEmpty()) },
|
||||
onClose = { versions = false },
|
||||
onRestored = {
|
||||
versions = false
|
||||
@@ -344,7 +353,7 @@ private fun MenuEntry(label: Int, onClick: () -> Unit) = DropdownMenuItem(text =
|
||||
|
||||
/** A file that was read, by its kind. What cannot be drawn falls back to the details page, saying why. */
|
||||
@Composable
|
||||
private fun Shown(path: String, file: FileContent, actions: FileActions) {
|
||||
private fun Shown(path: String, file: FileContent, actions: FileActions, tableAsText: Boolean = false) {
|
||||
val context = LocalContext.current
|
||||
val name = file.name.ifBlank { FileKinds.name(path) }
|
||||
val type = listOf(file.fileKind.orEmpty(), file.mime).filter { it.isNotBlank() }.joinToString(" · ")
|
||||
@@ -369,11 +378,13 @@ private fun Shown(path: String, file: FileContent, actions: FileActions) {
|
||||
|
||||
FileView.Pdf -> PdfBody(path, name, file.size, details)
|
||||
|
||||
FileView.Audio -> MediaBody(path, file.size, video = false, fallback = details)
|
||||
FileView.Audio -> MediaBody(Raw.Path(path), file.size, video = false, fallback = details)
|
||||
|
||||
FileView.Video -> MediaBody(path, file.size, video = true, fallback = details)
|
||||
FileView.Video -> MediaBody(Raw.Path(path), file.size, video = true, fallback = details)
|
||||
|
||||
FileView.Table -> {
|
||||
FileView.Table -> if (tableAsText && withheld == null) {
|
||||
FileBody("text", "", 0, file.text)
|
||||
} else {
|
||||
val table by produceState<Fetched<Table>>(Fetched.Loading(), path, file.sha) {
|
||||
value = try {
|
||||
// Up to 1 MB the server sent the text; of a longer table the first megabyte is asked for.
|
||||
|
||||
Reference in new issue
Block a user