Android 1.0 for server 2.0: the file viewer, and older servers refused
CI / check (push) Canceled after 0s

The show card. A tool call may now carry `show` (event["show"], harness spec 3.0.0): a file's
name, path, kind, line and which copy -- node and version in the chat's tree, or the copy a linked
device sent (shown_id). The transcript draws it as a card with Open; the viewer is a full-screen,
read-only dialog that fetches the text and opens at the named line. Markdown goes through the same
Markwon setup as a reply (rule 4); code, text and Markdown over 200 000 characters are numbered
lines in a lazy list, the number column measured from the file's longest number. HTML is never
rendered: no WebView exists in the app, so it is shown as source, and "Open in the browser" opens
the web UI's viewer, which renders it in its sealed frame. Copy takes the whole file.

The text comes from GET /api/v2/chats/{chat}/show?node=&version= (or ?shown=), plain text, at most
1 MB. That route is the app's half of a contract the server does not have yet: /api/v2 neither
publishes `show` on a tool call nor serves the file to a token. Until it does, the card does not
appear, and a viewer that meets a missing route says so and offers the browser.

Older servers are refused: the discovery document's device-link protocol must be 3 (LLeMbas 2.0),
at sign-in and, for an instance signed in to before, when the chat list opens. The protocol and
not the version string, because the server's dev still says 1.7.x before its first beta.

Also: gen-strings.py takes a server ref like the other two generators, so the strings come from
the same commit as the contract and the tokens rather than from a shared working tree; the
Reports notification channel goes (2.0 has no reports) and is deleted on first start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Opus 5.5 committed 2026-10-28 04:31:07 +00:00
1 parent 052d0a3894
commit fd1af60dbb
25 files changed
+754 -62

No files matched your search

