From bac89b5e680401ce29a106ba1b37bdcffd6c8f36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Bene=C5=A1?= Date: Tue, 24 Nov 2026 13:52:03 +0000 Subject: [PATCH] A review of the shown files and the diff card: the sheet opens the gate, the diff is bounded first The assistant's sheet is a session's window and no activity, so the gate a reply's picture now waits at never opened for it: the session says when it shows and hides, and the lock still keeps the gate shut. An edit's diff is worked out off the main thread, one file after another, and each text is cut to 2000 lines and 200000 characters before anything is split or compared; a change that was cut says so. Lines are compared without the carriage return before their newline, and a change of line endings is said once. Invisible, direction-changing and line-breaking characters in a line or a path are written as their code point. The call's arguments stay on the card when the diffs say nothing. "Open with" takes the type from the copy's first bytes, else from its name's extension, and no longer from the instance's word. Tests: the too-long case now shares lines out of order and can fail; the device file fixtures are checked by field; the gate with the session; the bounds, the line endings, the escaping, the arguments and the type. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 11 +- .../java/eu/llembas/android/InstanceGate.kt | 25 +- .../main/java/eu/llembas/android/api/Diff.kt | 107 ++++++++- .../main/java/eu/llembas/android/api/Files.kt | 49 ++++ .../llembas/android/assist/AssistService.kt | 4 + .../java/eu/llembas/android/ui/chat/Cards.kt | 9 +- .../eu/llembas/android/ui/chat/ChatScreen.kt | 2 +- .../eu/llembas/android/ui/chat/DiffCard.kt | 119 ++++++--- .../llembas/android/ui/files/FilesScreen.kt | 2 +- .../android/ui/files/TransferViewModel.kt | 7 +- .../eu/llembas/android/ui/files/Transfers.kt | 22 +- .../llembas/android/ui/viewer/TreeViewer.kt | 2 +- app/src/main/res/values-cs/strings.xml | 2 + app/src/main/res/values-de/strings.xml | 2 + app/src/main/res/values-es/strings.xml | 2 + app/src/main/res/values-fr/strings.xml | 2 + app/src/main/res/values-hu/strings.xml | 2 + app/src/main/res/values-it/strings.xml | 2 + app/src/main/res/values-pl/strings.xml | 2 + app/src/main/res/values-sk/strings.xml | 2 + app/src/main/res/values/strings.xml | 2 + .../java/eu/llembas/android/ShownMediaTest.kt | 225 ++++++++++++++++-- .../eu/llembas/android/shots/ScreenShots.kt | 5 +- scripts/strings.py | 2 + scripts/strings_own.json | 32 ++- 25 files changed, 554 insertions(+), 87 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b86d2d8..e62b445 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,11 +23,20 @@ What is said here of shown files and of an edit's diff needs an instance newer t sign and by colour, with a little unchanged text around them; a new file and a deleted one say so. Long lines scroll sideways inside their own box; a long change is folded to its first lines with "Show all". Both texts are drawn as plain text. Allow and Deny are as they were. + A character that cannot be seen or that changes the direction of a line, in a line or in a + path, is written as its code point (``), so what the card shows is what is written. A + file whose line endings change says so once instead of showing every line twice. A very long + change is compared only at its beginning and says so, and is worked out beside the screen, + not in it. The call's arguments stay in view when there is no change to show. ### Changed - **A picture in a chat is fetched only while the app is in front of an unlocked phone**, like - every other file of the account; one that comes into view behind the lock waits. + every other file of the account; one that comes into view behind the lock waits. The + assistant's sheet counts as the app in front, so a picture in it is fetched as before. +- **"Open with" offers a file as what it is.** The type handed to the other app is read from the + file's own first bytes, or from its name's extension where the bytes carry no mark, and no + longer taken from what the instance said of it. - Pinned to the server's `dev` at `809b87b`. A linked computer's files and the editor's two models are read from the instance and not shown anywhere yet: this app has no browser for a computer's files and no screen for the editor's settings. diff --git a/app/src/main/java/eu/llembas/android/InstanceGate.kt b/app/src/main/java/eu/llembas/android/InstanceGate.kt index 314eafa..cbb38c0 100644 --- a/app/src/main/java/eu/llembas/android/InstanceGate.kt +++ b/app/src/main/java/eu/llembas/android/InstanceGate.kt @@ -11,6 +11,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeoutOrNull +import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger /** @@ -20,11 +21,13 @@ import java.util.concurrent.atomic.AtomicInteger * is not touched, so what the person started finishes; the next one waits here, and goes on by * itself when the app is in front of an unlocked phone again. * - * The process has one ([LembasApp.gate]). It hears of the app's activities starting and stopping - * and of the screen going off and the phone being unlocked; [locked] is asked each time. + * The process has one ([LembasApp.gate]). It hears of the app's activities starting and stopping, + * of the assistant's sheet showing and hiding (a session's window, which is no activity), and of + * the screen going off and the phone being unlocked; [locked] is asked each time. */ class InstanceGate(private val locked: () -> Boolean) { private val started = AtomicInteger(0) + private val sheet = AtomicBoolean(false) private val state = MutableStateFlow(false) /** Whether a request may start now, as it was last looked at. */ @@ -40,9 +43,25 @@ class InstanceGate(private val locked: () -> Boolean) { look() } + /** + * The assistant's sheet is up. It is a window of the system's session and no activity, so it + * says so itself: the app is in front while it shows, as while an activity is started. Told + * once however often the system shows a sheet that is already up. The lock still shuts the + * gate: a sheet over the lock screen asks the instance for nothing. + */ + fun sessionShown() { + sheet.set(true) + look() + } + + fun sessionHidden() { + sheet.set(false) + look() + } + /** Looks again (the screen went off, the phone was unlocked) and says whether a request may start. */ fun look(): Boolean { - val now = started.get() > 0 && !locked() + val now = (started.get() > 0 || sheet.get()) && !locked() state.value = now return now } diff --git a/app/src/main/java/eu/llembas/android/api/Diff.kt b/app/src/main/java/eu/llembas/android/api/Diff.kt index 3e48c41..8cd6456 100644 --- a/app/src/main/java/eu/llembas/android/api/Diff.kt +++ b/app/src/main/java/eu/llembas/android/api/Diff.kt @@ -2,15 +2,21 @@ package eu.llembas.android.api // An edit's diff on its approval card, worked out on the phone from the two texts the card // carries (`contract/event_ask_edit.json`). Lines only: what is drawn is text with a sign, and -// every step is bounded, because both texts are a model's and a file's words of any size. +// every step is bounded before it is taken, because both texts are a model's and a file's words +// of any size. /** What a line of a diff is: in both texts, only in the new one, only in the old one, or the mark of lines left out between two changes. */ enum class DiffSign { Same, Added, Removed, Gap } data class DiffLine(val sign: DiffSign, val text: String) -/** One file's change as the card draws it: the changed lines with a little around them, and how many were added and removed. */ -data class DiffView(val lines: List, val added: Int, val removed: Int) { +/** + * One file's change as the card draws it: the changed lines with a little around them, and how + * many were added and removed. [endings] says a change of line endings (`"LF" to "CRLF"`), which + * is said once instead of as every line going and coming. [cut]: the texts were longer than what + * a phone compares, and only their beginning was. + */ +data class DiffView(val lines: List, val added: Int, val removed: Int, val endings: Pair? = null, val cut: Boolean = false) { /** The lines drawn: the first [DIFF_FOLD] until the person opens it, and never more than [DIFF_MOST]. */ fun shown(open: Boolean): List = lines.take(if (open) DIFF_MOST else DIFF_FOLD) @@ -19,6 +25,9 @@ data class DiffView(val lines: List, val added: Int, val removed: Int) /** The lines not drawn even when open. */ val beyond: Int get() = (lines.size - DIFF_MOST).coerceAtLeast(0) + + /** Whether the block says anything of the change at all; a card whose diffs say nothing keeps its arguments in view. */ + val says: Boolean get() = lines.isNotEmpty() || endings != null || cut } /** How many lines of a file's diff the card shows before it is opened. */ @@ -33,11 +42,40 @@ const val DIFF_CONTEXT = 3 /** Past this many pairs of lines the two middles are not compared: the old one is shown going and the new one coming. */ private const val DIFF_CELLS = 1_000_000L -/** A text's lines; the newline that ends the last one starts no empty line. */ -internal fun textLines(text: String): List { - if (text.isEmpty()) return emptyList() - val lines = text.split('\n') - return if (lines.last().isEmpty()) lines.dropLast(1) else lines +/** The most lines of one text that are compared, and the most characters: what is past either is left out before any work is done. */ +const val DIFF_TEXT_LINES = 2_000 +const val DIFF_TEXT_CHARS = 200_000 + +/** A text's lines as they are compared, and whether the text went on past what is. */ +data class TextLines(val lines: List, val cut: Boolean) + +/** + * The lines of [text], at most [mostLines] of them from at most its first [mostChars] + * characters: nothing past either bound is read, split or kept. The newline that ends the last + * line starts no empty one, and a line is compared without the `\r` before its newline, so a + * file whose line endings change is not a file whose every line changes. + */ +fun textLines(text: String, mostLines: Int = DIFF_TEXT_LINES, mostChars: Int = DIFF_TEXT_CHARS): TextLines { + val end = minOf(text.length, mostChars) + val lines = ArrayList() + var from = 0 + while (from < end && lines.size < mostLines) { + val newline = text.indexOf('\n', from).let { if (it < 0 || it >= end) -1 else it } + val to = if (newline < 0) end else newline + lines += text.substring(from, if (to > from && text[to - 1] == '\r') to - 1 else to) + from = if (newline < 0) end else newline + 1 + } + return TextLines(lines, cut = from < text.length) +} + +/** How [text]'s lines end, where it has any: `CRLF` when its first newline follows a `\r`, else `LF`; null for a text of one line. */ +internal fun lineEnding(text: String): String? { + val newline = text.indexOf('\n') + return when { + newline < 0 -> null + newline > 0 && text[newline - 1] == '\r' -> "CRLF" + else -> "LF" + } } /** @@ -107,8 +145,55 @@ fun hunks(lines: List, context: Int = DIFF_CONTEXT): List { return out } -/** This file's change for the card: a file that is made is all added, one that goes is all removed. */ +/** + * This file's change for the card: a file that is made is all added, one that goes is all + * removed. Bounded before it starts ([textLines]) and while it runs ([diffLines]); it is still + * work for a background thread, never for a frame. + */ fun FileDiff.view(): DiffView { - val all = diffLines(textLines(oldText.orEmpty()), textLines(if (deleted) "" else newText)) - return DiffView(hunks(all), added = all.count { it.sign == DiffSign.Added }, removed = all.count { it.sign == DiffSign.Removed }) + val before = oldText.orEmpty() + val after = if (deleted) "" else newText + val old = textLines(before) + val new = textLines(after) + val all = diffLines(old.lines, new.lines) + val from = lineEnding(before) + val to = lineEnding(after) + return DiffView( + hunks(all), + added = all.count { it.sign == DiffSign.Added }, + removed = all.count { it.sign == DiffSign.Removed }, + endings = if (from != null && to != null && from != to) from to to else null, + cut = old.cut || new.cut, + ) +} + +/** Whether an approval's item shows its `detail` (the call's arguments): always without diffs, and with them when none of them says anything. [views] is null while they are worked out. */ +fun showsDetail(item: CardItem, views: List?): Boolean = item.diffs.isEmpty() || (views != null && views.none { it.says }) + +// Characters a person cannot see, or that would move or break a line: on a card where somebody +// decides, each is written as its code point. +private fun unseen(c: Char): Boolean = when (c.code) { + in 0x00..0x1F, in 0x7F..0x9F -> true + 0x00AD, 0x061C, 0x180E, 0xFEFF -> true + in 0x200B..0x200F, in 0x2028..0x202E, in 0x2060..0x206F -> true + in 0xFFF9..0xFFFB -> true + else -> false +} + +/** + * [text] with every invisible, direction-changing or line-breaking character written as + * ``: a bidi override, a zero-width space, a line separator, a control. A tab is four + * spaces. What is drawn reads as what is written. + */ +fun visibly(text: String): String { + if (text.none { it == '\t' || unseen(it) }) return text + return buildString(text.length + 16) { + for (c in text) { + when { + c == '\t' -> append(" ") + unseen(c) -> append("') + else -> append(c) + } + } + } } diff --git a/app/src/main/java/eu/llembas/android/api/Files.kt b/app/src/main/java/eu/llembas/android/api/Files.kt index 106ef98..278324e 100644 --- a/app/src/main/java/eu/llembas/android/api/Files.kt +++ b/app/src/main/java/eu/llembas/android/api/Files.kt @@ -365,3 +365,52 @@ class RangeReader(private val length: Long, private val block: Int = BLOCK, priv const val BLOCK = 512 * 1024 } } + +/** How much of a file's beginning says what it is. */ +const val SNIFF_BYTES = 16 + +private fun ByteArray.begins(at: Int, vararg bytes: Int): Boolean = + size >= at + bytes.size && bytes.indices.all { (this[at + it].toInt() and 0xFF) == bytes[it] } + +private fun ByteArray.says(at: Int, word: String): Boolean = size >= at + word.length && word.indices.all { this[at + it].toInt() == word[it].code } + +/** + * What a file is by its first bytes ([head], [SNIFF_BYTES] of them are enough), for the kinds a + * chat hands out: pictures, sound, video, a PDF, a 3D model, the archives. Null for anything + * else -- text has no mark, and a guess is worse than none. + */ +fun sniffType(head: ByteArray): String? = when { + head.begins(0, 0x89, 0x50, 0x4E, 0x47) -> "image/png" + head.begins(0, 0xFF, 0xD8, 0xFF) -> "image/jpeg" + head.says(0, "GIF8") -> "image/gif" + head.says(0, "RIFF") && head.says(8, "WEBP") -> "image/webp" + head.says(0, "RIFF") && head.says(8, "WAVE") -> "audio/wav" + head.says(0, "BM") -> "image/bmp" + head.says(0, "%PDF-") -> "application/pdf" + head.says(0, "OggS") -> "audio/ogg" + head.says(0, "fLaC") -> "audio/flac" + head.says(0, "ID3") || head.begins(0, 0xFF, 0xFB) || head.begins(0, 0xFF, 0xF3) -> "audio/mpeg" + head.says(4, "ftyp") -> "video/mp4" + head.begins(0, 0x1A, 0x45, 0xDF, 0xA3) -> "video/webm" + head.says(0, "glTF") -> "model/gltf-binary" + head.says(0, "PK\u0003\u0004") -> "application/zip" + head.begins(0, 0x1F, 0x8B) -> "application/gzip" + head.says(0, "7z") && head.begins(2, 0xBC, 0xAF) -> "application/x-7z-compressed" + else -> null +} + +/** + * The type a copy is offered to another app as ("Open with"): what its bytes say, else what its + * name's extension says ([named], the platform's table), else anything. A zip is the one mark + * that many kinds of document carry inside, so there a known extension is the better word. The + * type the instance said is not asked: it is not the phone's own reading. + */ +fun openType(head: ByteArray, named: String?): String { + val sniffed = sniffType(head) + val byName = named?.ifBlank { null } + return when { + sniffed == null -> byName ?: "*/*" + sniffed == "application/zip" && byName != null -> byName + else -> sniffed + } +} diff --git a/app/src/main/java/eu/llembas/android/assist/AssistService.kt b/app/src/main/java/eu/llembas/android/assist/AssistService.kt index 7c220de..0f34d7c 100644 --- a/app/src/main/java/eu/llembas/android/assist/AssistService.kt +++ b/app/src/main/java/eu/llembas/android/assist/AssistService.kt @@ -201,6 +201,9 @@ class LembasAssistSession(context: Context) : up = true AssistPresence.shown() } + // The sheet is the app in front: what it draws of the account (a reply's picture) may be + // asked for, unless the phone is locked. Said each time; the gate keeps it as one. + context.lembas.gate.sessionShown() AssistLink.sheetShown(SystemClock.elapsedRealtime()) // One sheet, never two: a sheet the wake word opened as a screen of the app, because // this one was slow to come, goes now that this one is here. @@ -230,6 +233,7 @@ class LembasAssistSession(context: Context) : up = false AssistPresence.hidden() } + context.lembas.gate.sessionHidden() controller.close() scope.cancel() scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) diff --git a/app/src/main/java/eu/llembas/android/ui/chat/Cards.kt b/app/src/main/java/eu/llembas/android/ui/chat/Cards.kt index 556a79f..191e333 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/Cards.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/Cards.kt @@ -37,6 +37,7 @@ import eu.llembas.android.api.CardAnswer import eu.llembas.android.api.CardItem import eu.llembas.android.api.LembasJson import eu.llembas.android.api.Plan +import eu.llembas.android.api.showsDetail import eu.llembas.android.ui.theme.LocalPalette /** The sentinel the web card's "Something else" row submits (`interaction.OTHER`). */ @@ -73,6 +74,7 @@ private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) { var refusing by remember { mutableStateOf(false) } Text(stringResource(R.string.card_approval), style = MaterialTheme.typography.titleMedium) card.items.forEach { item -> + val views = diffViews(item.diffs) // A subagent asks, not the chat's own turn: said first, as the page says it. val subagent = item.subagent if (subagent != null) { @@ -100,11 +102,12 @@ private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) { if (approvalTexts(listOf(item), edits).isNotEmpty()) { Text(stringResource(R.string.card_edit_runs), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted) } - } else if (item.detail.isNotBlank() && item.diffs.isEmpty()) { + } else if (item.detail.isNotBlank() && showsDetail(item, views)) { Text(item.detail, fontFamily = FontFamily.Monospace) } - // An edit says what it would change: the diff stands where the call's arguments would, as text. - if (item.diffs.isNotEmpty()) CardDiffs(item.diffs) + // An edit says what it would change: the diff stands where the call's arguments would, + // as text. Diffs that say nothing (the same text twice) leave the arguments in view. + if (item.diffs.isNotEmpty()) CardDiffs(item.diffs, views) if (item.reason.isNotBlank()) Text(item.reason, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint) } // A corrected command goes with an allow, never with a refusal, and only when it was corrected. diff --git a/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt b/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt index 023046e..6da65e7 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt @@ -199,7 +199,7 @@ fun ChatScreen( override fun share(media: GeneratedMedia) = transfers.share(media.raw, media.title, media.mime) - override fun openWith(media: GeneratedMedia) = transfers.openWith(media.raw, media.title, media.mime) + override fun openWith(media: GeneratedMedia) = transfers.openWith(media.raw, media.title) override fun cancel(job: MediaJob) = model.cancelJob(job) } diff --git a/app/src/main/java/eu/llembas/android/ui/chat/DiffCard.kt b/app/src/main/java/eu/llembas/android/ui/chat/DiffCard.kt index 1fd40bf..558b7db 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/DiffCard.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/DiffCard.kt @@ -21,12 +21,14 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState 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.draw.clip +import androidx.compose.ui.platform.LocalInspectionMode import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription @@ -39,10 +41,15 @@ import androidx.compose.ui.unit.dp import eu.llembas.android.R import eu.llembas.android.api.DiffLine import eu.llembas.android.api.DiffSign +import eu.llembas.android.api.DiffView import eu.llembas.android.api.FileDiff import eu.llembas.android.api.view +import eu.llembas.android.api.visibly import eu.llembas.android.ui.theme.LocalPalette import eu.llembas.android.ui.theme.Palette +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.withContext // An edit's diff on its approval card: per file its path, how many lines come and go, and the // changed lines as text -- a sign before each and the theme's colour behind it, in one width of @@ -54,7 +61,11 @@ internal const val DIFF_LINE_MOST = 400 private val DiffShape = RoundedCornerShape(12.dp) -/** A line as the card writes it: its sign, then its text with tabs as spaces and cut at [DIFF_LINE_MOST]. */ +/** + * A line as the card writes it: its sign, then its text cut at [DIFF_LINE_MOST], with whatever + * a person could not see in it -- a direction override, a zero-width space, a line separator -- + * written as its code point ([visibly]). + */ internal fun diffRow(line: DiffLine): String { val sign = when (line.sign) { DiffSign.Added -> "+ " @@ -62,8 +73,8 @@ internal fun diffRow(line: DiffLine): String { DiffSign.Same -> " " DiffSign.Gap -> return "⋯" } - val text = line.text.replace("\r", "").replace("\t", " ") - return sign + if (text.length > DIFF_LINE_MOST) text.take(DIFF_LINE_MOST) + "…" else text + val long = line.text.length > DIFF_LINE_MOST + return sign + visibly(if (long) line.text.take(DIFF_LINE_MOST) else line.text) + if (long) "…" else "" } private fun diffText(lines: List, palette: Palette): AnnotatedString = buildAnnotatedString { @@ -79,27 +90,48 @@ private fun diffText(lines: List, palette: Palette): AnnotatedString = } } -/** The diffs of one item of an approval card, a block per file. */ +/** + * The diffs of an item, worked out: null until they are. Off the main thread -- two texts of a + * megabyte are not compared inside a frame -- and one file after another, so fifty files hold + * one comparison's memory at a time. A screenshot has no later frame: there it is done at once. + */ @Composable -fun CardDiffs(diffs: List, modifier: Modifier = Modifier) { +fun diffViews(diffs: List): List? { + if (diffs.isEmpty()) return emptyList() + if (LocalInspectionMode.current) return remember(diffs) { diffs.map { it.view() } } + val views by produceState?>(null, diffs) { + value = withContext(Dispatchers.Default) { + diffs.map { + ensureActive() + it.view() + } + } + } + return views +} + +/** The diffs of one item of an approval card, a block per file; [views] as [diffViews] gave them. */ +@Composable +fun CardDiffs(diffs: List, views: List?, modifier: Modifier = Modifier) { Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) { - diffs.forEachIndexed { at, diff -> key(at, diff.path) { FileDiffBlock(diff) } } + diffs.forEachIndexed { at, diff -> key(at, diff.path) { FileDiffBlock(diff, views?.getOrNull(at)) } } } } /** * One file's change. The path gives (it wraps) and the two counts keep their width. The lines - * are folded to the first few; "Show all" opens them, up to what a card lays out. + * are folded to the first few; "Show all" opens them, up to what a card lays out. Until [view] + * is worked out the block is its path alone. */ @Composable -private fun FileDiffBlock(diff: FileDiff) { +private fun FileDiffBlock(diff: FileDiff, view: DiffView?) { val palette = LocalPalette.current - val view = remember(diff) { diff.view() } var open by rememberSaveable(diff.path) { mutableStateOf(false) } + val path = remember(diff.path) { visibly(diff.path) } Column(Modifier.fillMaxWidth().clip(DiffShape).background(palette.codeBg).border(1.dp, palette.codeBorder, DiffShape)) { Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text(diff.path, style = MaterialTheme.typography.bodySmall, fontFamily = FontFamily.Monospace, color = palette.ink) + Text(path, style = MaterialTheme.typography.bodySmall, fontFamily = FontFamily.Monospace, color = palette.ink) val state = when { diff.deleted -> stringResource(R.string.diff_deleted) diff.made -> stringResource(R.string.files_new_file) @@ -107,38 +139,49 @@ private fun FileDiffBlock(diff: FileDiff) { } if (state != null) Text(state, style = MaterialTheme.typography.labelSmall, color = palette.inkMuted) } - Spacer(Modifier.width(12.dp)) - val counts = stringResource(R.string.diff_counts, view.added.toString(), view.removed.toString()) - Row(Modifier.clearAndSetSemantics { contentDescription = counts }, horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Text("+${view.added}", style = MaterialTheme.typography.labelMedium, fontFamily = FontFamily.Monospace, color = palette.success) - Text("−${view.removed}", style = MaterialTheme.typography.labelMedium, fontFamily = FontFamily.Monospace, color = palette.danger) + if (view != null) { + Spacer(Modifier.width(12.dp)) + val counts = stringResource(R.string.diff_counts, view.added.toString(), view.removed.toString()) + Row(Modifier.clearAndSetSemantics { contentDescription = counts }, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text("+${view.added}", style = MaterialTheme.typography.labelMedium, fontFamily = FontFamily.Monospace, color = palette.success) + Text("−${view.removed}", style = MaterialTheme.typography.labelMedium, fontFamily = FontFamily.Monospace, color = palette.danger) + } } } - val lines = view.shown(open) - if (lines.isNotEmpty()) { - val text = remember(lines, palette) { diffText(lines, palette) } - Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())) { - Text( - text, - style = MaterialTheme.typography.bodySmall, - fontFamily = FontFamily.Monospace, - softWrap = false, - modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp), - ) + if (view != null) { + // Said once, where every line would otherwise go and come with the same words. + view.endings?.let { (from, to) -> DiffNote(stringResource(R.string.diff_endings, from, to)) } + val lines = view.shown(open) + if (lines.isNotEmpty()) { + val text = remember(lines, palette) { diffText(lines, palette) } + Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())) { + Text( + text, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + softWrap = false, + modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp), + ) + } } - } - if (open && view.beyond > 0) { - Text( - stringResource(R.string.diff_more, view.beyond.toString()), - style = MaterialTheme.typography.bodySmall, - color = palette.inkMuted, - modifier = Modifier.padding(horizontal = 12.dp), - ) - } - if (view.folds) { - TextButton(onClick = { open = !open }, modifier = Modifier.heightIn(min = 48.dp).padding(horizontal = 4.dp)) { - Text(if (open) stringResource(R.string.diff_show_less) else stringResource(R.string.diff_show_all, view.lines.size.toString())) + if (open && view.beyond > 0) DiffNote(stringResource(R.string.diff_more, view.beyond.toString())) + if (view.cut) DiffNote(stringResource(R.string.diff_cut)) + if (view.folds) { + TextButton(onClick = { open = !open }, modifier = Modifier.heightIn(min = 48.dp).padding(horizontal = 4.dp)) { + Text(if (open) stringResource(R.string.diff_show_less) else stringResource(R.string.diff_show_all, view.lines.size.toString())) + } } } } } + +/** A sentence of the block's own, under its lines. */ +@Composable +private fun DiffNote(text: String) { + Text( + text, + style = MaterialTheme.typography.bodySmall, + color = LocalPalette.current.inkMuted, + modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp), + ) +} 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 05878b2..6569ef0 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 @@ -439,7 +439,7 @@ fun FilesScreen(onBack: () -> Unit, start: String? = null, model: FilesViewModel model.clearSelection() } - override fun openWith(entry: FileEntry) = transfers.openWith(entry.path, entry.name, entry.mime) + override fun openWith(entry: FileEntry) = transfers.openWith(entry.path, entry.name) } } 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 index bbd13f3..e05e01f 100644 --- a/app/src/main/java/eu/llembas/android/ui/files/TransferViewModel.kt +++ b/app/src/main/java/eu/llembas/android/ui/files/TransferViewModel.kt @@ -91,13 +91,14 @@ class TransferViewModel(app: Application) : AndroidViewModel(app) { _state.update { it.copy(notice = app.getString(R.string.files_downloaded)) } } - fun openWith(path: String, name: String, mime: String) = openWith(Raw.Path(path), name, mime) + fun openWith(path: String, name: String) = openWith(Raw.Path(path), name) - fun openWith(what: Raw, name: String, mime: String) = start { api, progress -> + /** A copy for another app to open; its type is read from the copy ([Handover.view]), not taken from the instance. */ + fun openWith(what: Raw, name: String) = start { api, progress -> FileCache.sweepShared(app) turn() val copy = api.copyInto(api.raw(what), FileCache.shared(app, name), progress = progress) - _state.update { it.copy(launch = Handover.view(app, copy, mime)) } + _state.update { it.copy(launch = Handover.view(app, copy)) } } /** One thing that is not named by a path (a generated file by its id), shared as itself. */ 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 index 46cda75..e52244f 100644 --- a/app/src/main/java/eu/llembas/android/ui/files/Transfers.kt +++ b/app/src/main/java/eu/llembas/android/ui/files/Transfers.kt @@ -8,12 +8,15 @@ import android.content.Intent import android.net.Uri import android.provider.DocumentsContract import android.provider.OpenableColumns +import android.webkit.MimeTypeMap 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 eu.llembas.android.api.SNIFF_BYTES +import eu.llembas.android.api.openType import eu.llembas.android.share.SharedSource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @@ -185,9 +188,24 @@ suspend fun ApiClient.copyInto(request: okhttp3.Request, file: File, most: Long /** 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 { + /** + * "Open with" for the copy [file]. What it is offered as is read from the copy itself + * ([openType]: its first bytes, else its name's extension) -- never the type the instance + * said, which for a file an agent showed is one more thing a model had a hand in. + */ + fun view(context: Context, file: File): Intent { val uri = FileCache.uri(context, file) - val intent = Intent(Intent.ACTION_VIEW).setDataAndType(uri, mime.ifBlank { "*/*" }).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + // A copy that cannot be read again is offered by its name alone. + val head = try { + file.inputStream().use { stream -> + val bytes = ByteArray(SNIFF_BYTES) + bytes.copyOf(stream.read(bytes).coerceAtLeast(0)) + } + } catch (e: IOException) { + ByteArray(0) + } + val named = MimeTypeMap.getSingleton().getMimeTypeFromExtension(file.extension.lowercase()) + val intent = Intent(Intent.ACTION_VIEW).setDataAndType(uri, openType(head, named)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) return Intent.createChooser(intent, null) } 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 index 1d0a832..99fcf48 100644 --- a/app/src/main/java/eu/llembas/android/ui/viewer/TreeViewer.kt +++ b/app/src/main/java/eu/llembas/android/ui/viewer/TreeViewer.kt @@ -182,7 +182,7 @@ fun TreeFileViewer(path: String, onClose: () -> Unit, startEditing: Boolean = fa 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 openWith() = transfers.openWith(path, name) override fun share() = transfers.share(listOf(FileEntry(name = name, path = path, mime = file?.mime.orEmpty()))) } diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index d9e3100..e55adfe 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -425,6 +425,8 @@ Zobrazit všechny řádky (%1$s) Zobrazit méně Další řádky, které se zde nezobrazují: %1$s. + Konce řádků se mění z %1$s na %2$s. + Tato změna je příliš dlouhá na to, aby se zde porovnala. Zobrazen je jen její začátek. Tento soubor už neexistuje. Ve frontě Běží diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index eb2cae6..6759b73 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -425,6 +425,8 @@ Alle %1$s Zeilen anzeigen Weniger anzeigen %1$s weitere Zeilen werden hier nicht angezeigt. + Die Zeilenenden ändern sich von %1$s zu %2$s. + Diese Änderung ist zu lang, um hier verglichen zu werden. Nur ihr Anfang wird angezeigt. Diese Datei gibt es nicht mehr. In der Warteschlange Läuft diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index b876ae0..6da9d66 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -425,6 +425,8 @@ Mostrar las %1$s líneas Mostrar menos Aquí no se muestran %1$s líneas más. + Los finales de línea cambian de %1$s a %2$s. + Este cambio es demasiado largo para compararlo aquí. Solo se muestra su comienzo. Ese archivo ya no existe. En cola En ejecución diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 5cec0c9..9a2932b 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -425,6 +425,8 @@ Afficher les %1$s lignes Afficher moins %1$s lignes de plus ne sont pas affichées ici. + Les fins de ligne passent de %1$s à %2$s. + Cette modification est trop longue pour être comparée ici. Seul son début est affiché. Ce fichier n\'existe plus. En file d’attente En cours diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 6cf1d95..93bdae4 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -425,6 +425,8 @@ Mind a(z) %1$s sor megjelenítése Kevesebb megjelenítése További %1$s sor itt nem látható. + A sorvégek megváltoznak: %1$s helyett %2$s. + Ez a változás túl hosszú ahhoz, hogy itt össze lehessen hasonlítani. Csak az eleje látható. Ez a fájl már nem létezik. Sorban áll Fut diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index d8a394e..eb06c4c 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -425,6 +425,8 @@ Mostra tutte le %1$s righe Mostra meno Altre %1$s righe non sono mostrate qui. + I fine riga cambiano da %1$s a %2$s. + Questa modifica è troppo lunga per essere confrontata qui. Ne è mostrato solo l’inizio. Questo file non esiste più. In coda In esecuzione diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index af25f78..63e71e4 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -425,6 +425,8 @@ Pokaż wszystkie wiersze (%1$s) Pokaż mniej Dalsze wiersze, których tu nie pokazano: %1$s. + Końce wierszy zmieniają się z %1$s na %2$s. + Ta zmiana jest zbyt długa, by ją tu porównać. Pokazano tylko jej początek. Ten plik już nie istnieje. W kolejce Działa diff --git a/app/src/main/res/values-sk/strings.xml b/app/src/main/res/values-sk/strings.xml index 1091b8b..80640db 100644 --- a/app/src/main/res/values-sk/strings.xml +++ b/app/src/main/res/values-sk/strings.xml @@ -425,6 +425,8 @@ Zobraziť všetky riadky (%1$s) Zobraziť menej Ďalšie riadky, ktoré sa tu nezobrazujú: %1$s. + Konce riadkov sa menia z %1$s na %2$s. + Táto zmena je príliš dlhá na to, aby sa tu porovnala. Zobrazený je len jej začiatok. Tento súbor už neexistuje. Vo fronte Beží diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 7776803..df57b36 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -427,6 +427,8 @@ Show all %1$s lines Show less %1$s more lines are not shown here. + The line endings change from %1$s to %2$s. + This change is too long to compare here. Only its beginning is shown. That file no longer exists. Queued Running diff --git a/app/src/test/java/eu/llembas/android/ShownMediaTest.kt b/app/src/test/java/eu/llembas/android/ShownMediaTest.kt index 9f5d4b7..ad68fc3 100644 --- a/app/src/test/java/eu/llembas/android/ShownMediaTest.kt +++ b/app/src/test/java/eu/llembas/android/ShownMediaTest.kt @@ -3,6 +3,8 @@ package eu.llembas.android import eu.llembas.android.api.AskFrame import eu.llembas.android.api.DIFF_FOLD import eu.llembas.android.api.DIFF_MOST +import eu.llembas.android.api.DIFF_TEXT_CHARS +import eu.llembas.android.api.DIFF_TEXT_LINES import eu.llembas.android.api.DeviceList import eu.llembas.android.api.DiffLine import eu.llembas.android.api.DiffSign @@ -12,17 +14,31 @@ import eu.llembas.android.api.GeneratedMedia import eu.llembas.android.api.LembasJson import eu.llembas.android.api.MediaView import eu.llembas.android.api.Raw +import eu.llembas.android.api.TextLines import eu.llembas.android.api.ToolCall import eu.llembas.android.api.diffLines import eu.llembas.android.api.hunks +import eu.llembas.android.api.openType +import eu.llembas.android.api.showsDetail +import eu.llembas.android.api.sniffType +import eu.llembas.android.api.textLines import eu.llembas.android.api.view +import eu.llembas.android.api.visibly import eu.llembas.android.ui.chat.DIFF_LINE_MOST import eu.llembas.android.ui.chat.approvalTexts import eu.llembas.android.ui.chat.diffRow import eu.llembas.android.ui.chat.mediaKindWord import eu.llembas.android.ui.chat.offersAlways +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.json.boolean +import kotlinx.serialization.json.int +import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull @@ -35,6 +51,7 @@ import org.junit.Test * diff on its approval card, and the shapes that are parsed and not drawn yet (a linked * computer's files, an editor's two models). */ +@OptIn(ExperimentalCoroutinesApi::class) class ShownMediaTest { private fun contract(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) { "contract/$name.json is missing" @@ -237,18 +254,164 @@ class ShownMediaTest { assertEquals(short.lines, short.shown(open = false)) assertEquals(0, short.beyond) - // Two texts too long to compare line against line are not compared: the old goes, the new comes. - val a = (1..1500).map { "old $it" } - val b = (1..1500).map { "new $it" } - val both = diffLines(a, b) + // Two middles too long to compare line against line are not compared: the old goes, the + // new comes. They share every line, in the other order -- compared, some would be "same". + val a = (1..1500).map { "line $it" } + val both = diffLines(a, a.reversed()) assertEquals(3000, both.size) - assertEquals(1500, both.count { it.sign == DiffSign.Removed }) + assertTrue(both.none { it.sign == DiffSign.Same }) assertTrue(both.take(1500).all { it.sign == DiffSign.Removed }) + assertTrue(both.drop(1500).all { it.sign == DiffSign.Added }) + // The same two, short enough, are compared: something is found to be the same. + val few = (1..50).map { "line $it" } + assertTrue(diffLines(few, few.reversed()).any { it.sign == DiffSign.Same }) // One line of any length is one bounded line of the card; a tab is spaces. val row = diffRow(DiffLine(DiffSign.Added, "x".repeat(5000))) assertEquals(2 + DIFF_LINE_MOST + 1, row.length) - assertEquals(" a", diffRow(DiffLine(DiffSign.Same, "\ta\r"))) + assertEquals(" " + " a", diffRow(DiffLine(DiffSign.Same, "\ta"))) + } + + @Test + fun aTextIsCutBeforeItIsComparedNotAfter() { + // Two megabytes of newlines: only the first lines are ever split off. + val newlines = "\n".repeat(2_000_000) + val cut = textLines(newlines) + assertEquals(DIFF_TEXT_LINES, cut.lines.size) + assertTrue(cut.cut) + // One line of two megabytes: only its beginning is kept. + val one = textLines("x".repeat(2_000_000)) + assertEquals(1, one.lines.size) + assertEquals(DIFF_TEXT_CHARS, one.lines.single().length) + assertTrue(one.cut) + // A text within both bounds is whole, and says so. + assertEquals(TextLines(listOf("a", "b"), cut = false), textLines("a\nb\n")) + assertEquals(TextLines(listOf("a", "b"), cut = false), textLines("a\nb")) + assertEquals(TextLines(listOf("a"), cut = true), textLines("a\nb\n", mostLines = 1)) + assertEquals(TextLines(listOf("a"), cut = true), textLines("a\nbcd", mostChars = 2)) + assertEquals(TextLines(listOf("a", "b"), cut = true), textLines("a\nbcd", mostChars = 3)) + + // A new file of that size is a card of bounded size that says it is not all there. + val huge = FileDiff(path = "huge.txt", oldText = null, newText = (1..100_000).joinToString("\n") { "row $it" }).view() + assertTrue(huge.cut) + assertEquals(DIFF_TEXT_LINES, huge.added) + assertEquals(DIFF_TEXT_LINES, huge.lines.size) + assertTrue(huge.says) + assertFalse(edit().diffs[0].view().cut) + } + + @Test + fun aChangeOfLineEndingsIsSaidOnceNotAsEveryLine() { + val crlf = FileDiff(path = "a.txt", oldText = "one\ntwo\nthree\n", newText = "one\r\ntwo\r\nthree\r\n").view() + assertTrue(crlf.lines.isEmpty()) + assertEquals(0 to 0, crlf.added to crlf.removed) + assertEquals("LF" to "CRLF", crlf.endings) + assertTrue(crlf.says) + // With a real change beside it, only that line goes and comes. + val both = FileDiff(path = "a.txt", oldText = "one\r\ntwo\r\n", newText = "one\nTWO\n").view() + assertEquals("CRLF" to "LF", both.endings) + assertEquals(listOf(DiffSign.Same, DiffSign.Removed, DiffSign.Added), both.lines.map { it.sign }) + assertEquals(listOf("one", "two", "TWO"), both.lines.map { it.text }) + // The same endings, a new file, a file of one line: nothing to say of endings. + assertNull(edit().diffs[0].view().endings) + assertNull(edit().diffs[1].view().endings) + assertNull(FileDiff(path = "p", oldText = "a", newText = "a\r\nb\r\n").view().endings) + } + + @Test + fun whatCannotBeSeenIsWrittenAsItsCodePoint() { + // A direction override makes a line read as something it is not; a line separator breaks it in two. + assertEquals("+ if (admin) {", diffRow(DiffLine(DiffSign.Added, "if (admin\u202E) {"))) + assertEquals("- ab", diffRow(DiffLine(DiffSign.Removed, "a\u2028b"))) + assertEquals("ab", visibly("a\u200Bb\uFEFF\u2066\u0000\r\u0085")) + // A path is read too: it names what is changed. + assertEquals("src/yp.nevo", visibly("src/\u202Eyp.nevo")) + // Ordinary text, other scripts and wide characters are left as they are. + listOf("def bake(loaf):", "žltý kôň — ünïcödé", "日本語 \uD83C\uDF5E", "").forEach { assertEquals(it, visibly(it)) } + } + + @Test + fun theArgumentsStayInViewWhenTheDiffsSayNothing() { + val item = edit() + // Diffs that say something stand in the arguments' place, once they are worked out and while they are. + assertFalse(showsDetail(item, item.diffs.map { it.view() })) + assertFalse(showsDetail(item, null)) + // The same text twice, or an entry with nothing in it: the card would say "+0 -0" and nothing else. + val same = item.copy(diffs = listOf(FileDiff(path = "a.txt", oldText = "a\n", newText = "a\n"), FileDiff())) + assertTrue(same.diffs.map { it.view() }.none { it.says }) + assertTrue(showsDetail(same, same.diffs.map { it.view() })) + // A card without diffs is as it always was. + assertTrue(showsDetail(item.copy(diffs = emptyList()), emptyList())) + assertTrue(showsDetail(item.copy(diffs = emptyList()), null)) + } + + // --- The gate and the assistant's sheet --------------------------------------------------------- + + @Test + fun theAssistantsSheetIsTheAppInFrontAndTheLockStillShutsTheGate() = runTest { + var locked = false + val gate = InstanceGate { locked } + // No activity: the sheet is a session's window. A picture in it waits as a chat's does... + val fetched = mutableListOf() + val picture = launch { + gate.passLater() + fetched += "picture" + } + runCurrent() + assertTrue(fetched.isEmpty()) + // ...until the sheet shows, which no activity's start would ever say. + gate.sessionShown() + runCurrent() + assertEquals(listOf("picture"), fetched) + picture.join() + // Shown again while up, hidden once: shut. + gate.sessionShown() + gate.sessionHidden() + assertFalse(gate.open.value) + + // Over the lock screen the sheet opens nothing; the unlock does. + locked = true + gate.sessionShown() + assertFalse(gate.open.value) + locked = false + assertTrue(gate.look()) + // An activity of the app in front keeps the gate open when the sheet goes. + gate.activityStarted() + gate.sessionHidden() + assertTrue(gate.open.value) + gate.activityStopped() + assertFalse(gate.open.value) + } + + // --- Open with ---------------------------------------------------------------------------------- + + private fun bytes(vararg values: Int) = ByteArray(values.size) { values[it].toByte() } + + @Test + fun aFileIsOfferedAsWhatItsBytesSayNotAsWhatItWasCalled() { + val png = bytes(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A) + val pdf = "%PDF-1.7\n".toByteArray() + val zip = bytes(0x50, 0x4B, 0x03, 0x04, 0x14, 0x00) + assertEquals("image/png", sniffType(png)) + assertEquals("application/pdf", sniffType(pdf)) + assertEquals("image/jpeg", sniffType(bytes(0xFF, 0xD8, 0xFF, 0xE0))) + assertEquals("video/mp4", sniffType(bytes(0, 0, 0, 0x20) + "ftypisom".toByteArray())) + assertEquals("audio/wav", sniffType("RIFF".toByteArray() + bytes(0, 0, 0, 0) + "WAVE".toByteArray())) + assertEquals("image/webp", sniffType("RIFF".toByteArray() + bytes(0, 0, 0, 0) + "WEBP".toByteArray())) + assertNull(sniffType("just words".toByteArray())) + assertNull(sniffType(ByteArray(0))) + assertNull(sniffType(bytes(0x89))) + + // The bytes decide, whatever the name says. + assertEquals("application/pdf", openType(pdf, "image/png")) + assertEquals("image/png", openType(png, null)) + // No mark in the bytes: the name's extension, else anything. + assertEquals("text/plain", openType("just words".toByteArray(), "text/plain")) + assertEquals("*/*", openType("just words".toByteArray(), null)) + assertEquals("*/*", openType(ByteArray(0), "")) + // A zip is what many documents are inside: a known extension is the better word there. + assertEquals("application/epub+zip", openType(zip, "application/epub+zip")) + assertEquals("application/zip", openType(zip, null)) } // --- Parsed, and not drawn yet ------------------------------------------------------------------ @@ -280,14 +443,48 @@ class ShownMediaTest { assertNull(unset.main.model) } + private fun fixture(name: String) = LembasJson.parseToJsonElement(contract(name)).jsonObject + + private fun kotlinx.serialization.json.JsonObject.word(key: String) = getValue(key).jsonPrimitive.content + @Test - fun theShapesNothingUsesYetAreRead() { - // A linked computer's files and a message's editor context: no screen and no model of - // them here yet, and the app's reader takes each as the server wrote it. - listOf( - "device_fs_roots", "device_fs_listing", "device_fs_stat", "device_fs_content", "device_fs_content_withheld", "device_fs_written", - "device_fs_conflict", "device_fs_batch", "device_fs_deleted", "device_fs_no_trash", "device_fs_search", "device_fs_search_content", - "message_editor", - ).forEach { name -> assertTrue(name, LembasJson.parseToJsonElement(contract(name)).jsonObject.isNotEmpty()) } + fun aComputersFilesAndAMessagesEditorContextSayWhatTheApiSays() { + // No screen and no model of these here yet. The fields a browser would stand on are + // where App-API puts them, so a pin that moves them fails here. + val roots = fixture("device_fs_roots") + assertEquals("", roots.word("path")) + assertTrue(roots.getValue("entries").jsonArray.isNotEmpty()) + + val listing = fixture("device_fs_listing") + assertEquals("/home/dev/project", listing.word("path")) + val entries = listing.getValue("entries").jsonArray.map { it.jsonObject } + val keys = setOf("name", "path", "kind", "size", "mtime", "updated_at", "file_kind", "link", "outside", "protected", "runs_code", "writable") + entries.forEach { assertEquals(keys, it.keys) } + assertTrue(entries.map { it.word("kind") }.containsAll(listOf("dir", "file"))) + assertTrue(entries.single { it.word("name") == "shared" }.getValue("outside").jsonPrimitive.boolean) + assertTrue(entries.single { it.word("name") == ".env" }.getValue("protected").jsonPrimitive.boolean) + + val content = fixture("device_fs_content") + assertTrue(content.word("sha").startsWith("sha256:")) + assertTrue(content.word("text").isNotEmpty()) + val withheld = fixture("device_fs_content_withheld") + assertEquals("", withheld.word("text")) + assertTrue(withheld.getValue("withheld").jsonObject.word("reason") in setOf("not_text", "too_large")) + + val conflict = fixture("device_fs_conflict") + assertEquals("changed", conflict.word("reason")) + assertTrue(conflict.getValue("conflict").jsonPrimitive.boolean) + assertTrue(conflict.word("sha").startsWith("sha256:")) + assertEquals("no_trash", fixture("device_fs_no_trash").word("reason")) + assertTrue(fixture("device_fs_written").word("sha").startsWith("sha256:")) + + val batch = fixture("device_fs_batch") + assertFalse(batch.getValue("atomic").jsonPrimitive.boolean) + assertTrue(batch.getValue("results").jsonArray.all { "ok" in it.jsonObject && "path" in it.jsonObject }) + + val editor = fixture("message_editor") + assertEquals("/home/dev/project/src/oven.py", editor.word("path")) + assertEquals(2, editor.getValue("selection").jsonObject.getValue("start").jsonPrimitive.int) + assertEquals("warning", editor.getValue("diagnostics").jsonArray.single().jsonObject.word("severity")) } } diff --git a/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt b/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt index fa3244a..68cea33 100644 --- a/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt +++ b/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt @@ -147,7 +147,8 @@ class ScreenShots { @Test fun editDiffCard() { // An edit's approval card with its diff: a changed file with one line wider than the phone - // (it scrolls in its own box), a new file long enough to fold, and a file that goes. The + // (it scrolls in its own box), a new file long enough to fold, a file that goes, and one + // whose line endings change with a character in it that cannot be seen. The // card itself must not be wider than the phone, at a small one's width and large type too. val long = " return loaf.heat(240, minutes=timer.MINUTES, rack=\"middle\", steam=True, turn_after=20) # hotter, as asked" val card = Card( @@ -171,6 +172,8 @@ class ScreenShots { ), FileDiff(path = "src/bakery/timer.py", oldText = null, newText = (1..30).joinToString("\n") { "STEP_$it = ${it * 5}" } + "\n"), FileDiff(path = "src/bakery/old.py", oldText = "x = 1\ny = 2\n", newText = "", deleted = true), + // Line endings that change are said once; a direction override in a line is written out. + FileDiff(path = "src/bakery/notes.txt", oldText = "keep warm\nserve\n", newText = "keep warm\r\nserve\u202E now\r\n"), ), ), ), diff --git a/scripts/strings.py b/scripts/strings.py index 6c56eed..9399635 100755 --- a/scripts/strings.py +++ b/scripts/strings.py @@ -459,6 +459,8 @@ STRINGS: dict[str, str] = { "diff_show_all": "Show all %1$s lines", "diff_show_less": "Show less", "diff_more": "%1$s more lines are not shown here.", + "diff_endings": "The line endings change from %1$s to %2$s.", + "diff_cut": "This change is too long to compare here. Only its beginning is shown.", "media_gone": "That file no longer exists.", "job_queued": "Queued", "job_running": "Running", diff --git a/scripts/strings_own.json b/scripts/strings_own.json index 6d02aa2..f5a3783 100644 --- a/scripts/strings_own.json +++ b/scripts/strings_own.json @@ -432,7 +432,9 @@ "diff_counts": "Přidané řádky: %1$s, odebrané: %2$s", "diff_show_all": "Zobrazit všechny řádky (%1$s)", "diff_show_less": "Zobrazit méně", - "diff_more": "Další řádky, které se zde nezobrazují: %1$s." + "diff_more": "Další řádky, které se zde nezobrazují: %1$s.", + "diff_endings": "Konce řádků se mění z %1$s na %2$s.", + "diff_cut": "Tato změna je příliš dlouhá na to, aby se zde porovnala. Zobrazen je jen její začátek." }, "de": { "about_version": "LLeMbas für Android %1$s", @@ -868,7 +870,9 @@ "diff_counts": "Zeilen hinzugefügt: %1$s, entfernt: %2$s", "diff_show_all": "Alle %1$s Zeilen anzeigen", "diff_show_less": "Weniger anzeigen", - "diff_more": "%1$s weitere Zeilen werden hier nicht angezeigt." + "diff_more": "%1$s weitere Zeilen werden hier nicht angezeigt.", + "diff_endings": "Die Zeilenenden ändern sich von %1$s zu %2$s.", + "diff_cut": "Diese Änderung ist zu lang, um hier verglichen zu werden. Nur ihr Anfang wird angezeigt." }, "es": { "about_version": "LLeMbas para Android %1$s", @@ -1303,7 +1307,9 @@ "diff_counts": "Líneas añadidas: %1$s, eliminadas: %2$s", "diff_show_all": "Mostrar las %1$s líneas", "diff_show_less": "Mostrar menos", - "diff_more": "Aquí no se muestran %1$s líneas más." + "diff_more": "Aquí no se muestran %1$s líneas más.", + "diff_endings": "Los finales de línea cambian de %1$s a %2$s.", + "diff_cut": "Este cambio es demasiado largo para compararlo aquí. Solo se muestra su comienzo." }, "fr": { "about_version": "LLeMbas pour Android %1$s", @@ -1739,7 +1745,9 @@ "diff_counts": "Lignes ajoutées : %1$s, supprimées : %2$s", "diff_show_all": "Afficher les %1$s lignes", "diff_show_less": "Afficher moins", - "diff_more": "%1$s lignes de plus ne sont pas affichées ici." + "diff_more": "%1$s lignes de plus ne sont pas affichées ici.", + "diff_endings": "Les fins de ligne passent de %1$s à %2$s.", + "diff_cut": "Cette modification est trop longue pour être comparée ici. Seul son début est affiché." }, "hu": { "about_version": "LLeMbas Androidra %1$s", @@ -2175,7 +2183,9 @@ "diff_counts": "Hozzáadott sorok: %1$s, eltávolított: %2$s", "diff_show_all": "Mind a(z) %1$s sor megjelenítése", "diff_show_less": "Kevesebb megjelenítése", - "diff_more": "További %1$s sor itt nem látható." + "diff_more": "További %1$s sor itt nem látható.", + "diff_endings": "A sorvégek megváltoznak: %1$s helyett %2$s.", + "diff_cut": "Ez a változás túl hosszú ahhoz, hogy itt össze lehessen hasonlítani. Csak az eleje látható." }, "it": { "about_version": "LLeMbas per Android %1$s", @@ -2610,7 +2620,9 @@ "diff_counts": "Righe aggiunte: %1$s, rimosse: %2$s", "diff_show_all": "Mostra tutte le %1$s righe", "diff_show_less": "Mostra meno", - "diff_more": "Altre %1$s righe non sono mostrate qui." + "diff_more": "Altre %1$s righe non sono mostrate qui.", + "diff_endings": "I fine riga cambiano da %1$s a %2$s.", + "diff_cut": "Questa modifica è troppo lunga per essere confrontata qui. Ne è mostrato solo l’inizio." }, "pl": { "about_version": "LLeMbas na Androida %1$s", @@ -3045,7 +3057,9 @@ "diff_counts": "Dodane wiersze: %1$s, usunięte: %2$s", "diff_show_all": "Pokaż wszystkie wiersze (%1$s)", "diff_show_less": "Pokaż mniej", - "diff_more": "Dalsze wiersze, których tu nie pokazano: %1$s." + "diff_more": "Dalsze wiersze, których tu nie pokazano: %1$s.", + "diff_endings": "Końce wierszy zmieniają się z %1$s na %2$s.", + "diff_cut": "Ta zmiana jest zbyt długa, by ją tu porównać. Pokazano tylko jej początek." }, "sk": { "about_version": "LLeMbas pre Android %1$s", @@ -3480,6 +3494,8 @@ "diff_counts": "Pridané riadky: %1$s, odobraté: %2$s", "diff_show_all": "Zobraziť všetky riadky (%1$s)", "diff_show_less": "Zobraziť menej", - "diff_more": "Ďalšie riadky, ktoré sa tu nezobrazujú: %1$s." + "diff_more": "Ďalšie riadky, ktoré sa tu nezobrazujú: %1$s.", + "diff_endings": "Konce riadkov sa menia z %1$s na %2$s.", + "diff_cut": "Táto zmena je príliš dlhá na to, aby sa tu porovnala. Zobrazený je len jej začiatok." } }