Files is a file manager, and the viewer draws a file by what it is
CI / check (push) Canceled after 0s
CI / check (push) Canceled after 0s
Files listed and showed text. It now does what the web's explorer does, through the server's /api/v2/files routes: upload (the system picker, several at once, each streamed from where it is with its progress, one request a file so a 413 for one does not take the others), new folder, new text file (never over one that is there), rename, move and copy through a folder picker that is walked rather than typed into, delete to the trash, a long press to choose and a bar that moves, copies, downloads, shares or deletes all that is chosen through /files/batch -- which answers path by path, and what it refused is said in its own sentences. The trash: list, restore, remove for good, empty. A file's versions: list, restore. Leaving the instance: a download goes into a document the person chose (ACTION_CREATE_DOCUMENT), streamed, several things or a folder as the server's zip. Open with and Share hand another app a copy in the private cache through the FileProvider the camera already uses (one more cache-path, read-only, per grant); the copies go when Files is left, when the app starts and at sign-out. No permission is added. The viewer goes by file_kind. Text kinds as before, now editable up to the server's 1 MB: a save says the sha it opened, a 409 shows the server's sentence with Reload and Save anyway, and leaving with unsaved text asks. The text being edited lives in a ViewModel: a megabyte does not fit a saved instance state. A picture is copied to the cache, decoded with its edge and pixel count capped whatever the file claims, and zooms and pans. A PDF is drawn page by page by the platform's PdfRenderer from a cache copy. Sound and video are played by the platform's MediaPlayer through a MediaDataSource that asks the app's own HTTP client for each piece with a Range request: the token stays in the Authorization header and the player is never given an address, so no player library is added. CSV and TSV are a grid with a row and column cap; a notebook is its cells' text, outputs as plain text only. Archives, 3D models and binaries are their details with Download, Open with and Share. An SVG is its source: the app has no WebView and draws nothing a file could script. Nothing is rendered as HTML. The share sheet has a third place to send to: Save to Files, into a folder chosen with the same picker; shared text is kept as a note. Strings: 61 new keys, 49 worded as the server's explorer words them and translated from its catalogues at the pinned commit, 12 the app's own in all eight languages. An instance without these routes still lists and shows text; what it cannot do says so. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
32 files changed
+4618
-138
No files matched your search
@@ -33,6 +33,8 @@ class LembasApp : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
instances = InstanceStore(this)
|
||||
// Copies of the account's files a viewer or another app was handed, left by a process that was killed.
|
||||
eu.llembas.android.ui.files.FileCache.clear(this)
|
||||
// Whether the app is on screen: the wake word may open the assistant's sheet as an
|
||||
// activity only then (Android blocks one started from the background, silently).
|
||||
registerActivityLifecycleCallbacks(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.KSerializer
|
||||
@@ -22,6 +23,7 @@ import okhttp3.RequestBody
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import okhttp3.Response
|
||||
import java.io.IOException
|
||||
import java.io.OutputStream
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
@@ -600,6 +602,181 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
return call(authed(url.toString()).get().build(), FileContent.serializer())
|
||||
}
|
||||
|
||||
// --- The file manager's writes, the trash, versions and bytes ---------------------------------
|
||||
// Each write answers the listing of the directory it changed; a refusal is the tree's own
|
||||
// sentence (400), a path that cannot be read a 404, and both come back as an ApiException.
|
||||
|
||||
private fun filesUrl(path: String, vararg query: Pair<String, String?>): String = "$v2/files$path".toHttpUrl().newBuilder()
|
||||
.apply { query.forEach { (name, value) -> if (value != null) addQueryParameter(name, value) } }
|
||||
.build()
|
||||
.toString()
|
||||
|
||||
suspend fun makeFolder(dir: String, name: String): FileListing = send(
|
||||
"POST",
|
||||
"/files/mkdir",
|
||||
buildJsonObject {
|
||||
put("path", dir)
|
||||
put("name", name)
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun renameFile(path: String, name: String): FileListing = send(
|
||||
"POST",
|
||||
"/files/rename",
|
||||
buildJsonObject {
|
||||
put("path", path)
|
||||
put("name", name)
|
||||
},
|
||||
)
|
||||
|
||||
/** Copy [path] into the directory [to]; the answer's `copied` says what the copy is called. */
|
||||
suspend fun copyFile(path: String, to: String, name: String? = null): FileListing = send(
|
||||
"POST",
|
||||
"/files/copy",
|
||||
buildJsonObject {
|
||||
put("path", path)
|
||||
put("to", to)
|
||||
name?.let { put("name", it) }
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* Move or copy [paths] into the directory [to], or delete them (to the trash): `op` is
|
||||
* `move`, `copy` or `delete`. Each path is done by itself, so the answer is read for what
|
||||
* failed even though the request succeeded.
|
||||
*/
|
||||
suspend fun batchFiles(op: String, paths: List<String>, to: String? = null): BatchAnswer = send(
|
||||
"POST",
|
||||
"/files/batch",
|
||||
buildJsonObject {
|
||||
put("op", op)
|
||||
put("paths", JsonArray(paths.map { JsonPrimitive(it) }))
|
||||
to?.let { put("to", it) }
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* Save a text file. [base] is the `sha` the file had when it was opened: when it holds
|
||||
* something else by now the server writes nothing and this throws [SaveConflict] with its
|
||||
* sentence, unless [force]. Without a [base] nothing is compared, and a path with no file
|
||||
* makes one.
|
||||
*/
|
||||
suspend fun saveFile(path: String, text: String, base: String? = null, force: Boolean = false): FileContent = withContext(Dispatchers.IO) {
|
||||
val body = buildJsonObject {
|
||||
put("path", path)
|
||||
put("text", text)
|
||||
base?.takeIf { it.isNotBlank() }?.let { put("base", it) }
|
||||
if (force) put("force", true)
|
||||
}
|
||||
http.newCall(authed("$v2/files/content").put(body.toString().toRequestBody(JSON)).build()).await().use { response ->
|
||||
val said = runCatching { response.body?.string().orEmpty() }.getOrDefault("")
|
||||
if (response.code == 409) {
|
||||
val conflict = runCatching { LembasJson.parseToJsonElement(said) as? JsonObject }.getOrNull() ?: JsonObject(emptyMap())
|
||||
if ((conflict["conflict"] as? JsonPrimitive)?.content == "true") {
|
||||
throw SaveConflict(refusal(said).orEmpty(), (conflict["sha"] as? JsonPrimitive)?.takeUnless { it is JsonNull }?.content.orEmpty())
|
||||
}
|
||||
}
|
||||
if (!response.isSuccessful) throw ApiException(response.code, refusal(said) ?: "The server answered ${response.code}.")
|
||||
LembasJson.decodeFromString(FileContent.serializer(), said)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun trash(): TrashList = get("/files/trash")
|
||||
|
||||
suspend fun restoreTrashed(id: String): TrashList = send("POST", "/files/restore", buildJsonObject { put("id", id) })
|
||||
|
||||
/** Remove for good: the one thing named, or with no [id] everything in the trash. */
|
||||
suspend fun removeTrashed(id: String? = null): TrashList = call(authed(filesUrl("/trash", "id" to id)).delete().build(), TrashList.serializer())
|
||||
|
||||
suspend fun fileVersions(path: String): FileVersions = call(authed(filesUrl("/versions", "path" to path)).get().build(), FileVersions.serializer())
|
||||
|
||||
/** Make an older version the file again, as a new version: nothing is lost. */
|
||||
suspend fun restoreVersion(path: String, version: String): FileVersions = send(
|
||||
"POST",
|
||||
"/files/versions/restore",
|
||||
buildJsonObject {
|
||||
put("path", path)
|
||||
put("version", version)
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* Upload one file into the directory [dir], streamed: [body] writes the file's bytes as they
|
||||
* are read, so a large file is never held in memory. A file over the instance's limit is a
|
||||
* 413 whose sentence names it.
|
||||
*/
|
||||
suspend fun uploadFile(dir: String, name: String, body: RequestBody): FileListing {
|
||||
val form = MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("files", name, body).build()
|
||||
return call(authed(filesUrl("/upload", "path" to dir)).post(form).build(), FileListing.serializer())
|
||||
}
|
||||
|
||||
/**
|
||||
* The request for a file's bytes (`/files/raw`), or for [range] of them. The token goes in
|
||||
* the Authorization header, as on every call: the address names the path and nothing else.
|
||||
*/
|
||||
fun rawFile(path: String, range: LongRange? = null, inline: Boolean = false): Request = authed(
|
||||
filesUrl(
|
||||
"/raw",
|
||||
"path" to path,
|
||||
"inline" to if (inline) "1" else null,
|
||||
),
|
||||
)
|
||||
.header("Accept", "*/*")
|
||||
.apply { range?.let { header("Range", "bytes=${it.first}-${it.last}") } }
|
||||
.get()
|
||||
.build()
|
||||
|
||||
/** The request for [paths] (files and folders) as one zip. */
|
||||
fun zipFiles(paths: List<String>): Request = authed("$v2/files/zip")
|
||||
.header("Accept", "*/*")
|
||||
.post(buildJsonObject { put("paths", JsonArray(paths.map { JsonPrimitive(it) })) }.toString().toRequestBody(JSON))
|
||||
.build()
|
||||
|
||||
/**
|
||||
* Run [request] and copy what it answers into [out] as it comes, saying how far it is
|
||||
* ([progress]: bytes so far, and the total when the server said one, else -1). At most
|
||||
* [most] bytes are taken: more than that is refused as a 413, with nothing more read.
|
||||
*/
|
||||
suspend fun download(request: Request, out: OutputStream, most: Long = Long.MAX_VALUE, progress: (done: Long, total: Long) -> Unit = { _, _ -> }): Long =
|
||||
withContext(Dispatchers.IO) {
|
||||
http.newCall(request).await().use { response ->
|
||||
if (!response.isSuccessful) throw ApiException(response.code, detail(response))
|
||||
val body = response.body ?: throw ApiException(response.code, "")
|
||||
val total = body.contentLength()
|
||||
if (total > most) throw ApiException(413, "")
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
var done = 0L
|
||||
body.byteStream().use { stream ->
|
||||
while (true) {
|
||||
ensureActive()
|
||||
val n = stream.read(buffer)
|
||||
if (n < 0) break
|
||||
done += n
|
||||
if (done > most) throw ApiException(413, "")
|
||||
out.write(buffer, 0, n)
|
||||
progress(done, total)
|
||||
}
|
||||
}
|
||||
out.flush()
|
||||
done
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The bytes `[from, to]` of a file, for a player or a table's first rows: a `Range` request,
|
||||
* blocking, on whatever thread asks (never the main one). A server that answers the whole
|
||||
* file to a range that does not start at 0 is refused rather than read from the wrong place.
|
||||
*/
|
||||
fun rawBytes(path: String, from: Long, to: Long): ByteArray = http.newCall(rawFile(path, from..to)).execute().use { response ->
|
||||
if (!response.isSuccessful) throw ApiException(response.code, detail(response))
|
||||
if (response.code != 206 && from > 0) throw ApiException(416, "")
|
||||
val want = to - from + 1
|
||||
response.body!!.source().use { source ->
|
||||
source.request(want)
|
||||
source.buffer.readByteArray(minOf(source.buffer.size, want))
|
||||
}
|
||||
}
|
||||
|
||||
/** A file of the tree in the web UI's own viewer (`/files/view`), for what the app does not draw. */
|
||||
fun webFile(path: String): String = "$base/files/view".toHttpUrl().newBuilder().addQueryParameter("path", path).build().toString()
|
||||
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import java.io.IOException
|
||||
|
||||
// The person's files as a file manager needs them: the shapes of the trash, the versions and a
|
||||
// batch (`contract/files_*.json`, `file_versions.json`, `file_save_conflict.json`), and what the
|
||||
// app decides from a file's kind without a phone: which viewer, a table's rows, a notebook's cells.
|
||||
|
||||
/** One thing in the trash: restored or removed for good by its [id]. */
|
||||
@Serializable
|
||||
data class TrashItem(
|
||||
val id: String = "",
|
||||
val name: String = "",
|
||||
val path: String = "",
|
||||
val kind: String = "file",
|
||||
val size: Long = 0,
|
||||
@SerialName("trashed_at") val trashedAt: String? = null,
|
||||
)
|
||||
|
||||
/** `GET /files/trash`, and what is left after a restore ([restored]: where it went back to) or a removal. */
|
||||
@Serializable
|
||||
data class TrashList(val items: List<TrashItem> = emptyList(), val restored: String? = null, val removed: Int = 0)
|
||||
|
||||
/** One version of a file, newest first in [FileVersions]; [current] is what the file holds now. */
|
||||
@Serializable
|
||||
data class FileVersion(
|
||||
val id: String = "",
|
||||
val sha: String = "",
|
||||
val size: Long = 0,
|
||||
val at: String? = null,
|
||||
val by: String? = null,
|
||||
@SerialName("chat_id") val chatId: String? = null,
|
||||
val current: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class FileVersions(val path: String = "", val sha: String = "", val versions: List<FileVersion> = emptyList())
|
||||
|
||||
/** One path of a batch: done ([ok], and where it is now) or refused, in the server's sentence. */
|
||||
@Serializable
|
||||
data class BatchResult(val path: String = "", val ok: Boolean = false, val to: String? = null, val error: String? = null)
|
||||
|
||||
/** `POST /files/batch`: never all-or-nothing, so [failed] is read even from a 200. */
|
||||
@Serializable
|
||||
data class BatchAnswer(val op: String = "", val to: String? = null, val results: List<BatchResult> = emptyList(), val done: Int = 0, val failed: Int = 0) {
|
||||
/** The server's sentences for what was refused, each once, at most [most]. */
|
||||
fun refusals(most: Int = 3): List<String> = results.filter { !it.ok }.mapNotNull { it.error?.ifBlank { null } }.distinct().take(most)
|
||||
}
|
||||
|
||||
/**
|
||||
* A save the server refused because the file changed since it was opened (409, `conflict: true`):
|
||||
* its sentence, and the [sha] the file holds now. Nothing was written.
|
||||
*/
|
||||
class SaveConflict(message: String, val sha: String) : IOException(message)
|
||||
|
||||
/** The viewer a file gets, by the server's word for what it is. */
|
||||
enum class FileView {
|
||||
/** Markdown, code, text, and the source of an HTML page or an SVG: drawn as text, editable. */
|
||||
Text,
|
||||
Image,
|
||||
Pdf,
|
||||
Audio,
|
||||
Video,
|
||||
Table,
|
||||
Notebook,
|
||||
|
||||
/** Nothing to draw here: what the file is, and Download, Open with, Share. */
|
||||
Details,
|
||||
}
|
||||
|
||||
object FileKinds {
|
||||
/** The kinds whose text the server hands over and the app may save back. */
|
||||
val TEXT = setOf("markdown", "code", "text", "html", "svg")
|
||||
|
||||
/**
|
||||
* The viewer for a file of [kind]. A server that does not say the kind (null) is read as
|
||||
* before: as text, and the content answer says when it is not. An SVG is its source -- the
|
||||
* app has no WebView and draws nothing a file could script.
|
||||
*/
|
||||
fun viewer(kind: String?): FileView = when (kind) {
|
||||
null, "", in TEXT -> FileView.Text
|
||||
"image" -> FileView.Image
|
||||
"pdf" -> FileView.Pdf
|
||||
"audio" -> FileView.Audio
|
||||
"video" -> FileView.Video
|
||||
"table" -> FileView.Table
|
||||
"notebook" -> FileView.Notebook
|
||||
else -> FileView.Details
|
||||
}
|
||||
|
||||
/** Whether the app offers to edit it: a text kind (a table too, as its text) the person may change. */
|
||||
fun editable(kind: String?, writable: Boolean?, withheld: Boolean): Boolean = writable == true && !withheld && (kind in TEXT || kind == "table")
|
||||
|
||||
/** Why [name] cannot be a file's or a folder's name, as the server would refuse it; false for a good one. */
|
||||
fun badName(name: String): Boolean = name.isBlank() || "/" in name || name.trim() in setOf(".", "..")
|
||||
|
||||
/** [name] inside the directory [dir]. */
|
||||
fun child(dir: String, name: String): String = dir.trimEnd('/') + "/" + name.trim()
|
||||
|
||||
/** The directory a path is in; `/` for a path at the top. */
|
||||
fun parent(path: String): String = path.trimEnd('/').substringBeforeLast('/', "").ifEmpty { "/" }
|
||||
|
||||
/** The last name of a path. */
|
||||
fun name(path: String): String = path.trimEnd('/').substringAfterLast('/').ifBlank { path }
|
||||
|
||||
/** A name another app may be given: no separators, no control characters, never empty. */
|
||||
fun safeName(name: String): String {
|
||||
val kept = name.map { if (it == '/' || it == '\\' || it.isISOControl()) '_' else it }.joinToString("")
|
||||
return kept.trim().trim('.').ifBlank { "file" }.takeLast(120)
|
||||
}
|
||||
}
|
||||
|
||||
/** A table's first rows and columns; [cut] when the file has more than is laid out. */
|
||||
data class Table(val rows: List<List<String>>, val columns: Int, val cut: Boolean)
|
||||
|
||||
/**
|
||||
* A CSV or TSV file as rows of cells: quoted cells, doubled quotes and line breaks inside quotes
|
||||
* as RFC 4180 has them. At most [maxRows] rows of at most [maxColumns] cells are kept, each cell
|
||||
* at most [maxCell] characters -- a table is for looking at, the text has all of it. [partial]:
|
||||
* the text is only the file's beginning, so its last line may be half a row and is left out.
|
||||
*/
|
||||
fun parseTable(text: String, delimiter: Char, maxRows: Int = 500, maxColumns: Int = 40, maxCell: Int = 200, partial: Boolean = false): Table {
|
||||
val rows = mutableListOf<List<String>>()
|
||||
var row = mutableListOf<String>()
|
||||
val cell = StringBuilder()
|
||||
var quoted = false
|
||||
var cut = partial
|
||||
var widest = 0
|
||||
var i = 0
|
||||
|
||||
fun endCell() {
|
||||
if (row.size < maxColumns) row += cell.toString().take(maxCell) else cut = true
|
||||
cell.setLength(0)
|
||||
}
|
||||
|
||||
fun endRow(): Boolean {
|
||||
endCell()
|
||||
if (row.size > 1 || row[0].isNotEmpty()) {
|
||||
rows += row
|
||||
widest = maxOf(widest, row.size)
|
||||
}
|
||||
row = mutableListOf()
|
||||
return rows.size < maxRows
|
||||
}
|
||||
|
||||
var open = true
|
||||
while (i < text.length) {
|
||||
val c = text[i]
|
||||
when {
|
||||
quoted && c == '"' && i + 1 < text.length && text[i + 1] == '"' -> {
|
||||
cell.append('"')
|
||||
i++
|
||||
}
|
||||
|
||||
c == '"' && (quoted || cell.isEmpty()) -> quoted = !quoted
|
||||
|
||||
!quoted && c == delimiter -> endCell()
|
||||
|
||||
!quoted && (c == '\n' || c == '\r') -> {
|
||||
if (c == '\r' && i + 1 < text.length && text[i + 1] == '\n') i++
|
||||
if (!endRow()) {
|
||||
cut = cut || i + 1 < text.length
|
||||
open = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
else -> if (cell.length <= maxCell) cell.append(c)
|
||||
}
|
||||
i++
|
||||
}
|
||||
// What is left after the last line break: a whole last row, unless the text was cut short.
|
||||
if (open && !partial && (cell.isNotEmpty() || row.isNotEmpty())) endRow()
|
||||
return Table(rows, widest, cut)
|
||||
}
|
||||
|
||||
/** The delimiter a table file is cut by: a tab for `.tsv` (or a first line with tabs and no commas), else a comma. */
|
||||
fun tableDelimiter(name: String, text: String): Char {
|
||||
if (name.endsWith(".tsv", ignoreCase = true) || name.endsWith(".tab", ignoreCase = true)) return '\t'
|
||||
val first = text.lineSequence().firstOrNull().orEmpty()
|
||||
return if ('\t' in first && ',' !in first) {
|
||||
'\t'
|
||||
} else if (';' in first && ',' !in first) {
|
||||
';'
|
||||
} else {
|
||||
','
|
||||
}
|
||||
}
|
||||
|
||||
/** One cell of a notebook, as text: its [source], and what it printed ([output], plain text only). */
|
||||
data class NotebookCell(val kind: String, val source: String, val output: String = "", val count: Int? = null, val cut: Boolean = false)
|
||||
|
||||
/** A notebook's first cells; [more]: how many are not shown. Null from [parseNotebook]: not a notebook. */
|
||||
data class Notebook(val cells: List<NotebookCell>, val more: Int = 0, val language: String = "")
|
||||
|
||||
/**
|
||||
* A Jupyter notebook, read-only, as text and nothing else: a cell's source, and of its outputs
|
||||
* only the plain text (a stream, `text/plain`, an error's name and value). HTML, pictures and
|
||||
* scripts in an output are not drawn and not kept. Null for a file that is not a notebook.
|
||||
*/
|
||||
fun parseNotebook(text: String, maxCells: Int = 200, maxChars: Int = 20_000): Notebook? {
|
||||
val root = runCatching { LembasJson.parseToJsonElement(text) as? JsonObject }.getOrNull() ?: return null
|
||||
val cells = root["cells"] as? JsonArray ?: return null
|
||||
|
||||
fun words(of: JsonElement?): String = when (of) {
|
||||
is JsonPrimitive -> if (of.isString) of.content else ""
|
||||
is JsonArray -> of.joinToString("") { (it as? JsonPrimitive)?.takeIf { p -> p.isString }?.content.orEmpty() }
|
||||
else -> ""
|
||||
}
|
||||
|
||||
fun printed(cell: JsonObject): String = (cell["outputs"] as? JsonArray).orEmpty().mapNotNull { it as? JsonObject }.joinToString("") { out ->
|
||||
when ((out["output_type"] as? JsonPrimitive)?.content) {
|
||||
"stream" -> words(out["text"])
|
||||
"error" -> listOf(words(out["ename"]), words(out["evalue"])).filter { it.isNotBlank() }.joinToString(": ") + "\n"
|
||||
else -> words((out["data"] as? JsonObject)?.get("text/plain")).let { if (it.isEmpty() || it.endsWith("\n")) it else it + "\n" }
|
||||
}
|
||||
}.trimEnd('\n')
|
||||
|
||||
val language = (((root["metadata"] as? JsonObject)?.get("kernelspec") as? JsonObject)?.get("language") as? JsonPrimitive)?.content
|
||||
?: ((((root["metadata"] as? JsonObject)?.get("language_info") as? JsonObject)?.get("name")) as? JsonPrimitive)?.content
|
||||
val read = cells.mapNotNull { it as? JsonObject }.take(maxCells).map { cell ->
|
||||
val source = words(cell["source"])
|
||||
val output = printed(cell)
|
||||
NotebookCell(
|
||||
kind = (cell["cell_type"] as? JsonPrimitive)?.content ?: "code",
|
||||
source = source.take(maxChars),
|
||||
output = output.take(maxChars),
|
||||
count = (cell["execution_count"] as? JsonPrimitive)?.content?.toIntOrNull(),
|
||||
cut = source.length > maxChars || output.length > maxChars,
|
||||
)
|
||||
}
|
||||
return Notebook(read, more = (cells.size - read.size).coerceAtLeast(0), language = language.orEmpty())
|
||||
}
|
||||
|
||||
/**
|
||||
* How much smaller a picture of [width] × [height] is decoded (a power of two, `inSampleSize`):
|
||||
* so its longer edge is at most about [edge] and it holds at most [pixels] pixels, whatever the
|
||||
* file claims. A picture of 30 000 × 30 000 is then a few megabytes in memory, not gigabytes.
|
||||
*/
|
||||
fun sampleFor(width: Int, height: Int, edge: Int = 2560, pixels: Long = 8_000_000): Int {
|
||||
if (width <= 0 || height <= 0) return 1
|
||||
var sample = 1
|
||||
while (maxOf(width, height) / sample > edge || (width.toLong() / sample) * (height.toLong() / sample) > pixels) sample *= 2
|
||||
return sample
|
||||
}
|
||||
|
||||
/**
|
||||
* A file read a piece at a time, for a player that seeks: [fetch] gets the bytes `[from, to]`
|
||||
* (a `Range` request with the token in its header), a few blocks are kept, and a read is
|
||||
* answered from the block its position is in. [length] is the file's size as the server said it.
|
||||
*/
|
||||
class RangeReader(private val length: Long, private val block: Int = BLOCK, private val keep: Int = 6, private val fetch: (from: Long, to: Long) -> ByteArray) {
|
||||
private val blocks = object : LinkedHashMap<Long, ByteArray>(keep, 0.75f, true) {
|
||||
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, ByteArray>?): Boolean = size > keep
|
||||
}
|
||||
|
||||
/** Up to [size] bytes from [position] into [buffer] at [offset]; -1 at or past the end. */
|
||||
@Synchronized
|
||||
fun read(position: Long, buffer: ByteArray, offset: Int, size: Int): Int {
|
||||
if (position < 0 || position >= length) return -1
|
||||
if (size <= 0) return 0
|
||||
val index = position / block
|
||||
val start = index * block
|
||||
val bytes = blocks[index] ?: fetch(start, minOf(start + block, length) - 1).also { blocks[index] = it }
|
||||
val within = (position - start).toInt()
|
||||
if (within >= bytes.size) return -1
|
||||
val n = minOf(size, bytes.size - within)
|
||||
System.arraycopy(bytes, within, buffer, offset, n)
|
||||
return n
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun close() = blocks.clear()
|
||||
|
||||
companion object {
|
||||
const val BLOCK = 512 * 1024
|
||||
}
|
||||
}
|
||||
@@ -563,6 +563,12 @@ data class FileEntry(
|
||||
val name: String = "",
|
||||
val path: String = "",
|
||||
val kind: String = "file",
|
||||
/**
|
||||
* What the file is, read by the server from its name and its own bytes: `markdown`, `code`,
|
||||
* `text`, `html`, `image`, `svg`, `pdf`, `audio`, `video`, `table`, `notebook`, `model3d`,
|
||||
* `archive` or `binary`. Null for a folder, and from a server that does not say it.
|
||||
*/
|
||||
@SerialName("file_kind") val fileKind: String? = null,
|
||||
val size: Long = 0,
|
||||
val mime: String = "",
|
||||
@SerialName("updated_at") val updatedAt: String? = null,
|
||||
@@ -573,7 +579,13 @@ data class FileEntry(
|
||||
|
||||
/** A directory, through the person's own access. `parent` is null at `/`. */
|
||||
@Serializable
|
||||
data class FileListing(val path: String = "/", val parent: String? = null, val entries: List<FileEntry> = emptyList())
|
||||
data class FileListing(
|
||||
val path: String = "/",
|
||||
val parent: String? = null,
|
||||
val entries: List<FileEntry> = emptyList(),
|
||||
/** After a copy: the new entry, under the name the server gave it (a taken name is numbered). */
|
||||
val copied: FileEntry? = null,
|
||||
)
|
||||
|
||||
/** Why a file's text did not come: `reason` is `not_text` or `too_large`; `message` says it. */
|
||||
@Serializable
|
||||
@@ -590,7 +602,12 @@ data class FileContent(
|
||||
val size: Long = 0,
|
||||
val mime: String = "",
|
||||
val kind: String = "text",
|
||||
/** What the file is ([FileEntry.fileKind]); null from a server that does not say it. */
|
||||
@SerialName("file_kind") val fileKind: String? = null,
|
||||
/** Whether the person may change it; null from a server that does not say (then: no editing). */
|
||||
val writable: Boolean? = null,
|
||||
val language: String = "",
|
||||
/** What the file holds now: sent back as a save's `base`, so a save over somebody else's change is refused. */
|
||||
val sha: String = "",
|
||||
val text: String = "",
|
||||
val withheld: Withheld? = null,
|
||||
|
||||
@@ -5,17 +5,20 @@ import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.provider.OpenableColumns
|
||||
import android.widget.Toast
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.core.content.IntentCompat
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.assist.AssistSheetFrame
|
||||
import eu.llembas.android.assist.LastAssist
|
||||
@@ -23,6 +26,10 @@ import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.files.FolderPicker
|
||||
import eu.llembas.android.ui.files.describe
|
||||
import eu.llembas.android.ui.files.filesSay
|
||||
import eu.llembas.android.ui.files.uploadFrom
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
@@ -43,6 +50,7 @@ class ShareActivity :
|
||||
ShareActions {
|
||||
private val state = MutableStateFlow(ShareState())
|
||||
private var uris: List<Uri> = emptyList()
|
||||
private val choosing = MutableStateFlow(false)
|
||||
|
||||
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
||||
|
||||
@@ -70,18 +78,65 @@ class ShareActivity :
|
||||
?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) },
|
||||
)
|
||||
}
|
||||
// Where "Save to Files" starts: the folder the instance opens the person's files at.
|
||||
runCatching { store.client()?.files("/")?.path }.getOrNull()?.let { home -> state.update { it.copy(folder = it.folder ?: home) } }
|
||||
}
|
||||
setContent {
|
||||
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
val shown by state.collectAsState()
|
||||
val picking by choosing.collectAsState()
|
||||
LembasTheme(prefs.theme) {
|
||||
AssistSheetFrame(onDismiss = ::cancel) { handle, _ -> ShareSheetContent(shown, this@ShareActivity, handle) }
|
||||
if (picking) {
|
||||
FolderPicker(
|
||||
stringResource(R.string.files_choose_folder),
|
||||
stringResource(R.string.files_save_here),
|
||||
shown.folder ?: "/",
|
||||
onPick = { folder ->
|
||||
choosing.value = false
|
||||
state.update { it.copy(folder = folder) }
|
||||
},
|
||||
onDismiss = { choosing.value = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun cancel() = finish()
|
||||
|
||||
override fun chooseFolder() {
|
||||
choosing.value = true
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep what was shared in the person's files: each file streamed into the folder as it is,
|
||||
* the text (when there is any) as a note beside them. No chat is made and no model is asked.
|
||||
* What the instance refuses -- a file over its limit, a folder that may not be written --
|
||||
* is said in its own sentence, and the sheet stays.
|
||||
*/
|
||||
override fun saveToFiles() {
|
||||
val now = state.value
|
||||
val folder = now.folder ?: return
|
||||
if (now.sending) return
|
||||
state.update { it.copy(sending = true, error = null) }
|
||||
lifecycleScope.launch {
|
||||
try {
|
||||
val api = lembas.instances.client() ?: run {
|
||||
startActivity(Intent(this@ShareActivity, MainActivity::class.java))
|
||||
finish()
|
||||
return@launch
|
||||
}
|
||||
for (uri in uris) api.uploadFrom(contentResolver, contentResolver.describe(uri), folder)
|
||||
if (now.text.isNotBlank()) api.saveFile(FileKinds.child(folder, sharedNoteName(java.time.LocalDateTime.now())), now.text + "\n")
|
||||
Toast.makeText(this@ShareActivity, R.string.files_uploaded, Toast.LENGTH_SHORT).show()
|
||||
finish()
|
||||
} catch (e: Exception) {
|
||||
state.update { it.copy(sending = false, error = filesSay(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun send(ask: String, toLast: Boolean) {
|
||||
if (state.value.sending) return
|
||||
state.update { it.copy(sending = true, error = null) }
|
||||
|
||||
@@ -21,6 +21,7 @@ import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.filled.EditNote
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.History
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material3.Button
|
||||
@@ -64,6 +65,8 @@ data class ShareState(
|
||||
val last: LastAssist? = null,
|
||||
val sending: Boolean = false,
|
||||
val error: String? = null,
|
||||
/** Where "Save to Files" would put it: the person's own folder until they choose another; null while it is not known. */
|
||||
val folder: String? = null,
|
||||
)
|
||||
|
||||
/** What the share sheet can do; nothing by default, for the screenshot tests. */
|
||||
@@ -71,20 +74,28 @@ interface ShareActions {
|
||||
/** Send it with [ask] (empty: the default request) to a new chat, or [toLast] to the last assistant chat. */
|
||||
fun send(ask: String, toLast: Boolean) {}
|
||||
|
||||
/** Keep what was shared as files in [ShareState.folder], asking no model anything. */
|
||||
fun saveToFiles() {}
|
||||
|
||||
/** Choose another folder to save into. */
|
||||
fun chooseFolder() {}
|
||||
|
||||
fun cancel() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* The share sheet's contents, from [state] alone: what came in (the text, the files by name),
|
||||
* what to do with it (a line of the person's own, optional), where it goes -- a new chat, or the
|
||||
* last chat the assistant made -- and Send. Rows of unknown height stack; the two choices are
|
||||
* whole-row tap targets of at least 56 dp.
|
||||
* what to do with it (a line of the person's own, optional), where it goes -- a new chat, the
|
||||
* last chat the assistant made, or the person's Files, where nothing is asked of a model -- and
|
||||
* Send or Save. Rows of unknown height stack; the choices are whole-row tap targets of at least
|
||||
* 56 dp.
|
||||
*/
|
||||
@Composable
|
||||
fun ColumnScope.ShareSheetContent(state: ShareState, actions: ShareActions, handle: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
var ask by remember { mutableStateOf("") }
|
||||
var toLast by remember { mutableStateOf(false) }
|
||||
var toFiles by remember { mutableStateOf(false) }
|
||||
val last = state.last
|
||||
|
||||
Column(handle.fillMaxWidth()) {
|
||||
@@ -157,25 +168,43 @@ fun ColumnScope.ShareSheetContent(state: ShareState, actions: ShareActions, hand
|
||||
unfocusedIndicatorColor = Color.Transparent,
|
||||
),
|
||||
maxLines = 4,
|
||||
enabled = !state.sending,
|
||||
// Files keep what was shared as it is: there is nobody to tell what to do with it.
|
||||
enabled = !state.sending && !toFiles,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
|
||||
)
|
||||
|
||||
// Where it goes.
|
||||
if (last != null) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = palette.surfaceRaised,
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column {
|
||||
Destination(Icons.Filled.EditNote, stringResource(R.string.new_chat), null, selected = !toLast, enabled = !state.sending) { toLast = false }
|
||||
Destination(Icons.Filled.History, stringResource(R.string.assist_continue), last.title, selected = toLast, enabled = !state.sending) {
|
||||
toLast =
|
||||
true
|
||||
Surface(
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = palette.surfaceRaised,
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column {
|
||||
Destination(Icons.Filled.EditNote, stringResource(R.string.new_chat), null, selected = !toLast && !toFiles, enabled = !state.sending) {
|
||||
toLast = false
|
||||
toFiles = false
|
||||
}
|
||||
if (last != null) {
|
||||
Destination(
|
||||
Icons.Filled.History,
|
||||
stringResource(R.string.assist_continue),
|
||||
last.title,
|
||||
selected = toLast && !toFiles,
|
||||
enabled = !state.sending,
|
||||
) {
|
||||
toLast = true
|
||||
toFiles = false
|
||||
}
|
||||
}
|
||||
Destination(Icons.Filled.Folder, stringResource(R.string.share_to_files), state.folder, selected = toFiles, enabled = !state.sending) {
|
||||
toFiles = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if (toFiles) {
|
||||
TextButton(onClick = actions::chooseFolder, enabled = !state.sending, modifier = Modifier.heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.files_choose_folder))
|
||||
}
|
||||
}
|
||||
state.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger) }
|
||||
@@ -189,11 +218,21 @@ fun ColumnScope.ShareSheetContent(state: ShareState, actions: ShareActions, hand
|
||||
TextButton(onClick = actions::cancel, modifier = Modifier.heightIn(min = 48.dp)) { Text(stringResource(R.string.cancel)) }
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Button(
|
||||
onClick = { actions.send(ask, toLast && last != null) },
|
||||
enabled = !state.sending && (state.text.isNotBlank() || state.files.isNotEmpty()),
|
||||
onClick = { if (toFiles) actions.saveToFiles() else actions.send(ask, toLast && last != null) },
|
||||
enabled = !state.sending && (state.text.isNotBlank() || state.files.isNotEmpty()) && (!toFiles || state.folder != null),
|
||||
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.heightIn(min = 48.dp),
|
||||
) { Text(stringResource(if (state.sending) R.string.share_sending else R.string.send)) }
|
||||
) {
|
||||
Text(
|
||||
stringResource(
|
||||
when {
|
||||
toFiles -> R.string.save
|
||||
state.sending -> R.string.share_sending
|
||||
else -> R.string.send
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,3 +267,7 @@ fun shareMessage(ask: String, shared: String, fallback: String): String {
|
||||
val request = ask.trim().ifBlank { fallback }
|
||||
return if (shared.isBlank()) request else "$request\n\n---\n\n${shared.trim()}"
|
||||
}
|
||||
|
||||
/** What shared text is called when it is kept as a file: `shared-20260102-030405.txt`, from the moment it was saved. */
|
||||
fun sharedNoteName(at: java.time.LocalDateTime): String =
|
||||
"shared-" + at.format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss", java.util.Locale.ROOT)) + ".txt"
|
||||
@@ -0,0 +1,469 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.files
|
||||
|
||||
import android.text.format.Formatter
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
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.DeleteForever
|
||||
import androidx.compose.material.icons.filled.DeleteSweep
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.FolderShared
|
||||
import androidx.compose.material.icons.filled.RestoreFromTrash
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
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.FileEntry
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileVersion
|
||||
import eu.llembas.android.api.TrashItem
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.scheduled.ScheduleLogic
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
// The file manager's smaller pages: a name, a yes or no, the folder to move or copy into, the
|
||||
// trash, and a file's versions. Each is drawn from its state alone.
|
||||
|
||||
/** Ask for a name: a new folder's, a new file's, or a new one for something that has one. */
|
||||
@Composable
|
||||
fun NameDialog(title: String, ask: String?, initial: String, confirm: String, onName: (String) -> Unit, onDismiss: () -> Unit) {
|
||||
var name by remember { mutableStateOf(initial) }
|
||||
val bad = FileKinds.badName(name)
|
||||
val problem: (@Composable () -> Unit)? = if (name.isNotEmpty() && bad) {
|
||||
{ Text(stringResource(R.string.files_bad_name)) }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(title) },
|
||||
text = {
|
||||
Column {
|
||||
ask?.let { Text(it, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(bottom = 12.dp)) }
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
singleLine = true,
|
||||
isError = name.isNotEmpty() && bad,
|
||||
supportingText = problem,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { onName(name.trim()) }, enabled = !bad && name.trim() != initial) { Text(confirm) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** A question with one thing to do and a way not to. */
|
||||
@Composable
|
||||
fun ConfirmDialog(text: String, confirm: String, onConfirm: () -> Unit, onDismiss: () -> Unit) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
text = { Text(text, style = MaterialTheme.typography.bodyLarge) },
|
||||
confirmButton = { TextButton(onClick = onConfirm) { Text(confirm) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** Where the folder picker is: the folders of [path], on their way or refused. */
|
||||
data class FolderPickState(
|
||||
val path: String = "/",
|
||||
val parent: String? = null,
|
||||
val folders: List<FileEntry> = emptyList(),
|
||||
val loading: Boolean = true,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* Choosing a folder of the tree by walking to it: where something is moved or copied, or where
|
||||
* a share is saved. No path is typed. [hidden]: the things being moved, which cannot be their
|
||||
* own destination.
|
||||
*/
|
||||
@Composable
|
||||
fun FolderPicker(title: String, confirm: String, start: String, onPick: (String) -> Unit, onDismiss: () -> Unit, hidden: Set<String> = emptySet()) {
|
||||
val context = LocalContext.current
|
||||
var state by remember { mutableStateOf(FolderPickState(path = start)) }
|
||||
var asked by remember { mutableStateOf(start) }
|
||||
var again by remember { mutableIntStateOf(0) }
|
||||
LaunchedEffect(asked, again) {
|
||||
state = state.copy(loading = true, error = null)
|
||||
state = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
val listing = api.files(asked)
|
||||
FolderPickState(listing.path, listing.parent, listing.entries.filter { it.isFolder && it.path !in hidden }, loading = false)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
state.copy(loading = false, error = context.filesSay(e))
|
||||
}
|
||||
}
|
||||
val up: () -> Unit = {
|
||||
val parent = state.parent
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
/** The folder picker's page: where it is, that folder's folders, and the one button that chooses the folder shown. */
|
||||
@Composable
|
||||
fun FolderPickContent(
|
||||
title: String,
|
||||
confirm: String,
|
||||
state: FolderPickState,
|
||||
onOpen: (String) -> Unit = {},
|
||||
onUp: () -> Unit = {},
|
||||
onPick: () -> Unit = {},
|
||||
onDismiss: () -> Unit = {},
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = if (state.parent != null) onUp else onDismiss) {
|
||||
Icon(
|
||||
if (state.parent != null) Icons.AutoMirrored.Filled.ArrowBack else Icons.Filled.Close,
|
||||
contentDescription = stringResource(if (state.parent != null) R.string.back else R.string.close),
|
||||
)
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Column {
|
||||
Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
state.path,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.StartEllipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
Button(
|
||||
onClick = onPick,
|
||||
enabled = !state.loading && state.error == null,
|
||||
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp).heightIn(min = 48.dp),
|
||||
) { Text(confirm) }
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
when {
|
||||
state.error != null -> Text(state.error, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
|
||||
state.loading && state.folders.isEmpty() -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
|
||||
state.folders.isEmpty() -> Text(
|
||||
stringResource(R.string.files_no_folders),
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.align(Alignment.Center).padding(32.dp),
|
||||
)
|
||||
|
||||
else -> LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.folders, key = { it.path }) { folder ->
|
||||
ListItem(
|
||||
modifier = Modifier.fillMaxWidth().clickable { onOpen(folder.path) },
|
||||
leadingContent = {
|
||||
Icon(
|
||||
if (folder.kind == "mount") Icons.Filled.FolderShared else Icons.Filled.Folder,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
headlineContent = { Text(folder.name.ifBlank { folder.path }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The trash as the page draws it. */
|
||||
data class TrashState(val items: List<TrashItem> = emptyList(), val loading: Boolean = true, val error: String? = null)
|
||||
|
||||
/** What the trash page can do; nothing by default, for the screenshot tests. */
|
||||
interface TrashActions {
|
||||
fun restore(item: TrashItem) {}
|
||||
|
||||
fun remove(item: TrashItem) {}
|
||||
|
||||
fun empty() {}
|
||||
|
||||
fun close() {}
|
||||
}
|
||||
|
||||
/** The trash: what was deleted, each to be restored or removed for good, and all of it emptied. [onChanged]: something went back to the tree. */
|
||||
@Composable
|
||||
fun TrashDialog(onClose: () -> Unit, onChanged: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var state by remember { mutableStateOf(TrashState()) }
|
||||
var asking by remember { mutableStateOf<TrashItem?>(null) }
|
||||
var emptying by remember { mutableStateOf(false) }
|
||||
var said by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
fun act(block: suspend (ApiClient) -> List<TrashItem>) {
|
||||
scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
state = TrashState(block(api), loading = false)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
val words = context.filesSay(e)
|
||||
if (state.loading) state = state.copy(loading = false, error = words) else said = words
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) { act { it.trash().items } }
|
||||
val actions = remember {
|
||||
object : TrashActions {
|
||||
override fun restore(item: TrashItem) = act { api ->
|
||||
api.restoreTrashed(item.id).items.also { onChanged() }
|
||||
}
|
||||
|
||||
override fun remove(item: TrashItem) {
|
||||
asking = item
|
||||
}
|
||||
|
||||
override fun empty() {
|
||||
emptying = true
|
||||
}
|
||||
|
||||
override fun close() = onClose()
|
||||
}
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
TrashContent(state, actions)
|
||||
}
|
||||
asking?.let { item ->
|
||||
ConfirmDialog(
|
||||
stringResource(R.string.trash_remove_confirm, item.name),
|
||||
stringResource(R.string.trash_remove),
|
||||
onConfirm = {
|
||||
asking = null
|
||||
act { it.removeTrashed(item.id).items }
|
||||
},
|
||||
onDismiss = { asking = null },
|
||||
)
|
||||
}
|
||||
if (emptying) {
|
||||
ConfirmDialog(
|
||||
stringResource(R.string.trash_empty_confirm),
|
||||
stringResource(R.string.trash_empty),
|
||||
onConfirm = {
|
||||
emptying = false
|
||||
act { it.removeTrashed().items }
|
||||
},
|
||||
onDismiss = { emptying = false },
|
||||
)
|
||||
}
|
||||
said?.let { SaidDialog(it, onClose = { said = null }) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The trash's page. A row is the thing's name over where it was, and two buttons of 48 dp at
|
||||
* its end: the name gives, the buttons keep their size.
|
||||
*/
|
||||
@Composable
|
||||
fun TrashContent(state: TrashState, actions: TrashActions) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = actions::close) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = { Text(stringResource(R.string.trash), maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
actions = {
|
||||
IconButton(onClick = actions::empty, enabled = state.items.isNotEmpty()) {
|
||||
Icon(Icons.Filled.DeleteSweep, contentDescription = stringResource(R.string.trash_empty))
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
when {
|
||||
state.error != null -> Text(state.error, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
|
||||
state.loading -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
|
||||
state.items.isEmpty() -> Text(
|
||||
stringResource(R.string.trash_is_empty),
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.align(Alignment.Center).padding(32.dp),
|
||||
)
|
||||
|
||||
else -> LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.items, key = { it.id }) { item ->
|
||||
ListItem(
|
||||
leadingContent = { EntryIcon(if (item.kind == "file") null else item.kind, null, selected = false) },
|
||||
headlineContent = { Text(item.name.ifBlank { item.path }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = {
|
||||
val size = if (item.kind == "file") Formatter.formatShortFileSize(context, item.size) else null
|
||||
Text(listOfNotNull(FileKinds.parent(item.path), size).joinToString(" · "), maxLines = 1, overflow = TextOverflow.StartEllipsis)
|
||||
},
|
||||
trailingContent = {
|
||||
Row {
|
||||
IconButton(onClick = { actions.restore(item) }) {
|
||||
Icon(Icons.Filled.RestoreFromTrash, contentDescription = stringResource(R.string.restore))
|
||||
}
|
||||
IconButton(onClick = { actions.remove(item) }) {
|
||||
Icon(Icons.Filled.DeleteForever, contentDescription = stringResource(R.string.trash_remove), tint = palette.danger)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A file's versions as the page draws them. */
|
||||
data class VersionsState(val versions: List<FileVersion> = emptyList(), val loading: Boolean = true, val error: String? = null)
|
||||
|
||||
/** 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) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var state by remember(path) { mutableStateOf(VersionsState()) }
|
||||
var asking by remember { mutableStateOf<FileVersion?>(null) }
|
||||
LaunchedEffect(path) {
|
||||
state = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
VersionsState(api.fileVersions(path).versions, loading = false)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
VersionsState(loading = false, error = context.filesSay(e))
|
||||
}
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
VersionsContent(FileKinds.name(path), state, onRestore = { asking = it }, onClose = onClose)
|
||||
}
|
||||
asking?.let { version ->
|
||||
ConfirmDialog(
|
||||
stringResource(R.string.version_restore_confirm),
|
||||
stringResource(R.string.version_restore),
|
||||
onConfirm = {
|
||||
asking = null
|
||||
scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
api.restoreVersion(path, version.id)
|
||||
onRestored()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
state = state.copy(error = context.filesSay(e))
|
||||
}
|
||||
}
|
||||
},
|
||||
onDismiss = { asking = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** The versions' page: when, by whom and how large; the one the file holds now says so, the others can be restored. */
|
||||
@Composable
|
||||
fun VersionsContent(name: String, state: VersionsState, onRestore: (FileVersion) -> Unit = {}, onClose: () -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = onClose) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = {
|
||||
Column {
|
||||
Text(stringResource(R.string.versions), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(name, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||
state.error?.let { Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) }
|
||||
if (state.loading) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
|
||||
return@Column
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.versions, key = { it.id }) { version ->
|
||||
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)
|
||||
},
|
||||
trailingContent = {
|
||||
if (version.current) {
|
||||
Text(stringResource(R.string.version_current), style = MaterialTheme.typography.labelLarge, color = palette.inkMuted)
|
||||
} else {
|
||||
TextButton(onClick = { onRestore(version) }) { Text(stringResource(R.string.restore)) }
|
||||
}
|
||||
},
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,59 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class, androidx.compose.foundation.ExperimentalFoundationApi::class)
|
||||
|
||||
package eu.llembas.android.ui.files
|
||||
|
||||
import android.app.Application
|
||||
import android.net.Uri
|
||||
import android.text.format.Formatter
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
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.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
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.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Archive
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Code
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.DriveFileMove
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.FolderShared
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Movie
|
||||
import androidx.compose.material.icons.filled.MusicNote
|
||||
import androidx.compose.material.icons.filled.PictureAsPdf
|
||||
import androidx.compose.material.icons.filled.RestoreFromTrash
|
||||
import androidx.compose.material.icons.filled.SelectAll
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.TableChart
|
||||
import androidx.compose.material3.BottomAppBar
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.ListItemDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
@@ -31,10 +63,12 @@ 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.saveable.rememberSaveable
|
||||
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.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
@@ -45,34 +79,137 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
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.FileKinds
|
||||
import eu.llembas.android.api.FileListing
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.viewer.TreeFileViewer
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** One directory of the person's tree, and whether it is on its way. */
|
||||
/**
|
||||
* One directory of the person's tree: what is in it, what is chosen in it, and what is under
|
||||
* way. [error] is a listing that could not be read (said above the list, which stays); [said] a
|
||||
* refusal of something the person did (a sentence to read, in a dialog); [notice] a word that
|
||||
* it was done.
|
||||
*/
|
||||
data class FilesState(
|
||||
val path: String = "/",
|
||||
val parent: String? = null,
|
||||
val entries: List<FileEntry> = emptyList(),
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
)
|
||||
val selected: Set<String> = emptySet(),
|
||||
/** An upload under way: which file of how many, and how far it is. */
|
||||
val upload: Transfer? = null,
|
||||
/** A write under way (a move, a rename…): the list waits for it. */
|
||||
val working: Boolean = false,
|
||||
val said: String? = null,
|
||||
val notice: String? = null,
|
||||
) {
|
||||
val selecting: Boolean get() = selected.isNotEmpty()
|
||||
|
||||
/** The chosen entries, in the list's order. */
|
||||
val chosen: List<FileEntry> get() = entries.filter { it.path in selected }
|
||||
|
||||
fun toggled(path: String): FilesState = copy(selected = if (path in selected) selected - path else selected + path)
|
||||
|
||||
fun allSelected(): FilesState = copy(selected = entries.map { it.path }.toSet())
|
||||
|
||||
/** A listing read: the directory it is of, and of what was chosen only what is still there. */
|
||||
fun listed(listing: FileListing): FilesState {
|
||||
val same = listing.path == path
|
||||
val there = listing.entries.map { it.path }.toSet()
|
||||
return copy(
|
||||
path = listing.path,
|
||||
parent = listing.parent,
|
||||
entries = listing.entries,
|
||||
loading = false,
|
||||
error = null,
|
||||
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. */
|
||||
data class BatchOutcome(val said: String?, val done: Int)
|
||||
|
||||
fun outcome(answer: BatchAnswer): BatchOutcome {
|
||||
if (answer.failed == 0) return BatchOutcome(null, answer.done)
|
||||
// Where the server gave no sentence, at least which ones: their names.
|
||||
val names = answer.results.filter { !it.ok }.take(3).joinToString(", ") { FileKinds.name(it.path) }
|
||||
return BatchOutcome(answer.refusals().joinToString("\n").ifBlank { names }, answer.done)
|
||||
}
|
||||
|
||||
/** Something the Files page asks the person before it is done, or a page it opens over itself. */
|
||||
sealed interface Ask {
|
||||
data object NewFolder : Ask
|
||||
|
||||
data object NewFile : Ask
|
||||
|
||||
data object Trash : Ask
|
||||
|
||||
data class Rename(val entry: FileEntry) : Ask
|
||||
|
||||
data class Delete(val entries: List<FileEntry>) : Ask
|
||||
|
||||
data class Move(val entries: List<FileEntry>) : Ask
|
||||
|
||||
data class Copy(val entries: List<FileEntry>) : Ask
|
||||
|
||||
data class Versions(val entry: FileEntry) : Ask
|
||||
}
|
||||
|
||||
/** What the Files page can do; nothing by default, for the screenshot tests. */
|
||||
interface FilesActions {
|
||||
fun back() {}
|
||||
|
||||
fun open(entry: FileEntry) {}
|
||||
|
||||
fun reload() {}
|
||||
|
||||
fun toggle(entry: FileEntry) {}
|
||||
|
||||
fun selectAll() {}
|
||||
|
||||
fun clearSelection() {}
|
||||
|
||||
fun pickUpload() {}
|
||||
|
||||
fun ask(what: Ask) {}
|
||||
|
||||
fun download(entries: List<FileEntry>) {}
|
||||
|
||||
fun share(entries: List<FileEntry>) {}
|
||||
|
||||
fun openWith(entry: FileEntry) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* The person's files, read-only: `GET /api/v2/files` as the explorer's listing. The tree is read
|
||||
* as the person, with no chat -- their own access, the same the web UI's explorer draws by.
|
||||
* The person's files as a file manager: `GET /api/v2/files` and the explorer's writes. The tree
|
||||
* is read and changed as the person, with no chat -- their own access, the same the web UI's
|
||||
* explorer draws by -- and every refusal is the server's own sentence.
|
||||
*/
|
||||
class FilesViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(FilesState(loading = true))
|
||||
val state = _state.asStateFlow()
|
||||
private var loading: Job? = null
|
||||
private var uploading: Job? = null
|
||||
private val app: Application get() = getApplication()
|
||||
|
||||
private suspend fun api(): ApiClient = app.lembas.instances.client() ?: throw ApiException(401, app.getString(R.string.assist_signed_out))
|
||||
|
||||
/**
|
||||
* Opens a directory. A refusal (a path no longer readable, the server unreachable) keeps the
|
||||
@@ -83,16 +220,12 @@ class FilesViewModel(app: Application) : AndroidViewModel(app) {
|
||||
loading = viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client()
|
||||
if (api == null) {
|
||||
_state.update { it.copy(loading = false) }
|
||||
return@launch
|
||||
}
|
||||
val listing = api.files(path)
|
||||
_state.value = FilesState(path = listing.path, parent = listing.parent, entries = listing.entries)
|
||||
val listing = api().files(path)
|
||||
_state.update { it.listed(listing) }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
if (e is kotlinx.coroutines.CancellationException) throw e
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
_state.update { it.copy(loading = false, error = app.explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,85 +237,458 @@ class FilesViewModel(app: Application) : AndroidViewModel(app) {
|
||||
open(parent)
|
||||
return true
|
||||
}
|
||||
|
||||
fun toggle(entry: FileEntry) = _state.update { it.toggled(entry.path) }
|
||||
|
||||
fun selectAll() = _state.update { it.allSelected() }
|
||||
|
||||
fun clearSelection() = _state.update { it.copy(selected = emptySet()) }
|
||||
|
||||
fun clearSaid() = _state.update { it.copy(said = null, notice = null) }
|
||||
|
||||
/** One write, then the directory read again: what is there is what the server says is there. */
|
||||
private fun write(block: suspend (ApiClient) -> String?) {
|
||||
if (_state.value.working) return
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(working = true, said = null, notice = null) }
|
||||
try {
|
||||
val notice = block(api())
|
||||
_state.update { it.copy(notice = notice) }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(said = app.filesSay(e)) }
|
||||
} finally {
|
||||
_state.update { it.copy(working = false) }
|
||||
}
|
||||
reload()
|
||||
}
|
||||
}
|
||||
|
||||
fun newFolder(name: String) = write { api ->
|
||||
api.makeFolder(_state.value.path, name)
|
||||
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, "")
|
||||
then(path)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun rename(entry: FileEntry, name: String) = write { api ->
|
||||
api.renameFile(entry.path, name)
|
||||
null
|
||||
}
|
||||
|
||||
/** Move or copy the entries into the directory [to], or with `delete` put them in the trash; each is answered for by itself. */
|
||||
fun batch(op: String, entries: List<FileEntry>, to: String? = null) = write { api ->
|
||||
val done = outcome(api.batchFiles(op, entries.map { it.path }, to))
|
||||
_state.update { it.copy(selected = emptySet(), said = done.said) }
|
||||
when {
|
||||
done.done == 0 -> null
|
||||
op == "delete" -> app.getString(R.string.files_trashed)
|
||||
op == "copy" -> app.getString(R.string.copied)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload files of the phone into the directory shown, one request each: a file the instance
|
||||
* refuses (too large: its 413 names the file) does not take the others with it. Each is
|
||||
* streamed from where it is; none is read into memory.
|
||||
*/
|
||||
fun upload(uris: List<Uri>) {
|
||||
if (uris.isEmpty() || uploading?.isActive == true) return
|
||||
val dir = _state.value.path
|
||||
uploading = viewModelScope.launch {
|
||||
val refused = mutableListOf<String>()
|
||||
var sent = 0
|
||||
try {
|
||||
val api = api()
|
||||
val files = uris.map { app.contentResolver.describe(it) }
|
||||
files.forEachIndexed { i, file ->
|
||||
val words = app.getString(R.string.files_uploading, (i + 1).toString(), files.size.toString())
|
||||
_state.update { it.copy(upload = Transfer(words, 0, file.size)) }
|
||||
var last = 0L
|
||||
try {
|
||||
api.uploadFrom(app.contentResolver, file, dir) { bytes ->
|
||||
if (bytes - last >= 256 * 1024) {
|
||||
last = bytes
|
||||
_state.update { it.copy(upload = it.upload?.copy(done = bytes)) }
|
||||
}
|
||||
}
|
||||
sent++
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
refused += app.filesSay(e)
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
refused += app.filesSay(e)
|
||||
} finally {
|
||||
val words = refused.distinct().take(3).joinToString("\n").ifBlank { null }
|
||||
_state.update { it.copy(upload = null, said = words, notice = if (sent > 0) app.getString(R.string.files_uploaded) else null) }
|
||||
reload()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun cancelUpload() {
|
||||
uploading?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun FilesScreen(onBack: () -> Unit, model: FilesViewModel = viewModel()) {
|
||||
fun FilesScreen(onBack: () -> Unit, model: FilesViewModel = viewModel(), transfers: TransferViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
val palette = LocalPalette.current
|
||||
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) }
|
||||
LaunchedEffect(state.notice) {
|
||||
state.notice?.let {
|
||||
Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
|
||||
model.clearSaid()
|
||||
}
|
||||
}
|
||||
|
||||
// Back goes up one directory first, as a file manager's does; at the top it leaves.
|
||||
BackHandler(enabled = state.parent != null) { model.up() }
|
||||
// Back lets go of what is chosen first, then goes up one directory, as a file manager's does; at the top it leaves.
|
||||
BackHandler(enabled = state.selecting || state.parent != null) { if (state.selecting) model.clearSelection() else model.up() }
|
||||
|
||||
val pick = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { model.upload(it) }
|
||||
val saveTo = rememberLauncherForActivityResult(CreateFile()) { to ->
|
||||
val what = saving
|
||||
saving = emptyList()
|
||||
if (to != null && what.isNotEmpty()) {
|
||||
transfers.download(what.map { it.path }, zip = asZip(what), to = to)
|
||||
model.clearSelection()
|
||||
}
|
||||
}
|
||||
val actions = remember(model, transfers) {
|
||||
object : FilesActions {
|
||||
override fun back() {
|
||||
if (!model.up()) onBack()
|
||||
}
|
||||
|
||||
override fun open(entry: FileEntry) {
|
||||
if (entry.isFolder) {
|
||||
model.open(entry.path)
|
||||
} else {
|
||||
writing = false
|
||||
viewing = entry.path
|
||||
}
|
||||
}
|
||||
|
||||
override fun reload() = model.reload()
|
||||
|
||||
override fun toggle(entry: FileEntry) = model.toggle(entry)
|
||||
|
||||
override fun selectAll() = model.selectAll()
|
||||
|
||||
override fun clearSelection() = model.clearSelection()
|
||||
|
||||
override fun pickUpload() = pick.launch(arrayOf("*/*"))
|
||||
|
||||
override fun ask(what: Ask) {
|
||||
asked = what
|
||||
}
|
||||
|
||||
override fun download(entries: List<FileEntry>) {
|
||||
if (entries.isEmpty()) return
|
||||
saving = entries
|
||||
val zip = asZip(entries)
|
||||
saveTo.launch(
|
||||
CreateFile.Ask(
|
||||
if (zip) {
|
||||
TransferViewModel.zipName(
|
||||
entries.map {
|
||||
it.path
|
||||
},
|
||||
)
|
||||
} else {
|
||||
entries[0].name
|
||||
},
|
||||
if (zip) "application/zip" else entries[0].mime,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
override fun share(entries: List<FileEntry>) {
|
||||
transfers.share(entries)
|
||||
model.clearSelection()
|
||||
}
|
||||
|
||||
override fun openWith(entry: FileEntry) = transfers.openWith(entry.path, entry.name, entry.mime)
|
||||
}
|
||||
}
|
||||
|
||||
FilesContent(state, actions)
|
||||
|
||||
when (val now = asked) {
|
||||
null -> Unit
|
||||
|
||||
Ask.NewFolder -> NameDialog(
|
||||
stringResource(R.string.folder_new),
|
||||
stringResource(R.string.files_new_folder_ask),
|
||||
"",
|
||||
stringResource(R.string.save),
|
||||
onName = {
|
||||
asked = null
|
||||
model.newFolder(it)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
Ask.NewFile -> NameDialog(
|
||||
stringResource(R.string.files_new_file),
|
||||
stringResource(R.string.files_new_file_ask),
|
||||
"",
|
||||
stringResource(R.string.save),
|
||||
onName = { name ->
|
||||
asked = null
|
||||
model.newFile(name) { path ->
|
||||
writing = true
|
||||
viewing = path
|
||||
}
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
is Ask.Rename -> NameDialog(
|
||||
stringResource(R.string.rename),
|
||||
stringResource(R.string.files_new_name),
|
||||
now.entry.name,
|
||||
stringResource(R.string.rename),
|
||||
onName = {
|
||||
asked = null
|
||||
model.rename(now.entry, it)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
is Ask.Delete -> ConfirmDialog(
|
||||
if (now.entries.size == 1) {
|
||||
stringResource(R.string.files_trash_one, now.entries[0].name)
|
||||
} else {
|
||||
stringResource(R.string.files_trash_many, now.entries.size.toString())
|
||||
},
|
||||
stringResource(R.string.files_to_trash),
|
||||
onConfirm = {
|
||||
asked = null
|
||||
model.batch("delete", now.entries)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
is Ask.Move -> FolderPicker(
|
||||
stringResource(R.string.files_move_which),
|
||||
stringResource(R.string.files_move_here),
|
||||
state.path,
|
||||
onPick = {
|
||||
asked = null
|
||||
model.batch("move", now.entries, it)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
hidden = now.entries.map { it.path }.toSet(),
|
||||
)
|
||||
|
||||
is Ask.Copy -> FolderPicker(
|
||||
stringResource(R.string.files_copy_which),
|
||||
stringResource(R.string.files_copy_here),
|
||||
state.path,
|
||||
onPick = {
|
||||
asked = null
|
||||
model.batch("copy", now.entries, it)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
is Ask.Versions -> VersionsDialog(
|
||||
now.entry.path,
|
||||
onClose = { asked = null },
|
||||
onRestored = {
|
||||
asked = null
|
||||
model.reload()
|
||||
},
|
||||
)
|
||||
|
||||
Ask.Trash -> TrashDialog(onClose = { asked = null }, onChanged = model::reload)
|
||||
}
|
||||
|
||||
state.upload?.let { TransferDialog(it, onCancel = model::cancelUpload) }
|
||||
state.said?.let { SaidDialog(it, onClose = model::clearSaid) }
|
||||
TransferHost(transfers)
|
||||
viewing?.let { path -> TreeFileViewer(path, onClose = { viewing = null }, startEditing = writing, onChanged = model::reload) }
|
||||
}
|
||||
|
||||
/** Several things, or a folder, leave as one zip; a single file as itself. */
|
||||
fun asZip(entries: List<FileEntry>): Boolean = entries.size > 1 || entries.any { it.isFolder }
|
||||
|
||||
/**
|
||||
* The Files page, from [state] alone. A tap opens; a long press chooses, and while anything is
|
||||
* chosen a tap chooses too and the bar at the bottom acts on all of it. Each row's own menu
|
||||
* (the three dots, 48 dp) has what can be done to that one thing.
|
||||
*/
|
||||
@Composable
|
||||
fun FilesContent(state: FilesState, actions: FilesActions) {
|
||||
val palette = LocalPalette.current
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = { if (!model.up()) onBack() }) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||
if (state.selecting) {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = actions::clearSelection) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.cancel)) }
|
||||
},
|
||||
title = { Text(stringResource(R.string.files_selected, state.selected.size.toString()), maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
actions = {
|
||||
IconButton(onClick = actions::selectAll) {
|
||||
Icon(Icons.Filled.SelectAll, contentDescription = stringResource(R.string.files_select_all))
|
||||
}
|
||||
},
|
||||
)
|
||||
} else {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = actions::back) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) }
|
||||
},
|
||||
title = {
|
||||
Column {
|
||||
Text(stringResource(R.string.files), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
if (state.parent == null) stringResource(R.string.files_all) else state.path,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = if (state.parent == null) null else FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.StartEllipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
Box {
|
||||
IconButton(onClick = { adding = true }) { Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.files_upload)) }
|
||||
DropdownMenu(expanded = adding, onDismissRequest = { adding = false }) {
|
||||
MenuItem(R.string.files_upload) {
|
||||
adding = false
|
||||
actions.pickUpload()
|
||||
}
|
||||
MenuItem(R.string.folder_new) {
|
||||
adding = false
|
||||
actions.ask(Ask.NewFolder)
|
||||
}
|
||||
MenuItem(R.string.files_new_file) {
|
||||
adding = false
|
||||
actions.ask(Ask.NewFile)
|
||||
}
|
||||
}
|
||||
}
|
||||
IconButton(onClick = {
|
||||
actions.ask(Ask.Trash)
|
||||
}) { Icon(Icons.Filled.RestoreFromTrash, contentDescription = stringResource(R.string.trash)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
},
|
||||
bottomBar = {
|
||||
if (state.selecting) {
|
||||
val chosen = state.chosen
|
||||
// Five actions of one size, spread evenly: none of them is a word, so none can crowd another.
|
||||
BottomAppBar {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically) {
|
||||
BarButton(Icons.Filled.DriveFileMove, R.string.files_move) { actions.ask(Ask.Move(chosen)) }
|
||||
BarButton(Icons.Filled.ContentCopy, R.string.files_copy_to) { actions.ask(Ask.Copy(chosen)) }
|
||||
BarButton(Icons.Filled.Download, if (asZip(chosen)) R.string.files_download_zip else R.string.download) { actions.download(chosen) }
|
||||
BarButton(Icons.Filled.Share, R.string.report_share) { actions.share(chosen) }
|
||||
BarButton(Icons.Filled.Delete, R.string.files_to_trash) { actions.ask(Ask.Delete(chosen)) }
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Column {
|
||||
Text(stringResource(R.string.files), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
if (state.parent == null) stringResource(R.string.files_all) else state.path,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = if (state.parent == null) null else FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.StartEllipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||
state.error?.let {
|
||||
Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
}
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = { model.reload() }, modifier = Modifier.fillMaxSize()) {
|
||||
if (state.working) LinearProgressIndicator(Modifier.fillMaxWidth().height(2.dp))
|
||||
state.error?.let { Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) }
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = actions::reload, modifier = Modifier.fillMaxSize()) {
|
||||
if (state.entries.isEmpty() && !state.loading && state.error == null) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
stringResource(R.string.files_empty),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(32.dp),
|
||||
)
|
||||
Text(stringResource(R.string.files_empty), color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(32.dp))
|
||||
}
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.entries, key = { it.path }) { entry ->
|
||||
EntryRow(entry) { if (entry.isFolder) model.open(entry.path) else viewing = entry.path }
|
||||
EntryRow(entry, selected = entry.path in state.selected, selecting = state.selecting, actions = actions)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
viewing?.let { path -> TreeFileViewer(path, onClose = { viewing = null }) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EntryRow(entry: FileEntry, onOpen: () -> Unit) {
|
||||
private fun MenuItem(label: Int, onClick: () -> Unit) = DropdownMenuItem(text = { Text(stringResource(label)) }, onClick = onClick)
|
||||
|
||||
@Composable
|
||||
private fun BarButton(icon: ImageVector, label: Int, onClick: () -> Unit) {
|
||||
IconButton(onClick = onClick) { Icon(icon, contentDescription = stringResource(label)) }
|
||||
}
|
||||
|
||||
/** What an entry is, as a picture: a folder, a shared folder, or the file's kind; a tick when it is chosen. */
|
||||
@Composable
|
||||
internal fun EntryIcon(folder: String?, fileKind: String?, selected: Boolean) {
|
||||
val palette = LocalPalette.current
|
||||
val icon = when {
|
||||
selected -> Icons.Filled.CheckCircle
|
||||
|
||||
folder == "mount" -> Icons.Filled.FolderShared
|
||||
|
||||
folder != null -> Icons.Filled.Folder
|
||||
|
||||
else -> when (fileKind) {
|
||||
"image", "svg" -> Icons.Filled.Image
|
||||
"pdf" -> Icons.Filled.PictureAsPdf
|
||||
"audio" -> Icons.Filled.MusicNote
|
||||
"video" -> Icons.Filled.Movie
|
||||
"table" -> Icons.Filled.TableChart
|
||||
"code", "html", "notebook" -> Icons.Filled.Code
|
||||
"archive" -> Icons.Filled.Archive
|
||||
"model3d", "binary" -> Icons.AutoMirrored.Filled.InsertDriveFile
|
||||
else -> Icons.Filled.Description
|
||||
}
|
||||
}
|
||||
Icon(icon, contentDescription = null, tint = if (selected) palette.accent else MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EntryRow(entry: FileEntry, selected: Boolean, selecting: Boolean, actions: FilesActions) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
ListItem(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen),
|
||||
leadingContent = {
|
||||
Icon(
|
||||
when (entry.kind) {
|
||||
"mount" -> Icons.Filled.FolderShared
|
||||
"dir" -> Icons.Filled.Folder
|
||||
else -> Icons.Filled.Description
|
||||
},
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.combinedClickable(
|
||||
onClick = { if (selecting) actions.toggle(entry) else actions.open(entry) },
|
||||
onLongClick = { actions.toggle(entry) },
|
||||
),
|
||||
colors = ListItemDefaults.colors(containerColor = if (selected) palette.accentSoft else palette.bg),
|
||||
leadingContent = { EntryIcon(if (entry.isFolder) entry.kind else null, entry.fileKind, selected) },
|
||||
headlineContent = { Text(entry.name.ifBlank { entry.path }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = if (entry.isFolder) {
|
||||
null
|
||||
@@ -192,5 +698,33 @@ private fun EntryRow(entry: FileEntry, onOpen: () -> Unit) {
|
||||
Text(line, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
},
|
||||
trailingContent = if (selecting) {
|
||||
null
|
||||
} else {
|
||||
{
|
||||
Box {
|
||||
IconButton(onClick = { menu = true }) { Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more)) }
|
||||
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||
val one = listOf(entry)
|
||||
val then: (() -> Unit) -> (() -> Unit) = { act ->
|
||||
{
|
||||
menu = false
|
||||
act()
|
||||
}
|
||||
}
|
||||
MenuItem(R.string.rename, then { actions.ask(Ask.Rename(entry)) })
|
||||
MenuItem(R.string.files_move, then { actions.ask(Ask.Move(one)) })
|
||||
MenuItem(R.string.files_copy_to, then { actions.ask(Ask.Copy(one)) })
|
||||
MenuItem(if (entry.isFolder) R.string.files_download_zip else R.string.download, then { actions.download(one) })
|
||||
MenuItem(R.string.report_share, then { actions.share(one) })
|
||||
if (!entry.isFolder) {
|
||||
MenuItem(R.string.files_open_with, then { actions.openWith(entry) })
|
||||
MenuItem(R.string.versions, then { actions.ask(Ask.Versions(entry)) })
|
||||
}
|
||||
MenuItem(R.string.files_to_trash, then { actions.ask(Ask.Delete(one)) })
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package eu.llembas.android.ui.files
|
||||
|
||||
import android.app.Application
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.text.format.Formatter
|
||||
import android.widget.Toast
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
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.getValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import eu.llembas.android.R
|
||||
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.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** Something on its way to or from the instance: what it is, and how far ([total] -1: not known). */
|
||||
data class Transfer(val text: String, val done: Long = 0, val total: Long = -1)
|
||||
|
||||
/** A transfer under way, what it ended in, and the other app to open once a copy is ready. */
|
||||
data class TransferState(val running: Transfer? = null, val error: String? = null, val notice: String? = null, val launch: Intent? = null)
|
||||
|
||||
/** A failure of the file manager in words: an instance without these routes says so, the rest as everywhere. */
|
||||
fun Context.filesSay(e: Throwable): String = when {
|
||||
noSuchRoute(e) -> getString(R.string.viewer_unavailable)
|
||||
e is ApiException && e.message.isNullOrBlank() -> getString(R.string.files_not_shown)
|
||||
else -> explain(e)
|
||||
}
|
||||
|
||||
/**
|
||||
* Files leaving the instance for the phone: a download into a document the person chose, and a
|
||||
* copy in the private cache for another app (Open with, Share). One at a time, with its
|
||||
* progress, and it can be given up. It outlives a turn of the phone; the copies do not outlive
|
||||
* the screen ([onCleared]).
|
||||
*/
|
||||
class TransferViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(TransferState())
|
||||
val state = _state.asStateFlow()
|
||||
private var job: Job? = null
|
||||
private val app: Application get() = getApplication()
|
||||
|
||||
/** One file's bytes, or with [zip] several files and folders as one zip, into the document [to]. */
|
||||
fun download(paths: List<String>, zip: Boolean, to: Uri) = start { api, progress ->
|
||||
api.downloadTo(app, if (zip) api.zipFiles(paths) else api.rawFile(paths.first()), to, progress)
|
||||
_state.update { it.copy(notice = app.getString(R.string.files_downloaded)) }
|
||||
}
|
||||
|
||||
fun openWith(path: String, name: String, mime: String) = start { api, progress ->
|
||||
FileCache.sweepShared(app)
|
||||
val copy = api.copyInto(api.rawFile(path), FileCache.shared(app, name), progress = progress)
|
||||
_state.update { it.copy(launch = Handover.view(app, copy, mime)) }
|
||||
}
|
||||
|
||||
/** 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
|
||||
FileCache.sweepShared(app)
|
||||
val plain = entries.none { it.isFolder } && entries.size <= SHARE_MOST
|
||||
val copies = if (plain) {
|
||||
entries.map { api.copyInto(api.rawFile(it.path), FileCache.shared(app, it.name), progress = progress) }
|
||||
} else {
|
||||
listOf(api.copyInto(api.zipFiles(entries.map { it.path }), FileCache.shared(app, zipName(entries.map { it.path })), progress = progress))
|
||||
}
|
||||
val mime = if (plain) entries.map { it.mime }.distinct().singleOrNull()?.ifBlank { null } ?: "*/*" else "application/zip"
|
||||
_state.update { it.copy(launch = Handover.share(app, copies, mime)) }
|
||||
}
|
||||
|
||||
fun launched() = _state.update { it.copy(launch = null) }
|
||||
|
||||
fun say(error: String) = _state.update { it.copy(error = error) }
|
||||
|
||||
fun clear() = _state.update { it.copy(error = null, notice = null) }
|
||||
|
||||
fun cancel() {
|
||||
job?.cancel()
|
||||
}
|
||||
|
||||
private fun start(block: suspend (ApiClient, (Long, Long) -> Unit) -> Unit) {
|
||||
if (job?.isActive == true) return
|
||||
job = viewModelScope.launch {
|
||||
_state.update { it.copy(running = Transfer(app.getString(R.string.files_downloading)), error = null, notice = null) }
|
||||
try {
|
||||
val api = app.lembas.instances.client() ?: throw ApiException(401, app.getString(R.string.assist_signed_out))
|
||||
block(api, stepped { done, total -> _state.update { it.copy(running = it.running?.copy(done = done, total = total)) } })
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = app.filesSay(e)) }
|
||||
} finally {
|
||||
_state.update { it.copy(running = null) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCleared() {
|
||||
FileCache.clear(app)
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** More files than this are shared as one zip. */
|
||||
const val SHARE_MOST = 10
|
||||
|
||||
/** What a zip of [paths] is called: the one thing's name, else the folder they are in. */
|
||||
fun zipName(paths: List<String>): String {
|
||||
val one = paths.singleOrNull()?.let { FileKinds.name(it) }
|
||||
val folder = paths.firstOrNull()?.let { FileKinds.name(FileKinds.parent(it)) }?.takeIf { it != "/" }
|
||||
return (one ?: folder ?: "files").removeSuffix(".zip") + ".zip"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* is done -- which names no file.
|
||||
*/
|
||||
@Composable
|
||||
fun TransferHost(model: TransferViewModel) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
val context = LocalContext.current
|
||||
LaunchedEffect(state.launch) {
|
||||
val intent = state.launch ?: return@LaunchedEffect
|
||||
try {
|
||||
context.startActivity(intent)
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
model.say(context.getString(R.string.files_no_app))
|
||||
}
|
||||
model.launched()
|
||||
}
|
||||
LaunchedEffect(state.notice) {
|
||||
state.notice?.let {
|
||||
Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
|
||||
model.clear()
|
||||
}
|
||||
}
|
||||
state.running?.let { TransferDialog(it, onCancel = model::cancel) }
|
||||
state.error?.let { SaidDialog(it, onClose = model::clear) }
|
||||
}
|
||||
|
||||
/** A transfer under way: what, how far, and Cancel. Drawn from [transfer] alone. */
|
||||
@Composable
|
||||
fun TransferDialog(transfer: Transfer, onCancel: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
AlertDialog(
|
||||
onDismissRequest = {},
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(transfer.text, style = MaterialTheme.typography.bodyLarge)
|
||||
if (transfer.total > 0) {
|
||||
LinearProgressIndicator(progress = { (transfer.done.toFloat() / transfer.total).coerceIn(0f, 1f) }, modifier = Modifier.fillMaxWidth())
|
||||
} else {
|
||||
LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
}
|
||||
if (transfer.done > 0) {
|
||||
val done = Formatter.formatShortFileSize(context, transfer.done)
|
||||
val line = if (transfer.total > 0) done + " / " + Formatter.formatShortFileSize(context, transfer.total) else done
|
||||
Text(line, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onCancel) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** A sentence the person has to read (a refusal, a failure), with one way on. */
|
||||
@Composable
|
||||
fun SaidDialog(text: String, onClose: () -> Unit) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onClose,
|
||||
text = { Text(text, style = MaterialTheme.typography.bodyLarge) },
|
||||
confirmButton = { TextButton(onClick = onClose) { Text(stringResource(R.string.close)) } },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package eu.llembas.android.ui.files
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ClipData
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.provider.DocumentsContract
|
||||
import android.provider.OpenableColumns
|
||||
import androidx.activity.result.contract.ActivityResultContract
|
||||
import androidx.core.content.FileProvider
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileListing
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.MediaType
|
||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||
import okhttp3.RequestBody
|
||||
import okio.BufferedSink
|
||||
import okio.source
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* The copies of the account's files this phone holds for a moment, all in the app's private
|
||||
* cache and nowhere else: [viewing] for what a viewer needs as a file (a PDF's pages, a
|
||||
* picture's pixels), deleted when the viewer closes; [shared] for what another app is handed
|
||||
* through the FileProvider (Open with, Share), which cannot be deleted the moment it is handed
|
||||
* over -- the other app is still reading it -- so it goes when Files is left, when the app next
|
||||
* starts, and at sign-out. No storage permission is involved: what the person keeps, they save
|
||||
* through the system's own "Save to" page.
|
||||
*/
|
||||
object FileCache {
|
||||
private const val VIEWING = "viewing"
|
||||
private const val SHARED = "shared"
|
||||
|
||||
private fun dir(context: Context, name: String): File = File(context.cacheDir, name).apply { mkdirs() }
|
||||
|
||||
/** A new, empty place for one viewer's copy. */
|
||||
fun viewing(context: Context, name: String): File = File(dir(context, VIEWING), UUID.randomUUID().toString() + "-" + FileKinds.safeName(name).takeLast(40))
|
||||
|
||||
/** A new place for a copy another app will read, under its own name in a folder of its own. */
|
||||
fun shared(context: Context, name: String): File =
|
||||
File(File(dir(context, SHARED), UUID.randomUUID().toString()).apply { mkdirs() }, FileKinds.safeName(name))
|
||||
|
||||
/** Every copy, gone: at sign-out, when the app starts, and when Files is left. */
|
||||
fun clear(context: Context) {
|
||||
for (name in listOf(VIEWING, SHARED)) runCatching { File(context.cacheDir, name).deleteRecursively() }
|
||||
}
|
||||
|
||||
/** The shared copies older than [olderThanMs]: before a new one is made, so they do not pile up. */
|
||||
fun sweepShared(context: Context, olderThanMs: Long = 30 * 60 * 1000L) {
|
||||
val limit = System.currentTimeMillis() - olderThanMs
|
||||
File(context.cacheDir, SHARED).listFiles()?.forEach { if (it.lastModified() < limit) runCatching { it.deleteRecursively() } }
|
||||
}
|
||||
|
||||
/** The address another app is given for a [shared] copy: the app's FileProvider, read-only, for that one grant. */
|
||||
fun uri(context: Context, file: File): Uri = FileProvider.getUriForFile(context, context.packageName + ".files", file)
|
||||
}
|
||||
|
||||
/** "Save to": the system's page for where a file goes (the Storage Access Framework), by a suggested name and type. */
|
||||
class CreateFile : ActivityResultContract<CreateFile.Ask, Uri?>() {
|
||||
data class Ask(val name: String, val mime: String)
|
||||
|
||||
override fun createIntent(context: Context, input: Ask): Intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
|
||||
.addCategory(Intent.CATEGORY_OPENABLE)
|
||||
.setType(input.mime.ifBlank { "application/octet-stream" })
|
||||
.putExtra(Intent.EXTRA_TITLE, input.name)
|
||||
|
||||
override fun parseResult(resultCode: Int, intent: Intent?): Uri? = intent?.data?.takeIf { resultCode == Activity.RESULT_OK }
|
||||
}
|
||||
|
||||
/** A file on the phone, as the picker or another app's share named it. */
|
||||
data class LocalFile(val uri: Uri, val name: String, val size: Long, val mime: String)
|
||||
|
||||
fun ContentResolver.describe(uri: Uri): LocalFile {
|
||||
var name: String? = null
|
||||
var size = -1L
|
||||
runCatching {
|
||||
query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { c ->
|
||||
if (c.moveToFirst()) {
|
||||
c.getColumnIndex(OpenableColumns.DISPLAY_NAME).takeIf { it >= 0 }?.let { name = c.getString(it) }
|
||||
c.getColumnIndex(OpenableColumns.SIZE).takeIf { it >= 0 && !c.isNull(it) }?.let { size = c.getLong(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
val said = name?.substringAfterLast('/')?.ifBlank { null } ?: uri.lastPathSegment?.substringAfterLast('/')?.ifBlank { null } ?: "upload"
|
||||
return LocalFile(uri, said, size, getType(uri) ?: "application/octet-stream")
|
||||
}
|
||||
|
||||
/**
|
||||
* A request body that reads [open]'s stream as it is sent: the file is never in memory whole.
|
||||
* [length] is its size when known (-1: sent chunked). [progress] hears how many bytes went.
|
||||
*/
|
||||
class StreamBody(
|
||||
private val type: MediaType?,
|
||||
private val length: Long,
|
||||
private val progress: (Long) -> Unit = {},
|
||||
private val open: () -> java.io.InputStream?,
|
||||
) : RequestBody() {
|
||||
override fun contentType(): MediaType? = type
|
||||
|
||||
override fun contentLength(): Long = length
|
||||
|
||||
/** The stream is read once: a failed upload is said, not silently sent again from a stream that may not open twice. */
|
||||
override fun isOneShot(): Boolean = true
|
||||
|
||||
override fun writeTo(sink: BufferedSink) {
|
||||
val stream = open() ?: throw IOException("The file could not be opened.")
|
||||
stream.source().use { source ->
|
||||
var sent = 0L
|
||||
while (true) {
|
||||
val n = source.read(sink.buffer, 64 * 1024L)
|
||||
if (n < 0) break
|
||||
sent += n
|
||||
sink.emitCompleteSegments()
|
||||
progress(sent)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Upload one file of the phone into [dir], streamed from its content address. */
|
||||
suspend fun ApiClient.uploadFrom(resolver: ContentResolver, file: LocalFile, dir: String, progress: (Long) -> Unit = {}): FileListing =
|
||||
uploadFile(dir, file.name, StreamBody(file.mime.toMediaTypeOrNull(), file.size, progress) { resolver.openInputStream(file.uri) })
|
||||
|
||||
/**
|
||||
* Download what [request] answers into the document [to] the person chose. A download that
|
||||
* fails or is given up leaves no half file behind where the provider lets it be removed.
|
||||
*/
|
||||
suspend fun ApiClient.downloadTo(context: Context, request: okhttp3.Request, to: Uri, progress: (Long, Long) -> Unit = { _, _ -> }) {
|
||||
try {
|
||||
withContext(Dispatchers.IO) {
|
||||
val out = context.contentResolver.openOutputStream(to, "w") ?: throw IOException("The file could not be written.")
|
||||
out.use { download(request, it, progress = progress) }
|
||||
}
|
||||
} catch (e: Throwable) {
|
||||
withContext(kotlinx.coroutines.NonCancellable + Dispatchers.IO) { runCatching { DocumentsContract.deleteDocument(context.contentResolver, to) } }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
/** A copy of what [request] answers in [file] (the private cache), at most [most] bytes. */
|
||||
suspend fun ApiClient.copyInto(request: okhttp3.Request, file: File, most: Long = Long.MAX_VALUE, progress: (Long, Long) -> Unit = { _, _ -> }): File {
|
||||
try {
|
||||
withContext(Dispatchers.IO) {
|
||||
file.parentFile?.mkdirs()
|
||||
file.outputStream().use { download(request, it, most, progress) }
|
||||
}
|
||||
} catch (e: Throwable) {
|
||||
withContext(kotlinx.coroutines.NonCancellable + Dispatchers.IO) { runCatching { file.delete() } }
|
||||
throw e
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
/** Hand [files] (cache copies) to another app: "Open with" for one, Share for one or several. Read-only, for this one grant. */
|
||||
object Handover {
|
||||
fun view(context: Context, file: File, mime: String): Intent {
|
||||
val uri = FileCache.uri(context, file)
|
||||
val intent = Intent(Intent.ACTION_VIEW).setDataAndType(uri, mime.ifBlank { "*/*" }).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
return Intent.createChooser(intent, null)
|
||||
}
|
||||
|
||||
fun share(context: Context, files: List<File>, mime: String): Intent {
|
||||
val uris = files.map { FileCache.uri(context, it) }
|
||||
val intent = if (uris.size == 1) {
|
||||
Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_STREAM, uris[0])
|
||||
} else {
|
||||
Intent(Intent.ACTION_SEND_MULTIPLE).putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList(uris))
|
||||
}
|
||||
intent.setType(mime.ifBlank { "*/*" }).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
// The chooser's own preview reads the address too: it is told through the clip.
|
||||
intent.clipData = ClipData.newRawUri(null, uris[0]).apply { uris.drop(1).forEach { addItem(ClipData.Item(it)) } }
|
||||
return Intent.createChooser(intent, null)
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a failure says the server has no such route at all (an older instance), rather than refusing. */
|
||||
fun noSuchRoute(e: Throwable): Boolean = e is ApiException && (e.status == 405 || (e.status == 404 && e.message == "Not Found"))
|
||||
|
||||
/** [report], heard only every quarter megabyte and at the end: a transfer does not redraw the screen for every packet. */
|
||||
fun stepped(report: (Long, Long) -> Unit): (Long, Long) -> Unit {
|
||||
var last = 0L
|
||||
return { done, total ->
|
||||
if (done - last >= 256 * 1024 || done == total) {
|
||||
last = done
|
||||
report(done, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,6 +104,7 @@ import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.notify.NotificationAccess
|
||||
import eu.llembas.android.push.Push
|
||||
import eu.llembas.android.ui.files.FileCache
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.update.AppVersion
|
||||
import eu.llembas.android.update.ReleaseCheck
|
||||
@@ -265,6 +266,8 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
Push.disable(context, instance)
|
||||
runCatching { store.clientFor(instance).signOut() }
|
||||
store.remove(instance.id)
|
||||
// The copies of the account's files this phone held for a viewer or another app go with it.
|
||||
FileCache.clear(context)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
package eu.llembas.android.ui.viewer
|
||||
|
||||
import android.text.format.Formatter
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.gestures.detectTransformGestures
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.filled.Pause
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material3.FilledIconButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButtonDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Slider
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableFloatStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clipToBounds
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Notebook
|
||||
import eu.llembas.android.api.Table
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import java.util.Locale
|
||||
|
||||
// What the viewer draws for each kind of file, each from its state alone (the screenshot tests
|
||||
// draw these). Everything a file holds is drawn as text or as pixels the app decoded itself:
|
||||
// nothing here interprets a file -- no HTML, no script, no WebView.
|
||||
|
||||
/** What the details page can do; nothing by default, for the screenshot tests. */
|
||||
interface FileActions {
|
||||
fun download() {}
|
||||
|
||||
fun openWith() {}
|
||||
|
||||
fun share() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* A file there is nothing to draw of (an archive, a 3D model, a binary, or one a viewer could
|
||||
* not show): what it is, [note] saying why it is not shown, and the three ways out. The
|
||||
* buttons stack: their words are of unknown length in nine languages.
|
||||
*/
|
||||
@Composable
|
||||
fun DetailsBody(name: String, type: String, size: Long, note: String?, actions: FileActions) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
Column(
|
||||
Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Icon(Icons.AutoMirrored.Filled.InsertDriveFile, contentDescription = null, tint = palette.inkFaint, modifier = Modifier.size(56.dp))
|
||||
Text(name, style = MaterialTheme.typography.titleMedium, textAlign = TextAlign.Center)
|
||||
Column(Modifier.fillMaxWidth().border(1.dp, palette.border, RoundedCornerShape(16.dp)).padding(horizontal = 16.dp, vertical = 8.dp)) {
|
||||
Fact(stringResource(R.string.files_type), type)
|
||||
Fact(stringResource(R.string.files_size), Formatter.formatShortFileSize(context, size))
|
||||
}
|
||||
note?.takeIf { it.isNotBlank() }?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted, textAlign = TextAlign.Center) }
|
||||
OutlinedButton(onClick = actions::download, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) { Text(stringResource(R.string.download)) }
|
||||
OutlinedButton(onClick = actions::openWith, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) { Text(stringResource(R.string.files_open_with)) }
|
||||
OutlinedButton(onClick = actions::share, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) { Text(stringResource(R.string.report_share)) }
|
||||
}
|
||||
}
|
||||
|
||||
/** A label and its value on one line: the label keeps its width, the value takes the rest and wraps. */
|
||||
@Composable
|
||||
private fun Fact(label: String, value: String) {
|
||||
val palette = LocalPalette.current
|
||||
Row(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {
|
||||
Text(label, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted, modifier = Modifier.width(96.dp))
|
||||
Text(value, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
|
||||
/** The width every column of a table has: fixed, so a row's cells line up whatever they hold. */
|
||||
private val COLUMN = 148.dp
|
||||
|
||||
/**
|
||||
* A CSV or TSV file as a grid: every cell one line in a column of one width, the first row as
|
||||
* the heading, the whole grid scrolling sideways as one and down as a list. Cells are text.
|
||||
*/
|
||||
@Composable
|
||||
fun TableBody(table: Table) {
|
||||
val palette = LocalPalette.current
|
||||
val sideways = rememberScrollState()
|
||||
val style = TextStyle(fontSize = 13.sp, lineHeight = 18.sp, color = palette.ink)
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
if (table.cut) Note(stringResource(R.string.table_cut))
|
||||
Box(Modifier.fillMaxSize().horizontalScroll(sideways)) {
|
||||
LazyColumn(Modifier.width(COLUMN * table.columns.coerceAtLeast(1))) {
|
||||
itemsIndexed(table.rows) { i, row ->
|
||||
Row(Modifier.background(if (i == 0) palette.bgSunken else palette.bg)) {
|
||||
for (c in 0 until table.columns.coerceAtLeast(1)) {
|
||||
Text(
|
||||
row.getOrElse(c) { "" },
|
||||
style = if (i == 0) style.copy(fontWeight = FontWeight.SemiBold) else style,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.width(COLUMN).border(0.5.dp, palette.border).padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A quiet line above a body, saying what is not shown. */
|
||||
@Composable
|
||||
internal fun Note(text: String) {
|
||||
val palette = LocalPalette.current
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.fillMaxWidth().background(palette.bgSunken).padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/** A notebook, read-only: each cell's source as text, and under it the plain text it printed. */
|
||||
@Composable
|
||||
fun NotebookBody(notebook: Notebook) {
|
||||
val palette = LocalPalette.current
|
||||
val mono = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 13.sp, lineHeight = 18.sp, color = palette.ink)
|
||||
if (notebook.cells.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.notebook_empty), color = palette.inkMuted, modifier = Modifier.padding(32.dp))
|
||||
}
|
||||
return
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
itemsIndexed(notebook.cells) { _, cell ->
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
if (cell.count != null) "${cell.kind} [${cell.count}]" else cell.kind,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(bottom = 4.dp),
|
||||
)
|
||||
val code = cell.kind == "code"
|
||||
Text(
|
||||
cell.source.ifEmpty { " " },
|
||||
style = if (code) mono else MaterialTheme.typography.bodyMedium.copy(color = palette.ink),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(if (code) palette.codeBg else palette.bg, RoundedCornerShape(8.dp))
|
||||
.padding(if (code) 10.dp else 0.dp),
|
||||
)
|
||||
if (cell.output.isNotEmpty()) {
|
||||
Text(cell.output, style = mono.copy(color = palette.inkMuted), modifier = Modifier.fillMaxWidth().padding(start = 10.dp, top = 6.dp))
|
||||
}
|
||||
if (cell.cut) Text(stringResource(R.string.notebook_cell_cut), style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
|
||||
}
|
||||
}
|
||||
if (notebook.more > 0) {
|
||||
item {
|
||||
Text(stringResource(R.string.notebook_more, notebook.more.toString()), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** How far a picture zoomed to [scale] may be moved inside a view of [size]: never past its own edge. */
|
||||
fun clampPan(offset: Offset, scale: Float, size: IntSize): Offset {
|
||||
val x = size.width * (scale - 1f) / 2f
|
||||
val y = size.height * (scale - 1f) / 2f
|
||||
return Offset(offset.x.coerceIn(-x, x), offset.y.coerceIn(-y, y))
|
||||
}
|
||||
|
||||
const val ZOOM_MAX = 8f
|
||||
|
||||
/** A picture, whole: two fingers zoom and move it, a double tap zooms in and back. */
|
||||
@Composable
|
||||
fun ZoomableImage(bitmap: ImageBitmap, description: String) {
|
||||
val palette = LocalPalette.current
|
||||
var scale by remember(bitmap) { mutableFloatStateOf(1f) }
|
||||
var offset by remember(bitmap) { mutableStateOf(Offset.Zero) }
|
||||
var size by remember { mutableStateOf(IntSize.Zero) }
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(palette.bgSunken)
|
||||
.clipToBounds()
|
||||
.onSizeChanged { size = it }
|
||||
.pointerInput(bitmap) {
|
||||
detectTransformGestures { _, pan, zoom, _ ->
|
||||
scale = (scale * zoom).coerceIn(1f, ZOOM_MAX)
|
||||
offset = clampPan(offset + pan, scale, size)
|
||||
}
|
||||
}
|
||||
.pointerInput(bitmap) {
|
||||
detectTapGestures(
|
||||
onDoubleTap = {
|
||||
scale = if (scale > 1f) 1f else 3f
|
||||
offset = Offset.Zero
|
||||
},
|
||||
)
|
||||
},
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Image(
|
||||
bitmap,
|
||||
contentDescription = description,
|
||||
contentScale = ContentScale.Fit,
|
||||
modifier = Modifier.fillMaxSize().graphicsLayer {
|
||||
scaleX = scale
|
||||
scaleY = scale
|
||||
translationX = offset.x
|
||||
translationY = offset.y
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** What a player shows: whether it can play yet, is playing, where it is and how long the file is. */
|
||||
data class PlayerUi(val ready: Boolean = false, val playing: Boolean = false, val positionMs: Int = 0, val durationMs: Int = 0)
|
||||
|
||||
/** `m:ss`, or `h:mm:ss` from an hour on: a time read off a player, the same in every language. */
|
||||
fun playTime(ms: Int): String {
|
||||
val all = (ms.coerceAtLeast(0) / 1000)
|
||||
val h = all / 3600
|
||||
val m = all % 3600 / 60
|
||||
val s = all % 60
|
||||
return if (h > 0) String.format(Locale.ROOT, "%d:%02d:%02d", h, m, s) else String.format(Locale.ROOT, "%d:%02d", m, s)
|
||||
}
|
||||
|
||||
/**
|
||||
* A player's controls: the place in the file as a slider the whole width, the two times under
|
||||
* its two ends, and Play or Pause in the middle (56 dp). Nothing here depends on a text's length.
|
||||
*/
|
||||
@Composable
|
||||
fun PlayerControls(ui: PlayerUi, onToggle: () -> Unit, onSeek: (Int) -> Unit, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
var dragging by remember { mutableStateOf<Float?>(null) }
|
||||
val length = ui.durationMs.coerceAtLeast(1).toFloat()
|
||||
Column(modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Slider(
|
||||
value = (dragging ?: ui.positionMs.toFloat()).coerceIn(0f, length),
|
||||
onValueChange = { dragging = it },
|
||||
onValueChangeFinished = {
|
||||
dragging?.let { onSeek(it.toInt()) }
|
||||
dragging = null
|
||||
},
|
||||
valueRange = 0f..length,
|
||||
enabled = ui.ready && ui.durationMs > 0,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
Text(playTime((dragging ?: ui.positionMs.toFloat()).toInt()), style = MaterialTheme.typography.labelMedium, color = palette.inkMuted)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(playTime(ui.durationMs), style = MaterialTheme.typography.labelMedium, color = palette.inkMuted)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
FilledIconButton(
|
||||
onClick = onToggle,
|
||||
enabled = ui.ready,
|
||||
colors = IconButtonDefaults.filledIconButtonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.size(56.dp),
|
||||
) {
|
||||
Icon(
|
||||
if (ui.playing) Icons.Filled.Pause else Icons.Filled.PlayArrow,
|
||||
contentDescription = stringResource(if (ui.playing) R.string.pause else R.string.play),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A text file being edited: the whole text in one field, in the code's type. The field is the
|
||||
* screen; saving and leaving are the bar's.
|
||||
*/
|
||||
@Composable
|
||||
fun EditorBody(text: String, onChange: (String) -> Unit, enabled: Boolean = true) {
|
||||
val palette = LocalPalette.current
|
||||
BasicTextField(
|
||||
value = text,
|
||||
onValueChange = onChange,
|
||||
enabled = enabled,
|
||||
textStyle = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 14.sp, lineHeight = 20.sp, color = palette.ink),
|
||||
cursorBrush = SolidColor(palette.accent),
|
||||
modifier = Modifier.fillMaxSize().background(palette.codeBg).padding(12.dp),
|
||||
)
|
||||
}
|
||||
@@ -112,31 +112,6 @@ fun FileViewer(chatId: String, show: ShowCard, onClose: () -> Unit) {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A file of the person's tree (the Files screen), in the same viewer and under the same rules:
|
||||
* the person's own files are no more trusted than a model's, since a model may have written
|
||||
* them. A file the server withholds (not text, over 1 MB) says why, and offers the web UI.
|
||||
*/
|
||||
@Composable
|
||||
fun TreeFileViewer(path: String, onClose: () -> Unit) {
|
||||
Viewer(
|
||||
file = Viewed(path.substringAfterLast('/').ifBlank { path }, path, 0, "text"),
|
||||
key = path,
|
||||
webUrl = { it.webFile(path) },
|
||||
load = { api, context ->
|
||||
val file = api.fileContent(path)
|
||||
val withheld = file.withheld
|
||||
when {
|
||||
withheld == null -> Loaded.Text(file.text, file.viewKind, file.language)
|
||||
withheld.message.isNotBlank() -> Loaded.Failed(withheld.message)
|
||||
withheld.reason == "too_large" -> Loaded.Failed(context.getString(R.string.viewer_too_large))
|
||||
else -> Loaded.Failed(context.getString(R.string.viewer_not_text))
|
||||
}
|
||||
},
|
||||
onClose = onClose,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Viewer(file: Viewed, key: Any, webUrl: (ApiClient) -> String?, load: suspend (ApiClient, Context) -> Loaded, onClose: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
@@ -321,12 +296,12 @@ private fun linesOf(text: AnnotatedString): List<AnnotatedString> {
|
||||
}
|
||||
}
|
||||
|
||||
private fun copy(context: Context, label: String, text: String) {
|
||||
internal fun copy(context: Context, label: String, text: String) {
|
||||
context.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText(label, text))
|
||||
}
|
||||
|
||||
/** The web UI's viewer, in the browser (a Custom Tab), where the person's own session is. */
|
||||
private fun openOutside(context: Context, url: String) {
|
||||
internal fun openOutside(context: Context, url: String) {
|
||||
val uri = Uri.parse(url)
|
||||
if (uri.scheme?.lowercase() !in setOf("http", "https")) return
|
||||
runCatching { CustomTabsIntent.Builder().build().launchUrl(context, uri) }
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
package eu.llembas.android.ui.viewer
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.pdf.PdfRenderer
|
||||
import android.media.AudioAttributes
|
||||
import android.media.MediaDataSource
|
||||
import android.media.MediaPlayer
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
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.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.MusicNote
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
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.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
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.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
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.sampleFor
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.files.FileCache
|
||||
import eu.llembas.android.ui.files.copyInto
|
||||
import eu.llembas.android.ui.files.stepped
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.unreachable
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
|
||||
// The viewers that need the file's bytes: a picture, a PDF, sound and video. The bytes come
|
||||
// from the instance the app is signed in to, with the token in the Authorization header -- the
|
||||
// address handed to nothing: the platform's player reads through [RemoteMedia], which asks the
|
||||
// app's own HTTP client for each piece. No player library is added for this.
|
||||
|
||||
/** The most a picture's file may weigh to be decoded on the phone, and a PDF's to be copied for its pages. */
|
||||
const val IMAGE_MAX_BYTES = 64L * 1024 * 1024
|
||||
const val PDF_MAX_BYTES = 256L * 1024 * 1024
|
||||
|
||||
/** How a viewer's bytes came: on their way ([done] of [total], -1 unknown), there, or not shown. */
|
||||
sealed interface Fetched<out T> {
|
||||
data class Loading(val done: Long = 0, val total: Long = -1) : Fetched<Nothing>
|
||||
|
||||
data class Ready<T>(val value: T) : Fetched<T>
|
||||
|
||||
/** [message]: the server's sentence or the network's; null: this phone could not draw it. */
|
||||
data class Failed(val message: String?) : Fetched<Nothing>
|
||||
}
|
||||
|
||||
/**
|
||||
* [file] decoded for the screen: its bounds are read first, and it is sampled down
|
||||
* ([sampleFor]) so neither edge nor the pixel count is more than a phone shows -- a picture
|
||||
* that claims a huge size costs a bounded amount of memory, or is not decoded at all.
|
||||
*/
|
||||
fun decodeCapped(file: File): Bitmap? {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(file.path, bounds)
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
|
||||
var sample = sampleFor(bounds.outWidth, bounds.outHeight)
|
||||
repeat(3) {
|
||||
try {
|
||||
return BitmapFactory.decodeFile(file.path, BitmapFactory.Options().apply { inSampleSize = sample })
|
||||
} catch (e: OutOfMemoryError) {
|
||||
sample *= 2
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** A picture of the tree: copied into the private cache (at most [IMAGE_MAX_BYTES]), decoded small, and the copy deleted at once. */
|
||||
@Composable
|
||||
fun ImageBody(path: String, name: String, size: Long, fallback: @Composable (String?) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val picture by produceState<Fetched<ImageBitmap>>(Fetched.Loading(), path) {
|
||||
if (size > IMAGE_MAX_BYTES) {
|
||||
value = Fetched.Failed(null)
|
||||
return@produceState
|
||||
}
|
||||
val copy = FileCache.viewing(context, name)
|
||||
value = try {
|
||||
val api = context.lembas.instances.client() ?: throw IOException(context.getString(R.string.assist_signed_out))
|
||||
api.copyInto(api.rawFile(path), copy, IMAGE_MAX_BYTES, stepped { done, total -> value = Fetched.Loading(done, total) })
|
||||
val bitmap = withContext(Dispatchers.Default) { decodeCapped(copy) }
|
||||
if (bitmap == null) Fetched.Failed(null) else Fetched.Ready(bitmap.asImageBitmap())
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Fetched.Failed(viewerSays(context, e))
|
||||
} finally {
|
||||
copy.delete()
|
||||
}
|
||||
}
|
||||
when (val now = picture) {
|
||||
is Fetched.Loading -> Progress(now)
|
||||
is Fetched.Failed -> fallback(now.message)
|
||||
is Fetched.Ready -> ZoomableImage(now.value, name)
|
||||
}
|
||||
}
|
||||
|
||||
/** A transfer under way, in the middle of the page: how far, when the size is known. */
|
||||
@Composable
|
||||
internal fun Progress(now: Fetched.Loading) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
if (now.total > 0) CircularProgressIndicator(progress = { (now.done.toFloat() / now.total).coerceIn(0f, 1f) }) else CircularProgressIndicator()
|
||||
}
|
||||
}
|
||||
|
||||
/** A PDF's pages, drawn by the platform's own renderer from a copy in the private cache. One page is open at a time. */
|
||||
class PdfPages(private val copy: File) {
|
||||
private val descriptor = ParcelFileDescriptor.open(copy, ParcelFileDescriptor.MODE_READ_ONLY)
|
||||
private val renderer = try {
|
||||
PdfRenderer(descriptor)
|
||||
} catch (e: Throwable) {
|
||||
descriptor.close()
|
||||
throw e
|
||||
}
|
||||
private var closed = false
|
||||
val count: Int = renderer.pageCount
|
||||
|
||||
/** Page [index] as pixels [width] wide; null once closed or when it cannot be drawn. */
|
||||
@Synchronized
|
||||
fun page(index: Int, width: Int): ImageBitmap? {
|
||||
if (closed || index !in 0 until count || width <= 0) return null
|
||||
return runCatching {
|
||||
renderer.openPage(index).use { page ->
|
||||
var w = width
|
||||
var h = (page.height.toLong() * w / page.width.coerceAtLeast(1)).toInt().coerceAtLeast(1)
|
||||
// A page of an odd shape (a long receipt) is drawn smaller rather than as a huge bitmap.
|
||||
while (w.toLong() * h > PAGE_MAX_PIXELS) {
|
||||
w /= 2
|
||||
h /= 2
|
||||
}
|
||||
val bitmap = Bitmap.createBitmap(w.coerceAtLeast(1), h.coerceAtLeast(1), Bitmap.Config.ARGB_8888)
|
||||
// The paper: a PDF draws on transparent, and print is read on white in either theme.
|
||||
bitmap.eraseColor(PAPER)
|
||||
page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
|
||||
bitmap.asImageBitmap()
|
||||
}
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun close() {
|
||||
if (closed) return
|
||||
closed = true
|
||||
runCatching { renderer.close() }
|
||||
runCatching { descriptor.close() }
|
||||
copy.delete()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val PAGE_MAX_PIXELS = 6_000_000L
|
||||
const val PAPER = android.graphics.Color.WHITE
|
||||
}
|
||||
}
|
||||
|
||||
/** A PDF, page by page, as wide as the screen. */
|
||||
@Composable
|
||||
fun PdfBody(path: String, name: String, size: Long, fallback: @Composable (String?) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
var pages by remember(path) { mutableStateOf<Fetched<PdfPages>>(Fetched.Loading()) }
|
||||
DisposableEffect(path) {
|
||||
onDispose { (pages as? Fetched.Ready)?.value?.close() }
|
||||
}
|
||||
LaunchedEffect(path) {
|
||||
if (size > PDF_MAX_BYTES) {
|
||||
pages = Fetched.Failed(null)
|
||||
return@LaunchedEffect
|
||||
}
|
||||
val copy = FileCache.viewing(context, name)
|
||||
pages = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
api.copyInto(api.rawFile(path), copy, PDF_MAX_BYTES, stepped { done, total -> pages = Fetched.Loading(done, total) })
|
||||
Fetched.Ready(withContext(Dispatchers.IO) { PdfPages(copy) })
|
||||
} catch (e: CancellationException) {
|
||||
copy.delete()
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
copy.delete()
|
||||
// A password, or not a PDF after all: the renderer's own words are for a developer.
|
||||
Fetched.Failed(if (e is ApiException || unreachable(e)) viewerSays(context, e) else null)
|
||||
}
|
||||
}
|
||||
when (val now = pages) {
|
||||
is Fetched.Loading -> Progress(now)
|
||||
is Fetched.Failed -> fallback(now.message)
|
||||
is Fetched.Ready -> PdfPagesList(now.value)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PdfPagesList(pages: PdfPages) {
|
||||
val palette = LocalPalette.current
|
||||
val list = rememberLazyListState()
|
||||
Column(Modifier.fillMaxSize().background(palette.bgSunken)) {
|
||||
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
|
||||
val width = with(LocalDensity.current) { maxWidth.toPx() }.toInt().coerceIn(1, 1600)
|
||||
LazyColumn(
|
||||
state = list,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
items(pages.count) { index ->
|
||||
val page by produceState<ImageBitmap?>(null, pages, index, width) {
|
||||
value = withContext(Dispatchers.Default) { pages.page(index, width) }
|
||||
}
|
||||
val drawn = page
|
||||
if (drawn != null) {
|
||||
Image(drawn, contentDescription = null, contentScale = ContentScale.FillWidth, modifier = Modifier.fillMaxWidth())
|
||||
} else {
|
||||
// Until it is drawn: a sheet of the usual shape, so the list does not jump far.
|
||||
Box(Modifier.fillMaxWidth().aspectRatio(0.707f).background(palette.surfaceRaised))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.viewer_page, (list.firstVisibleItemIndex + 1).toString(), pages.count.toString()),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.fillMaxWidth().background(palette.bg).padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
class RemoteMedia(api: ApiClient, path: String, private val length: Long) : MediaDataSource() {
|
||||
private val reader = RangeReader(length) { from, to -> api.rawBytes(path, from, to) }
|
||||
|
||||
override fun readAt(position: Long, buffer: ByteArray, offset: Int, size: Int): Int = reader.read(position, buffer, offset, size)
|
||||
|
||||
override fun getSize(): Long = length
|
||||
|
||||
override fun close() = reader.close()
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
@Composable
|
||||
fun MediaBody(path: String, 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) }
|
||||
|
||||
DisposableEffect(path) {
|
||||
var held: MediaPlayer? = null
|
||||
var source: RemoteMedia? = null
|
||||
val starting = scope.launch {
|
||||
val api = context.lembas.instances.client()
|
||||
if (api == null || size <= 0) {
|
||||
failed = true
|
||||
return@launch
|
||||
}
|
||||
try {
|
||||
val media = RemoteMedia(api, path, size).also { source = it }
|
||||
val made = MediaPlayer().also { held = it }
|
||||
made.setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(if (video) AudioAttributes.CONTENT_TYPE_MOVIE else AudioAttributes.CONTENT_TYPE_MUSIC)
|
||||
.build(),
|
||||
)
|
||||
made.setDataSource(media)
|
||||
made.setOnPreparedListener {
|
||||
ui = ui.copy(ready = true, durationMs = it.duration.coerceAtLeast(0))
|
||||
player = it
|
||||
}
|
||||
made.setOnCompletionListener { ui = ui.copy(playing = false, positionMs = ui.durationMs) }
|
||||
made.setOnErrorListener { _, _, _ ->
|
||||
failed = true
|
||||
true
|
||||
}
|
||||
made.setOnVideoSizeChangedListener { _, w, h -> if (w > 0 && h > 0) ratio = (w.toFloat() / h).coerceIn(0.3f, 4f) }
|
||||
made.prepareAsync()
|
||||
} catch (e: Exception) {
|
||||
failed = true
|
||||
}
|
||||
}
|
||||
onDispose {
|
||||
starting.cancel()
|
||||
player = null
|
||||
held?.runCatching { release() }
|
||||
source?.runCatching { close() }
|
||||
}
|
||||
}
|
||||
|
||||
// The picture goes where the surface is, for as long as there is one.
|
||||
LaunchedEffect(player, surface) { player?.runCatching { setDisplay(surface) } }
|
||||
LaunchedEffect(player, ui.playing) {
|
||||
while (ui.playing) {
|
||||
player?.runCatching { currentPosition }?.getOrNull()?.let { ui = ui.copy(positionMs = it) }
|
||||
delay(500)
|
||||
}
|
||||
}
|
||||
LifecycleEventEffect(Lifecycle.Event.ON_STOP) {
|
||||
player?.runCatching { if (isPlaying) pause() }
|
||||
ui = ui.copy(playing = false)
|
||||
}
|
||||
|
||||
if (failed) {
|
||||
fallback(null)
|
||||
return
|
||||
}
|
||||
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
if (video) {
|
||||
AndroidView(
|
||||
factory = { viewContext ->
|
||||
SurfaceView(viewContext).apply {
|
||||
holder.addCallback(
|
||||
object : SurfaceHolder.Callback {
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||
surface = holder
|
||||
}
|
||||
|
||||
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = Unit
|
||||
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||
player?.runCatching { setDisplay(null) }
|
||||
surface = null
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth().weight(1f, fill = false).aspectRatio(ratio),
|
||||
)
|
||||
} else {
|
||||
Icon(Icons.Filled.MusicNote, contentDescription = null, tint = palette.inkFaint, modifier = Modifier.padding(24.dp).size(72.dp))
|
||||
}
|
||||
PlayerControls(
|
||||
ui,
|
||||
onToggle = {
|
||||
val now = player ?: return@PlayerControls
|
||||
runCatching {
|
||||
if (now.isPlaying) {
|
||||
now.pause()
|
||||
ui = ui.copy(playing = false)
|
||||
} else {
|
||||
if (ui.durationMs > 0 && ui.positionMs >= ui.durationMs) now.seekTo(0)
|
||||
now.start()
|
||||
ui = ui.copy(playing = true)
|
||||
}
|
||||
}
|
||||
},
|
||||
onSeek = { to ->
|
||||
player?.runCatching { seekTo(to) }
|
||||
ui = ui.copy(positionMs = to)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.viewer
|
||||
|
||||
import android.content.Context
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
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.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileContent
|
||||
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.SaveConflict
|
||||
import eu.llembas.android.api.Table
|
||||
import eu.llembas.android.api.parseNotebook
|
||||
import eu.llembas.android.api.parseTable
|
||||
import eu.llembas.android.api.tableDelimiter
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.files.CreateFile
|
||||
import eu.llembas.android.ui.files.SaidDialog
|
||||
import eu.llembas.android.ui.files.TransferHost
|
||||
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.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** What a viewer says of a failure: the server's or the network's sentence; null for "too large for this phone". */
|
||||
internal fun viewerSays(context: Context, e: Throwable): String? {
|
||||
val tooLarge = e is ApiException && e.status == 413 && e.message.isNullOrBlank()
|
||||
return if (tooLarge) null else context.explain(e)
|
||||
}
|
||||
|
||||
/**
|
||||
* The text being edited, kept apart from the screen: a megabyte does not fit what Android saves
|
||||
* of a screen when the phone is turned, and unsaved words must not go with it. [draft] is null
|
||||
* while nothing is edited; [touched] once a key was pressed.
|
||||
*/
|
||||
class EditViewModel : ViewModel() {
|
||||
var draft by mutableStateOf<String?>(null)
|
||||
private set
|
||||
var touched by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/** The `sha` the text had when it was read: a save says it, so somebody else's change is not written over. */
|
||||
var base: String = ""
|
||||
private set
|
||||
|
||||
fun start(text: String, sha: String) {
|
||||
draft = text
|
||||
base = sha
|
||||
touched = false
|
||||
}
|
||||
|
||||
fun type(text: String) {
|
||||
draft = text
|
||||
touched = true
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
draft = null
|
||||
touched = false
|
||||
}
|
||||
}
|
||||
|
||||
/** A file of the tree, opened: on its way, not to be had, or what the server says of it. */
|
||||
private sealed interface Opened {
|
||||
data object Loading : Opened
|
||||
|
||||
data class Failed(val message: String) : Opened
|
||||
|
||||
data class Ready(val file: FileContent) : Opened
|
||||
}
|
||||
|
||||
/**
|
||||
* A file of the person's tree, full screen, drawn by what the server says it is (`file_kind`):
|
||||
* text kinds as text (and edited as text), a picture, a PDF's pages, sound and video streamed, a
|
||||
* table's grid, a notebook's cells, and for the rest what it is with Download, Open with and
|
||||
* Share. The person's own files are no more trusted than a model's, since a model may have
|
||||
* written them: **nothing is rendered as HTML and nothing a file holds is run** -- an HTML page
|
||||
* and an SVG are their source. [onChanged]: the file was saved or a version restored, so a
|
||||
* listing behind this is stale.
|
||||
*/
|
||||
@Composable
|
||||
fun TreeFileViewer(path: String, onClose: () -> Unit, startEditing: Boolean = false, onChanged: () -> Unit = {}) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val edit: EditViewModel = viewModel(key = "edit:$path")
|
||||
// Its own, not the Files page's: two hosts of one would each open the other app.
|
||||
val transfers: TransferViewModel = viewModel(key = "viewer-transfers")
|
||||
var opened by remember(path) { mutableStateOf<Opened>(Opened.Loading) }
|
||||
var reads by remember(path) { mutableIntStateOf(0) }
|
||||
var web by remember(path) { mutableStateOf<String?>(null) }
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
var versions by remember { mutableStateOf(false) }
|
||||
var leaving by remember { mutableStateOf(false) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
var conflict by remember { mutableStateOf<String?>(null) }
|
||||
var said by remember { mutableStateOf<String?>(null) }
|
||||
var wantsEdit by remember(path) { mutableStateOf(startEditing) }
|
||||
val name = FileKinds.name(path)
|
||||
|
||||
LaunchedEffect(path, reads) {
|
||||
val api = context.lembas.instances.client()
|
||||
if (api == null) {
|
||||
opened = Opened.Failed(context.getString(R.string.assist_signed_out))
|
||||
return@LaunchedEffect
|
||||
}
|
||||
web = api.webFile(path)
|
||||
opened = try {
|
||||
val file = api.fileContent(path)
|
||||
// A new file opens ready to be written in; so does one whose text was read again after a conflict.
|
||||
if (wantsEdit && FileKinds.editable(file.fileKind, file.writable, file.withheld != null)) edit.start(file.text, file.sha)
|
||||
wantsEdit = false
|
||||
Opened.Ready(file)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Opened.Failed(context.filesSay(e))
|
||||
}
|
||||
}
|
||||
|
||||
val file = (opened as? Opened.Ready)?.file
|
||||
val draft = edit.draft
|
||||
val saveTo = rememberLauncherForActivityResult(CreateFile()) { to -> if (to != null) transfers.download(listOf(path), zip = false, to = to) }
|
||||
val actions = remember(path, file?.mime) {
|
||||
object : FileActions {
|
||||
override fun download() = saveTo.launch(CreateFile.Ask(name, file?.mime.orEmpty()))
|
||||
|
||||
override fun openWith() = transfers.openWith(path, name, file?.mime.orEmpty())
|
||||
|
||||
override fun share() = transfers.share(listOf(FileEntry(name = name, path = path, mime = file?.mime.orEmpty())))
|
||||
}
|
||||
}
|
||||
|
||||
fun save(force: Boolean) {
|
||||
val text = edit.draft ?: return
|
||||
saving = true
|
||||
scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
val saved = api.saveFile(path, text, base = edit.base, force = force)
|
||||
edit.stop()
|
||||
opened = Opened.Ready(saved)
|
||||
onChanged()
|
||||
} catch (e: SaveConflict) {
|
||||
// Nothing was written. The server's sentence, with the two ways on.
|
||||
conflict = e.message?.ifBlank { null } ?: context.getString(R.string.files_conflict)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
said = context.filesSay(e)
|
||||
} finally {
|
||||
saving = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Leaving with words that were not saved asks first: Back, the cross, and a tap outside all come here.
|
||||
fun close() {
|
||||
when {
|
||||
draft != null && edit.touched -> leaving = true
|
||||
draft != null -> edit.stop()
|
||||
else -> onClose()
|
||||
}
|
||||
}
|
||||
|
||||
Dialog(onDismissRequest = { close() }, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = { close() }) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = {
|
||||
Column {
|
||||
Text(name, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
path,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.StartEllipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
if (draft != null) {
|
||||
IconButton(onClick = { save(force = false) }, enabled = !saving && edit.touched) {
|
||||
Icon(Icons.Filled.Check, contentDescription = stringResource(R.string.save))
|
||||
}
|
||||
} else if (file != null) {
|
||||
if (FileKinds.editable(file.fileKind, file.writable, file.withheld != null)) {
|
||||
IconButton(onClick = {
|
||||
edit.start(file.text, file.sha)
|
||||
}) { Icon(Icons.Filled.Edit, contentDescription = stringResource(R.string.edit)) }
|
||||
}
|
||||
Box {
|
||||
IconButton(onClick = { menu = true }) { Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more)) }
|
||||
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||
val then: (() -> Unit) -> (() -> Unit) = { act ->
|
||||
{
|
||||
menu = false
|
||||
act()
|
||||
}
|
||||
}
|
||||
val text = file.text.takeIf { file.withheld == null && it.isNotEmpty() }
|
||||
if (text != null) MenuEntry(R.string.viewer_copy, then { copy(context, name, text) })
|
||||
if (file.fileKind != null) {
|
||||
MenuEntry(R.string.download, then { actions.download() })
|
||||
MenuEntry(R.string.files_open_with, then { actions.openWith() })
|
||||
MenuEntry(R.string.report_share, then { actions.share() })
|
||||
MenuEntry(R.string.versions, then { versions = true })
|
||||
}
|
||||
web?.let { url -> MenuEntry(R.string.viewer_open_browser, then { openOutside(context, url) }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||
if (saving) LinearProgressIndicator(Modifier.fillMaxWidth().height(2.dp))
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (leaving) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { leaving = false },
|
||||
text = { Text(stringResource(R.string.files_unsaved)) },
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
leaving = false
|
||||
edit.stop()
|
||||
},
|
||||
) { Text(stringResource(R.string.discard)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { leaving = false }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
conflict?.let { sentence ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { conflict = null },
|
||||
text = { Text(sentence) },
|
||||
// Two ways on, and neither is the default: the words stack, so each is a whole row.
|
||||
confirmButton = {
|
||||
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.End) {
|
||||
TextButton(
|
||||
onClick = {
|
||||
conflict = null
|
||||
// What the file holds now, in place of what was typed here.
|
||||
edit.stop()
|
||||
wantsEdit = true
|
||||
reads++
|
||||
},
|
||||
) { Text(stringResource(R.string.reload)) }
|
||||
TextButton(
|
||||
onClick = {
|
||||
conflict = null
|
||||
save(force = true)
|
||||
},
|
||||
) { Text(stringResource(R.string.files_save_anyway)) }
|
||||
TextButton(onClick = { conflict = null }) { Text(stringResource(R.string.cancel)) }
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
said?.let { SaidDialog(it, onClose = { said = null }) }
|
||||
if (versions) {
|
||||
VersionsDialog(
|
||||
path,
|
||||
onClose = { versions = false },
|
||||
onRestored = {
|
||||
versions = false
|
||||
reads++
|
||||
onChanged()
|
||||
},
|
||||
)
|
||||
}
|
||||
TransferHost(transfers)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MenuEntry(label: Int, onClick: () -> Unit) = DropdownMenuItem(text = { Text(stringResource(label)) }, onClick = onClick)
|
||||
|
||||
/** 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) {
|
||||
val context = LocalContext.current
|
||||
val name = file.name.ifBlank { FileKinds.name(path) }
|
||||
val type = listOf(file.fileKind.orEmpty(), file.mime).filter { it.isNotBlank() }.joinToString(" · ")
|
||||
val details: @Composable (String?) -> Unit = { note -> DetailsBody(name, type, file.size, note ?: stringResource(R.string.files_not_shown), actions) }
|
||||
val withheld = file.withheld
|
||||
when (FileKinds.viewer(file.fileKind)) {
|
||||
FileView.Text -> when {
|
||||
withheld != null -> {
|
||||
val why = if (withheld.reason == "too_large") R.string.viewer_too_large else R.string.viewer_not_text
|
||||
details(withheld.message.ifBlank { stringResource(why) })
|
||||
}
|
||||
|
||||
file.fileKind == "svg" -> Column(Modifier.fillMaxSize()) {
|
||||
Note(stringResource(R.string.files_svg_source))
|
||||
FileBody("code", "xml", 0, file.text)
|
||||
}
|
||||
|
||||
else -> FileBody(file.viewKind, file.language, 0, file.text)
|
||||
}
|
||||
|
||||
FileView.Image -> ImageBody(path, name, file.size, details)
|
||||
|
||||
FileView.Pdf -> PdfBody(path, name, file.size, details)
|
||||
|
||||
FileView.Audio -> MediaBody(path, file.size, video = false, fallback = details)
|
||||
|
||||
FileView.Video -> MediaBody(path, file.size, video = true, fallback = details)
|
||||
|
||||
FileView.Table -> {
|
||||
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.
|
||||
val text = if (withheld == null) {
|
||||
file.text
|
||||
} else {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
withContext(Dispatchers.IO) { api.rawBytes(path, 0, TABLE_HEAD - 1).toString(Charsets.UTF_8) }
|
||||
}
|
||||
Fetched.Ready(withContext(Dispatchers.Default) { parseTable(text, tableDelimiter(name, text), partial = withheld != null) })
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Fetched.Failed(if (noSuchRoute(e)) null else viewerSays(context, e))
|
||||
}
|
||||
}
|
||||
when (val now = table) {
|
||||
is Fetched.Loading -> Progress(now)
|
||||
is Fetched.Failed -> details(now.message)
|
||||
is Fetched.Ready -> if (now.value.rows.isEmpty()) FileBody("text", "", 0, file.text) else TableBody(now.value)
|
||||
}
|
||||
}
|
||||
|
||||
FileView.Notebook -> {
|
||||
val notebook = remember(file.sha, file.text) { if (withheld == null) parseNotebook(file.text) else null }
|
||||
if (notebook != null) NotebookBody(notebook) else details(withheld?.message?.ifBlank { null })
|
||||
}
|
||||
|
||||
FileView.Details -> details(
|
||||
stringResource(if (file.fileKind == "archive") R.string.archive_note else R.string.files_no_viewer),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** How much of a table too long to be sent as text is read for its first rows. */
|
||||
private const val TABLE_HEAD = 1024L * 1024
|
||||
Reference in new issue
Block a user