From 5d1e36868c2e77516c82b357ddac4f18a0077cbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Bene=C5=A1?= Date: Wed, 18 Nov 2026 21:24:39 +0000 Subject: [PATCH] Files is a file manager, and the viewer draws a file by what it is 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 --- CHANGELOG.md | 27 + app/src/main/AndroidManifest.xml | 4 +- .../main/java/eu/llembas/android/LembasApp.kt | 2 + .../java/eu/llembas/android/api/ApiClient.kt | 177 +++++ .../main/java/eu/llembas/android/api/Files.kt | 284 ++++++++ .../java/eu/llembas/android/api/Models.kt | 19 +- .../eu/llembas/android/share/ShareActivity.kt | 55 ++ .../eu/llembas/android/share/ShareSheet.kt | 81 ++- .../llembas/android/ui/files/FileDialogs.kt | 469 +++++++++++++ .../llembas/android/ui/files/FilesScreen.kt | 660 ++++++++++++++++-- .../android/ui/files/TransferViewModel.kt | 200 ++++++ .../eu/llembas/android/ui/files/Transfers.kt | 195 ++++++ .../android/ui/settings/SettingsScreen.kt | 3 + .../eu/llembas/android/ui/viewer/Bodies.kt | 331 +++++++++ .../llembas/android/ui/viewer/FileViewer.kt | 29 +- .../eu/llembas/android/ui/viewer/Media.kt | 404 +++++++++++ .../llembas/android/ui/viewer/TreeViewer.kt | 412 +++++++++++ app/src/main/res/values-cs/strings.xml | 61 ++ app/src/main/res/values-de/strings.xml | 61 ++ app/src/main/res/values-es/strings.xml | 61 ++ app/src/main/res/values-fr/strings.xml | 61 ++ app/src/main/res/values-hu/strings.xml | 61 ++ app/src/main/res/values-it/strings.xml | 61 ++ app/src/main/res/values-pl/strings.xml | 61 ++ app/src/main/res/values-sk/strings.xml | 61 ++ app/src/main/res/values/strings.xml | 61 ++ app/src/main/res/xml/file_paths.xml | 7 +- .../java/eu/llembas/android/FileLogicTest.kt | 261 +++++++ .../eu/llembas/android/FilesClientTest.kt | 235 +++++++ .../eu/llembas/android/shots/FileShots.kt | 138 ++++ scripts/strings.py | 70 +- scripts/strings_own.json | 144 +++- 32 files changed, 4618 insertions(+), 138 deletions(-) create mode 100644 app/src/main/java/eu/llembas/android/api/Files.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/files/FileDialogs.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/files/TransferViewModel.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/files/Transfers.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/viewer/Bodies.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/viewer/Media.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/viewer/TreeViewer.kt create mode 100644 app/src/test/java/eu/llembas/android/FileLogicTest.kt create mode 100644 app/src/test/java/eu/llembas/android/FilesClientTest.kt create mode 100644 app/src/test/java/eu/llembas/android/shots/FileShots.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 3628510..a6666e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,33 @@ is in alpha and releases come off `main`. ## [Unreleased] +For Files as described here the instance must be newer than LLeMbas 2.0.0-beta.16. On an older +one Files lists and shows text as before, and says so where it cannot do more. + +### Added + +- **Files is a file manager.** Upload from the phone (several at once, with progress; a file + over the instance's limit is refused in the instance's own words and the others still go), + make a folder or a text file, rename, move and copy by walking to the folder rather than + typing a path, and delete to the trash. A long press chooses; with several chosen, a bar moves, + copies, downloads, shares or deletes them all, and says which the instance refused. +- **The trash and a file's versions.** What was deleted can be restored or removed for good, + one thing or everything. A file's earlier versions are listed, and any of them can be made + the file again without losing the others. +- **Download, Open with and Share.** A file is saved where you choose in the phone's own + "Save to" page; several files or a folder come as one zip. Open with and Share hand another + app a copy from the app's private storage, which is deleted again. The app asks for no + storage permission. +- **Text files can be edited.** Markdown, code, plain text, a page's source and a table's text, + up to the instance's 1 MB. If the file changed on the instance while you were writing, nothing + is written over: you choose Reload or Save anyway. Leaving with unsaved text asks first. +- **A viewer for each kind of file.** Pictures, with zoom and pan; PDFs, page by page; sound and + video, streamed, with seeking; CSV and TSV as a grid; notebooks as their cells' text. For + archives, 3D models and anything else: what it is, with Download, Open with and Share. An + HTML page and an SVG are shown as their source -- the app draws nothing a file could script. +- **"Save to Files" in the share sheet.** Something shared from another app can be kept in a + folder of your files instead of being sent into a chat; shared text is kept as a note. + ### Fixed - **A chat on a model two connections serve shows the right connection.** When an instance has diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 3166529..fb01213 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -211,7 +211,9 @@ android:name=".push.ScheduleActionReceiver" android:exported="false" /> - + ): 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, 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): 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() diff --git a/app/src/main/java/eu/llembas/android/api/Files.kt b/app/src/main/java/eu/llembas/android/api/Files.kt new file mode 100644 index 0000000..8c03f97 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/api/Files.kt @@ -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 = 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 = 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 = 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 = 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>, 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>() + var row = mutableListOf() + 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, 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(keep, 0.75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry?): 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 + } +} diff --git a/app/src/main/java/eu/llembas/android/api/Models.kt b/app/src/main/java/eu/llembas/android/api/Models.kt index 83c46b4..77586f4 100644 --- a/app/src/main/java/eu/llembas/android/api/Models.kt +++ b/app/src/main/java/eu/llembas/android/api/Models.kt @@ -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 = emptyList()) +data class FileListing( + val path: String = "/", + val parent: String? = null, + val entries: List = 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, diff --git a/app/src/main/java/eu/llembas/android/share/ShareActivity.kt b/app/src/main/java/eu/llembas/android/share/ShareActivity.kt index 718f97f..bd72260 100644 --- a/app/src/main/java/eu/llembas/android/share/ShareActivity.kt +++ b/app/src/main/java/eu/llembas/android/share/ShareActivity.kt @@ -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 = 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) } diff --git a/app/src/main/java/eu/llembas/android/share/ShareSheet.kt b/app/src/main/java/eu/llembas/android/share/ShareSheet.kt index 8e67324..56ccf48 100644 --- a/app/src/main/java/eu/llembas/android/share/ShareSheet.kt +++ b/app/src/main/java/eu/llembas/android/share/ShareSheet.kt @@ -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" diff --git a/app/src/main/java/eu/llembas/android/ui/files/FileDialogs.kt b/app/src/main/java/eu/llembas/android/ui/files/FileDialogs.kt new file mode 100644 index 0000000..1e3956b --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/files/FileDialogs.kt @@ -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 = 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 = 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 = 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(null) } + var emptying by remember { mutableStateOf(false) } + var said by remember { mutableStateOf(null) } + + fun act(block: suspend (ApiClient) -> List) { + 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 = 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(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() + } + } + } + } +} diff --git a/app/src/main/java/eu/llembas/android/ui/files/FilesScreen.kt b/app/src/main/java/eu/llembas/android/ui/files/FilesScreen.kt index bb0c8e7..3487347 100644 --- a/app/src/main/java/eu/llembas/android/ui/files/FilesScreen.kt +++ b/app/src/main/java/eu/llembas/android/ui/files/FilesScreen.kt @@ -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 = emptyList(), val loading: Boolean = false, val error: String? = null, -) + val selected: Set = 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 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) : Ask + + data class Move(val entries: List) : Ask + + data class Copy(val entries: List) : 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) {} + + fun share(entries: List) {} + + 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().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().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, 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) { + if (uris.isEmpty() || uploading?.isActive == true) return + val dir = _state.value.path + uploading = viewModelScope.launch { + val refused = mutableListOf() + 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(null) } + var writing by rememberSaveable { mutableStateOf(false) } + var asked by remember { mutableStateOf(null) } + var saving by remember { mutableStateOf>(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) { + 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) { + 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): 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)) }) + } + } + } + }, ) } diff --git a/app/src/main/java/eu/llembas/android/ui/files/TransferViewModel.kt b/app/src/main/java/eu/llembas/android/ui/files/TransferViewModel.kt new file mode 100644 index 0000000..1c0c508 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/files/TransferViewModel.kt @@ -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, 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) = 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 { + 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)) } }, + ) +} diff --git a/app/src/main/java/eu/llembas/android/ui/files/Transfers.kt b/app/src/main/java/eu/llembas/android/ui/files/Transfers.kt new file mode 100644 index 0000000..9355d6e --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/files/Transfers.kt @@ -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() { + 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, 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) + } + } +} diff --git a/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt b/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt index 03d22cf..a2d5af7 100644 --- a/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt @@ -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) } } diff --git a/app/src/main/java/eu/llembas/android/ui/viewer/Bodies.kt b/app/src/main/java/eu/llembas/android/ui/viewer/Bodies.kt new file mode 100644 index 0000000..54a81b2 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/viewer/Bodies.kt @@ -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(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), + ) +} diff --git a/app/src/main/java/eu/llembas/android/ui/viewer/FileViewer.kt b/app/src/main/java/eu/llembas/android/ui/viewer/FileViewer.kt index e4454be..0750d41 100644 --- a/app/src/main/java/eu/llembas/android/ui/viewer/FileViewer.kt +++ b/app/src/main/java/eu/llembas/android/ui/viewer/FileViewer.kt @@ -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 { } } -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) } diff --git a/app/src/main/java/eu/llembas/android/ui/viewer/Media.kt b/app/src/main/java/eu/llembas/android/ui/viewer/Media.kt new file mode 100644 index 0000000..acb6f82 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/viewer/Media.kt @@ -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 { + data class Loading(val done: Long = 0, val total: Long = -1) : Fetched + + data class Ready(val value: T) : Fetched + + /** [message]: the server's sentence or the network's; null: this phone could not draw it. */ + data class Failed(val message: String?) : Fetched +} + +/** + * [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.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.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(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(null) } + var surface by remember(path) { mutableStateOf(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) + }, + ) + } +} diff --git a/app/src/main/java/eu/llembas/android/ui/viewer/TreeViewer.kt b/app/src/main/java/eu/llembas/android/ui/viewer/TreeViewer.kt new file mode 100644 index 0000000..491dd8a --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/viewer/TreeViewer.kt @@ -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(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.Loading) } + var reads by remember(path) { mutableIntStateOf(0) } + var web by remember(path) { mutableStateOf(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(null) } + var said by remember { mutableStateOf(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.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 diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index c03b87c..213fe4d 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -348,6 +348,67 @@ Soubory Všechny soubory Zatím tu nic není. Ani hobití nora. + Nahrát + Nový soubor + Jak se má soubor jmenovat? I s příponou, například notes.md. + Jak se má složka jmenovat? + Název nesmí být prázdný ani obsahovat lomítko. + Něco s názvem %1$s tu už je. + Přejmenovat + Nový název + Přesunout + Kopírovat do… + Přesunout sem + Kopírovat sem + Do které složky přesunout? + Do které složky kopírovat? + Vybrat složku + Uložit sem + Nejsou tu žádné složky. + Přesunout do koše + Přesunout „%1$s“ do koše? Odtamtud ho lze obnovit. + Přesunout vybrané (%1$s) do koše? Odtud je lze obnovit. + Přesunuto do koše. + Vybráno: %1$s + Vybrat vše + Stáhnout + Stáhnout jako zip + Stahuje se… + Staženo. + Nahrává se %1$s z %2$s… + Nahráno. + Otevřít v… + Žádná aplikace v tomto telefonu tento druh souboru neotevře. + Koš + Koš je prázdný. + Vysypat koš + Trvale odstranit vše v koši? Nelze to vrátit zpět. + Odstranit trvale + Trvale odstranit „%1$s“? Nelze to vrátit zpět. + Obnovit + Verze + Obnovit tuto verzi + Udělat z této verze aktuální? Ta současná zůstane v seznamu. + Aktuální + Typ + Velikost + Pro tento druh souboru není prohlížeč. + Tento soubor se zde nepodařilo zobrazit. Stále jej lze stáhnout. + Toto je zdroj obrázku. Chcete-li vidět obrázek, otevřete jej v jiné aplikaci. + Obsah tohoto druhu archivu zde nelze vypsat. + Do tabulky jsou rozloženy jen první řádky a sloupce. Text obsahuje vše. + Tento zápisník nemá žádné buňky. + Dalších %1$s buněk se nezobrazuje. + Tato buňka je delší, než se zde zobrazuje. + Strana %1$s z %2$s + Přehrát + Pozastavit + Soubor se od otevření změnil. Načtěte ho znovu, nebo přesto uložte. + Přesto uložit + Načíst znovu + Zahodit + Zahodit změny v tomto souboru? + Uložit do Souborů Nastavení Instance Odhlásit se diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 7961c6e..472893f 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -348,6 +348,67 @@ Dateien Alle Dateien Hier ist noch nichts. Nicht einmal eine Hobbithöhle. + Hochladen + Neue Datei + Wie soll die Datei heißen? Mit Endung, etwa notes.md. + Wie soll der Ordner heißen? + Ein Name darf weder leer sein noch einen Schrägstrich enthalten. + Hier gibt es schon etwas namens %1$s. + Umbenennen + Neuer Name + Verschieben + Kopieren nach… + Hierher verschieben + Hierher kopieren + In welchen Ordner verschieben? + In welchen Ordner kopieren? + Ordner wählen + Hier speichern + Hier gibt es keine Ordner. + In den Papierkorb + „%1$s“ in den Papierkorb verschieben? Von dort lässt es sich wiederherstellen. + Die %1$s ausgewählten in den Papierkorb verschieben? Von dort lassen sie sich wiederherstellen. + In den Papierkorb verschoben. + %1$s ausgewählt + Alle auswählen + Herunterladen + Als Zip herunterladen + Wird heruntergeladen… + Heruntergeladen. + %1$s von %2$s wird hochgeladen… + Hochgeladen. + Öffnen mit… + Keine App auf diesem Telefon öffnet diese Art von Datei. + Papierkorb + Der Papierkorb ist leer. + Papierkorb leeren + Alles im Papierkorb endgültig entfernen? Das lässt sich nicht rückgängig machen. + Endgültig entfernen + „%1$s“ endgültig entfernen? Das lässt sich nicht rückgängig machen. + Wiederherstellen + Versionen + Diese Version wiederherstellen + Diese Version zur aktuellen machen? Die jetzige bleibt in der Liste. + Aktuell + Typ + Größe + Für diese Art von Datei gibt es keinen Betrachter. + Diese Datei konnte hier nicht gezeigt werden. Sie lässt sich weiterhin herunterladen. + Das ist der Quelltext des Bildes. Öffne es mit einer anderen App, um das Bild zu sehen. + Der Inhalt dieser Art von Archiv kann hier nicht aufgelistet werden. + Nur die ersten Zeilen und Spalten sind als Tabelle gesetzt. Der Text enthält alles. + Dieses Notebook hat keine Zellen. + %1$s weitere Zellen werden nicht gezeigt. + Diese Zelle ist länger, als hier gezeigt wird. + Seite %1$s von %2$s + Abspielen + Pausieren + Die Datei hat sich geändert, seit Sie sie geöffnet haben. Laden Sie sie neu oder speichern Sie trotzdem. + Trotzdem speichern + Neu laden + Verwerfen + Die Änderungen an dieser Datei verwerfen? + In Dateien speichern Einstellungen Instanzen Abmelden diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 3709e80..61f70a3 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -348,6 +348,67 @@ Archivos Todos los archivos Aquí aún no hay nada. Ni siquiera un agujero hobbit. + Subir + Nuevo archivo + ¿Cómo debe llamarse el archivo? Con su extensión, por ejemplo notes.md. + ¿Cómo debe llamarse la carpeta? + Un nombre no puede estar vacío ni contener una barra. + Ya hay algo llamado %1$s aquí. + Renombrar + Nombre nuevo + Mover + Copiar a… + Mover aquí + Copiar aquí + ¿A qué carpeta mover? + ¿A qué carpeta copiar? + Elegir una carpeta + Guardar aquí + Aquí no hay carpetas. + Mover a la papelera + ¿Mover «%1$s» a la papelera? Se puede restaurar desde allí. + ¿Mover los %1$s seleccionados a la papelera? Desde allí se pueden restaurar. + Movido a la papelera. + Seleccionados: %1$s + Seleccionar todo + Descargar + Descargar como zip + Descargando… + Descargado. + Subiendo %1$s de %2$s… + Subido. + Abrir con… + Ninguna aplicación de este teléfono abre este tipo de archivo. + Papelera + La papelera está vacía. + Vaciar la papelera + ¿Eliminar para siempre todo lo que hay en la papelera? No se puede deshacer. + Eliminar para siempre + ¿Eliminar «%1$s» para siempre? No se puede deshacer. + Restaurar + Versiones + Restaurar esta versión + ¿Hacer actual esta versión? La actual se queda en la lista. + Actual + Tipo + Tamaño + No hay visor para este tipo de archivo. + Este archivo no se pudo mostrar aquí. Aún se puede descargar. + Este es el código fuente de la imagen. Ábrela con otra aplicación para ver la imagen. + El contenido de este tipo de archivo comprimido no se puede listar aquí. + Solo las primeras filas y columnas se disponen como tabla. El texto lo contiene todo. + Este cuaderno no tiene celdas. + No se muestran %1$s celdas más. + Esta celda es más larga de lo que se muestra aquí. + Página %1$s de %2$s + Reproducir + Pausar + El archivo ha cambiado desde que lo abrió. Vuelva a cargarlo o guárdelo de todos modos. + Guardar de todos modos + Recargar + Descartar + ¿Descartar los cambios en este archivo? + Guardar en Archivos Ajustes Instancias Cerrar sesión diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 0f8c57e..2167d02 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -348,6 +348,67 @@ Fichiers Tous les fichiers Rien ici pour l\'instant. Pas même un trou de hobbit. + Envoyer + Nouveau fichier + Comment le fichier doit-il s’appeler ? Avec son extension, par exemple notes.md. + Comment le dossier doit-il s\'appeler ? + Un nom ne peut être ni vide ni contenir de barre oblique. + Il y a déjà quelque chose nommé %1$s ici. + Renommer + Nouveau nom + Déplacer + Copier vers… + Déplacer ici + Copier ici + Déplacer vers quel dossier ? + Copier vers quel dossier ? + Choisir un dossier + Enregistrer ici + Aucun dossier ici. + Placer dans la corbeille + Placer « %1$s » dans la corbeille ? On peut l\'y restaurer. + Placer les %1$s éléments sélectionnés dans la corbeille ? Ils peuvent y être restaurés. + Placé dans la corbeille. + Sélectionnés : %1$s + Tout sélectionner + Télécharger + Télécharger en zip + Téléchargement… + Téléchargé. + Envoi de %1$s sur %2$s… + Envoyé. + Ouvrir avec… + Aucune application de ce téléphone n’ouvre ce type de fichier. + Corbeille + La corbeille est vide. + Vider la corbeille + Supprimer définitivement tout le contenu de la corbeille ? C’est irréversible. + Supprimer définitivement + Supprimer définitivement « %1$s » ? C’est irréversible. + Restaurer + Versions + Restaurer cette version + Faire de cette version l\'actuelle ? L\'actuelle reste dans la liste. + Actuelle + Type + Taille + Il n\'y a pas de visionneuse pour ce type de fichier. + Ce fichier n\'a pas pu être affiché ici. Il peut toujours être téléchargé. + Ceci est la source de l’image. Ouvrez-la avec une autre application pour voir l’image. + Le contenu de ce type d\'archive ne peut pas être listé ici. + Seules les premières lignes et colonnes sont mises en tableau. Le texte contient tout. + Ce notebook n\'a aucune cellule. + %1$s autres cellules ne sont pas affichées. + Cette cellule est plus longue que ce qui est affiché ici. + Page %1$s sur %2$s + Lire + Mettre en pause + Le fichier a changé depuis que vous l\'avez ouvert. Rechargez-le, ou enregistrez quand même. + Enregistrer quand même + Recharger + Abandonner + Abandonner les modifications de ce fichier ? + Enregistrer dans Fichiers Paramètres Instances Se déconnecter diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 1726ee2..e135997 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -348,6 +348,67 @@ Fájlok Minden fájl Itt még nincs semmi. Még egy hobbitlyuk sem. + Feltöltés + Új fájl + Mi legyen a fájl neve? Kiterjesztéssel együtt, például notes.md. + Mi legyen a mappa neve? + A név nem lehet üres, és nem tartalmazhat perjelet. + Már van itt valami %1$s néven. + Átnevezés + Új név + Áthelyezés + Másolás ide… + Áthelyezés ide + Másolás ide + Melyik mappába kerüljön át? + Melyik mappába másolja? + Mappa választása + Mentés ide + Itt nincsenek könyvtárak. + Áthelyezés a lomtárba + Áthelyezi a lomtárba: „%1$s”? Onnan visszaállítható. + A lomtárba helyezi a kijelölteket (%1$s)? Onnan visszaállíthatók. + A lomtárba került. + Kijelölve: %1$s + Összes kijelölése + Letöltés + Letöltés zipként + Letöltés… + Letöltve. + Feltöltés: %1$s / %2$s… + Feltöltve. + Megnyitás ezzel… + Ezen a telefonon egyetlen alkalmazás sem nyitja meg az ilyen fájlt. + Lomtár + A lomtár üres. + Lomtár ürítése + Véglegesen eltávolítja a lomtár teljes tartalmát? Ez nem vonható vissza. + Végleges eltávolítás + Véglegesen eltávolítja ezt: „%1$s”? Ez nem vonható vissza. + Visszaállítás + Változatok + Változat visszaállítása + Legyen ez az aktuális változat? A mostani a listában marad. + Jelenlegi + Típus + Méret + Ehhez a fájlfajtához nincs megjelenítő. + Ezt a fájlt itt nem sikerült megjeleníteni. Továbbra is letölthető. + Ez a kép forrása. A kép megtekintéséhez nyissa meg egy másik alkalmazással. + Az ilyen fajta archívum tartalma itt nem listázható. + Csak az első sorok és oszlopok kerültek táblázatba. A szöveg mindent tartalmaz. + Ennek a jegyzetfüzetnek nincsenek cellái. + További %1$s cella nem jelenik meg. + Ez a cella hosszabb, mint ami itt látszik. + %1$s. / %2$s oldal + Lejátszás + Szüneteltetés + A fájl megváltozott, mióta megnyitotta. Töltse be újra, vagy mentse mégis. + Mentés mégis + Újratöltés + Elvetés + Elveti a fájl módosításait? + Mentés a Fájlokba Beállítások Példányok Kijelentkezés diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 209aad0..904f2ee 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -348,6 +348,67 @@ File Tutti i file Ancora niente qui. Nemmeno una caverna hobbit. + Carica + Nuovo file + Come deve chiamarsi il file? Con l’estensione, ad esempio notes.md. + Come deve chiamarsi la cartella? + Un nome non può essere vuoto né contenere una barra. + Qui c’è già qualcosa chiamato %1$s. + Rinomina + Nuovo nome + Sposta + Copia in… + Sposta qui + Copia qui + In quale cartella spostare? + In quale cartella copiare? + Scegli una cartella + Salva qui + Nessuna cartella qui. + Sposta nel cestino + Spostare «%1$s» nel cestino? Si può ripristinare da lì. + Spostare i %1$s selezionati nel cestino? Da lì si possono ripristinare. + Spostato nel cestino. + Selezionati: %1$s + Seleziona tutto + Scarica + Scarica come zip + Download in corso… + Scaricato. + Caricamento di %1$s su %2$s… + Caricato. + Apri con… + Nessuna app su questo telefono apre questo tipo di file. + Cestino + Il cestino è vuoto. + Svuota il cestino + Rimuovere definitivamente tutto ciò che è nel cestino? Non si può annullare. + Rimuovi definitivamente + Rimuovere definitivamente «%1$s»? Non si può annullare. + Ripristina + Versioni + Ripristina questa versione + Rendere questa versione quella attuale? Quella attuale resta nell\'elenco. + Attuale + Tipo + Dimensione + Non c\'è un visualizzatore per questo tipo di file. + Non è stato possibile mostrare qui questo file. Si può comunque scaricare. + Questo è il sorgente dell’immagine. Aprila con un’altra app per vedere l’immagine. + Il contenuto di questo tipo di archivio non può essere elencato qui. + Solo le prime righe e colonne sono disposte in tabella. Il testo contiene tutto. + Questo notebook non ha celle. + Altre %1$s celle non vengono mostrate. + Questa cella è più lunga di quanto mostrato qui. + Pagina %1$s di %2$s + Riproduci + Metti in pausa + Il file è cambiato da quando l\'hai aperto. Ricaricalo o salva comunque. + Salva comunque + Ricarica + Scarta + Scartare le modifiche a questo file? + Salva in File Impostazioni Istanze Esci diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 9b98e59..335cd2b 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -348,6 +348,67 @@ Pliki Wszystkie pliki Jeszcze nic tu nie ma. Nawet hobbiciej norki. + Prześlij + Nowy plik + Jak ma się nazywać plik? Z rozszerzeniem, na przykład notes.md. + Jak ma się nazywać folder? + Nazwa nie może być pusta ani zawierać ukośnika. + Coś o nazwie %1$s już tu jest. + Zmień nazwę + Nowa nazwa + Przenieś + Kopiuj do… + Przenieś tutaj + Kopiuj tutaj + Do którego folderu przenieść? + Do którego folderu skopiować? + Wybierz folder + Zapisz tutaj + Brak katalogów. + Przenieś do kosza + Przenieść „%1$s” do kosza? Można go stamtąd przywrócić. + Przenieść zaznaczone (%1$s) do kosza? Stamtąd można je przywrócić. + Przeniesiono do kosza. + Zaznaczone: %1$s + Zaznacz wszystko + Pobierz + Pobierz jako zip + Pobieranie… + Pobrano. + Przesyłanie %1$s z %2$s… + Przesłano. + Otwórz za pomocą… + Żadna aplikacja na tym telefonie nie otwiera tego rodzaju pliku. + Kosz + Kosz jest pusty. + Opróżnij kosz + Usunąć na stałe wszystko z kosza? Tego nie da się cofnąć. + Usuń na stałe + Usunąć „%1$s” na stałe? Tego nie da się cofnąć. + Przywróć + Wersje + Przywróć tę wersję + Uczynić tę wersję bieżącą? Obecna zostanie na liście. + Bieżąca + Typ + Rozmiar + Nie ma przeglądarki dla tego rodzaju pliku. + Nie udało się tu pokazać tego pliku. Nadal można go pobrać. + To jest źródło obrazu. Otwórz je w innej aplikacji, aby zobaczyć obraz. + Zawartości tego rodzaju archiwum nie można tu wypisać. + W tabeli ułożono tylko pierwsze wiersze i kolumny. Tekst zawiera wszystko. + Ten notatnik nie ma komórek. + Kolejnych %1$s komórek nie pokazano. + Ta komórka jest dłuższa, niż tu pokazano. + Strona %1$s z %2$s + Odtwórz + Wstrzymaj + Plik zmienił się od otwarcia. Wczytaj go ponownie albo zapisz mimo to. + Zapisz mimo to + Przeładuj + Odrzuć + Odrzucić zmiany w tym pliku? + Zapisz w Plikach Ustawienia Instancje Wyloguj się diff --git a/app/src/main/res/values-sk/strings.xml b/app/src/main/res/values-sk/strings.xml index b9f0249..be5e962 100644 --- a/app/src/main/res/values-sk/strings.xml +++ b/app/src/main/res/values-sk/strings.xml @@ -348,6 +348,67 @@ Súbory Všetky súbory Zatiaľ tu nič nie je. Ani hobitia nora. + Nahrať + Nový súbor + Ako sa má súbor volať? Aj s príponou, napríklad notes.md. + Ako sa má priečinok volať? + Názov nesmie byť prázdny ani obsahovať lomku. + Niečo s názvom %1$s tu už je. + Premenovať + Nový názov + Presunúť + Kopírovať do… + Presunúť sem + Kopírovať sem + Do ktorého priečinka presunúť? + Do ktorého priečinka kopírovať? + Vybrať priečinok + Uložiť sem + Nie sú tu žiadne priečinky. + Presunúť do koša + Presunúť „%1$s“ do koša? Odtiaľ sa dá obnoviť. + Presunúť vybrané (%1$s) do koša? Odtiaľ sa dajú obnoviť. + Presunuté do koša. + Vybrané: %1$s + Vybrať všetko + Stiahnuť + Stiahnuť ako zip + Sťahuje sa… + Stiahnuté. + Nahráva sa %1$s z %2$s… + Nahrané. + Otvoriť v… + Žiadna aplikácia v tomto telefóne tento druh súboru neotvorí. + Kôš + Kôš je prázdny. + Vyprázdniť kôš + Natrvalo odstrániť všetko v koši? Nedá sa to vrátiť späť. + Odstrániť natrvalo + Natrvalo odstrániť „%1$s“? Nedá sa to vrátiť späť. + Obnoviť + Verzie + Obnoviť túto verziu + Urobiť z tejto verzie aktuálnu? Súčasná zostane v zozname. + Aktuálna + Typ + Veľkosť + Pre tento druh súboru nie je prehliadač. + Tento súbor sa tu nepodarilo zobraziť. Stále sa dá stiahnuť. + Toto je zdroj obrázka. Ak chcete vidieť obrázok, otvorte ho v inej aplikácii. + Obsah tohto druhu archívu sa tu nedá vypísať. + Do tabuľky sú rozložené len prvé riadky a stĺpce. Text obsahuje všetko. + Tento zápisník nemá žiadne bunky. + Ďalších %1$s buniek sa nezobrazuje. + Táto bunka je dlhšia, než sa tu zobrazuje. + Strana %1$s z %2$s + Prehrať + Pozastaviť + Súbor sa od otvorenia zmenil. Načítajte ho znova alebo ho napriek tomu uložte. + Napriek tomu uložiť + Znova načítať + Zahodiť + Zahodiť zmeny v tomto súbore? + Uložiť do Súborov Nastavenia Inštancie Odhlásiť sa diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 326eba4..698a1c1 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -350,6 +350,67 @@ Files All files Nothing here yet. Not even a hobbit hole. + Upload + New file + What should the file be called? With its extension, such as notes.md. + What should the folder be called? + A name cannot be empty or hold a slash. + There is already something called %1$s here. + Rename + New name + Move + Copy to… + Move here + Copy here + Move to which folder? + Copy to which folder? + Choose a folder + Save here + No directories here. + Move to the trash + Move “%1$s” to the trash? It can be restored from there. + Move the %1$s selected to the trash? They can be restored from there. + Moved to the trash. + %1$s selected + Select all + Download + Download as a zip + Downloading… + Downloaded. + Uploading %1$s of %2$s… + Uploaded. + Open with… + No app on this phone opens this kind of file. + Trash + The trash is empty. + Empty the trash + Remove everything in the trash for good? This cannot be undone. + Remove for good + Remove “%1$s” for good? This cannot be undone. + Restore + Versions + Restore this version + Make this version the current one? The current one stays in the list. + Current + Type + Size + There is no viewer for this kind of file. + This file could not be shown here. It can still be downloaded. + This is the picture\'s source. Open it with another app to see the picture. + What is inside this kind of archive cannot be listed here. + Only the first rows and columns are laid out. The text has all of it. + This notebook has no cells. + %1$s more cells are not shown. + This cell is longer than is shown here. + Page %1$s of %2$s + Play + Pause + This file changed since you opened it. Reload it, or save anyway. + Save anyway + Reload + Discard + Discard your changes to this file? + Save to Files Settings Instances Sign out diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xml index 79e2033..a23d4db 100644 --- a/app/src/main/res/xml/file_paths.xml +++ b/app/src/main/res/xml/file_paths.xml @@ -1,6 +1,9 @@ - + + diff --git a/app/src/test/java/eu/llembas/android/FileLogicTest.kt b/app/src/test/java/eu/llembas/android/FileLogicTest.kt new file mode 100644 index 0000000..4901c6b --- /dev/null +++ b/app/src/test/java/eu/llembas/android/FileLogicTest.kt @@ -0,0 +1,261 @@ +package eu.llembas.android + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.unit.IntSize +import eu.llembas.android.api.BatchAnswer +import eu.llembas.android.api.FileContent +import eu.llembas.android.api.FileEntry +import eu.llembas.android.api.FileKinds +import eu.llembas.android.api.FileListing +import eu.llembas.android.api.FileVersions +import eu.llembas.android.api.FileView +import eu.llembas.android.api.LembasJson +import eu.llembas.android.api.TrashList +import eu.llembas.android.api.parseNotebook +import eu.llembas.android.api.parseTable +import eu.llembas.android.api.sampleFor +import eu.llembas.android.api.tableDelimiter +import eu.llembas.android.share.sharedNoteName +import eu.llembas.android.ui.files.FilesState +import eu.llembas.android.ui.files.TransferViewModel +import eu.llembas.android.ui.files.asZip +import eu.llembas.android.ui.files.outcome +import eu.llembas.android.ui.viewer.clampPan +import eu.llembas.android.ui.viewer.playTime +import kotlinx.serialization.KSerializer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.LocalDateTime + +/** What the file manager decides without a phone: the viewer for a kind, a table, a notebook, what is chosen, what a batch said. */ +class FileLogicTest { + private fun read(name: String, serializer: KSerializer): T = LembasJson.decodeFromString( + serializer, + requireNotNull(javaClass.classLoader!!.getResource("$name.json")) { + "contract/$name.json is missing" + }.readText(), + ) + + @Test + fun thePinnedFilesContract() { + val listing = read("files_listing", FileListing.serializer()) + assertEquals(listOf(null, "markdown", "image"), listing.entries.map { it.fileKind }) + assertNull(listing.copied) + val copied = read("files_copied", FileListing.serializer()) + assertEquals("lembas (2).md", copied.copied!!.name) + assertEquals("/home/frodo/lembas (2).md", copied.copied!!.path) + + val file = read("file_content", FileContent.serializer()) + assertEquals("markdown", file.fileKind) + assertEquals(true, file.writable) + assertEquals("ab".repeat(32), file.sha) + val picture = read("file_content_withheld", FileContent.serializer()) + assertEquals("image", picture.fileKind) + assertEquals(false, picture.writable) + + val trash = read("files_trash", TrashList.serializer()) + assertEquals("node5", trash.items.single().id) + assertEquals("/home/frodo/old.md", trash.items.single().path) + assertEquals(12L, trash.items.single().size) + assertEquals("/home/frodo/old.md", read("files_restored", TrashList.serializer()).restored) + assertEquals(1, read("files_trash_emptied", TrashList.serializer()).removed) + + val versions = read("file_versions", FileVersions.serializer()) + assertEquals(listOf("ver2", "ver1"), versions.versions.map { it.id }) + assertTrue(versions.versions[0].current) + assertFalse(versions.versions[1].current) + assertEquals("Frodo", versions.versions[1].by) + assertNull(versions.versions[1].chatId) + + // A batch is answered path by path: one moved, one refused in the server's own sentence. + val batch = read("files_batch", BatchAnswer.serializer()) + assertEquals(1, batch.done) + assertEquals(1, batch.failed) + assertEquals("/home/frodo/recipes/lembas.md", batch.results[0].to) + val said = outcome(batch) + assertEquals(1, said.done) + assertEquals("Read-only: /home/frodo/map.png can be read in this session but not changed.", said.said) + assertNull(outcome(batch.copy(failed = 0)).said) + // Without a sentence, at least which one. + assertEquals("map.png", outcome(batch.copy(results = batch.results.map { it.copy(error = null) })).said) + } + + @Test + fun aKindChoosesItsViewer() { + for (kind in listOf("markdown", "code", "text", "html", "svg")) assertEquals(kind, FileView.Text, FileKinds.viewer(kind)) + assertEquals(FileView.Image, FileKinds.viewer("image")) + assertEquals(FileView.Pdf, FileKinds.viewer("pdf")) + assertEquals(FileView.Audio, FileKinds.viewer("audio")) + assertEquals(FileView.Video, FileKinds.viewer("video")) + assertEquals(FileView.Table, FileKinds.viewer("table")) + assertEquals(FileView.Notebook, FileKinds.viewer("notebook")) + for (kind in listOf("archive", "model3d", "binary", "something-new")) assertEquals(kind, FileView.Details, FileKinds.viewer(kind)) + // A server that does not say the kind is read as before: as text. + assertEquals(FileView.Text, FileKinds.viewer(null)) + + // Editing: a text kind (a table too) the person may change, and nothing withheld or unsaid. + assertTrue(FileKinds.editable("markdown", writable = true, withheld = false)) + assertTrue(FileKinds.editable("svg", writable = true, withheld = false)) + assertTrue(FileKinds.editable("table", writable = true, withheld = false)) + assertFalse(FileKinds.editable("markdown", writable = false, withheld = false)) + assertFalse(FileKinds.editable("markdown", writable = null, withheld = false)) + assertFalse(FileKinds.editable("markdown", writable = true, withheld = true)) + assertFalse(FileKinds.editable("notebook", writable = true, withheld = false)) + assertFalse(FileKinds.editable("image", writable = true, withheld = false)) + assertFalse(FileKinds.editable(null, writable = true, withheld = false)) + } + + @Test + fun namesAndPaths() { + assertTrue(FileKinds.badName("")) + assertTrue(FileKinds.badName(" ")) + assertTrue(FileKinds.badName("a/b")) + assertTrue(FileKinds.badName("..")) + assertFalse(FileKinds.badName("notes.md")) + assertEquals("/home/frodo/notes.md", FileKinds.child("/home/frodo/", " notes.md ")) + assertEquals("/notes.md", FileKinds.child("/", "notes.md")) + assertEquals("/home/frodo", FileKinds.parent("/home/frodo/notes.md")) + assertEquals("/", FileKinds.parent("/home")) + assertEquals("notes.md", FileKinds.name("/home/frodo/notes.md")) + assertEquals("recipes", FileKinds.name("/home/frodo/recipes/")) + // What another app is told a file is called holds no way out of its folder. + assertEquals("_.._etc_passwd", FileKinds.safeName("../../etc/passwd")) + assertEquals("file", FileKinds.safeName("..")) + assertEquals("file", FileKinds.safeName(" ")) + assertEquals("a_b", FileKinds.safeName("a\\b")) + assertEquals("map.png", FileKinds.safeName("map.png")) + + assertFalse(asZip(listOf(FileEntry(name = "a.md", path = "/h/a.md")))) + assertTrue(asZip(listOf(FileEntry(name = "r", path = "/h/r", kind = "dir")))) + assertTrue(asZip(listOf(FileEntry(name = "a.md", path = "/h/a.md"), FileEntry(name = "b.md", path = "/h/b.md")))) + assertEquals("recipes.zip", TransferViewModel.zipName(listOf("/home/frodo/recipes"))) + assertEquals("frodo.zip", TransferViewModel.zipName(listOf("/home/frodo/a.md", "/home/frodo/b.md"))) + assertEquals("files.zip", TransferViewModel.zipName(emptyList())) + assertEquals("shared-20260102-030405.txt", sharedNoteName(LocalDateTime.of(2026, 1, 2, 3, 4, 5))) + } + + @Test + fun whatIsChosenInADirectory() { + val listing = read("files_listing", FileListing.serializer()) + var state = FilesState(path = "/home/frodo").listed(listing) + assertFalse(state.selecting) + state = state.toggled("/home/frodo/lembas.md").toggled("/home/frodo/map.png") + assertTrue(state.selecting) + assertEquals(listOf("lembas.md", "map.png"), state.chosen.map { it.name }) + assertEquals(listOf("map.png"), state.toggled("/home/frodo/lembas.md").chosen.map { it.name }) + assertEquals(3, state.allSelected().selected.size) + // The same directory read again keeps what is still there; another directory keeps nothing. + val without = listing.copy(entries = listing.entries.filter { it.name != "map.png" }) + assertEquals(setOf("/home/frodo/lembas.md"), state.listed(without).selected) + assertTrue(state.listed(listing.copy(path = "/home/frodo/recipes")).selected.isEmpty()) + // A new file is never written over one that is there. + assertTrue(state.taken("lembas.md")) + assertTrue(state.taken(" lembas.md ")) + assertFalse(state.taken("lembas.txt")) + } + + @Test + fun aTableIsCutIntoCells() { + val table = parseTable("name,what\r\n\"Baggins, Frodo\",\"says \"\"hello\"\"\"\nSam,\"two\nlines\"\n\nlast,row", ',') + assertEquals( + listOf(listOf("name", "what"), listOf("Baggins, Frodo", "says \"hello\""), listOf("Sam", "two\nlines"), listOf("last", "row")), + table.rows, + ) + assertEquals(2, table.columns) + assertFalse(table.cut) + // Tabs, a ragged row, and a quote inside a bare cell left as it is. + val tabs = parseTable("a\tb\tc\n1\t2\n5\" pipe\tx\ty\n", '\t') + assertEquals(listOf(listOf("a", "b", "c"), listOf("1", "2"), listOf("5\" pipe", "x", "y")), tabs.rows) + assertEquals(3, tabs.columns) + // Caps: rows, columns and a cell's length; what was left out is said. + val many = parseTable((1..10).joinToString("\n") { "$it,x,y,z" }, ',', maxRows = 3, maxColumns = 2, maxCell = 1) + assertEquals(listOf(listOf("1", "x"), listOf("2", "x"), listOf("3", "x")), many.rows) + assertTrue(many.cut) + assertEquals("a", parseTable("abcdef,2", ',', maxCell = 1).rows[0][0]) + // Only the beginning of a long file: its last, half line is not shown as a row. + val head = parseTable("a,b\n1,2\n3,", ',', partial = true) + assertEquals(listOf(listOf("a", "b"), listOf("1", "2")), head.rows) + assertTrue(head.cut) + assertTrue(parseTable("", ',').rows.isEmpty()) + + assertEquals('\t', tableDelimiter("list.tsv", "a,b")) + assertEquals('\t', tableDelimiter("list.csv", "a\tb\n1\t2")) + assertEquals(';', tableDelimiter("list.csv", "a;b\n1;2")) + assertEquals(',', tableDelimiter("list.csv", "a,b;c")) + } + + @Test + fun aNotebookIsItsCellsAsText() { + val text = """ + {"metadata": {"kernelspec": {"language": "python"}}, "cells": [ + {"cell_type": "markdown", "source": ["# Waybread\n", "Notes."]}, + {"cell_type": "code", "execution_count": 3, "source": "print('hi')", + "outputs": [ + {"output_type": "stream", "text": ["hi\n"]}, + {"output_type": "execute_result", "data": {"text/plain": "42", "text/html": "42", "image/png": "AAAA"}}, + {"output_type": "error", "ename": "ValueError", "evalue": "no"} + ]}, + {"cell_type": "code", "execution_count": null, "source": []} + ]} + """.trimIndent() + val notebook = parseNotebook(text) + assertNotNull(notebook) + assertEquals("python", notebook!!.language) + assertEquals(listOf("markdown", "code", "code"), notebook.cells.map { it.kind }) + assertEquals("# Waybread\nNotes.", notebook.cells[0].source) + assertEquals(3, notebook.cells[1].count) + // Only what is plain text of an output is kept: no HTML, no picture. + assertEquals("hi\n42\nValueError: no", notebook.cells[1].output) + assertFalse(notebook.cells[1].output.contains("onclick")) + assertNull(notebook.cells[2].count) + assertEquals("", notebook.cells[2].source) + assertEquals(0, notebook.more) + + val long = parseNotebook(text, maxCells = 1, maxChars = 4)!! + assertEquals(2, long.more) + assertEquals("# Wa", long.cells.single().source) + assertTrue(long.cells.single().cut) + // Not a notebook: nothing to draw as one. + assertNull(parseNotebook("[1, 2]")) + assertNull(parseNotebook("{\"cells\": 3}")) + assertNull(parseNotebook("not json")) + assertTrue(parseNotebook("{\"cells\": []}")!!.cells.isEmpty()) + } + + @Test + fun aPictureIsDecodedSmallWhateverItClaims() { + assertEquals(1, sampleFor(1920, 1080)) + assertEquals(2, sampleFor(4000, 3000)) + // 30 000 px square: at most a few megapixels are ever decoded. + val sample = sampleFor(30_000, 30_000) + assertTrue((30_000L / sample) * (30_000L / sample) <= 8_000_000) + assertTrue(30_000 / sample <= 2560) + // A ribbon: its long edge decides. + assertTrue(100_000 / sampleFor(100_000, 10) <= 2560) + assertEquals(1, sampleFor(0, 0)) + } + + @Test + fun aZoomedPictureStaysInItsFrameAndAPlayerSaysItsTime() { + val size = IntSize(1000, 500) + // Not zoomed: it does not move. Zoomed twice: half its size either way, and no further. + val still = clampPan(Offset(300f, -80f), 1f, size) + assertEquals(0f, still.x, 0f) + assertEquals(0f, still.y, 0f) + val right = clampPan(Offset(900f, -80f), 2f, size) + assertEquals(500f, right.x, 0f) + assertEquals(-80f, right.y, 0f) + val corner = clampPan(Offset(-900f, 400f), 2f, size) + assertEquals(-500f, corner.x, 0f) + assertEquals(250f, corner.y, 0f) + + assertEquals("0:00", playTime(0)) + assertEquals("0:00", playTime(-5)) + assertEquals("1:05", playTime(65_400)) + assertEquals("1:00:07", playTime(3_607_000)) + } +} diff --git a/app/src/test/java/eu/llembas/android/FilesClientTest.kt b/app/src/test/java/eu/llembas/android/FilesClientTest.kt new file mode 100644 index 0000000..091b8cd --- /dev/null +++ b/app/src/test/java/eu/llembas/android/FilesClientTest.kt @@ -0,0 +1,235 @@ +package eu.llembas.android + +import eu.llembas.android.api.ApiClient +import eu.llembas.android.api.ApiException +import eu.llembas.android.api.RangeReader +import eu.llembas.android.api.SaveConflict +import eu.llembas.android.ui.files.StreamBody +import kotlinx.coroutines.test.runTest +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okio.Buffer +import org.junit.After +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Before +import org.junit.Test +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream + +/** The file manager's calls, against a server that answers as the pinned contract says. */ +class FilesClientTest { + private lateinit var server: MockWebServer + + @Before + fun up() { + server = MockWebServer().apply { start() } + } + + @After + fun down() = server.shutdown() + + private fun client() = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test") + + private fun contract(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) { + "contract/$name.json is missing" + }.readText() + + @Test + fun anUploadIsStreamedIntoItsFolderAndSaysHowFarItIs() = runTest { + server.enqueue(MockResponse().setResponseCode(201).setBody(contract("files_listing"))) + val bytes = ByteArray(300_000) { (it % 251).toByte() } + val heard = mutableListOf() + val body = StreamBody("application/octet-stream".toMediaType(), bytes.size.toLong(), { heard += it }) { ByteArrayInputStream(bytes) } + val listing = client().uploadFile("/home/frodo", "big.bin", body) + assertEquals("/home/frodo", listing.path) + val request = server.takeRequest() + assertEquals("POST", request.method) + assertEquals("/api/v2/files/upload?path=%2Fhome%2Ffrodo", request.path) + assertEquals("Bearer lmb_test", request.getHeader("Authorization")) + val sent = request.body.readByteArray() + val head = String(sent, 0, 400, Charsets.ISO_8859_1) + assertTrue(head, head.contains("name=\"files\"; filename=\"big.bin\"")) + // Every byte went, in pieces, and the last word on progress is the whole file. + assertTrue(sent.size > bytes.size) + assertTrue(heard.size > 1) + assertEquals(bytes.size.toLong(), heard.last()) + assertTrue(body.isOneShot()) + } + + @Test + fun aFileOverTheLimitIsRefusedInTheServersSentence() = runTest { + val sentence = "big.bin is larger than 50 MB, the most that can be uploaded here." + server.enqueue(MockResponse().setResponseCode(413).setBody("""{"detail":"$sentence"}""")) + try { + client().uploadFile("/home/frodo", "big.bin", StreamBody(null, 3, {}) { ByteArrayInputStream(byteArrayOf(1, 2, 3)) }) + fail("a 413 is a refusal") + } catch (e: ApiException) { + assertEquals(413, e.status) + assertEquals(sentence, e.message) + } + } + + @Test + fun aSaveSaysWhatItOpenedAndAConflictWritesNothing() = runTest { + val api = client() + server.enqueue(MockResponse().setBody(contract("file_content"))) + val saved = api.saveFile("/home/frodo/lembas.md", "# Lembas\n", base = "abab") + assertEquals("markdown", saved.fileKind) + assertEquals(true, saved.writable) + val first = server.takeRequest() + assertEquals("PUT", first.method) + assertEquals("/api/v2/files/content", first.path) + val said = first.body.readUtf8() + assertTrue(said, said.contains("\"base\":\"abab\"")) + assertTrue(said, said.contains("\"path\":\"/home/frodo/lembas.md\"")) + assertFalse(said, said.contains("force")) + + // The file changed meanwhile: the server's sentence and what the file holds now. + server.enqueue(MockResponse().setResponseCode(409).setBody(contract("file_save_conflict"))) + try { + api.saveFile("/home/frodo/lembas.md", "mine", base = "abab") + fail("a conflict is not a save") + } catch (e: SaveConflict) { + assertEquals("This file changed since you opened it. Reload it, or save anyway.", e.message) + assertEquals("ab".repeat(32), e.sha) + } + server.takeRequest() + + // Save anyway says so; a new file says no base at all. + server.enqueue(MockResponse().setBody(contract("file_content"))) + api.saveFile("/home/frodo/lembas.md", "mine", base = "abab", force = true) + assertTrue(server.takeRequest().body.readUtf8().contains("\"force\":true")) + server.enqueue(MockResponse().setBody(contract("file_content"))) + api.saveFile("/home/frodo/new.md", "") + assertFalse(server.takeRequest().body.readUtf8().contains("base")) + + // Any other 409 is a refusal like any other. + server.enqueue(MockResponse().setResponseCode(409).setBody("""{"detail":"Not now."}""")) + try { + api.saveFile("/home/frodo/lembas.md", "mine", base = "abab") + fail("a refusal") + } catch (e: ApiException) { + assertEquals("Not now.", e.message) + } + } + + @Test + fun aDownloadIsCopiedAsItComesWithTheTokenInItsHeaderOnly() = runTest { + val api = client() + server.enqueue(MockResponse().setBody("hello world")) + val out = ByteArrayOutputStream() + var last = 0L to 0L + val done = api.download(api.rawFile("/home/frodo/map of the road.png"), out) { now, total -> last = now to total } + assertEquals(11L, done) + assertEquals("hello world", out.toString("UTF-8")) + assertEquals(11L to 11L, last) + val request = server.takeRequest() + assertEquals("/api/v2/files/raw?path=%2Fhome%2Ffrodo%2Fmap%20of%20the%20road.png", request.path) + assertEquals("Bearer lmb_test", request.getHeader("Authorization")) + assertFalse(request.requestUrl.toString().contains("lmb_test")) + assertNull(request.getHeader("Range")) + + // More than the caller will take is refused before it is copied. + server.enqueue(MockResponse().setBody("hello world")) + try { + api.download(api.rawFile("/home/frodo/map.png"), ByteArrayOutputStream(), most = 4) + fail("too much") + } catch (e: ApiException) { + assertEquals(413, e.status) + } + } + + @Test + fun aPieceOfAFileIsARangeRequest() { + val api = client() + server.enqueue(MockResponse().setResponseCode(206).setHeader("Content-Range", "bytes 4-7/11").setBody("o wo")) + assertEquals("o wo", api.rawBytes("/home/frodo/song.mp3", 4, 7).toString(Charsets.UTF_8)) + val request = server.takeRequest() + assertEquals("bytes=4-7", request.getHeader("Range")) + assertEquals("Bearer lmb_test", request.getHeader("Authorization")) + assertFalse(request.requestUrl.toString().contains("lmb_test")) + + // A server that ignores the range would hand the wrong bytes: refused, not played. + server.enqueue(MockResponse().setBody("hello world")) + try { + api.rawBytes("/home/frodo/song.mp3", 4, 7) + fail("the whole file is not the piece asked for") + } catch (e: ApiException) { + assertEquals(416, e.status) + } + } + + @Test + fun aPlayerReadsBlockByBlockAndABlockIsFetchedOnce() { + val file = ByteArray(10) { it.toByte() } + val asked = mutableListOf>() + val reader = RangeReader(file.size.toLong(), block = 4, keep = 2) { from, to -> + asked += from to to + file.copyOfRange(from.toInt(), to.toInt() + 1) + } + val buffer = ByteArray(8) + // A read ends at its block's end; the player asks again for the rest. + assertEquals(4, reader.read(0, buffer, 0, 8)) + assertArrayEquals(byteArrayOf(0, 1, 2, 3), buffer.copyOf(4)) + assertEquals(2, reader.read(2, buffer, 0, 8)) + assertEquals(listOf(0L to 3L), asked) + // The last block is short, and the end is the end. + assertEquals(2, reader.read(8, buffer, 3, 5)) + assertArrayEquals(byteArrayOf(8, 9), buffer.copyOfRange(3, 5)) + assertEquals(listOf(0L to 3L, 8L to 9L), asked) + assertEquals(-1, reader.read(10, buffer, 0, 8)) + assertEquals(-1, reader.read(-1, buffer, 0, 8)) + assertEquals(0, reader.read(1, buffer, 0, 0)) + // A seek back to a block still kept asks nothing; one that fell out is asked for again. + assertEquals(1, reader.read(3, buffer, 0, 8)) + assertEquals(2, asked.size) + assertEquals(4, reader.read(4, buffer, 0, 8)) + assertEquals(4, reader.read(0, buffer, 0, 8)) + assertEquals(listOf(0L to 3L, 8L to 9L, 4L to 7L), asked) + assertEquals(2, reader.read(8, buffer, 0, 8)) + assertEquals(listOf(0L to 3L, 8L to 9L, 4L to 7L, 8L to 9L), asked) + } + + @Test + fun aBatchTheTrashAndTheVersions() = runTest { + val api = client() + server.enqueue(MockResponse().setBody(contract("files_batch"))) + val answer = api.batchFiles("move", listOf("/home/frodo/lembas.md", "/home/frodo/map.png"), "/home/frodo/recipes") + assertEquals(1, answer.done) + assertEquals(1, answer.failed) + val batch = server.takeRequest() + assertEquals("/api/v2/files/batch", batch.path) + val body = batch.body.readUtf8() + assertTrue(body, body.contains("\"op\":\"move\"")) + assertTrue(body, body.contains("\"paths\":[\"/home/frodo/lembas.md\",\"/home/frodo/map.png\"]")) + assertTrue(body, body.contains("\"to\":\"/home/frodo/recipes\"")) + + server.enqueue(MockResponse().setBody(contract("files_trash_emptied"))) + assertEquals(1, api.removeTrashed().removed) + val emptied = server.takeRequest() + assertEquals("DELETE", emptied.method) + assertEquals("/api/v2/files/trash", emptied.path) + server.enqueue(MockResponse().setBody(contract("files_trash_emptied"))) + api.removeTrashed("node5") + assertEquals("/api/v2/files/trash?id=node5", server.takeRequest().path) + + server.enqueue(MockResponse().setBody(contract("file_versions"))) + api.restoreVersion("/home/frodo/lembas.md", "ver1") + val restored = server.takeRequest() + assertEquals("/api/v2/files/versions/restore", restored.path) + assertTrue(restored.body.readUtf8().contains("\"version\":\"ver1\"")) + + // A zip is asked for by its paths, in the body: nothing of the account is in the address. + val zip = api.zipFiles(listOf("/home/frodo/recipes")) + assertEquals("POST", zip.method) + assertTrue(zip.url.toString().endsWith("/api/v2/files/zip")) + val asked = Buffer().also { zip.body!!.writeTo(it) }.readUtf8() + assertEquals("""{"paths":["/home/frodo/recipes"]}""", asked) + } +} diff --git a/app/src/test/java/eu/llembas/android/shots/FileShots.kt b/app/src/test/java/eu/llembas/android/shots/FileShots.kt new file mode 100644 index 0000000..fd398a4 --- /dev/null +++ b/app/src/test/java/eu/llembas/android/shots/FileShots.kt @@ -0,0 +1,138 @@ +package eu.llembas.android.shots + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.ui.Modifier +import eu.llembas.android.api.FileEntry +import eu.llembas.android.api.FileVersion +import eu.llembas.android.api.Notebook +import eu.llembas.android.api.NotebookCell +import eu.llembas.android.api.TrashItem +import eu.llembas.android.api.parseTable +import eu.llembas.android.ui.files.FilesActions +import eu.llembas.android.ui.files.FilesContent +import eu.llembas.android.ui.files.FilesState +import eu.llembas.android.ui.files.FolderPickContent +import eu.llembas.android.ui.files.FolderPickState +import eu.llembas.android.ui.files.TrashActions +import eu.llembas.android.ui.files.TrashContent +import eu.llembas.android.ui.files.TrashState +import eu.llembas.android.ui.files.VersionsContent +import eu.llembas.android.ui.files.VersionsState +import eu.llembas.android.ui.viewer.DetailsBody +import eu.llembas.android.ui.viewer.EditorBody +import eu.llembas.android.ui.viewer.FileActions +import eu.llembas.android.ui.viewer.NotebookBody +import eu.llembas.android.ui.viewer.PlayerControls +import eu.llembas.android.ui.viewer.PlayerUi +import eu.llembas.android.ui.viewer.TableBody +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +/** The file manager's pages and the viewers' bodies, each drawn from made-up state. */ +@RunWith(RobolectricTestRunner::class) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@Config(sdk = [35], qualifiers = "xhdpi") +class FileShots { + private val home = "/home/frodo" + + private fun file(name: String, kind: String, mime: String, size: Long) = + FileEntry(name = name, path = "$home/$name", kind = "file", fileKind = kind, size = size, mime = mime) + + private val entries = listOf( + FileEntry(name = "recipes", path = "$home/recipes", kind = "dir"), + FileEntry(name = "The Fellowship's shared provisions", path = "$home/shared", kind = "mount"), + file("lembas.md", "markdown", "text/markdown", 2_048), + file("map-of-the-road.png", "image", "image/png", 3_400_000), + file("provisions-for-a-very-long-journey-there-and-back-again.pdf", "pdf", "application/pdf", 780_000), + file("walking-song.mp3", "audio", "audio/mpeg", 4_100_000), + file("the-gates.mp4", "video", "video/mp4", 91_000_000), + file("stores.csv", "table", "text/csv", 5_120), + file("bake.ipynb", "notebook", "application/x-ipynb+json", 18_000), + file("backup.zip", "archive", "application/zip", 12_000_000), + ) + + private val listed = FilesState(path = home, parent = "/home", entries = entries) + + @Test + fun files() { + shoot("50-files") { FilesContent(listed, object : FilesActions {}) } + shoot("50-files", Phone.Small, fontScale = 1.5f) { FilesContent(listed, object : FilesActions {}) } + val chosen = listed.copy(selected = setOf("$home/lembas.md", "$home/map-of-the-road.png")) + shoot("50-files-selecting") { FilesContent(chosen, object : FilesActions {}) } + shoot("50-files-selecting", Phone.Small, fontScale = 1.5f) { FilesContent(chosen, object : FilesActions {}) } + shoot("50-files-empty") { FilesContent(FilesState(path = home, parent = "/home"), object : FilesActions {}) } + } + + @Test + fun folderPicker() { + val state = FolderPickState(path = home, parent = "/home", folders = entries.filter { it.isFolder }, loading = false) + shoot("51-folder-picker") { FolderPickContent("Move to which folder?", "Move here", state) } + shoot("51-folder-picker", Phone.Small, fontScale = 1.5f) { FolderPickContent("Move to which folder?", "Move here", state) } + shoot("51-folder-picker-empty") { FolderPickContent("Copy to which folder?", "Copy here", state.copy(folders = emptyList())) } + } + + @Test + fun trashAndVersions() { + val trash = TrashState( + items = listOf( + TrashItem(id = "n1", name = "old-notes-from-the-first-attempt-at-the-recipe.md", path = "$home/recipes/old-notes.md", size = 1_200), + TrashItem(id = "n2", name = "drafts", path = "$home/drafts", kind = "dir"), + ), + loading = false, + ) + shoot("52-trash") { TrashContent(trash, object : TrashActions {}) } + shoot("52-trash", Phone.Small, fontScale = 1.5f) { TrashContent(trash, object : TrashActions {}) } + shoot("52-trash-empty") { TrashContent(TrashState(loading = false), object : TrashActions {}) } + val versions = VersionsState( + versions = listOf( + FileVersion(id = "v3", size = 2_048, at = "2026-03-10T08:00:00+00:00", by = "Frodo", current = true), + FileVersion(id = "v2", size = 1_900, at = "2026-03-09T17:30:00+00:00", by = "Samwise Gamgee of Bagshot Row"), + FileVersion(id = "v1", size = 20, at = "2026-03-01T06:15:00+00:00"), + ), + loading = false, + ) + shoot("53-versions") { VersionsContent("lembas.md", versions) } + shoot("53-versions", Phone.Small, fontScale = 1.5f) { VersionsContent("lembas.md", versions) } + } + + @Test + fun viewers() { + val csv = "what,how many,where it is kept\nlembas,12,\"the leaf wrappings, top shelf\"\nwater skins,3,by the door\nrope,1\n" + + (1..30).joinToString("\n") { "item $it,$it,shelf ${it % 4}" } + shoot("54-viewer-table") { TableBody(parseTable(csv, ',')) } + shoot("54-viewer-table-cut", Phone.Small) { TableBody(parseTable(csv, ',', maxRows = 6)) } + val notebook = Notebook( + cells = listOf( + NotebookCell("markdown", "# Baking\nHow many cakes for the road."), + NotebookCell("code", "cakes = days * walkers\nprint(cakes)", output = "36", count = 1), + NotebookCell("code", "plot(cakes)", count = 2, cut = true), + ), + more = 4, + language = "python", + ) + shoot("55-viewer-notebook") { NotebookBody(notebook) } + shoot("55-viewer-notebook", Phone.Small, fontScale = 1.5f) { NotebookBody(notebook) } + val details: @androidx.compose.runtime.Composable () -> Unit = { + DetailsBody( + "backup.zip", + "archive · application/zip", + 12_000_000, + "What is inside this kind of archive cannot be listed here.", + object : FileActions {}, + ) + } + shoot("56-viewer-details", content = details) + shoot("56-viewer-details", Phone.Small, fontScale = 1.5f, content = details) + shoot("57-viewer-player") { + Column(Modifier.fillMaxSize()) { + PlayerControls(PlayerUi(ready = true, playing = true, positionMs = 65_000, durationMs = 214_000), onToggle = {}, onSeek = {}) + PlayerControls(PlayerUi(), onToggle = {}, onSeek = {}) + } + } + shoot("58-viewer-editor") { EditorBody("# Lembas\n\nWrap it in a leaf.\nKeep it dry.\n", onChange = {}) } + } +} diff --git a/scripts/strings.py b/scripts/strings.py index e072b40..ef24090 100755 --- a/scripts/strings.py +++ b/scripts/strings.py @@ -370,10 +370,71 @@ STRINGS: dict[str, str] = { "viewer_unavailable": "This server cannot hand the file to the app yet. Open it in the browser instead.", "viewer_too_large": "This file is too large to show here; at most 1 MB can be shown.", "viewer_not_text": "This is not a text file, so it is not shown here.", - # Files (the person's tree, read-only) + # Files (the person's tree, as a file manager). Worded as the server's explorer words them. "files": "Files", "files_all": "All files", "files_empty": "Nothing here yet. Not even a hobbit hole.", + "files_upload": "Upload", + "files_new_file": "New file", + "files_new_file_ask": "What should the file be called? With its extension, such as notes.md.", + "files_new_folder_ask": "What should the folder be called?", + "files_bad_name": "A name cannot be empty or hold a slash.", + "files_taken": "There is already something called %1$s here.", + "rename": "Rename", + "files_new_name": "New name", + "files_move": "Move", + "files_copy_to": "Copy to…", + "files_move_here": "Move here", + "files_copy_here": "Copy here", + "files_move_which": "Move to which folder?", + "files_copy_which": "Copy to which folder?", + "files_choose_folder": "Choose a folder", + "files_save_here": "Save here", + "files_no_folders": "No directories here.", + "files_to_trash": "Move to the trash", + "files_trash_one": "Move “%1$s” to the trash? It can be restored from there.", + "files_trash_many": "Move the %1$s selected to the trash? They can be restored from there.", + "files_trashed": "Moved to the trash.", + "files_selected": "%1$s selected", + "files_select_all": "Select all", + "download": "Download", + "files_download_zip": "Download as a zip", + "files_downloading": "Downloading…", + "files_downloaded": "Downloaded.", + "files_uploading": "Uploading %1$s of %2$s…", + "files_uploaded": "Uploaded.", + "files_open_with": "Open with…", + "files_no_app": "No app on this phone opens this kind of file.", + "trash": "Trash", + "trash_is_empty": "The trash is empty.", + "trash_empty": "Empty the trash", + "trash_empty_confirm": "Remove everything in the trash for good? This cannot be undone.", + "trash_remove": "Remove for good", + "trash_remove_confirm": "Remove “%1$s” for good? This cannot be undone.", + "restore": "Restore", + "versions": "Versions", + "version_restore": "Restore this version", + "version_restore_confirm": "Make this version the current one? The current one stays in the list.", + "version_current": "Current", + "files_type": "Type", + "files_size": "Size", + "files_no_viewer": "There is no viewer for this kind of file.", + "files_not_shown": "This file could not be shown here. It can still be downloaded.", + "files_svg_source": "This is the picture's source. Open it with another app to see the picture.", + "archive_note": "What is inside this kind of archive cannot be listed here.", + "table_cut": "Only the first rows and columns are laid out. The text has all of it.", + "notebook_empty": "This notebook has no cells.", + "notebook_more": "%1$s more cells are not shown.", + "notebook_cell_cut": "This cell is longer than is shown here.", + "viewer_page": "Page %1$s of %2$s", + "play": "Play", + "pause": "Pause", + "files_conflict": "This file changed since you opened it. Reload it, or save anyway.", + "files_save_anyway": "Save anyway", + "reload": "Reload", + "discard": "Discard", + "files_unsaved": "Discard your changes to this file?", + "share_to_files": "Save to Files", # Settings "settings": "Settings", "settings_instances": "Instances", @@ -678,4 +739,11 @@ SERVER_ENGLISH: dict[str, str] = { "agent_stop": "Stop %(name)s", "agent_stop_member_confirm": "Stop %(name)s and the members under it? They leave the team.", "folder_delete_confirm": "Delete the folder “%(name)s”? Chats inside it are kept.", + "files_taken": "There is already something called %(name)s here.", + "files_trash_one": "Move “%(name)s” to the trash? It can be restored from there.", + "files_trash_many": "Move the %(n)s selected to the trash? They can be restored from there.", + "files_selected": "%(n)s selected", + "trash_remove_confirm": "Remove “%(name)s” for good? This cannot be undone.", + "notebook_more": "%(n)s more cells are not shown.", + "viewer_page": "Page %(page)s of %(pages)s", } diff --git a/scripts/strings_own.json b/scripts/strings_own.json index 6145c92..496d39f 100644 --- a/scripts/strings_own.json +++ b/scripts/strings_own.json @@ -122,6 +122,15 @@ "empty_chat": "O čem si promluvíme?", "empty_chats": "Zatím žádné konverzace. Ne všichni, kdo bloudí, jsou ztraceni — založte jednu.", "experimental": "Experimentální", + "files_choose_folder": "Vybrat složku", + "files_downloaded": "Staženo.", + "files_downloading": "Stahuje se…", + "files_no_app": "Žádná aplikace v tomto telefonu tento druh souboru neotevře.", + "files_open_with": "Otevřít v…", + "files_save_here": "Uložit sem", + "files_svg_source": "Toto je zdroj obrázku. Chcete-li vidět obrázek, otevřete jej v jiné aplikaci.", + "files_unsaved": "Zahodit změny v tomto souboru?", + "files_uploading": "Nahrává se %1$s z %2$s…", "instance_in_use": "Používá se", "kind_agent_line": "Pracuje na počítači, který jste propojili: čte, zapisuje a spouští příkazy ve složce.", "kind_chat_line": "Mluvte s modelem: otázky, psaní, soubory, které přiložíte.", @@ -190,11 +199,13 @@ "plan_first": "Nejdřív plán", "plan_first_hint": "Model napíše plán, který schválíte, než začne jednat.", "plan_what_to_change": "Co by se mělo změnit?", + "play": "Přehrát", "push_enable": "Zapnout upozornění", "push_explained": "Upozornění chodí přes UnifiedPush, bez služeb Google: doručuje je distribuční aplikace, kterou jste zvolili; jsou zašifrované jen pro tento telefon.", "push_failed": "Nebyl zvolen žádný distributor, takže upozornění jsou stále vypnutá.", "push_no_distributor": "Abyste se dozvěděli, že je odpověď hotová, nainstalujte distributora UnifiedPush, například ntfy, a pak se vraťte sem. Bez něj aplikace nové odpovědi ukáže, jen když je otevřená.", "push_on": "Upozornění jsou pro tuto instanci zapnutá.", + "read_by_fallback": "Přečetl %1$s: vlastní model řeči tohoto chatu neodpověděl.", "regenerate": "Vygenerovat znovu", "report": "Zpráva", "report_chat_title": "Zpráva: %1$s", @@ -249,6 +260,7 @@ "share_default_prompt": "Podívejte se na tohle.", "share_label": "Zeptat se LLeMbas", "share_sending": "Odesílá se do LLeMbas…", + "share_to_files": "Uložit do Souborů", "shortcut_last": "Poslední chat", "shown": "Zobrazeno", "signin_address": "Adresa instance", @@ -288,6 +300,7 @@ "thinking_switch_hint": "Pomalejší a lepší u těžkých otázek.", "tile_ask": "Zeptat se LLeMbas", "tools_used": "Použité nástroje: %1$s", + "transcribed_by_fallback": "Přepsal %1$s: vlastní model řeči tohoto chatu neodpověděl.", "tree_context": "kontext %1$s%%", "tune": "Možnosti", "update_allow_installs": "Povolte aplikaci LLeMbas instalovat aktualizace a pak to zkontrolujte znovu.", @@ -306,6 +319,7 @@ "update_notice_title": "LLeMbas pro Android %1$s", "update_notifications_manual": "Toto je sestavení „notifications“: aktualizaci nainstalujte ze stránky vydání, soubor končící na -notifications.apk.", "update_unreachable": "Aktualizaci se nepodařilo stáhnout.", + "version_current": "Aktuální", "viewer_html_source": "Toto je zdrojový kód stránky. Samotnou stránku uvidíte po otevření v prohlížeči.", "viewer_long_markdown": "Dlouhý soubor, proto je zobrazen jako prostý text.", "viewer_open_browser": "Otevřít v prohlížeči", @@ -395,9 +409,7 @@ "wake_word_unavailable": "V tomto sestavení není. Sestavení pro F-Droid nemá modul pro budicí slovo, protože F-Droid sestavuje každou knihovnu ze zdrojů; sestavení z llembas.eu ho má.", "widget_description": "Ptejte se hlasem nebo textem, nebo pokračujte v poslední konverzaci s asistentem. Neukazuje nic z vašeho účtu.", "widget_hint": "Zeptejte se na cokoli", - "widget_speak": "Mluvit", - "transcribed_by_fallback": "Přepsal %1$s: vlastní model řeči tohoto chatu neodpověděl.", - "read_by_fallback": "Přečetl %1$s: vlastní model řeči tohoto chatu neodpověděl." + "widget_speak": "Mluvit" }, "de": { "about_version": "LLeMbas für Android %1$s", @@ -522,6 +534,15 @@ "empty_chat": "Worüber sprechen wir?", "empty_chats": "Noch keine Chats. Nicht jeder, der wandert, ist verloren — fangen Sie einen an.", "experimental": "Experimentell", + "files_choose_folder": "Ordner wählen", + "files_downloaded": "Heruntergeladen.", + "files_downloading": "Wird heruntergeladen…", + "files_no_app": "Keine App auf diesem Telefon öffnet diese Art von Datei.", + "files_open_with": "Öffnen mit…", + "files_save_here": "Hier speichern", + "files_svg_source": "Das ist der Quelltext des Bildes. Öffne es mit einer anderen App, um das Bild zu sehen.", + "files_unsaved": "Die Änderungen an dieser Datei verwerfen?", + "files_uploading": "%1$s von %2$s wird hochgeladen…", "instance_in_use": "In Verwendung", "kind_agent_line": "Arbeitet auf einem verknüpften Computer: liest, schreibt und führt Befehle in einem Ordner aus.", "kind_chat_line": "Mit einem Modell sprechen: Fragen, Texte, Dateien, die Sie anhängen.", @@ -591,11 +612,13 @@ "plan_first": "Erst planen", "plan_first_hint": "Das Modell schreibt einen Plan, den du genehmigst, bevor es handelt.", "plan_what_to_change": "Was soll sich ändern?", + "play": "Abspielen", "push_enable": "Benachrichtigungen einschalten", "push_explained": "Benachrichtigungen kommen über UnifiedPush, ohne Google-Dienste: Die von Ihnen gewählte Distributor-App trägt sie, verschlüsselt nur für dieses Telefon.", "push_failed": "Es wurde kein Distributor gewählt, daher sind die Benachrichtigungen noch ausgeschaltet.", "push_no_distributor": "Um erfahren zu lassen, wenn eine Antwort fertig ist, installieren Sie einen UnifiedPush-Distributor wie ntfy und kommen Sie dann hierher zurück. Ohne einen zeigt die App neue Antworten nur, wenn sie geöffnet ist.", "push_on": "Benachrichtigungen sind für diese Instanz eingeschaltet.", + "read_by_fallback": "Vorgelesen von %1$s: Das eigene Sprachmodell dieses Chats hat nicht geantwortet.", "regenerate": "Neu generieren", "report": "Bericht", "report_chat_title": "Bericht: %1$s", @@ -650,6 +673,7 @@ "share_default_prompt": "Schauen Sie sich das an.", "share_label": "LLeMbas fragen", "share_sending": "Wird an LLeMbas gesendet…", + "share_to_files": "In Dateien speichern", "shortcut_last": "Letzter Chat", "shown": "Angezeigt", "signin_address": "Adresse der Instanz", @@ -689,6 +713,7 @@ "thinking_switch_hint": "Langsamer, und besser bei schwierigen Fragen.", "tile_ask": "LLeMbas fragen", "tools_used": "%1$s Werkzeuge genutzt", + "transcribed_by_fallback": "Transkribiert von %1$s: Das eigene Sprachmodell dieses Chats hat nicht geantwortet.", "tree_context": "%1$s%% Kontext", "tune": "Optionen", "update_allow_installs": "Erlauben Sie LLeMbas, Updates zu installieren, und prüfen Sie dann erneut.", @@ -707,6 +732,7 @@ "update_notice_title": "LLeMbas für Android %1$s", "update_notifications_manual": "Dies ist der „notifications“-Build: Installiere das Update von der Release-Seite, die Datei, die auf -notifications.apk endet.", "update_unreachable": "Das Update konnte nicht abgerufen werden.", + "version_current": "Aktuell", "viewer_html_source": "Das ist der Quelltext der Seite. Die Seite selbst sehen Sie im Browser.", "viewer_long_markdown": "Eine lange Datei, daher wird sie als reiner Text angezeigt.", "viewer_open_browser": "Im Browser öffnen", @@ -796,9 +822,7 @@ "wake_word_unavailable": "Nicht in diesem Build. Der F-Droid-Build hat keine Aktivierungswort-Engine, weil F-Droid jede Bibliothek aus dem Quellcode baut; der Build von llembas.eu hat eine.", "widget_description": "Per Sprache oder Text fragen oder den letzten Assistenten-Chat fortsetzen. Zeigt nichts aus Ihrem Konto.", "widget_hint": "Frag mich alles", - "widget_speak": "Sprechen", - "transcribed_by_fallback": "Transkribiert von %1$s: Das eigene Sprachmodell dieses Chats hat nicht geantwortet.", - "read_by_fallback": "Vorgelesen von %1$s: Das eigene Sprachmodell dieses Chats hat nicht geantwortet." + "widget_speak": "Sprechen" }, "es": { "about_version": "LLeMbas para Android %1$s", @@ -923,6 +947,15 @@ "empty_chat": "¿De qué hablamos?", "empty_chats": "Aún no hay chats. No todos los que vagan están perdidos — empiece uno.", "experimental": "Experimental", + "files_choose_folder": "Elegir una carpeta", + "files_downloaded": "Descargado.", + "files_downloading": "Descargando…", + "files_no_app": "Ninguna aplicación de este teléfono abre este tipo de archivo.", + "files_open_with": "Abrir con…", + "files_save_here": "Guardar aquí", + "files_svg_source": "Este es el código fuente de la imagen. Ábrela con otra aplicación para ver la imagen.", + "files_unsaved": "¿Descartar los cambios en este archivo?", + "files_uploading": "Subiendo %1$s de %2$s…", "instance_in_use": "En uso", "kind_agent_line": "Trabaja en un ordenador que haya vinculado: lee, escribe y ejecuta comandos en una carpeta.", "kind_chat_line": "Hable con un modelo: preguntas, textos, los archivos que adjunte.", @@ -991,11 +1024,13 @@ "plan_first": "Primero un plan", "plan_first_hint": "El modelo escribe un plan que apruebas antes de que actúe.", "plan_what_to_change": "¿Qué debería cambiar?", + "play": "Reproducir", "push_enable": "Activar las notificaciones", "push_explained": "Las notificaciones llegan mediante UnifiedPush, sin servicios de Google: la aplicación distribuidora que eligió las transporta, cifradas solo para este teléfono.", "push_failed": "No se eligió ningún distribuidor, así que las notificaciones siguen desactivadas.", "push_no_distributor": "Para que le avisen cuando una respuesta esté lista, instale un distribuidor de UnifiedPush como ntfy y luego vuelva aquí. Sin uno, la aplicación muestra las respuestas nuevas solo cuando está abierta.", "push_on": "Las notificaciones están activadas para esta instancia.", + "read_by_fallback": "Leído por %1$s: el modelo de voz propio de este chat no respondió.", "regenerate": "Regenerar", "report": "Informe", "report_chat_title": "Informe: %1$s", @@ -1050,6 +1085,7 @@ "share_default_prompt": "Échele un vistazo a esto.", "share_label": "Preguntar a LLeMbas", "share_sending": "Enviando a LLeMbas…", + "share_to_files": "Guardar en Archivos", "shortcut_last": "Último chat", "shown": "Mostrado", "signin_address": "Dirección de la instancia", @@ -1089,6 +1125,7 @@ "thinking_switch_hint": "Más lento, y mejor con preguntas difíciles.", "tile_ask": "Preguntar a LLeMbas", "tools_used": "Usó %1$s herramientas", + "transcribed_by_fallback": "Transcrito por %1$s: el modelo de voz propio de este chat no respondió.", "tree_context": "%1$s%% de contexto", "tune": "Opciones", "update_allow_installs": "Permita que LLeMbas instale actualizaciones y vuelva a comprobarlo.", @@ -1107,6 +1144,7 @@ "update_notice_title": "LLeMbas para Android %1$s", "update_notifications_manual": "Esta es la versión «notifications»: instala la actualización desde su página, el archivo que termina en -notifications.apk.", "update_unreachable": "No se pudo obtener la actualización.", + "version_current": "Actual", "viewer_html_source": "Este es el código fuente de la página. Ábrala en el navegador para ver la página.", "viewer_long_markdown": "Un archivo largo, por eso se muestra como texto sin formato.", "viewer_open_browser": "Abrir en el navegador", @@ -1196,9 +1234,7 @@ "wake_word_unavailable": "No en esta versión. La versión de F-Droid no tiene motor de palabra de activación, porque F-Droid compila cada biblioteca desde el código fuente; la de llembas.eu sí lo tiene.", "widget_description": "Pregunta por voz o por texto, o continúa el último chat del asistente. No muestra nada de tu cuenta.", "widget_hint": "Pregunta lo que quieras", - "widget_speak": "Hablar", - "transcribed_by_fallback": "Transcrito por %1$s: el modelo de voz propio de este chat no respondió.", - "read_by_fallback": "Leído por %1$s: el modelo de voz propio de este chat no respondió." + "widget_speak": "Hablar" }, "fr": { "about_version": "LLeMbas pour Android %1$s", @@ -1323,6 +1359,15 @@ "empty_chat": "De quoi allons-nous parler ?", "empty_chats": "Pas encore de conversation. Tous ceux qui errent ne sont pas perdus — commencez-en une.", "experimental": "Expérimental", + "files_choose_folder": "Choisir un dossier", + "files_downloaded": "Téléchargé.", + "files_downloading": "Téléchargement…", + "files_no_app": "Aucune application de ce téléphone n’ouvre ce type de fichier.", + "files_open_with": "Ouvrir avec…", + "files_save_here": "Enregistrer ici", + "files_svg_source": "Ceci est la source de l’image. Ouvrez-la avec une autre application pour voir l’image.", + "files_unsaved": "Abandonner les modifications de ce fichier ?", + "files_uploading": "Envoi de %1$s sur %2$s…", "instance_in_use": "Utilisée", "kind_agent_line": "Travaille sur un ordinateur que vous avez lié : lit, écrit et lance des commandes dans un dossier.", "kind_chat_line": "Parlez avec un modèle : questions, rédaction, les fichiers que vous joignez.", @@ -1392,11 +1437,13 @@ "plan_first": "D’abord un plan", "plan_first_hint": "Le modèle rédige un plan que vous approuvez avant qu’il agisse.", "plan_what_to_change": "Qu'est-ce qui doit changer ?", + "play": "Lire", "push_enable": "Activer les notifications", "push_explained": "Les notifications arrivent par UnifiedPush, sans services Google : l'application distributrice que vous avez choisie les transporte, chiffrées pour ce téléphone uniquement.", "push_failed": "Aucun distributeur n'a été choisi, les notifications sont donc toujours désactivées.", "push_no_distributor": "Pour être averti quand une réponse est prête, installez un distributeur UnifiedPush tel que ntfy, puis revenez ici. Sans cela, l'application affiche les nouvelles réponses seulement quand elle est ouverte.", "push_on": "Les notifications sont activées pour cette instance.", + "read_by_fallback": "Lu par %1$s : le modèle vocal propre à cette discussion n'a pas répondu.", "regenerate": "Régénérer", "report": "Rapport", "report_chat_title": "Rapport : %1$s", @@ -1451,6 +1498,7 @@ "share_default_prompt": "Jetez un œil à ceci.", "share_label": "Demander à LLeMbas", "share_sending": "Envoi à LLeMbas…", + "share_to_files": "Enregistrer dans Fichiers", "shortcut_last": "Dernière discussion", "shown": "Affiché", "signin_address": "Adresse de l'instance", @@ -1490,6 +1538,7 @@ "thinking_switch_hint": "Plus lent, et meilleur sur les questions difficiles.", "tile_ask": "Demander à LLeMbas", "tools_used": "%1$s outils utilisés", + "transcribed_by_fallback": "Transcrit par %1$s : le modèle vocal propre à cette discussion n'a pas répondu.", "tree_context": "%1$s%% du contexte", "tune": "Options", "update_allow_installs": "Autorisez LLeMbas à installer des mises à jour, puis vérifiez à nouveau.", @@ -1508,6 +1557,7 @@ "update_notice_title": "LLeMbas pour Android %1$s", "update_notifications_manual": "Ceci est la version « notifications » : installez la mise à jour depuis sa page, le fichier se terminant par -notifications.apk.", "update_unreachable": "La mise à jour n'a pas pu être récupérée.", + "version_current": "Actuelle", "viewer_html_source": "Ceci est le code source de la page. Ouvrez-la dans le navigateur pour voir la page elle-même.", "viewer_long_markdown": "Un fichier long, il est donc affiché en texte brut.", "viewer_open_browser": "Ouvrir dans le navigateur", @@ -1597,9 +1647,7 @@ "wake_word_unavailable": "Pas dans cette version. La version F-Droid n’a pas de moteur de mot d’activation, car F-Droid compile chaque bibliothèque depuis les sources ; celle de llembas.eu en a un.", "widget_description": "Demandez à la voix ou par écrit, ou reprenez la dernière discussion de l’assistant. N’affiche rien de votre compte.", "widget_hint": "Posez une question", - "widget_speak": "Parler", - "transcribed_by_fallback": "Transcrit par %1$s : le modèle vocal propre à cette discussion n'a pas répondu.", - "read_by_fallback": "Lu par %1$s : le modèle vocal propre à cette discussion n'a pas répondu." + "widget_speak": "Parler" }, "hu": { "about_version": "LLeMbas Androidra %1$s", @@ -1724,6 +1772,15 @@ "empty_chat": "Miről beszéljünk?", "empty_chats": "Még nincs csevegés. Nem mindenki van elveszve, aki bolyong — kezdjen el egyet.", "experimental": "Kísérleti", + "files_choose_folder": "Mappa választása", + "files_downloaded": "Letöltve.", + "files_downloading": "Letöltés…", + "files_no_app": "Ezen a telefonon egyetlen alkalmazás sem nyitja meg az ilyen fájlt.", + "files_open_with": "Megnyitás ezzel…", + "files_save_here": "Mentés ide", + "files_svg_source": "Ez a kép forrása. A kép megtekintéséhez nyissa meg egy másik alkalmazással.", + "files_unsaved": "Elveti a fájl módosításait?", + "files_uploading": "Feltöltés: %1$s / %2$s…", "instance_in_use": "Használatban", "kind_agent_line": "Egy összekapcsolt számítógépen dolgozik: olvas, ír és parancsokat futtat egy mappában.", "kind_chat_line": "Beszélgessen egy modellel: kérdések, írás, a csatolt fájlok.", @@ -1793,11 +1850,13 @@ "plan_first": "Előbb terv", "plan_first_hint": "A modell tervet ír, amelyet jóváhagy, mielőtt cselekszik.", "plan_what_to_change": "Mi változzon?", + "play": "Lejátszás", "push_enable": "Értesítések bekapcsolása", "push_explained": "Az értesítések a UnifiedPush-on keresztül érkeznek, Google-szolgáltatások nélkül: az Ön által választott elosztó alkalmazás szállítja őket, titkosítva, csak ehhez a telefonhoz.", "push_failed": "Nem választottak elosztót, így az értesítések továbbra is ki vannak kapcsolva.", "push_no_distributor": "Hogy értesítést kapjon, amikor egy válasz elkészül, telepítsen egy UnifiedPush-elosztót, például az ntfy-t, majd jöjjön vissza ide. Ha nincs ilyen, az alkalmazás csak akkor mutatja az új válaszokat, amikor meg van nyitva.", "push_on": "Az értesítések be vannak kapcsolva ehhez a példányhoz.", + "read_by_fallback": "Felolvasta: %1$s — a csevegés saját beszédmodellje nem válaszolt.", "regenerate": "Újragenerálás", "report": "Jelentés", "report_chat_title": "Jelentés: %1$s", @@ -1852,6 +1911,7 @@ "share_default_prompt": "Nézze meg ezt.", "share_label": "Kérdés az LLeMbas-tól", "share_sending": "Küldés az LLeMbas-nak…", + "share_to_files": "Mentés a Fájlokba", "shortcut_last": "Utolsó csevegés", "shown": "Megjelenítve", "signin_address": "A példány címe", @@ -1891,6 +1951,7 @@ "thinking_switch_hint": "Lassabb, de jobb a nehéz kérdéseknél.", "tile_ask": "Kérdés az LLeMbas-tól", "tools_used": "%1$s eszköz használva", + "transcribed_by_fallback": "Átírta: %1$s — a csevegés saját beszédmodellje nem válaszolt.", "tree_context": "%1$s%% kontextus", "tune": "Beállítások", "update_allow_installs": "Engedélyezze, hogy az LLeMbas frissítéseket telepítsen, majd ellenőrizze újra.", @@ -1909,6 +1970,7 @@ "update_notice_title": "LLeMbas Androidra %1$s", "update_notifications_manual": "Ez a „notifications” változat: a frissítést a kiadás oldaláról telepítsd, a -notifications.apk végű fájlt.", "update_unreachable": "A frissítést nem sikerült letölteni.", + "version_current": "Jelenlegi", "viewer_html_source": "Ez az oldal forráskódja. Magát az oldalt a böngészőben megnyitva láthatja.", "viewer_long_markdown": "Hosszú fájl, ezért egyszerű szövegként jelenik meg.", "viewer_open_browser": "Megnyitás a böngészőben", @@ -1998,9 +2060,7 @@ "wake_word_unavailable": "Ebben a változatban nincs. Az F-Droid-változatban nincs ébresztőszó-motor, mert az F-Droid minden könyvtárat forrásból fordít; a llembas.eu-s változatban van.", "widget_description": "Kérdezz hanggal vagy szöveggel, vagy folytasd az asszisztens legutóbbi csevegését. A fiókodból semmit sem mutat.", "widget_hint": "Kérdezz bármit", - "widget_speak": "Beszéd", - "transcribed_by_fallback": "Átírta: %1$s — a csevegés saját beszédmodellje nem válaszolt.", - "read_by_fallback": "Felolvasta: %1$s — a csevegés saját beszédmodellje nem válaszolt." + "widget_speak": "Beszéd" }, "it": { "about_version": "LLeMbas per Android %1$s", @@ -2125,6 +2185,15 @@ "empty_chat": "Di cosa parliamo?", "empty_chats": "Ancora nessuna chat. Non tutti quelli che vagano sono perduti — iniziane una.", "experimental": "Sperimentale", + "files_choose_folder": "Scegli una cartella", + "files_downloaded": "Scaricato.", + "files_downloading": "Download in corso…", + "files_no_app": "Nessuna app su questo telefono apre questo tipo di file.", + "files_open_with": "Apri con…", + "files_save_here": "Salva qui", + "files_svg_source": "Questo è il sorgente dell’immagine. Aprila con un’altra app per vedere l’immagine.", + "files_unsaved": "Scartare le modifiche a questo file?", + "files_uploading": "Caricamento di %1$s su %2$s…", "instance_in_use": "In uso", "kind_agent_line": "Lavora su un computer che ha collegato: legge, scrive ed esegue comandi in una cartella.", "kind_chat_line": "Parli con un modello: domande, scrittura, i file che allega.", @@ -2193,11 +2262,13 @@ "plan_first": "Prima un piano", "plan_first_hint": "Il modello scrive un piano da approvare prima di agire.", "plan_what_to_change": "Cosa dovrebbe cambiare?", + "play": "Riproduci", "push_enable": "Attiva le notifiche", "push_explained": "Le notifiche arrivano tramite UnifiedPush, senza servizi Google: l'app di distribuzione che hai scelto le trasporta, cifrate solo per questo telefono.", "push_failed": "Non è stato scelto nessun distributore, quindi le notifiche sono ancora disattivate.", "push_no_distributor": "Per essere avvisato quando una risposta è pronta, installa un distributore UnifiedPush come ntfy, poi torna qui. Senza uno, l'app mostra le nuove risposte solo quando è aperta.", "push_on": "Le notifiche sono attive per questa istanza.", + "read_by_fallback": "Letto da %1$s: il modello vocale proprio di questa chat non ha risposto.", "regenerate": "Rigenera", "report": "Rapporto", "report_chat_title": "Rapporto: %1$s", @@ -2252,6 +2323,7 @@ "share_default_prompt": "Dai un'occhiata a questo.", "share_label": "Chiedi a LLeMbas", "share_sending": "Invio a LLeMbas…", + "share_to_files": "Salva in File", "shortcut_last": "Ultima chat", "shown": "Mostrato", "signin_address": "Indirizzo dell'istanza", @@ -2291,6 +2363,7 @@ "thinking_switch_hint": "Più lento, e migliore con le domande difficili.", "tile_ask": "Chiedi a LLeMbas", "tools_used": "Usati %1$s strumenti", + "transcribed_by_fallback": "Trascritto da %1$s: il modello vocale proprio di questa chat non ha risposto.", "tree_context": "%1$s%% del contesto", "tune": "Opzioni", "update_allow_installs": "Consenti a LLeMbas di installare gli aggiornamenti, poi controlla di nuovo.", @@ -2309,6 +2382,7 @@ "update_notice_title": "LLeMbas per Android %1$s", "update_notifications_manual": "Questa è la build «notifications»: installa l’aggiornamento dalla pagina della release, il file che termina in -notifications.apk.", "update_unreachable": "Non è stato possibile scaricare l'aggiornamento.", + "version_current": "Attuale", "viewer_html_source": "Questo è il sorgente della pagina. Aprila nel browser per vedere la pagina.", "viewer_long_markdown": "Un file lungo, quindi è mostrato come testo semplice.", "viewer_open_browser": "Apri nel browser", @@ -2398,9 +2472,7 @@ "wake_word_unavailable": "Non in questa build. La build F-Droid non ha un motore per la parola di attivazione, perché F-Droid compila ogni libreria dal sorgente; la build di llembas.eu ce l’ha.", "widget_description": "Chiedi a voce o per iscritto, o continua l’ultima chat dell’assistente. Non mostra nulla del tuo account.", "widget_hint": "Chiedi qualsiasi cosa", - "widget_speak": "Parla", - "transcribed_by_fallback": "Trascritto da %1$s: il modello vocale proprio di questa chat non ha risposto.", - "read_by_fallback": "Letto da %1$s: il modello vocale proprio di questa chat non ha risposto." + "widget_speak": "Parla" }, "pl": { "about_version": "LLeMbas na Androida %1$s", @@ -2525,6 +2597,15 @@ "empty_chat": "O czym porozmawiamy?", "empty_chats": "Nie ma jeszcze czatów. Nie każdy, kto błądzi, jest zgubiony — zacznij jeden.", "experimental": "Eksperymentalne", + "files_choose_folder": "Wybierz folder", + "files_downloaded": "Pobrano.", + "files_downloading": "Pobieranie…", + "files_no_app": "Żadna aplikacja na tym telefonie nie otwiera tego rodzaju pliku.", + "files_open_with": "Otwórz za pomocą…", + "files_save_here": "Zapisz tutaj", + "files_svg_source": "To jest źródło obrazu. Otwórz je w innej aplikacji, aby zobaczyć obraz.", + "files_unsaved": "Odrzucić zmiany w tym pliku?", + "files_uploading": "Przesyłanie %1$s z %2$s…", "instance_in_use": "W użyciu", "kind_agent_line": "Pracuje na połączonym komputerze: czyta, zapisuje i uruchamia polecenia w folderze.", "kind_chat_line": "Rozmawiaj z modelem: pytania, pisanie, pliki, które dołączysz.", @@ -2593,11 +2674,13 @@ "plan_first": "Najpierw plan", "plan_first_hint": "Model pisze plan do zatwierdzenia, zanim zacznie działać.", "plan_what_to_change": "Co powinno się zmienić?", + "play": "Odtwórz", "push_enable": "Włącz powiadomienia", "push_explained": "Powiadomienia przychodzą przez UnifiedPush, bez usług Google: niesie je wybrana aplikacja dystrybucyjna, zaszyfrowane tylko dla tego telefonu.", "push_failed": "Nie wybrano dystrybutora, więc powiadomienia są wciąż wyłączone.", "push_no_distributor": "Aby dostawać informacje, kiedy odpowiedź jest gotowa, zainstaluj dystrybutora UnifiedPush, na przykład ntfy, a potem wróć tutaj. Bez niego aplikacja pokazuje nowe odpowiedzi tylko wtedy, gdy jest otwarta.", "push_on": "Powiadomienia są włączone dla tej instancji.", + "read_by_fallback": "Przeczytał %1$s: własny model mowy tego czatu nie odpowiedział.", "regenerate": "Wygeneruj ponownie", "report": "Raport", "report_chat_title": "Raport: %1$s", @@ -2652,6 +2735,7 @@ "share_default_prompt": "Zobacz to.", "share_label": "Zapytaj LLeMbas", "share_sending": "Wysyłanie do LLeMbas…", + "share_to_files": "Zapisz w Plikach", "shortcut_last": "Ostatni czat", "shown": "Pokazano", "signin_address": "Adres instancji", @@ -2691,6 +2775,7 @@ "thinking_switch_hint": "Wolniej, i lepiej przy trudnych pytaniach.", "tile_ask": "Zapytaj LLeMbas", "tools_used": "Użyte narzędzia: %1$s", + "transcribed_by_fallback": "Transkrybował %1$s: własny model mowy tego czatu nie odpowiedział.", "tree_context": "%1$s%% kontekstu", "tune": "Opcje", "update_allow_installs": "Zezwól LLeMbas na instalowanie aktualizacji, a potem sprawdź ponownie.", @@ -2709,6 +2794,7 @@ "update_notice_title": "LLeMbas na Androida %1$s", "update_notifications_manual": "To jest wersja „notifications”: zainstaluj aktualizację ze strony wydania, plik kończący się na -notifications.apk.", "update_unreachable": "Nie udało się pobrać aktualizacji.", + "version_current": "Bieżąca", "viewer_html_source": "To jest źródło strony. Otwórz ją w przeglądarce, aby zobaczyć samą stronę.", "viewer_long_markdown": "Długi plik, dlatego jest pokazany jako zwykły tekst.", "viewer_open_browser": "Otwórz w przeglądarce", @@ -2798,9 +2884,7 @@ "wake_word_unavailable": "Nie w tej wersji. Wersja z F-Droid nie ma silnika słowa aktywującego, bo F-Droid buduje każdą bibliotekę ze źródeł; wersja z llembas.eu go ma.", "widget_description": "Pytaj głosem lub tekstem albo kontynuuj ostatni czat asystenta. Nie pokazuje niczego z Twojego konta.", "widget_hint": "Zapytaj o cokolwiek", - "widget_speak": "Mów", - "transcribed_by_fallback": "Transkrybował %1$s: własny model mowy tego czatu nie odpowiedział.", - "read_by_fallback": "Przeczytał %1$s: własny model mowy tego czatu nie odpowiedział." + "widget_speak": "Mów" }, "sk": { "about_version": "LLeMbas pre Android %1$s", @@ -2925,6 +3009,15 @@ "empty_chat": "O čom sa pozhovárame?", "empty_chats": "Zatiaľ žiadne konverzácie. Nie všetci, čo blúdia, sú stratení — začnite jednu.", "experimental": "Experimentálne", + "files_choose_folder": "Vybrať priečinok", + "files_downloaded": "Stiahnuté.", + "files_downloading": "Sťahuje sa…", + "files_no_app": "Žiadna aplikácia v tomto telefóne tento druh súboru neotvorí.", + "files_open_with": "Otvoriť v…", + "files_save_here": "Uložiť sem", + "files_svg_source": "Toto je zdroj obrázka. Ak chcete vidieť obrázok, otvorte ho v inej aplikácii.", + "files_unsaved": "Zahodiť zmeny v tomto súbore?", + "files_uploading": "Nahráva sa %1$s z %2$s…", "instance_in_use": "Používa sa", "kind_agent_line": "Pracuje na počítači, ktorý ste prepojili: číta, zapisuje a spúšťa príkazy v priečinku.", "kind_chat_line": "Rozprávajte sa s modelom: otázky, písanie, súbory, ktoré priložíte.", @@ -2993,11 +3086,13 @@ "plan_first": "Najprv plán", "plan_first_hint": "Model napíše plán, ktorý schválite, skôr než začne konať.", "plan_what_to_change": "Čo by sa malo zmeniť?", + "play": "Prehrať", "push_enable": "Zapnúť upozornenia", "push_explained": "Upozornenia chodia cez UnifiedPush, bez služieb Google: doručuje ich distribučná aplikácia, ktorú ste zvolili, zašifrované len pre tento telefón.", "push_failed": "Nebol zvolený žiadny distributor, takže upozornenia sú stále vypnuté.", "push_no_distributor": "Aby ste sa dozvedeli, že je odpoveď hotová, nainštalujte distributora UnifiedPush, napríklad ntfy, a potom sa vráťte sem. Bez neho aplikácia nové odpovede ukáže, len keď je otvorená.", "push_on": "Upozornenia sú pre túto inštanciu zapnuté.", + "read_by_fallback": "Prečítal %1$s: vlastný model reči tohto chatu neodpovedal.", "regenerate": "Vygenerovať znova", "report": "Správa", "report_chat_title": "Správa: %1$s", @@ -3052,6 +3147,7 @@ "share_default_prompt": "Pozrite sa na toto.", "share_label": "Spýtať sa LLeMbas", "share_sending": "Odosiela sa do LLeMbas…", + "share_to_files": "Uložiť do Súborov", "shortcut_last": "Posledný chat", "shown": "Zobrazené", "signin_address": "Adresa inštancie", @@ -3091,6 +3187,7 @@ "thinking_switch_hint": "Pomalšie a lepšie pri ťažkých otázkach.", "tile_ask": "Spýtať sa LLeMbas", "tools_used": "Použité nástroje: %1$s", + "transcribed_by_fallback": "Prepísal %1$s: vlastný model reči tohto chatu neodpovedal.", "tree_context": "kontext %1$s %%", "tune": "Možnosti", "update_allow_installs": "Povoľte aplikácii LLeMbas instalovať aktualizácie a potom to skontrolujte znova.", @@ -3109,6 +3206,7 @@ "update_notice_title": "LLeMbas pre Android %1$s", "update_notifications_manual": "Toto je zostavenie „notifications“: aktualizáciu nainštalujte zo stránky vydania, súbor končiaci na -notifications.apk.", "update_unreachable": "Aktualizáciu sa nepodarilo stiahnuť.", + "version_current": "Aktuálna", "viewer_html_source": "Toto je zdrojový kód stránky. Samotnú stránku uvidíte po otvorení v prehliadači.", "viewer_long_markdown": "Dlhý súbor, preto je zobrazený ako obyčajný text.", "viewer_open_browser": "Otvoriť v prehliadači", @@ -3198,8 +3296,6 @@ "wake_word_unavailable": "V tomto zostavení nie je. Zostavenie pre F-Droid nemá modul pre budiace slovo, pretože F-Droid zostavuje každú knižnicu zo zdrojov; zostavenie z llembas.eu ho má.", "widget_description": "Pýtajte sa hlasom alebo textom, alebo pokračujte v poslednej konverzácii s asistentom. Neukazuje nič z vášho účtu.", "widget_hint": "Opýtajte sa na čokoľvek", - "widget_speak": "Hovoriť", - "transcribed_by_fallback": "Prepísal %1$s: vlastný model reči tohto chatu neodpovedal.", - "read_by_fallback": "Prečítal %1$s: vlastný model reči tohto chatu neodpovedal." + "widget_speak": "Hovoriť" } }