Yokan / rebuild
Course 1 8624561

ReaderImageRequests.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderImageRequests.kt

implementation176 lines
1package eu.friedcutlet.yokan.ui.screens.reader23import androidx.compose.foundation.lazy.items4import androidx.compose.runtime.Composable5import androidx.compose.runtime.LaunchedEffect6import kotlinx.coroutines.coroutineScope7import kotlinx.coroutines.launch8import kotlinx.coroutines.CancellationException9import kotlinx.coroutines.channels.Channel10import coil3.Extras11import coil3.getExtra12import coil3.SingletonImageLoader13import coil3.compose.LocalPlatformContext14import coil3.network.NetworkHeaders15import coil3.network.httpHeaders16import coil3.request.ImageRequest17import coil3.request.CachePolicy18import coil3.intercept.Interceptor19import coil3.request.transformations20import eu.friedcutlet.yokan.database.DbPageUrl21import kotlinx.coroutines.sync.Semaphore22import kotlinx.coroutines.sync.withPermit2324/**25 * Starts a cancellable Coil prefetch session for the current reader position.26 *27 * Requests are processed in authority order with the same three-worker bound28 * as Mangayomi. This prevents a large preload window from becoming a burst of29 * simultaneous HTTP requests while still keeping the configured cache warm.30 */31@Composable32internal fun ReaderPagePrefetch(33    items: List<ReaderStreamItem>,34    currentStreamIndex: Int,35    forwardAmount: Int,36    layoutSampleKey: String = "",37    sampleChapterId: Long? = null,38    onShapeSampled: (String, ReaderPageIdentity, ReaderPageShape?) -> Unit = { _, _, _ -> },39) {40    if (items.isEmpty()) return41    val context = LocalPlatformContext.current42    LaunchedEffect(currentStreamIndex, items, forwardAmount, layoutSampleKey, sampleChapterId) {43        val loader = SingletonImageLoader.get(context)44        loadReaderPagesBounded(45            pages = (readerPrefetchPageItems(46                items = items,47                currentStreamIndex = currentStreamIndex,48                forwardAmount = forwardAmount,49            ) + items.filterIsInstance<ReaderStreamItem.Page>().filter { it.chapter.id == sampleChapterId && it.split != ReaderPageHalf.Second }50                .take(AUTOMATIC_LAYOUT_SAMPLE_COUNT)).distinctBy { it.identity() },51        ) { pageItem ->52            try {53                // Warm only the disk/network caches: a target-less request decodes at original size54                // without the visible page's transformations, so its bitmap would just evict usable ones.55                val result = loader.execute(56                    ImageRequest.Builder(context)57                        .readerPageData(pageItem.page, pageItem.chapter.id)58                        .memoryCachePolicy(CachePolicy.DISABLED)59                        .build(),60                )61                val shape = (result as? coil3.request.SuccessResult)?.image?.let { ReaderPageShape(it.width, it.height) }62                onShapeSampled(layoutSampleKey, pageItem.identity(), shape)63            } catch (cancelled: CancellationException) {64                throw cancelled65            } catch (_: Throwable) {66                onShapeSampled(layoutSampleKey, pageItem.identity(), null)67                // Prefetch failures are rendered and retried by the visible page.68            }69        }70    }71}7273internal const val READER_PREFETCH_CONCURRENCY = 37475private val ReaderPageRequestExtra = Extras.Key(default = false)7677internal class ReaderImageRequestLimiter(78    maxConcurrent: Int = READER_PREFETCH_CONCURRENCY,79) : Interceptor {80    private val semaphore = Semaphore(maxConcurrent)8182    override suspend fun intercept(chain: Interceptor.Chain) =83        if (chain.request.getExtra(ReaderPageRequestExtra)) {84            limit { chain.proceed() }85        } else {86            chain.proceed()87        }8889    internal suspend fun <T> limit(block: suspend () -> T): T = semaphore.withPermit { block() }90}9192internal val ReaderPageRequestLimiter = ReaderImageRequestLimiter()9394internal suspend fun <T> loadReaderPagesBounded(95    pages: List<T>,96    maxConcurrent: Int = READER_PREFETCH_CONCURRENCY,97    load: suspend (T) -> Unit,98) {99    require(maxConcurrent > 0)100    if (pages.isEmpty()) return101    coroutineScope {102        val queue = Channel<T>(Channel.UNLIMITED)103        pages.forEach { queue.trySend(it) }104        queue.close()105        repeat(minOf(maxConcurrent, pages.size)) {106            launch {107                for (page in queue) load(page)108            }109        }110    }111}112113internal fun chapterPageCacheKey(114    chapterId: Long?,115    url: String,116    headers: Map<String, String>? = null,117): String {118    val prefix = if (chapterId != null && chapterId > 0L) "ch_${chapterId}_" else ""119    val headerSuffix = headers?.takeIf { it.isNotEmpty() }?.let { "#readerHeaders=${readerPageHeaderFingerprint(it)}" } ?: ""120    return "$prefix$url$headerSuffix"121}122123/** Explicit memory keys ignore transformations; every processing variant adds its own key extra. */124internal fun ImageRequest.Builder.applyReaderPageProcessing(processing: ReaderPageProcessing): ImageRequest.Builder = apply {125    val steps = ArrayList<coil3.transform.Transformation>(3)126    if (processing.cropBorders) {127        steps += createBorderCropTransformation()128        memoryCacheKeyExtra("borderCrop", "true")129    }130    processing.leftHalf?.let { left ->131        steps += createPageHalfTransformation(left)132        memoryCacheKeyExtra("pageHalf", if (left) "left" else "right")133    }134    if (processing.rotation != 0) {135        steps += createWidePageRotation(processing.rotation)136        memoryCacheKeyExtra("rotateWide", processing.rotation.toString())137    }138    if (steps.isNotEmpty()) transformations(steps)139}140141internal fun ImageRequest.Builder.readerPageData(142    page: DbPageUrl,143    chapterId: Long? = null,144    revision: Long = 0L,145): ImageRequest.Builder = apply {146    data(page.url)147    extras[ReaderPageRequestExtra] = true148    extras[eu.friedcutlet.yokan.ui.image.ImageChapterIdExtra] = chapterId149    val headers = page.headers.orEmpty()150    val cacheKey = chapterPageCacheKey(chapterId, page.url, headers.takeIf { it.isNotEmpty() }) + "#revision=$revision"151    memoryCacheKey(cacheKey)152    diskCacheKey(cacheKey)153    if (headers.isNotEmpty()) {154        val networkHeaders = NetworkHeaders.Builder().apply {155            headers.forEach { (name, value) -> set(name, value) }156        }.build()157        httpHeaders(networkHeaders)158    }159}160161internal fun readerPageHeaderFingerprint(headers: Map<String, String>): String {162    var hash = 14695981039346656037uL163    headers.entries164        .sortedWith(compareBy({ it.key.lowercase() }, { it.key }, { it.value }))165        .forEach { (name, value) ->166            for (character in name.lowercase()) {167                hash = (hash xor character.code.toULong()) * 1099511628211uL168            }169            hash = (hash xor 0uL) * 1099511628211uL170            for (character in value) {171                hash = (hash xor character.code.toULong()) * 1099511628211uL172            }173            hash = (hash xor 0xFFuL) * 1099511628211uL174        }175    return hash.toString(16)176}177

Search chapters, reference and source filenames.