@@ -18,15 +18,16 @@ class LembasApp : Application() {
listOf(
NotificationChannel(CHANNEL_REPLIES, getString(R.string.channel_replies), NotificationManager.IMPORTANCE_DEFAULT),
NotificationChannel(CHANNEL_ASKS, getString(R.string.channel_asks), NotificationManager.IMPORTANCE_HIGH),
NotificationChannel(CHANNEL_REPORTS, getString(R.string.channel_reports), NotificationManager.IMPORTANCE_LOW),
),
)
// LLeMbas 2.0 has no reports, so 0.1's channel for them goes rather than sit empty in
// the system's settings.
manager.deleteNotificationChannel("reports")
}
companion object {
const val CHANNEL_REPLIES = "replies"
const val CHANNEL_ASKS = "asks"
const val CHANNEL_REPORTS = "reports"
}
}
@@ -227,6 +227,38 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
}
}
// --- What a `show` card opens -------------------------------------------------------------
/**
* The text of a file a `show` card named, as the chat sees it now: the server rebuilds the
* chat's view and checks the path again, so a grant taken away since takes the file away too.
* Always plain text -- the app never asks for a page to render.
*/
suspend fun shownText(chatId: String, show: ShowCard): String = withContext(Dispatchers.IO) {
val url = "$v2/chats/$chatId/show".toHttpUrl().newBuilder()
.apply { show.query.forEach { (k, v) -> addQueryParameter(k, v) } }
.build()
http.newCall(authed(url.toString()).header("Accept", "text/plain").get().build()).await().use {
if (!it.isSuccessful) throw ApiException(it.code, detail(it))
val body = it.body!!
// The server shows at most 1 MB; anything much larger is not a file it meant.
if (body.contentLength() > SHOWN_MAX_BYTES) throw ApiException(413, "")
val bytes = body.source().use { source ->
source.request(SHOWN_MAX_BYTES + 1)
source.buffer.readByteArray(minOf(source.buffer.size, SHOWN_MAX_BYTES + 1))
}
if (bytes.size > SHOWN_MAX_BYTES) throw ApiException(413, "")
bytes.toString(Charsets.UTF_8)
}
}
/** The same file in the web UI's viewer, which renders HTML in its sealed frame. */
fun webViewer(chatId: String, show: ShowCard): String = "$base/chat/$chatId/show".toHttpUrl().newBuilder()
.apply { show.query.forEach { (k, v) -> addQueryParameter(k, v) } }
.apply { if (show.line > 0) addQueryParameter("line", show.line.toString()) }
.build()
.toString()
// --- Push --------------------------------------------------------------------------------
suspend fun pushKey(): PushKey = get("/push")
@@ -265,6 +297,9 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
authed("$v2/chats/$chatId/messages/$messageId/stream").header("Accept", "text/event-stream").build()
companion object {
/** 1 MB, the server's own limit on a shown file, with room for a little more. */
const val SHOWN_MAX_BYTES = 1_100_000L
fun emptyBody(): RequestBody = ByteArray(0).toRequestBody(null)
}
}
@@ -0,0 +1,26 @@
package eu.llembas.android.api
/** The newest app API this app reads. A server with a newer one is told about, not guessed at. */
const val APP_API = 1
/**
* The device-link protocol of LLeMbas 2.0. This app is built for 2.0 -- the file tree, the
* access levels, the `show` card -- and a 1.x server (protocol 1 or 2) is refused with a
* sentence rather than half-working. The protocol, not the version string, is the test: a
* server's `dev` branch says 1.7.x until its first beta, and the protocol is what 2.0 raised on
* purpose so that old clients can tell.
*/
const val MIN_PROTOCOL = 3
/** Whether this app can work with a server, from its discovery document. */
enum class ServerFit { FITS, NOT_LEMBAS, TOO_OLD, TOO_NEW }
fun fit(found: Discovery): ServerFit {
val protocol = maxOf(found.protocol, found.protocols.maxOrNull() ?: 0)
return when {
found.service != "lembas" -> ServerFit.NOT_LEMBAS
protocol < MIN_PROTOCOL || found.appApi < 1 || "app" !in found.scopes -> ServerFit.TOO_OLD
found.appApi > APP_API -> ServerFit.TOO_NEW
else -> ServerFit.FITS
}
}
@@ -27,6 +27,9 @@ data class Discovery(
val version: String = "",
val name: String = "",
@SerialName("base_url") val baseUrl: String = "",
/** The device link's protocol: 3 from LLeMbas 2.0 on, which is what this app needs. */
val protocol: Int = 0,
val protocols: List<Int> = emptyList(),
@SerialName("app_api") val appApi: Int = 0,
val login: Login = Login(),
val scopes: List<String> = emptyList(),
@@ -191,9 +194,45 @@ data class ToolCall(
val truncated: Boolean = false,
val job: JsonElement? = null,
val children: List<ToolCall>? = null,
/** The `show` tool's card: a file put in front of the person. Never its text. */
val show: ShowCard? = null,
val block: ToolBlock = ToolBlock(),
)
/**
* What a `show` call put in front of the person (`event["show"]`, harness spec 3.0.0): the
* file's name and where it is, never its contents -- the viewer fetches those. A file from the
* chat's own tree names its node and version; a file a linked device sent names the copy the
* server kept (`shown_id`), with the tree's two ids empty.
*/
@Serializable
data class ShowCard(
val path: String = "",
val name: String = "",
/** `markdown`, `code`, `text` or `html`; anything else is read as `text`. */
val kind: String = "text",
val language: String = "",
val line: Int = 0,
@SerialName("node_id") val nodeId: String = "",
@SerialName("version_id") val versionId: String = "",
val sha: String = "",
val size: Long = 0,
val mime: String = "",
val source: String = "",
@SerialName("shown_id") val shownId: String = "",
) {
/** The kind the viewer draws: an unknown one is plain text, never something richer. */
val viewKind: String get() = if (kind in VIEW_KINDS) kind else "text"
/** Which file, as the server's viewer routes take it: the device's copy, or node and version. */
val query: List<Pair<String, String>>
get() = if (shownId.isNotEmpty()) listOf("shown" to shownId) else listOf("node" to nodeId, "version" to versionId)
companion object {
val VIEW_KINDS = setOf("markdown", "code", "text", "html")
}
}
@Serializable
data class SteerNote(val id: String = "", val text: String = "")
@@ -113,7 +113,6 @@ object Notifications {
)
val channel = when (payload.kind) {
"ask" -> LembasApp.CHANNEL_ASKS
"report" -> LembasApp.CHANNEL_REPORTS
else -> LembasApp.CHANNEL_REPLIES
}
val builder = NotificationCompat.Builder(context, channel)
@@ -28,9 +28,11 @@ import androidx.compose.material.icons.filled.Language
import androidx.compose.material.icons.filled.Psychology
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Terminal
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -46,6 +48,7 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import eu.llembas.android.R
import eu.llembas.android.api.Message
import eu.llembas.android.api.ShowCard
import eu.llembas.android.api.Step
import eu.llembas.android.api.ToolCall
import eu.llembas.android.ui.MarkdownText
@@ -79,15 +82,18 @@ fun UserBubble(message: Message, modifier: Modifier = Modifier) {
}
}
/** A reply's steps, in the order they happened: the same table of contents the web page draws. */
/**
* A reply's steps, in the order they happened: the same table of contents the web page draws.
* [onShow] opens a `show` card's file; without it (the assistant's sheet) the card only names it.
*/
@Composable
fun Steps(steps: List<Step>, modifier: Modifier = Modifier) {
fun Steps(steps: List<Step>, modifier: Modifier = Modifier, onShow: ((ShowCard) -> Unit)? = null) {
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
steps.forEach { step ->
when (step.kind) {
"thinking" -> Thinking(step)
"text" -> MarkdownText(step.markdown.orEmpty(), modifier = Modifier.fillMaxWidth())
"tools" -> step.calls.forEach { ToolCallBlock(it) }
"tools" -> step.calls.forEach { ToolCallBlock(it, onShow = onShow) }
"steer" -> step.messages.forEach { Steered(it.text) }
}
}
@@ -140,10 +146,15 @@ private fun iconFor(kind: String): ImageVector = when (kind) {
* scroller, so a megabyte of output never becomes the page.
*/
@Composable
fun ToolCallBlock(call: ToolCall, depth: Int = 0) {
fun ToolCallBlock(call: ToolCall, depth: Int = 0, onShow: ((ShowCard) -> Unit)? = null) {
val palette = LocalPalette.current
var open by rememberSaveable(call.id ?: call.block.title) { mutableStateOf(call.block.kind == "edit") }
val failed = call.status == "error" || !call.error.isNullOrEmpty()
val shown = call.show
if (shown != null && !failed) {
ShowCardRow(shown, depth, onShow)
return
}
Column(
Modifier
.fillMaxWidth()
@@ -192,7 +203,49 @@ fun ToolCallBlock(call: ToolCall, depth: Int = 0) {
if (call.truncated) {
Text(stringResource(R.string.output_cut), style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
}
call.children?.forEach { ToolCallBlock(it, depth + 1) }
call.children?.forEach { ToolCallBlock(it, depth + 1, onShow) }
}
}
}
}
/**
* A `show` card: the file's name and path, and Open. Nothing of its contents -- the words here
* are a path a model chose, drawn as text like everything else. The web page opens a card that
* arrives while it is open by itself, beside the conversation, when the screen is wide enough;
* a phone's screen is not, so here it waits for a tap.
*/
@Composable
private fun ShowCardRow(show: ShowCard, depth: Int, onShow: ((ShowCard) -> Unit)?) {
val palette = LocalPalette.current
Row(
Modifier
.fillMaxWidth()
.padding(start = (depth * 16).dp)
.background(palette.surfaceRaised, Rounded)
.border(1.dp, palette.border, Rounded)
.then(if (onShow != null) Modifier.clickable { onShow(show) } else Modifier)
.padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp)
.heightIn(min = 48.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(Icons.Filled.Visibility, contentDescription = stringResource(R.string.shown), modifier = Modifier.size(18.dp), tint = palette.leaf)
Spacer(Modifier.width(10.dp))
// The one part that gives: a long path shortens, the button keeps its size.
Column(Modifier.weight(1f)) {
Text(show.name.ifBlank { show.path }, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
show.path + if (show.line > 0) ":${show.line}" else "",
fontFamily = FontFamily.Monospace,
style = MaterialTheme.typography.labelSmall,
color = palette.inkFaint,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
if (onShow != null) {
TextButton(onClick = { onShow(show) }, modifier = Modifier.heightIn(min = 48.dp)) {
Text(stringResource(R.string.viewer_open))
}
}
}
@@ -74,9 +74,11 @@ import androidx.lifecycle.viewmodel.compose.viewModel
import eu.llembas.android.R
import eu.llembas.android.api.Message
import eu.llembas.android.api.ModelInfo
import eu.llembas.android.api.ShowCard
import eu.llembas.android.assist.Recorder
import eu.llembas.android.lembas
import eu.llembas.android.ui.theme.LocalPalette
import eu.llembas.android.ui.viewer.FileViewer
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@@ -88,6 +90,7 @@ fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit =
val snackbar = remember { SnackbarHostState() }
var menu by remember { mutableStateOf(false) }
var editing by remember { mutableStateOf<Message?>(null) }
var showing by remember { mutableStateOf<ShowCard?>(null) }
LaunchedEffect(chatId) { model.open(chatId) }
// A new chat gets its id from its first message; the route follows, so Back and a
@@ -202,13 +205,13 @@ fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit =
}
live != null && live.messageId == message.id && live.finished == null -> Column {
Steps(live.shown)
Steps(live.shown, onShow = { showing = it })
if (live.shown.isEmpty()) Text(stringResource(R.string.loading_line), color = palette.inkFaint)
live.metrics?.let { m -> ReplyFoot(message.copy(metrics = m)) }
}
else -> Column {
Steps(message.steps)
Steps(message.steps, onShow = { showing = it })
ReplyFoot(message)
if (live == null && message == rows.lastOrNull()) {
Row {
@@ -236,6 +239,10 @@ fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit =
}
}
showing?.let { file ->
state.chat?.id?.let { id -> FileViewer(id, file, onClose = { showing = null }) }
}
editing?.let { message ->
var text by remember(message.id) { mutableStateOf(message.text.orEmpty()) }
AlertDialog(
@@ -53,7 +53,10 @@ import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.llembas.android.R
import eu.llembas.android.api.Chat
import eu.llembas.android.api.Doorstep
import eu.llembas.android.api.fit
import eu.llembas.android.lembas
import eu.llembas.android.ui.signin.refusal
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
@@ -68,12 +71,29 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
val state = _state.asStateFlow()
private var kind = "chat"
/** Why this instance is refused, once it was asked what it is; null while it fits. */
private var refused: Int? = null
private var checked = false
fun load(kind: String) {
this.kind = kind
viewModelScope.launch {
_state.update { it.copy(loading = true, error = null) }
try {
val api = getApplication<Application>().lembas.instances.client() ?: return@launch
// An instance signed in to before it was downgraded, or by 0.1 against a 1.x
// server, is refused here as at sign-in. Unreachable is not refused: the chat
// list's own error says that better.
if (!checked) {
runCatching { Doorstep().discover(api.base) }.onSuccess {
checked = true
refused = refusal(fit(it))
}
}
refused?.let { said ->
_state.value = ChatsState(error = getApplication<Application>().getString(said))
return@launch
}
val page = api.chats(kind = kind)
_state.value = ChatsState(chats = page.chats, more = page.more)
} catch (e: Exception) {
@@ -43,6 +43,8 @@ import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.llembas.android.R
import eu.llembas.android.api.Doorstep
import eu.llembas.android.api.ServerFit
import eu.llembas.android.api.fit
import eu.llembas.android.api.normaliseBase
import eu.llembas.android.lembas
import kotlinx.coroutines.Job
@@ -60,8 +62,12 @@ sealed interface SignInState {
data object Done : SignInState
}
/** The newest API this app reads. A server with a newer one is told about, not guessed at. */
const val APP_API = 1
/** The sentence for a server this app will not work with, or null when it fits. */
fun refusal(fit: ServerFit): Int? = when (fit) {
ServerFit.FITS -> null
ServerFit.NOT_LEMBAS, ServerFit.TOO_OLD -> R.string.signin_too_old
ServerFit.TOO_NEW -> R.string.signin_too_new
}
class SignInViewModel(app: Application) : AndroidViewModel(app) {
private val _state = MutableStateFlow<SignInState>(SignInState.Address)
@@ -76,12 +82,8 @@ class SignInViewModel(app: Application) : AndroidViewModel(app) {
try {
val base = normaliseBase(typed)
val found = doorstep.discover(base)
if (found.service != "lembas" || found.appApi < 1 || "app" !in found.scopes) {
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_too_old))
return@launch
}
if (found.appApi > APP_API) {
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_too_new))
refusal(fit(found))?.let { said ->
_state.value = SignInState.Failed(getApplication<Application>().getString(said))
return@launch
}
val device = getApplication<Application>().getString(R.string.device_name)
@@ -0,0 +1,261 @@
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
package eu.llembas.android.ui.viewer
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.net.Uri
import androidx.browser.customtabs.CustomTabsIntent
import androidx.compose.foundation.background
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.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.OpenInNew
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import eu.llembas.android.R
import eu.llembas.android.api.ApiException
import eu.llembas.android.api.ShowCard
import eu.llembas.android.lembas
import eu.llembas.android.ui.MarkdownText
import eu.llembas.android.ui.theme.LocalPalette
import java.io.IOException
/**
* Markdown longer than this is shown as its lines instead. A TextView holding a whole megabyte
* of rendered Markdown stalls the phone; the same text as a lazy list of lines does not.
*/
private const val MARKDOWN_MAX_CHARS = 200_000
/** Where a file is on its way into the viewer. */
private sealed interface Loaded {
data object Loading : Loaded
data class Text(val text: String) : Loaded
/** [unavailable]: this server has no door for the app to read a shown file through. */
data class Failed(val message: String, val unavailable: Boolean = false) : Loaded
}
/**
* What a `show` card opens: the file, full screen, read-only, as the chat sees it now.
*
* Everything in it came from a model and is untrusted, as on the web page, so the rules are the
* same ones the transcript keeps: Markdown goes through [MarkdownText] (no images, no HTML, links
* outside for http, https and mailto only); code and text are drawn as lines, never interpreted.
* **HTML is shown as its source, never rendered** -- the app has no WebView, and a page a model
* wrote does not get one here. The web UI renders it in its sealed frame (an opaque origin with
* no network), and "Open in the browser" goes there.
*/
@Composable
fun FileViewer(chatId: String, show: ShowCard, onClose: () -> Unit) {
val context = LocalContext.current
val palette = LocalPalette.current
var loaded by remember(chatId, show) { mutableStateOf<Loaded>(Loaded.Loading) }
var web by remember(chatId, show) { mutableStateOf<String?>(null) }
LaunchedEffect(chatId, show) {
val api = context.lembas.instances.client()
if (api == null) {
loaded = Loaded.Failed(context.getString(R.string.assist_signed_out))
return@LaunchedEffect
}
web = api.webViewer(chatId, show)
loaded = try {
Loaded.Text(api.shownText(chatId, show))
} catch (e: ApiException) {
when {
e.status == 413 -> Loaded.Failed(context.getString(R.string.viewer_too_large))
// No such route at all (FastAPI's own "Not Found", or the wrong method): a
// server without the app's door to shown files. Its own 404 has a sentence.
e.status == 405 || (e.status == 404 && e.message == "Not Found") ->
Loaded.Failed(context.getString(R.string.viewer_unavailable), unavailable = true)
else -> Loaded.Failed(e.message ?: context.getString(R.string.viewer_unavailable))
}
} catch (e: IOException) {
Loaded.Failed(e.message ?: e.javaClass.simpleName)
}
}
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false)) {
Scaffold(
topBar = {
TopAppBar(
navigationIcon = {
IconButton(onClick = onClose) {
Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close))
}
},
title = {
Column {
Text(show.name.ifBlank { show.path }, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
show.path + if (show.line > 0) ":${show.line}" else "",
style = MaterialTheme.typography.labelSmall,
fontFamily = FontFamily.Monospace,
color = palette.inkFaint,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
},
actions = {
(loaded as? Loaded.Text)?.let { done ->
IconButton(onClick = { copy(context, show.name, done.text) }) {
Icon(Icons.Filled.ContentCopy, contentDescription = stringResource(R.string.viewer_copy))
}
}
web?.let { url ->
IconButton(onClick = { openOutside(context, url) }) {
Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = stringResource(R.string.viewer_open_browser))
}
}
},
)
},
) { padding ->
Box(Modifier.padding(padding).fillMaxSize()) {
when (val now = loaded) {
Loaded.Loading -> CircularProgressIndicator(Modifier.align(Alignment.Center))
is Loaded.Failed -> Column(
Modifier.align(Alignment.Center).padding(32.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(now.message, color = palette.inkMuted, textAlign = TextAlign.Center)
web?.let { url ->
OutlinedButton(onClick = { openOutside(context, url) }, modifier = Modifier.padding(top = 16.dp)) {
Text(stringResource(R.string.viewer_open_browser))
}
}
}
is Loaded.Text -> Body(show, now.text)
}
}
}
}
}
@Composable
private fun Body(show: ShowCard, text: String) {
val palette = LocalPalette.current
val kind = show.viewKind
if (kind == "markdown" && text.length <= MARKDOWN_MAX_CHARS) {
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp)) {
MarkdownText(text, modifier = Modifier.fillMaxWidth())
}
return
}
val note = when (kind) {
"html" -> R.string.viewer_html_source
"markdown" -> R.string.viewer_long_markdown
else -> null
}
Column(Modifier.fillMaxSize()) {
note?.let {
Text(
stringResource(it),
style = MaterialTheme.typography.bodySmall,
color = palette.inkMuted,
modifier = Modifier.fillMaxWidth().background(palette.bgSunken).padding(horizontal = 16.dp, vertical = 10.dp),
)
}
Lines(text, show.line)
}
}
/**
* A file as numbered lines, opened at the line the card named. The number column's width is
* measured, not guessed: it is the width of the longest number in this file, so every line's
* text starts at the same x whatever its number, and a wrapped line continues under its own
* text rather than under the numbers.
*/
@Composable
private fun Lines(text: String, line: Int) {
val palette = LocalPalette.current
val rows = remember(text) {
val split = text.split('\n')
if (split.size > 1 && split.last().isEmpty()) split.dropLast(1) else split
}
val style = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 13.sp, lineHeight = 18.sp, color = palette.ink)
val measurer = rememberTextMeasurer()
val density = LocalDensity.current
val gutter = remember(rows.size, density) {
with(density) { measurer.measure("9".repeat(rows.size.toString().length), style).size.width.toDp() }
}
val state = rememberLazyListState(initialFirstVisibleItemIndex = (line - 1).coerceIn(0, (rows.size - 1).coerceAtLeast(0)))
LazyColumn(
state = state,
modifier = Modifier.fillMaxSize().background(palette.codeBg),
contentPadding = PaddingValues(vertical = 8.dp),
) {
itemsIndexed(rows) { i, row ->
val here = line > 0 && i == line - 1
Row(
Modifier
.fillMaxWidth()
.then(if (here) Modifier.background(palette.accentSoft) else Modifier)
.padding(horizontal = 12.dp),
) {
Text((i + 1).toString(), style = style.copy(color = palette.inkFaint), textAlign = TextAlign.End, modifier = Modifier.width(gutter))
Spacer(Modifier.width(12.dp))
Text(row.ifEmpty { " " }, style = style, modifier = Modifier.weight(1f))
}
}
}
}
private 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) {
val uri = Uri.parse(url)
if (uri.scheme?.lowercase() !in setOf("http", "https")) return
runCatching { CustomTabsIntent.Builder().build().launchUrl(context, uri) }
}