android: library covers load through Coil, keyed by cover_key
Build Debug APK / build (push) Failing after 2m35s
Build Debug APK / build (push) Failing after 2m35s
Comics, music and PDF cards name their cover as a DocumentCover; one Fetcher reads it through the FFI (MuPDF renders a PDF's first page at the requested size) and a Keyer caches it under the lib's cover_key, registered app-wide by a new SynchronicityApplication. The per-screen thumbnail maps and decode loops are gone, and a cover that changes through sync is no longer held stale for as long as the screen is open. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WsxkM2ja42H2h5BPRexf2r
This commit is contained in:
1 parent
2e394cadc0
commit
9851aed695
10 files changed
+200
-137
No files matched your search
@@ -389,17 +389,6 @@ since it isn't worth taking before it shows up in a profile.
|
||||
|
||||
## Android/Kotlin Improvements
|
||||
|
||||
### Load document covers through a Coil fetcher
|
||||
- **Description**: Comics, music and PDF thumbnails are hand-rolled — per-agent thumbnail
|
||||
maps with IO decode loops (`ComicRepository`, `MusicRepository`, `ComicLibraryScreen`,
|
||||
`PdfLibraryScreen`) over `ui/ImageDecoding.decodeSampledImage`. A Coil `Fetcher`/`Keyer`
|
||||
for a document-blob model would give them downsampling, a memory cache and off-main
|
||||
loading, and `MediaItem` could carry the model for an `AsyncImage`; PDF covers want their
|
||||
own MuPDF fetcher. Podcasts already go through Coil (`PodcastCover`).
|
||||
- **The catch is the cache key**: it must include the blob hash, or a cover that changes
|
||||
through sync keeps showing the old one. Do it when it can be checked on a device, with a
|
||||
cover changing on another node while the library is open.
|
||||
|
||||
### Investigate whether mainline DHT lookups are silently blocked on the Android emulator
|
||||
- **More urgent, and probably broader than DNS** (logcat from an emulated node, 2026-08-25,
|
||||
during a sync that took minutes for ~20 tiny documents):
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
|
||||
<application
|
||||
android:name=".SynchronicityApplication"
|
||||
android:allowBackup="true"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:enableOnBackInvokedCallback="true"
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.gregshuflin.synchronicity
|
||||
|
||||
import android.app.Application
|
||||
import coil.ImageLoader
|
||||
import coil.ImageLoaderFactory
|
||||
import com.gregshuflin.synchronicity.covers.DocumentCover
|
||||
import com.gregshuflin.synchronicity.covers.DocumentCoverFetcher
|
||||
import com.gregshuflin.synchronicity.covers.DocumentCoverKeyer
|
||||
|
||||
/**
|
||||
* Exists to give Coil one app-wide [ImageLoader] that knows how to load a [DocumentCover], so the
|
||||
* library screens' covers share one memory cache with each other and with the podcast art.
|
||||
*/
|
||||
class SynchronicityApplication : Application(), ImageLoaderFactory {
|
||||
override fun newImageLoader(): ImageLoader =
|
||||
ImageLoader.Builder(this)
|
||||
.components {
|
||||
add(DocumentCoverKeyer())
|
||||
add(DocumentCoverFetcher.Factory())
|
||||
}
|
||||
.build()
|
||||
}
|
||||
+2
-20
@@ -8,14 +8,11 @@ import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshots.SnapshotStateMap
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.gregshuflin.synchronicity.ui.ImportFileButton
|
||||
@@ -35,9 +32,6 @@ import uniffi.synchronicity.libraryNoMatch
|
||||
|
||||
private const val TAG = "ComicLibraryScreen"
|
||||
|
||||
/** Longest edge, in pixels, of a decoded cover thumbnail. */
|
||||
private const val COVER_MAX_EDGE = 480
|
||||
|
||||
// Tab ids for the comics library bar — mirrors the desktop `ComicsView`'s constants of the
|
||||
// same names.
|
||||
private const val COMICS_TAB_LIBRARY = "library"
|
||||
@@ -73,7 +67,6 @@ fun ComicLibraryScreen(
|
||||
var searchQuery by remember { mutableStateOf("") }
|
||||
var inProgress by remember { mutableStateOf(false) }
|
||||
var inProgressEntries by remember { mutableStateOf<List<ComicInProgress>>(emptyList()) }
|
||||
val thumbnails: SnapshotStateMap<String, ImageBitmap> = remember { mutableStateMapOf() }
|
||||
|
||||
LaunchedEffect(reloadKey) {
|
||||
val loaded = repository.loadShelf() ?: return@LaunchedEffect
|
||||
@@ -84,17 +77,6 @@ fun ComicLibraryScreen(
|
||||
if (inProgress) inProgressEntries = repository.inProgress(loaded)
|
||||
}
|
||||
|
||||
// Stream cover thumbnails in as each decodes, mirroring the desktop's background cover loader.
|
||||
LaunchedEffect(shelf) {
|
||||
val current = shelf ?: return@LaunchedEffect
|
||||
for (node in nodes.filter { it.id !in thumbnails }) {
|
||||
val coverId = current.coverComic(node.id)
|
||||
if (coverId != null) {
|
||||
repository.loadCover(coverId, COVER_MAX_EDGE)?.let { thumbnails[node.id] = it }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Filtering the already-built item list keeps the search working the same way on
|
||||
// every tab and at every drill-in level, without a second query path.
|
||||
val query = searchQuery.trim()
|
||||
@@ -114,7 +96,7 @@ fun ComicLibraryScreen(
|
||||
id = entry.id,
|
||||
title = entry.title,
|
||||
subtitle = entry.subtitle,
|
||||
thumbnail = thumbnails[entry.id],
|
||||
cover = shelf?.coverOf(entry.id),
|
||||
availability = entry.availability,
|
||||
// Unconditional, for the reason [toMediaItem] gives: an issue
|
||||
// that hasn't synced here still opens and streams.
|
||||
@@ -123,7 +105,7 @@ fun ComicLibraryScreen(
|
||||
)
|
||||
}
|
||||
} else {
|
||||
level.map { (node, subtitle) -> toMediaItem(node, subtitle, thumbnails[node.id]) }
|
||||
level.map { (node, subtitle) -> toMediaItem(node, subtitle, shelf?.coverOf(node.id)) }
|
||||
}
|
||||
val items = unfiltered.filter { it.title.contains(query, ignoreCase = true) }
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import android.util.LruCache
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import com.gregshuflin.synchronicity.NativeLib
|
||||
import com.gregshuflin.synchronicity.covers.DocumentCover
|
||||
import com.gregshuflin.synchronicity.getOrLog
|
||||
import com.gregshuflin.synchronicity.importPickedFile
|
||||
import com.gregshuflin.synchronicity.ui.MediaItem
|
||||
@@ -96,18 +97,6 @@ class ComicRepository {
|
||||
NativeLib.ffi { comics().shelf() }.getOrLog(TAG, "Failed to load the comics library")
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a node's cover thumbnail (first page of the comic, or of a collection's first issue).
|
||||
*/
|
||||
suspend fun loadCover(comicId: String, maxEdgePx: Int): ImageBitmap? =
|
||||
withContext(Dispatchers.IO) {
|
||||
val bytes =
|
||||
NativeLib.ffi { comics().getCoverBytes(comicId) }
|
||||
.getOrLog(TAG, "Cover not available for comic $comicId")
|
||||
?: return@withContext null
|
||||
decodeSampledImage(bytes, maxEdgePx)?.asImageBitmap()
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a comic for reading: its ordered page ids and resume page. Records the comic as its
|
||||
* parent series' latest-read child (best-effort) so "continue reading" surfaces it. Null if the
|
||||
@@ -249,13 +238,20 @@ fun spatialRightTarget(direction: ReadingDirection, page: Int, total: Int): Int?
|
||||
ReadingDirection.RIGHT_TO_LEFT -> (page - 1).takeIf { it >= 0 }
|
||||
}
|
||||
|
||||
/** Project a [ComicTreeItem] into a [MediaItem], under [subtitle] (`ComicShelf.subtitle`). */
|
||||
fun toMediaItem(node: ComicTreeItem, subtitle: String, thumbnail: ImageBitmap?): MediaItem =
|
||||
/** [id]'s card cover as Coil loads it, or null while there is none to draw here. */
|
||||
fun ComicShelf.coverOf(id: String): DocumentCover? =
|
||||
cover(id)?.let { DocumentCover.Comic(it.comic, it.key) }
|
||||
|
||||
/**
|
||||
* Project a [ComicTreeItem] into a [MediaItem], under [subtitle] (`ComicShelf.subtitle`) and with
|
||||
* [cover] (`ComicShelf.cover`).
|
||||
*/
|
||||
fun toMediaItem(node: ComicTreeItem, subtitle: String, cover: DocumentCover?): MediaItem =
|
||||
MediaItem(
|
||||
id = node.id,
|
||||
title = node.title,
|
||||
subtitle = subtitle,
|
||||
thumbnail = thumbnail,
|
||||
cover = cover,
|
||||
availability = node.availability,
|
||||
// A comic that isn't downloaded still opens — the reader falls back to streaming
|
||||
// each page off whichever peer holds it (ADR 0016) — so the availability marker
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.gregshuflin.synchronicity.covers
|
||||
|
||||
import android.graphics.drawable.BitmapDrawable
|
||||
import coil.ImageLoader
|
||||
import coil.decode.DataSource
|
||||
import coil.decode.ImageSource
|
||||
import coil.fetch.DrawableResult
|
||||
import coil.fetch.FetchResult
|
||||
import coil.fetch.Fetcher
|
||||
import coil.fetch.SourceResult
|
||||
import coil.key.Keyer
|
||||
import coil.request.Options
|
||||
import coil.size.Dimension
|
||||
import com.gregshuflin.synchronicity.NativeLib
|
||||
import com.gregshuflin.synchronicity.getOrLog
|
||||
import com.gregshuflin.synchronicity.pdfs.renderPdfCover
|
||||
import java.io.IOException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import okio.Buffer
|
||||
import uniffi.synchronicity.LibraryEntryKind
|
||||
|
||||
private const val TAG = "DocumentCover"
|
||||
|
||||
/** Longest edge a PDF cover is rendered at when the request carries no size of its own. */
|
||||
private const val PDF_COVER_FALLBACK_EDGE = 320f
|
||||
|
||||
/**
|
||||
* A library card's cover, as Coil loads and caches it.
|
||||
*
|
||||
* [key] is the Rust side's `cover_key`: the hashes of the blobs the cover is drawn from, present
|
||||
* only while they are stored here. The cache is keyed on it rather than on the document id, so a
|
||||
* cover that changes through sync arrives with a new key instead of drawing the old picture out of
|
||||
* the cache. A card with no key has no cover to ask for; the reload that follows its bytes arriving
|
||||
* finds one, and the card asks then.
|
||||
*/
|
||||
sealed interface DocumentCover {
|
||||
val key: String
|
||||
|
||||
/** A comic's or a series' card: the first page of [comic]. */
|
||||
data class Comic(val comic: String, override val key: String) : DocumentCover
|
||||
|
||||
/** An album's cover, or an artist's portrait or mosaic. */
|
||||
data class MusicArt(val entry: String, val kind: LibraryEntryKind, override val key: String) :
|
||||
DocumentCover
|
||||
|
||||
/** A PDF's first page, rendered. */
|
||||
data class Pdf(val document: String, override val key: String) : DocumentCover
|
||||
}
|
||||
|
||||
/**
|
||||
* Caches a cover under its kind and [DocumentCover.key]. Coil asks for a key on the main thread,
|
||||
* which is why the key comes in the model rather than being looked up here.
|
||||
*/
|
||||
class DocumentCoverKeyer : Keyer<DocumentCover> {
|
||||
override fun key(data: DocumentCover, options: Options): String =
|
||||
"${data::class.simpleName}:${data.key}"
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a cover's bytes through the FFI and leaves decoding and downsampling to Coil — except a
|
||||
* PDF's, which MuPDF renders at the size the request asks for.
|
||||
*
|
||||
* Local bytes only: the key promised they are here, and a library of covers is not worth a peer
|
||||
* fetch each. Bytes that went missing since are an error, which draws the card's placeholder.
|
||||
*/
|
||||
class DocumentCoverFetcher(private val cover: DocumentCover, private val options: Options) :
|
||||
Fetcher {
|
||||
override suspend fun fetch(): FetchResult =
|
||||
withContext(Dispatchers.IO) {
|
||||
when (cover) {
|
||||
is DocumentCover.Comic ->
|
||||
encoded(
|
||||
NativeLib.ffi { comics().getCoverBytes(cover.comic) }
|
||||
.getOrLog(TAG, "Cover not available for comic ${cover.comic}")
|
||||
)
|
||||
is DocumentCover.MusicArt ->
|
||||
encoded(
|
||||
NativeLib.ffi { music().entryArt(cover.entry, cover.kind) }
|
||||
.getOrLog(TAG, "Art not available for ${cover.entry}")
|
||||
)
|
||||
is DocumentCover.Pdf -> {
|
||||
val bitmap =
|
||||
renderPdfCover(options.context, cover.document, longestEdge())
|
||||
?: throw CoverNotHere(cover)
|
||||
DrawableResult(
|
||||
drawable = BitmapDrawable(options.context.resources, bitmap),
|
||||
isSampled = true,
|
||||
dataSource = DataSource.DISK,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun encoded(bytes: ByteArray?): FetchResult =
|
||||
SourceResult(
|
||||
source =
|
||||
ImageSource(Buffer().write(bytes ?: throw CoverNotHere(cover)), options.context),
|
||||
mimeType = null,
|
||||
dataSource = DataSource.DISK,
|
||||
)
|
||||
|
||||
private fun longestEdge(): Float =
|
||||
listOf(options.size.width, options.size.height)
|
||||
.mapNotNull { (it as? Dimension.Pixels)?.px }
|
||||
.maxOrNull()
|
||||
?.toFloat() ?: PDF_COVER_FALLBACK_EDGE
|
||||
|
||||
class Factory : Fetcher.Factory<DocumentCover> {
|
||||
override fun create(data: DocumentCover, options: Options, imageLoader: ImageLoader) =
|
||||
DocumentCoverFetcher(data, options)
|
||||
}
|
||||
}
|
||||
|
||||
/** A cover whose bytes were not here after all. */
|
||||
private class CoverNotHere(cover: DocumentCover) : IOException("No local bytes for $cover")
|
||||
@@ -3,12 +3,10 @@ package com.gregshuflin.synchronicity.music
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import com.gregshuflin.synchronicity.NativeLib
|
||||
import com.gregshuflin.synchronicity.covers.DocumentCover
|
||||
import com.gregshuflin.synchronicity.getOrLog
|
||||
import com.gregshuflin.synchronicity.ui.MediaItem
|
||||
import com.gregshuflin.synchronicity.ui.decodeSampledImage
|
||||
import java.io.File
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -31,17 +29,6 @@ class MusicRepository {
|
||||
NativeLib.ffi { music().listLibrary(level) }.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
/**
|
||||
* Art for one library row that reported [LibraryEntry.hasCover]: an album's own cover, or the
|
||||
* portrait/mosaic derived for an artist. Null when there is nothing to draw, which is a
|
||||
* placeholder glyph rather than an error.
|
||||
*/
|
||||
suspend fun loadEntryArt(entry: LibraryEntry, maxEdgePx: Int): ImageBitmap? =
|
||||
withContext(Dispatchers.IO) {
|
||||
val bytes = NativeLib.ffi { music().entryArt(entry.id, entry.kind) }.getOrNull()
|
||||
bytes?.let { decodeSampledImage(it, maxEdgePx)?.asImageBitmap() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuild the tag-derived library from the tracks held on this node. Long enough to be a
|
||||
* tracked Job on the Rust side — it parses every not-yet-scanned audio blob — so the caller
|
||||
@@ -119,12 +106,12 @@ fun toMediaItem(node: LibraryTreeItem): MediaItem =
|
||||
* The subtitle is taken as composed ("4 albums", "1998 · 11 tracks", "3:42") rather than rebuilt
|
||||
* here, so an artist reads the same on the phone as it does on the desktop and in the CLI.
|
||||
*/
|
||||
fun toMediaItem(entry: LibraryEntry, thumbnail: ImageBitmap?): MediaItem =
|
||||
fun toMediaItem(entry: LibraryEntry): MediaItem =
|
||||
MediaItem(
|
||||
id = entry.id,
|
||||
title = entry.title,
|
||||
subtitle = entry.subtitle,
|
||||
thumbnail = thumbnail,
|
||||
cover = entry.coverKey?.let { DocumentCover.MusicArt(entry.id, entry.kind, it) },
|
||||
availability = entry.availability,
|
||||
// Always activatable, like the folder tree: an artist or album opens, and a track
|
||||
// whose audio is on a peer is dimmed but still streams.
|
||||
|
||||
@@ -17,14 +17,11 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshots.SnapshotStateMap
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.gregshuflin.synchronicity.jobs.rememberJobControl
|
||||
@@ -68,9 +65,6 @@ private const val TAG = "MusicScreen"
|
||||
private val MUSIC_PLAYER =
|
||||
PlayerCapabilities(back = TransportStep.Adjacent, forward = TransportStep.Adjacent)
|
||||
|
||||
/** Longest edge, in pixels, of a decoded album cover or artist mosaic. */
|
||||
private const val ART_MAX_EDGE = 480
|
||||
|
||||
/** Size of the spinner that stands in for the rebuild action while a build runs. */
|
||||
private val REBUILD_SPINNER_SIZE = 24.dp
|
||||
|
||||
@@ -117,10 +111,6 @@ fun MusicScreen(onBack: () -> Unit, modifier: Modifier = Modifier) {
|
||||
var path by remember { mutableStateOf<List<Pair<String, String>>>(emptyList()) }
|
||||
// The Library tab's own drill-in stack, at most two deep: an artist, then one of its albums.
|
||||
var libraryPath by remember { mutableStateOf<List<Pair<String, String>>>(emptyList()) }
|
||||
// Decoded album covers and artist mosaics, keyed by row id. Kept across drill-in/out so
|
||||
// walking back up a level doesn't re-decode a level already seen; a build clears it, since
|
||||
// that is the one thing that changes what a row's art should be.
|
||||
val art: SnapshotStateMap<String, ImageBitmap> = remember { mutableStateMapOf() }
|
||||
var foldersActive by remember { mutableStateOf(false) }
|
||||
var searchQuery by remember { mutableStateOf("") }
|
||||
var selectedTrack by remember { mutableStateOf<MusicTrack?>(null) }
|
||||
@@ -153,14 +143,6 @@ fun MusicScreen(onBack: () -> Unit, modifier: Modifier = Modifier) {
|
||||
libraryRows = repository.loadLibrary(libraryLevelOf(libraryPath))
|
||||
}
|
||||
|
||||
// Art streams in row by row as each decodes, so a level with forty albums draws its titles
|
||||
// immediately rather than waiting on the slowest cover.
|
||||
LaunchedEffect(libraryRows) {
|
||||
for (entry in libraryRows.filter { it.hasCover && it.id !in art }) {
|
||||
repository.loadEntryArt(entry, ART_MAX_EDGE)?.let { art[entry.id] = it }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Select [track] and get its audio onto the transport. [autoplay] starts it as well, which is
|
||||
* what a Previous/Next during playback wants and what a tap on a library row does not — a
|
||||
@@ -219,7 +201,6 @@ fun MusicScreen(onBack: () -> Unit, modifier: Modifier = Modifier) {
|
||||
buildStarting = false
|
||||
}
|
||||
libraryPath = emptyList()
|
||||
art.clear()
|
||||
reloadKey += 1
|
||||
Toast.makeText(context, libraryBuildSummary(summary), Toast.LENGTH_LONG).show()
|
||||
}
|
||||
@@ -230,7 +211,7 @@ fun MusicScreen(onBack: () -> Unit, modifier: Modifier = Modifier) {
|
||||
val query = searchQuery.trim()
|
||||
val level =
|
||||
if (foldersActive) childrenOf(nodes, path.lastOrNull()?.first).map { toMediaItem(it) }
|
||||
else libraryRows.map { toMediaItem(it, art[it.id]) }
|
||||
else libraryRows.map { toMediaItem(it) }
|
||||
val items = level.filter { it.title.contains(query, ignoreCase = true) }
|
||||
|
||||
SubAppScreen(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.gregshuflin.synchronicity.pdfs
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.util.Log
|
||||
import android.widget.Toast
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -15,7 +16,6 @@ import androidx.compose.material3.Surface
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
@@ -23,11 +23,10 @@ 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.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.gregshuflin.synchronicity.NativeLib
|
||||
import com.gregshuflin.synchronicity.covers.DocumentCover
|
||||
import com.gregshuflin.synchronicity.importPickedFile
|
||||
import com.gregshuflin.synchronicity.rememberReloadKey
|
||||
import com.gregshuflin.synchronicity.ui.ImportFileButton
|
||||
@@ -53,9 +52,6 @@ import uniffi.synchronicity.libraryNoMatch
|
||||
|
||||
private const val TAG = "PdfLibraryScreen"
|
||||
|
||||
/** Longest edge, in pixels, of a rendered cover thumbnail. */
|
||||
private const val THUMB_MAX_DIM = 320f
|
||||
|
||||
/** Names the cache files [materializePdf] writes, so it can sweep its own leftovers. */
|
||||
private const val OPEN_CACHE_PREFIX = "open-"
|
||||
|
||||
@@ -70,9 +66,6 @@ fun PdfLibraryScreen(
|
||||
val snackbar = LocalSnackbarController.current
|
||||
val fetchStrings = rememberContentFetchStrings()
|
||||
var pdfDocuments by remember { mutableStateOf<List<PdfListItem>>(emptyList()) }
|
||||
// Cover thumbnails stream in on a background dispatcher, keyed by document
|
||||
// id; the MediaLibrary falls back to a PDF glyph for any not yet rendered.
|
||||
val thumbnails = remember { mutableStateMapOf<String, ImageBitmap>() }
|
||||
var refreshTrigger by rememberReloadKey(ChangeChannel.DOCUMENTS)
|
||||
// Saveable so a rotation (or a trip into the viewer and back) doesn't
|
||||
// silently widen the list back out from under whatever the user was
|
||||
@@ -102,18 +95,8 @@ fun PdfLibraryScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// Render the first page of each PDF into a cover, mirroring the desktop
|
||||
// comics/PDF agents' "decode covers on a background executor" approach.
|
||||
LaunchedEffect(pdfDocuments) {
|
||||
for (doc in pdfDocuments) {
|
||||
if (doc.id in thumbnails) continue
|
||||
renderPdfCover(context, doc.id)?.let { thumbnails[doc.id] = it }
|
||||
}
|
||||
}
|
||||
|
||||
// Narrowing is live and purely local: it filters the already-loaded list by
|
||||
// title rather than re-querying, so it costs nothing per keystroke. Covers
|
||||
// still decode for the whole library above, not just what's showing.
|
||||
// title rather than re-querying, so it costs nothing per keystroke.
|
||||
val query = searchQuery.trim()
|
||||
val items =
|
||||
pdfDocuments
|
||||
@@ -123,7 +106,7 @@ fun PdfLibraryScreen(
|
||||
id = doc.id,
|
||||
title = doc.title,
|
||||
subtitle = doc.subtitle,
|
||||
thumbnail = thumbnails[doc.id],
|
||||
cover = doc.coverKey?.let { DocumentCover.Pdf(doc.id, it) },
|
||||
availability = doc.availability,
|
||||
)
|
||||
}
|
||||
@@ -272,8 +255,10 @@ private suspend fun materializePdf(context: Context, id: String): Result<String>
|
||||
private data class OpenFailure(val id: String, val name: String, val reason: String)
|
||||
|
||||
/**
|
||||
* Render a document's first page into a small cover [ImageBitmap], or null if its blob is missing
|
||||
* or can't be decoded (the MediaLibrary then shows its placeholder glyph instead).
|
||||
* Render a document's first page into a cover no larger than [maxDimensionPx] on its longest edge,
|
||||
* or null if its blob is missing or can't be decoded — for the cover fetcher
|
||||
* ([com.gregshuflin.synchronicity.covers.DocumentCoverFetcher]), whose failure the MediaLibrary
|
||||
* draws as its placeholder glyph.
|
||||
*
|
||||
* Via a cache file rather than a `ByteArray`. Reading the blob into the heap to rasterize one page
|
||||
* is what made a large PDF crash the library screen outright — a 271 MB document cannot be
|
||||
@@ -285,18 +270,19 @@ private data class OpenFailure(val id: String, val name: String, val reason: Str
|
||||
* library of covers is not worth a fetch each — so a document whose bytes are elsewhere is skipped
|
||||
* before it can start one.
|
||||
*/
|
||||
private suspend fun renderPdfCover(context: Context, id: String): ImageBitmap? =
|
||||
internal suspend fun renderPdfCover(context: Context, id: String, maxDimensionPx: Float): Bitmap? =
|
||||
withContext(Dispatchers.IO) {
|
||||
if (!NativeLib.ffi { documents().isBlobLocal(id) }.getOrDefault(false))
|
||||
return@withContext null
|
||||
val cacheFile = File(context.cacheDir, "cover-$id.pdf")
|
||||
// A file of its own per render: the grid and the list can ask for the same cover at once.
|
||||
val cacheFile = File.createTempFile("cover-", ".pdf", context.cacheDir)
|
||||
@Suppress("TooGenericExceptionCaught")
|
||||
try {
|
||||
if (NativeLib.ffi { pdf().writeToPath(id, cacheFile.absolutePath) }.isFailure) {
|
||||
return@withContext null
|
||||
}
|
||||
MuPdfDocument.openFromPath(cacheFile.absolutePath).use { doc ->
|
||||
doc.renderPage(pageIndex = 0, maxDimensionPx = THUMB_MAX_DIM).asImageBitmap()
|
||||
doc.renderPage(pageIndex = 0, maxDimensionPx = maxDimensionPx)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to render cover for $id", e)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.gregshuflin.synchronicity.ui
|
||||
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -42,13 +41,14 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import coil.compose.AsyncImage
|
||||
import com.gregshuflin.synchronicity.covers.DocumentCover
|
||||
import uniffi.synchronicity.DocumentAvailability
|
||||
|
||||
/**
|
||||
@@ -60,9 +60,8 @@ import uniffi.synchronicity.DocumentAvailability
|
||||
* It is deliberately API-compatible with the desktop component in terms of how the rest of
|
||||
* Synchronicity feeds and reacts to it, so an agent screen (comics, PDFs, …) can be built the same
|
||||
* way on both platforms:
|
||||
* - **Feed it [MediaItem]s.** The consumer owns the model and decodes cover thumbnails on its own
|
||||
* background dispatcher, streaming them in by updating the [items] list (the Compose equivalent
|
||||
* of the desktop `set_thumbnail`).
|
||||
* - **Feed it [MediaItem]s.** The consumer owns the model, and names each cover as a
|
||||
* [DocumentCover] that Coil loads, downsamples and caches as the card comes on screen.
|
||||
* - **React to a tap** via [onItemActivate], which carries the item's [MediaItem.id] — mirroring
|
||||
* the desktop `ItemActivated` event.
|
||||
* - **Declare its own tabs** with [tabs] (mirroring the desktop's consumer-defined `set_tabs`) and
|
||||
@@ -115,9 +114,8 @@ private const val DIM_UNAVAILABLE = 0.5f
|
||||
private val CARD_RULE_INSET = 2.dp
|
||||
|
||||
/**
|
||||
* One browsable entry in the library. The cover [thumbnail] is supplied already decoded (agents
|
||||
* load and downscale covers on their own background dispatcher); a missing one falls back to a
|
||||
* glyph placeholder.
|
||||
* One browsable entry in the library. [cover] names its cover for Coil to load; a missing one, or
|
||||
* one that fails, falls back to a glyph placeholder.
|
||||
*/
|
||||
data class MediaItem(
|
||||
/** Stable id echoed back to [onItemActivate] when the item is tapped. */
|
||||
@@ -125,7 +123,7 @@ data class MediaItem(
|
||||
val title: String,
|
||||
/** Secondary line (page count, author, …). Empty hides it. */
|
||||
val subtitle: String = "",
|
||||
val thumbnail: ImageBitmap? = null,
|
||||
val cover: DocumentCover? = null,
|
||||
/**
|
||||
* Where the underlying content can be read from. Drives dimming and the corner marker only,
|
||||
* never tappability — see [activatable].
|
||||
@@ -549,11 +547,6 @@ private fun MediaRow(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An item's cover: its decoded thumbnail scaled to fill, or a centered glyph placeholder of
|
||||
* [glyphSize] when no cover has loaded — a folder for a sub-collection (e.g. a manga series/volume
|
||||
* with no cached cover yet), the consumer's own [placeholderIcon] for a leaf item.
|
||||
*/
|
||||
/**
|
||||
* Dimming factor for a whole card/row, mirroring the desktop's `dimming` so the same content reads
|
||||
* the same on both modalities.
|
||||
@@ -565,23 +558,33 @@ private fun dimming(availability: DocumentAvailability): Float =
|
||||
DocumentAvailability.UNAVAILABLE -> DIM_UNAVAILABLE
|
||||
}
|
||||
|
||||
/**
|
||||
* An item's cover scaled to fill, over a centered glyph placeholder of [glyphSize] shown until it
|
||||
* loads, and instead of it when there is none or it fails — a folder for a sub-collection (e.g. a
|
||||
* manga series/volume with no cover here yet), the consumer's own [placeholderIcon] for a leaf
|
||||
* item.
|
||||
*/
|
||||
@Composable
|
||||
private fun CoverArt(item: MediaItem, placeholderIcon: ImageVector, glyphSize: Dp) {
|
||||
val thumbnail = item.thumbnail
|
||||
if (thumbnail != null) {
|
||||
Image(
|
||||
bitmap = thumbnail,
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
} else {
|
||||
Icon(
|
||||
imageVector = if (item.isCollection) Icons.Default.Folder else placeholderIcon,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(glyphSize),
|
||||
)
|
||||
var loaded by remember(item.cover) { mutableStateOf(false) }
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
if (!loaded) {
|
||||
Icon(
|
||||
imageVector = if (item.isCollection) Icons.Default.Folder else placeholderIcon,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(glyphSize),
|
||||
)
|
||||
}
|
||||
if (item.cover != null) {
|
||||
AsyncImage(
|
||||
model = item.cover,
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
onSuccess = { loaded = true },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user