Prerequisites: chapter sequence, image pipeline, downloads and profile ownership. File workbook.
How to write this chapter
Build a manga reader whose page streams, gestures and progress remain tied to the captured chapter/profile. Add processing only after navigation, layout and cleanup behave correctly.
The 72 assigned entries are integrated below at their implementation steps. Every text listing is complete, including imports, helpers and tests. Create the displayed paths in your new project; dependencies imported from other chapters are linked beside the file. Binary assets have direct downloads.
Read each step’s explanation, write its contracts and implementation, then trace the test assertions. The final application graph has dependencies across chapters: the ordering is a construction plan, and a step is not a promise that the whole app compiles before its referenced contracts exist.
Implementation sequence:
- Step 1: Define reader state, owned content streams and route lifetime.
- Step 2: Render paged/continuous layouts and synchronize page anchors.
- Step 3: Add gesture policies, reader chrome and system UI.
- Step 4: Trace progress, history and completion through awaited cleanup.
- Step 5: Implement page transforms, image actions and owned colorization.
- Verification: recreate the full test/fixture listings and run the relevant target tasks. [chapter-content-end]: #
Step 1: define reader state and content ownership
Write ReaderContract, ReaderViewModel, ReaderRuntime and route binding. State includes current title/chapter, chapter sequence, page stream, current position, loading/error, effective preferences, controls and page/download actions. Use the shared reader sequence for scanlator priority and duplicate releases. Resolve pages through ProfileReaderContent and ChapterPageResolver with headers and freshness.
Each chapter stream owns its work and download-protection lease. Changing chapters or retiring a profile cancels and joins old work, flushes progress and prevents late page results entering the new chapter. Keep saved progress distinct from the current visible-page gesture state.
Follow the code
The contract describes observable reader state independently of Compose rendering. The ViewModel/runtime loads a chapter sequence, resolves pages and owns asynchronous work and protection leases. A chapter switch cancels/joins old requests and guards late results against the new identity. The route registers awaited finalization with navigation. Keep visible gesture position distinct from the last saved database position.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderContract.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderRuntime.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderRoute.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderContract.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ReaderLoadState, Idle, PagesLoading, PagesReady, PagesError, ReaderEdge, Middle, AtStart, AtEnd, ReaderPageHalf and 71 further declarations.
The source describes its contract as:
Loading lifecycle for the current chapter. The reader UI is always navigable — even while [PagesLoading] the bottom bar / settings sheet can still be opened. The Box body swaps in a progress indicator until we transition to [PagesReady].
Cross-chapter imports used by this file: DbPageUrl, DbReaderMode, Chapter, Manga. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import eu.friedcutlet.yokan.services.colorization.PanelCrop
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Manga
/**
* Loading lifecycle for the current chapter. The reader UI is always
* navigable — even while [PagesLoading] the bottom bar / settings sheet
* can still be opened. The Box body swaps in a progress indicator until
* we transition to [PagesReady].
*/
sealed interface ReaderLoadState {
data object Idle : ReaderLoadState
data object PagesLoading : ReaderLoadState
data class PagesReady(val pages: List<DbPageUrl>) : ReaderLoadState
data class PagesError(val message: String) : ReaderLoadState
}
/** Whether the reader is at the start / end of the current chapter, for transition prompts. */
sealed interface ReaderEdge {
data object Middle : ReaderEdge
data object AtStart : ReaderEdge
data object AtEnd : ReaderEdge
}
/** Display half of a split landscape page; which image side it shows depends on direction and inversion. */
enum class ReaderPageHalf { First, Second }
sealed interface ReaderStreamItem {
data class Page(
val chapter: Chapter,
val page: DbPageUrl,
val chapterPageIndex: Int,
val split: ReaderPageHalf? = null,
) : ReaderStreamItem
data class Transition(
val completedChapter: Chapter,
val nextChapter: Chapter?,
val mangaTitle: String,
) : ReaderStreamItem
}
data class ReaderDisplayUnit(
val streamIndexes: IntRange,
val items: List<ReaderStreamItem>,
) {
val firstStreamIndex: Int get() = streamIndexes.first
}
data class ResolvedReaderImage(
val item: ReaderStreamItem.Page,
val page: DbPageUrl,
val bytes: ByteArray,
val originalBytes: ByteArray,
val fileName: String,
val originalFileName: String,
val mimeType: String,
/** The other page of a two-page spread containing [item], in reading order. */
val spreadPartner: ReaderStreamItem.Page? = null,
)
enum class ReaderImageExport { Save, Share, Copy }
/** Stable source identity; database page URLs are never rewritten for display overrides. */
data class ReaderPageIdentity(val chapterId: Long, val chapterPageIndex: Int, val sourceKey: String)
data class ColorizedReaderPage(
val identity: ReaderPageIdentity,
val revision: Long,
val filePath: String,
)
internal fun ReaderStreamItem.Page.identity(): ReaderPageIdentity = ReaderPageIdentity(
chapterId = chapter.id,
chapterPageIndex = chapterPageIndex,
sourceKey = readerPageSourceIdentity(page),
)
internal fun readerPageSourceIdentity(page: DbPageUrl): String = buildString {
append(page.url)
append('#')
append(readerPageHeaderFingerprint(page.headers.orEmpty()))
}
internal fun readerColorizedCachePath(root: String, identity: ReaderPageIdentity, revision: Long): String {
require(revision > 0)
var hash = 14695981039346656037uL
identity.sourceKey.forEach { hash = (hash xor it.code.toULong()) * 1099511628211uL }
return "${root.trimEnd('/')}/${identity.chapterId}-${identity.chapterPageIndex}-${hash.toString(16)}-$revision.png"
}
internal fun canApplyColorizationResult(
expectedGeneration: Int,
currentGeneration: Int,
identity: ReaderPageIdentity,
streamItems: List<ReaderStreamItem>,
): Boolean = expectedGeneration == currentGeneration && streamItems.any { (it as? ReaderStreamItem.Page)?.identity() == identity }
internal fun colorizedOverrideFor(
page: DbPageUrl,
chapterId: Long,
chapterPageIndex: Int,
overrides: Map<ReaderPageIdentity, ColorizedReaderPage>,
): ColorizedReaderPage? = overrides[ReaderPageIdentity(chapterId, chapterPageIndex, readerPageSourceIdentity(page))]
internal fun readerPageItems(
chapter: Chapter,
pages: List<DbPageUrl>,
): List<ReaderStreamItem.Page> = pages.mapIndexed { index, page ->
ReaderStreamItem.Page(chapter, page, index)
}
enum class ColorizerWork { Idle, Importing, Colorizing }
enum class ColorizerError { ImportFailed, InferenceFailed, RemoveFailed }
data class ReaderColorizerState(
val open: Boolean = false,
val supported: Boolean = false,
val modelInstalled: Boolean = false,
val work: ColorizerWork = ColorizerWork.Idle,
val crop: PanelCrop = PanelCrop(),
val preview: ByteArray? = null,
val showOriginal: Boolean = false,
/** True when the action target's displayed reader page has a colorized derivative. */
val hasAppliedColorization: Boolean = false,
val error: ColorizerError? = null,
)
data class ReaderState(
val manga: Manga,
val chapter: Chapter,
val previousChapter: Chapter? = null,
val nextChapter: Chapter? = null,
/** Prev/next order around [chapter]; backs the chapter list. */
val chapterSequence: List<Chapter> = emptyList(),
val load: ReaderLoadState = ReaderLoadState.Idle,
val currentPageIndex: Int = 0,
val currentStreamIndex: Int = 0,
val streamItems: List<ReaderStreamItem> = emptyList(),
val animatePageChange: Boolean = false,
val mode: DbReaderMode,
val doublePage: Boolean = false,
val automaticLayout: Boolean = false,
val automaticPairing: Boolean = false,
val layoutSampleKey: String = "",
val layoutSettled: Boolean = false,
val viewport: ReaderViewport = ReaderViewport(),
val pageShapes: Map<ReaderPageIdentity, ReaderPageShape> = emptyMap(),
/** Landscape pages of the current mode are split into two stream halves. */
val splitPages: Boolean = false,
val chromeVisible: Boolean = false,
val settingsSheetOpen: Boolean = false,
val chapterListOpen: Boolean = false,
val edge: ReaderEdge = ReaderEdge.Middle,
val autoScrolling: Boolean = false,
val autoScrollEnabled: Boolean = false,
val autoScrollOffset: Double = 10.0,
val holdScrollEnabled: Boolean = false,
val holdScroll: ReaderHoldScroll = ReaderHoldScroll(),
val readerActive: Boolean = true,
val imageActionsTarget: ResolvedReaderImage? = null,
val colorizer: ReaderColorizerState = ReaderColorizerState(),
val colorizedPages: Map<ReaderPageIdentity, ColorizedReaderPage> = emptyMap(),
) {
val pages: List<DbPageUrl> get() = (load as? ReaderLoadState.PagesReady)?.pages.orEmpty()
val pageCount: Int get() = pages.size
val canGoPreviousChapter: Boolean get() = previousChapter != null
val canGoNextChapter: Boolean get() = nextChapter != null
/** A sheet or dialog covers the pages, so auto and hold scrolling must not run. */
val overlayOpen: Boolean get() = settingsSheetOpen || chapterListOpen || imageActionsTarget != null || colorizer.open
}
sealed interface ReaderEvent {
data object Back : ReaderEvent
data object ToggleChrome : ReaderEvent
data object OpenSettingsSheet : ReaderEvent
data object CloseSettingsSheet : ReaderEvent
data object OpenChapterList : ReaderEvent
data object CloseChapterList : ReaderEvent
data object PreviousPage : ReaderEvent
data object NextPage : ReaderEvent
data class JumpToPage(val index: Int) : ReaderEvent
data class CurrentPageChanged(val index: Int) : ReaderEvent
data object PreviousChapter : ReaderEvent
data object NextChapter : ReaderEvent
data class SelectChapter(val chapter: Chapter) : ReaderEvent
data class ChangeMode(val mode: DbReaderMode) : ReaderEvent
data object AutomaticLayout : ReaderEvent
data object DefaultLayout : ReaderEvent
data object AutomaticPagePairing : ReaderEvent
data class ViewportChanged(val viewport: ReaderViewport) : ReaderEvent
data class PageShapeSampled(val key: String, val identity: ReaderPageIdentity, val shape: ReaderPageShape?) : ReaderEvent
data object ToggleDoublePage : ReaderEvent
data object ToggleFullscreen : ReaderEvent
data object ToggleBookmark : ReaderEvent
/** Retry the page-list fetch after [ReaderLoadState.PagesError]. */
data object Retry : ReaderEvent
/** Refetch the current chapter's page list from the source, staying on the same page. */
data object RefreshPages : ReaderEvent
/** A page image of [chapterId] failed to load; a dead link on a saved list refreshes it once. */
data class PageImageFailed(val chapterId: Long, val error: Throwable) : ReaderEvent
/** Flush progress and elapsed reading time when the app loses focus. */
data object ReadingPaused : ReaderEvent
/** Resume elapsed-time accounting after the app returns to the foreground. */
data object ReadingResumed : ReaderEvent
/** Toggle the rolling auto-scroll in continuous modes. */
data object ToggleAutoScroll : ReaderEvent
data class BeginHoldScroll(val gestureId: Long) : ReaderEvent
data class HoldScrollSpeed(val gestureId: Long, val distanceDp: Float) : ReaderEvent
data class EndHoldScroll(val gestureId: Long) : ReaderEvent
/** Dialogs, focus loss, zoom, user scrolling, and terminal content relinquish scroll ownership. */
data object InterruptScrolling : ReaderEvent
data class SetAutoScrollEnabled(val enabled: Boolean) : ReaderEvent
data class SetAutoScrollOffset(val offset: Double) : ReaderEvent
/** Resolve the page bytes before showing image actions. */
data class OpenImageActions(val item: ReaderStreamItem.Page) : ReaderEvent
data object CloseImageActions : ReaderEvent
/** Persist the resolved image as the manga's custom cover. */
data object SetResolvedImageAsCover : ReaderEvent
/** Save, share or copy the resolved image; [spread] merges the two pages shown together. */
data class ExportResolvedImage(val export: ReaderImageExport, val spread: Boolean = false) : ReaderEvent
data object OpenColorizer : ReaderEvent
data object CloseColorizer : ReaderEvent
data object ImportColorizerModel : ReaderEvent
data object RemoveColorizerModel : ReaderEvent
data class SelectPanelCrop(val crop: PanelCrop) : ReaderEvent
data object ColorizePanel : ReaderEvent
data object RestoreOriginalColorizedPage : ReaderEvent
data object ToggleColorizerOriginal : ReaderEvent
data object SaveColorizedPanel : ReaderEvent
data object ShareColorizedPanel : ReaderEvent
}
sealed interface ReaderEffect {
data object Exit : ReaderEffect
data class ShowMessage(val text: String) : ReaderEffect
/** Another chapter was chosen; the route opens it as a fresh reader entry. */
data class OpenChapter(val chapter: Chapter) : ReaderEffect
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderRuntime.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines isDeadPageLink, DbReaderMode.isVerticalLike, DbReaderMode.isHorizontalContinuous, DbReaderMode.isPaged, DbReaderMode.isRightToLeft, DbReaderMode.label, DbReaderMode.supportsAutoScroll, ReaderImageFormat, readerImageFormat, readerImageFileName and 15 further declarations.
The source describes its contract as:
Whether a page image failed because its URL itself is gone (expired or removed page, or a host that no longer resolves) rather than a transient error, so a fresh page list may fix it.
Cross-chapter imports used by this file: DbPageUrl, DbReaderMode, DbReaderModePreferences, Chapter. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import coil3.network.HttpException
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.database.DbReaderModePreferences
import eu.friedcutlet.yokan.domain.Chapter
private val DeadPageLinkStatusCodes = setOf(401, 403, 404, 410)
// Ktor's Darwin engine reports NSURLErrorCannotFindHost / NSURLErrorDNSLookupFailed in the message.
private val DarwinHostNotFound = Regex("NSURLErrorDomain Code=-100[36]\\b")
/**
* Whether a page image failed because its URL itself is gone (expired or removed page, or a host
* that no longer resolves) rather than a transient error, so a fresh page list may fix it.
*/
internal fun isDeadPageLink(error: Throwable): Boolean =
generateSequence(error) { it.cause?.takeIf { cause -> cause !== it } }.take(8).any { cause ->
(cause as? HttpException)?.response?.code in DeadPageLinkStatusCodes ||
cause::class.simpleName == "UnknownHostException" ||
DarwinHostNotFound.containsMatchIn(cause.message.orEmpty())
}
internal fun DbReaderMode.isVerticalLike(): Boolean =
this == DbReaderMode.VerticalContinuous || this == DbReaderMode.Webtoon
internal fun DbReaderMode.isHorizontalContinuous(): Boolean =
this == DbReaderMode.HorizontalContinuous || this == DbReaderMode.HorizontalContinuousRtl
internal fun DbReaderMode.isPaged(): Boolean =
this == DbReaderMode.Ltr || this == DbReaderMode.Rtl || this == DbReaderMode.Vertical
internal fun DbReaderMode.isRightToLeft(): Boolean =
this == DbReaderMode.Rtl || this == DbReaderMode.HorizontalContinuousRtl
internal fun DbReaderMode.label(): String = when (this) {
DbReaderMode.Ltr -> "LTR"
DbReaderMode.Rtl -> "RTL"
DbReaderMode.Vertical -> "Vertical"
DbReaderMode.VerticalContinuous -> "Vertical continuous"
DbReaderMode.HorizontalContinuous -> "Horizontal continuous"
DbReaderMode.HorizontalContinuousRtl -> "Horizontal continuous (RTL)"
DbReaderMode.Webtoon -> "Webtoon"
}
internal fun DbReaderMode.supportsAutoScroll(): Boolean =
isVerticalLike() || isHorizontalContinuous()
internal data class ReaderImageFormat(val mimeType: String, val extension: String)
internal fun readerImageFormat(bytes: ByteArray): ReaderImageFormat = when {
bytes.hasPrefix(0x89, 0x50, 0x4E, 0x47) -> ReaderImageFormat("image/png", "png")
bytes.hasPrefix(0xFF, 0xD8, 0xFF) -> ReaderImageFormat("image/jpeg", "jpg")
bytes.hasPrefix(0x47, 0x49, 0x46, 0x38) -> ReaderImageFormat("image/gif", "gif")
bytes.hasAscii(0, "RIFF") && bytes.hasAscii(8, "WEBP") -> ReaderImageFormat("image/webp", "webp")
bytes.hasAscii(4, "ftypavif") || bytes.hasAscii(4, "ftypavis") -> ReaderImageFormat("image/avif", "avif")
bytes.hasAscii(4, "ftypheic") || bytes.hasAscii(4, "ftypheif") -> ReaderImageFormat("image/heic", "heic")
else -> ReaderImageFormat("image/png", "png")
}
internal fun readerImageFileName(
mangaTitle: String,
chapterTitle: String,
pageIndex: Int,
extension: String,
): String {
val base = "$mangaTitle $chapterTitle - $pageIndex"
.replace(Regex("[^A-Za-z0-9 .()\\-\\s]"), "_")
.trim()
.ifBlank { "Yokan page $pageIndex" }
return "$base.$extension"
}
private fun ByteArray.hasPrefix(vararg expected: Int): Boolean =
size >= expected.size && expected.indices.all { this[it].toInt() and 0xFF == expected[it] }
private fun ByteArray.hasAscii(offset: Int, expected: String): Boolean =
size >= offset + expected.length &&
expected.indices.all { this[offset + it].toInt() and 0xFF == expected[it].code }
internal fun readerDisplayUnits(
items: List<ReaderStreamItem>,
mode: DbReaderMode,
doublePage: Boolean,
shapes: Map<ReaderPageIdentity, ReaderPageShape> = emptyMap(),
automaticPairing: Boolean = false,
): List<ReaderDisplayUnit> = buildList {
var index = 0
while (index < items.size) {
val item = items[index]
val page = item as? ReaderStreamItem.Page
val nextPage = items.getOrNull(index + 1) as? ReaderStreamItem.Page
val pairPages = doublePage &&
(!automaticPairing || (page != null && nextPage != null &&
shapes[page.identity()]?.let { it.valid && !it.wide && !it.tall } == true &&
shapes[nextPage.identity()]?.let { it.valid && !it.wide && !it.tall } == true)) &&
!mode.isHorizontalContinuous() &&
page != null &&
!(mode.isVerticalLike() && page.chapterPageIndex == 0) &&
nextPage?.chapter?.id == page.chapter.id &&
nextPage.chapterPageIndex == page.chapterPageIndex + 1 &&
page.split == null && nextPage.split == null
val lastIndex = if (pairPages) index + 1 else index
add(ReaderDisplayUnit(index..lastIndex, items.subList(index, lastIndex + 1)))
index = lastIndex + 1
}
}
internal fun displayUnitIndexForStreamIndex(
units: List<ReaderDisplayUnit>,
streamIndex: Int,
): Int = units.indexOfFirst { streamIndex in it.streamIndexes }.let { index ->
if (index >= 0) index else 0
}
/** Renderer echoes must not move a resumed/regrouped second page back to the spread's first. */
internal fun readerRendererPageChange(
units: List<ReaderDisplayUnit>,
unitIndex: Int,
logicalStreamIndex: Int,
): Int? = units.getOrNull(unitIndex)?.takeUnless { logicalStreamIndex in it.streamIndexes }?.firstStreamIndex
internal fun streamIndexForChapterPage(
items: List<ReaderStreamItem>,
chapterId: Long,
pageIndex: Int,
): Int = items.indexOfFirst { item ->
item is ReaderStreamItem.Page &&
item.chapter.id == chapterId &&
item.chapterPageIndex == pageIndex
}
internal const val ReaderPageTransitionDurationMillis = 150
internal fun doubleTapZoomDurationMillis(setting: Int): Int = when (setting) {
0 -> 10
1 -> 800
else -> 200
}
internal fun readerPagesForChapter(
items: List<ReaderStreamItem>,
chapterId: Long,
): List<DbPageUrl> = items.mapNotNull { item ->
(item as? ReaderStreamItem.Page)
?.takeIf { it.chapter.id == chapterId && it.split != ReaderPageHalf.Second }
?.page
}
/**
* Expands landscape pages into two halves when [enabled], or collapses halves otherwise, and maps
* [currentIndex] onto the same page half. A split page stays split while its shape is unknown.
*/
internal fun splitWidePagesInStream(
items: List<ReaderStreamItem>,
currentIndex: Int,
shapes: Map<ReaderPageIdentity, ReaderPageShape>,
enabled: Boolean,
): Pair<List<ReaderStreamItem>, Int> {
if (!enabled && items.none { (it as? ReaderStreamItem.Page)?.split != null }) return items to currentIndex
val result = ArrayList<ReaderStreamItem>(items.size + 8)
var index = currentIndex
items.forEachIndexed { i, item ->
val page = item as? ReaderStreamItem.Page
when {
page == null -> { if (i == currentIndex) index = result.size; result += item }
// Halves are always adjacent: the second maps to whatever replaced its first half.
page.split == ReaderPageHalf.Second -> if (i == currentIndex) index = result.lastIndex
else -> {
if (i == currentIndex) index = result.size
val landscape = shapes[page.identity()]?.let { it.valid && it.width > it.height } ?: (page.split != null)
if (enabled && landscape) {
result += page.copy(split = ReaderPageHalf.First)
result += page.copy(split = ReaderPageHalf.Second)
} else {
result += if (page.split == null) page else page.copy(split = null)
}
}
}
}
if (result.size == items.size && result.indices.all { result[it] == items[it] }) return items to currentIndex
return result to index.coerceIn(0, result.lastIndex.coerceAtLeast(0))
}
/** Coil-side processing of one stream page under the current mode's preferences. */
internal data class ReaderPageProcessing(
val cropBorders: Boolean = false,
/** Null shows the whole image; otherwise whether the left (true) or right half is shown. */
val leftHalf: Boolean? = null,
/** Quarter turn applied to landscape images: 90 clockwise, -90 counter-clockwise, 0 none. */
val rotation: Int = 0,
)
/** The first half follows the reading direction (left for LTR, right for RTL); inversion swaps it. */
internal fun readerPageProcessing(
item: ReaderStreamItem.Page,
rightToLeft: Boolean,
preferences: DbReaderModePreferences,
): ReaderPageProcessing = ReaderPageProcessing(
cropBorders = preferences.cropBorders,
leftHalf = item.split?.let { (it == ReaderPageHalf.First) != rightToLeft != preferences.invertSplit },
rotation = when {
item.split != null || !preferences.rotateWidePages -> 0
preferences.invertRotation -> -90
else -> 90
},
)
internal fun replaceChapterPagesInStream(
items: List<ReaderStreamItem>,
chapter: Chapter,
pages: List<DbPageUrl>,
): List<ReaderStreamItem> {
val first = items.indexOfFirst {
it is ReaderStreamItem.Page && it.chapter.id == chapter.id
}
if (first < 0) {
return if (items.isEmpty()) readerPageItems(chapter, pages) else items
}
var lastExclusive = first
while (
lastExclusive < items.size &&
(items[lastExclusive] as? ReaderStreamItem.Page)?.chapter?.id == chapter.id
) {
lastExclusive += 1
}
return buildList(items.size - (lastExclusive - first) + pages.size) {
addAll(items.subList(0, first))
addAll(readerPageItems(chapter, pages))
addAll(items.subList(lastExclusive, items.size))
}
}
internal fun readerPrefetchPageItems(
items: List<ReaderStreamItem>,
currentStreamIndex: Int,
forwardAmount: Int,
backwardAmount: Int = 2,
): List<ReaderStreamItem.Page> {
if (items.isEmpty()) return emptyList()
val start = currentStreamIndex.coerceIn(items.indices)
val forwardEnd = (start + forwardAmount.coerceAtLeast(0)).coerceAtMost(items.lastIndex)
val backwardEnd = (start - backwardAmount.coerceAtLeast(0)).coerceAtLeast(0)
return buildList {
for (index in start..forwardEnd) {
(items[index] as? ReaderStreamItem.Page)?.let(::add)
}
for (index in start - 1 downTo backwardEnd) {
(items[index] as? ReaderStreamItem.Page)?.let(::add)
}
}
}
internal fun readerPrefetchPages(
items: List<ReaderStreamItem>,
currentStreamIndex: Int,
forwardAmount: Int,
backwardAmount: Int = 2,
): List<DbPageUrl> =
readerPrefetchPageItems(items, currentStreamIndex, forwardAmount, backwardAmount).map { it.page }
/** Without [showTransition] the next chapter's pages follow directly; the end of the series always gets a card. */
internal fun appendNextChapterToStream(
items: List<ReaderStreamItem>,
completedChapter: Chapter,
nextChapter: Chapter?,
mangaTitle: String,
nextPages: List<DbPageUrl>,
showTransition: Boolean = true,
): List<ReaderStreamItem> {
if (items.any {
it is ReaderStreamItem.Transition && it.completedChapter.id == completedChapter.id ||
nextChapter != null && it is ReaderStreamItem.Page && it.chapter.id == nextChapter.id
}
) {
return items
}
val nextItems = nextChapter?.let { readerPageItems(it, nextPages) }.orEmpty()
return if (showTransition || nextChapter == null) {
items + ReaderStreamItem.Transition(completedChapter, nextChapter, mangaTitle) + nextItems
} else {
items + nextItems
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
Read content loading, sequence changes and final progress as one ownership flow. Each asynchronous result must still belong to the active chapter/session before it updates state.
The implementation below defines ReaderViewModel, updateState, onEvent, onCleared, awaitCleanup, refreshLayout, settleLayout, layoutSamples, stepPage, jumpToPage and 23 further declarations.
The source describes its contract as:
Reader screen state holder. Responsibilities owned here (not in the composable): - resolving page lists via the extension runtime, off the UI thread, so the screen renders immediately and shows a progress indicator instead of blocking; - persisting read progress as the user advances; - bidirectional chapter preload (prev + next chapter page-list); - chapter navigation: seamless in-stream switches stay here; jumping to another chapter emits [ReaderEffect.OpenChapter] for a fresh entry; - chrome toggle + settings sheet open/close state. Image actions and the panel colorizer live in [ReaderImageWork]. Per-image (Coil) prefetch is driven from the composable since it needs the platform's PlatformContext / ImageLoader, which aren't available to a pure-Kotlin ViewModel.
Cross-chapter imports used by this file: LibraryIndexStore, SettingsStore, YokanRepository, DbPageMode, DbPageUrl, DbReaderMode. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.DbPageMode
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.isIncognitoFor
import eu.friedcutlet.yokan.database.readerModePreferences
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ChapterRecognition
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.colorization.PanelColorizer
import eu.friedcutlet.yokan.services.extensions.ChapterPageResolver
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.library.readingChapterSequence
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.ui.navigation.AwaitedViewModelCleanup
import eu.friedcutlet.yokan.ui.navigation.ViewModelFinalizer
import eu.friedcutlet.yokan.ui.screens.ReadingSessionClock
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
/**
* Reader screen state holder.
*
* Responsibilities owned here (not in the composable):
* - resolving page lists via the extension runtime, off the UI thread, so
* the screen renders immediately and shows a progress indicator instead
* of blocking;
* - persisting read progress as the user advances;
* - bidirectional chapter preload (prev + next chapter page-list);
* - chapter navigation: seamless in-stream switches stay here; jumping to
* another chapter emits [ReaderEffect.OpenChapter] for a fresh entry;
* - chrome toggle + settings sheet open/close state.
*
* Image actions and the panel colorizer live in [ReaderImageWork].
*
* Per-image (Coil) prefetch is driven from the composable since it needs
* the platform's PlatformContext / ImageLoader, which aren't available to a
* pure-Kotlin ViewModel.
*/
class ReaderViewModel(
initialManga: Manga,
initialChapter: Chapter,
private val repository: YokanRepository,
private val settings: SettingsStore,
private val libraryIndex: LibraryIndexStore,
private val chapterPages: ChapterPageResolver,
/** Fetches a chapter's live page list: (source, chapter, forceRefresh). */
private val loadPages: suspend (Source?, Chapter, Boolean) -> List<DbPageUrl>,
files: LocalFileService,
imageHttp: HttpService,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel(), AwaitedViewModelCleanup {
/** Chapters showing a saved page list; a dead page link refreshes each one once per reader session. */
private val savedListChapterIds = mutableSetOf<Long>()
private val refreshJobs = mutableMapOf<Long, Job>()
private val _state = MutableStateFlow(
buildInitialState(initialManga, initialChapter, settings.db.value, savedPages(initialChapter, initialManga.sourceId)),
)
val state: StateFlow<ReaderState> = _state.asStateFlow()
private val _effects = Channel<ReaderEffect>(capacity = Channel.BUFFERED)
val effects: Flow<ReaderEffect> = _effects.receiveAsFlow()
/** Every stream, shape or split-preference change re-derives split halves and the matching position. */
private fun updateState(transform: (ReaderState) -> ReaderState) {
_state.update { before ->
val after = transform(before)
if (after.streamItems === before.streamItems && after.pageShapes === before.pageShapes && after.splitPages == before.splitPages) {
after
} else {
val (items, index) = splitWidePagesInStream(after.streamItems, after.currentStreamIndex, after.pageShapes, after.splitPages)
if (items === after.streamItems) after else after.copy(streamItems = items, currentStreamIndex = index)
}
}
}
private val images = ReaderImageWork(
scope = viewModelScope,
workDispatcher = workDispatcher,
localFiles = files,
imageHttp = imageHttp,
repository = repository,
panelColorizer = lazy { PanelColorizer() },
saveImagesInTitleFolder = { settings.db.value.features.reader.saveImagesInTitleFolder },
state = { state.value },
update = ::updateState,
emit = _effects::send,
)
private var layoutDeadlineJob: Job? = null
private var layoutGeneration = 0
private val layoutDecisions = linkedMapOf<String, Boolean>()
private val completedLayoutSamples = mutableSetOf<ReaderPageIdentity>()
private var pageLoadJob: Job? = null
private var preloadJob: Job? = null
private var sequenceJob: Job? = null
private var chapterCompleted = initialChapter.isRead
private var consumptionObserved = false
private var historyChapterId: Long? = null
private val readingClock = ReadingSessionClock()
private var sessionClosed = false
private val automationChapterIds = mutableSetOf<Long>()
private var autoScrollWasRunningBeforeSettings = false
init {
activateDownloadPolicy(initialChapter.id)
showChapterSequence(initialChapter.id)
ensurePagesLoaded(initialChapter, restoreResume = true)
viewModelScope.launch { settings.db.collect { refreshLayout() } }
}
fun onEvent(event: ReaderEvent) {
if (sessionClosed) return
when (event) {
ReaderEvent.Back -> {
closeReadingSession()
viewModelScope.launch { _effects.send(ReaderEffect.Exit) }
}
ReaderEvent.ToggleChrome -> updateState { it.copy(chromeVisible = !it.chromeVisible) }
ReaderEvent.OpenSettingsSheet -> {
autoScrollWasRunningBeforeSettings = state.value.autoScrolling
updateState { it.copy(settingsSheetOpen = true, autoScrolling = false, holdScroll = ReaderHoldScroll()) }
}
ReaderEvent.CloseSettingsSheet -> {
updateState {
val resume = (autoScrollWasRunningBeforeSettings || it.autoScrolling) &&
(it.autoScrollEnabled || it.holdScrollEnabled) && it.readerActive &&
it.mode.supportsAutoScroll()
it.copy(settingsSheetOpen = false, autoScrolling = resume)
}
autoScrollWasRunningBeforeSettings = false
}
ReaderEvent.OpenChapterList -> {
onEvent(ReaderEvent.InterruptScrolling)
updateState { it.copy(chapterListOpen = true) }
}
ReaderEvent.CloseChapterList -> updateState { it.copy(chapterListOpen = false) }
ReaderEvent.PreviousPage -> stepPage(-1)
ReaderEvent.NextPage -> stepPage(+1)
is ReaderEvent.JumpToPage -> jumpToPage(event.index)
is ReaderEvent.CurrentPageChanged -> onCurrentPageChanged(event.index)
ReaderEvent.PreviousChapter -> openChapter(state.value.previousChapter)
ReaderEvent.NextChapter -> goToNextChapter()
is ReaderEvent.SelectChapter -> {
updateState { it.copy(chapterListOpen = false) }
openChapter(event.chapter)
}
is ReaderEvent.ChangeMode -> {
val wasHolding = state.value.holdScroll.phase != ReaderHoldPhase.Idle
settings.updateDb { it.withPersonalReaderMode(state.value.manga.id, event.mode) }
updateState { it.copy(holdScroll = ReaderHoldScroll(), autoScrolling = !wasHolding && it.readerActive &&
!it.settingsSheetOpen && event.mode.supportsAutoScroll() && it.autoScrollEnabled) }
}
ReaderEvent.AutomaticLayout -> settings.updateDb { it.withPersonalAutomaticLayout(state.value.manga.id) }
ReaderEvent.DefaultLayout -> settings.updateDb { it.withDefaultReaderLayout(state.value.manga.id) }
ReaderEvent.AutomaticPagePairing -> settings.updateDb { it.withAutomaticPagePairing(state.value.manga.id) }
is ReaderEvent.ViewportChanged -> {
updateState { it.copy(viewport = event.viewport) }
refreshLayout()
}
is ReaderEvent.PageShapeSampled -> {
if (event.key == state.value.layoutSampleKey && state.value.streamItems.any { (it as? ReaderStreamItem.Page)?.identity() == event.identity }) {
event.shape?.takeIf { it.valid }?.let { shape -> updateState { current ->
if (current.pageShapes[event.identity] == shape) current
else current.copy(pageShapes = (current.pageShapes + (event.identity to shape)).entries.toList().takeLast(200).associate { it.key to it.value })
} }
completedLayoutSamples += event.identity
val samples = layoutSamples(state.value)
if (samples.isNotEmpty() && samples.all { it.identity() in completedLayoutSamples }) settleLayout(event.key)
}
}
ReaderEvent.ToggleDoublePage -> {
val next = !state.value.doublePage
settings.updateDb { it.withPersonalDoublePage(state.value.manga.id, next) }
}
ReaderEvent.ToggleFullscreen -> settings.updateDb { it.copy(fullScreenReader = !it.fullScreenReader) }
ReaderEvent.ToggleBookmark -> {
val chapter = state.value.chapter
repository.setChaptersBookmarked(setOf(chapter.id), !chapter.isBookmarked)
updateState { it.copy(chapter = it.chapter.copy(isBookmarked = !chapter.isBookmarked)) }
}
ReaderEvent.Retry -> {
val current = state.value.chapter
ensurePagesLoaded(current, restoreResume = false, force = true)
}
ReaderEvent.RefreshPages -> refreshPages(state.value.chapter)
is ReaderEvent.PageImageFailed -> {
if (isDeadPageLink(event.error) && savedListChapterIds.remove(event.chapterId)) {
chapterInStream(event.chapterId)?.let(::refreshPages)
}
}
ReaderEvent.ReadingPaused -> pauseReading()
ReaderEvent.ReadingResumed -> resumeReading()
ReaderEvent.ToggleAutoScroll -> updateState {
if ((!it.autoScrollEnabled && !it.holdScrollEnabled) || !it.mode.supportsAutoScroll() || !it.readerActive || it.settingsSheetOpen || it.imageActionsTarget != null) {
it
} else {
// Play/pause is also the accessible alternative to holding. Pausing a hold
// cannot let a later pointer update reclaim ownership.
it.copy(autoScrolling = if (it.holdScroll.phase != ReaderHoldPhase.Idle) false else !it.autoScrolling,
holdScroll = ReaderHoldScroll())
}
}
is ReaderEvent.BeginHoldScroll -> updateState {
if (!sessionClosed && it.readerActive && it.holdScrollEnabled && it.mode.supportsAutoScroll() &&
!it.overlayOpen && it.streamItems.any { item -> item is ReaderStreamItem.Page }) {
val base = readerHoldSpeed(it.autoScrollOffset.toFloat(), 0f)
it.copy(holdScroll = ReaderHoldScroll(event.gestureId, base, base), autoScrolling = false)
} else it
}
is ReaderEvent.HoldScrollSpeed -> updateState {
if (it.holdScroll.gestureId == event.gestureId) it.copy(holdScroll = it.holdScroll.copy(
speed = readerHoldSpeed(it.holdScroll.baseSpeed, event.distanceDp))) else it
}
is ReaderEvent.EndHoldScroll -> updateState {
if (it.holdScroll.gestureId == event.gestureId) it.copy(holdScroll = ReaderHoldScroll(), autoScrolling = false) else it
}
ReaderEvent.InterruptScrolling -> {
autoScrollWasRunningBeforeSettings = false
updateState { it.copy(holdScroll = ReaderHoldScroll(), autoScrolling = false) }
}
is ReaderEvent.SetAutoScrollEnabled -> {
val mangaId = state.value.manga.id
val offset = state.value.autoScrollOffset
settings.updateDb { it.withAutoScrollSettings(mangaId, event.enabled, offset) }
updateState {
it.copy(
autoScrollEnabled = event.enabled,
holdScroll = ReaderHoldScroll(),
autoScrolling = event.enabled && it.readerActive && !it.settingsSheetOpen && it.imageActionsTarget == null && it.mode.supportsAutoScroll(),
)
}
}
is ReaderEvent.SetAutoScrollOffset -> {
val mangaId = state.value.manga.id
val enabled = state.value.autoScrollEnabled
val offset = event.offset.coerceIn(2.0, 30.0)
settings.updateDb { it.withAutoScrollSettings(mangaId, enabled, offset) }
updateState { it.copy(autoScrollOffset = offset) }
}
is ReaderEvent.OpenImageActions -> {
onEvent(ReaderEvent.InterruptScrolling)
images.open(event.item)
}
ReaderEvent.CloseImageActions -> images.close()
ReaderEvent.SetResolvedImageAsCover -> images.setAsCover()
is ReaderEvent.ExportResolvedImage -> images.export(event.export, event.spread)
ReaderEvent.OpenColorizer -> images.openColorizer()
ReaderEvent.CloseColorizer -> images.closeColorizer()
ReaderEvent.ImportColorizerModel -> images.importModel()
ReaderEvent.RemoveColorizerModel -> images.removeModel()
is ReaderEvent.SelectPanelCrop -> images.selectCrop(event.crop)
ReaderEvent.ColorizePanel -> images.colorize()
ReaderEvent.RestoreOriginalColorizedPage -> images.restoreOriginal()
ReaderEvent.ToggleColorizerOriginal -> images.toggleOriginal()
ReaderEvent.SaveColorizedPanel -> images.saveColorized()
ReaderEvent.ShareColorizedPanel -> images.shareColorized()
}
}
private val retirement by lazy {
// A blocked image write may finish after cancellation. Join it before deleting this
// reader's temporary directory, and retain failed deletions for a cleanup retry.
ViewModelFinalizer(requireNotNull(viewModelScope.coroutineContext[Job]), workDispatcher, images::deleteCache)
}
override fun onCleared() {
try { closeReadingSession() }
finally {
pageLoadJob?.cancel()
preloadJob?.cancel()
images.cancel()
pageLoadJob = null
preloadJob = null
retirement.retire()
super.onCleared()
}
}
override suspend fun awaitCleanup() {
closeReadingSession()
retirement.closeAndJoin()
}
private fun refreshLayout() {
val current = state.value
if (sessionClosed) return
val db = settings.db.value
val automatic = db.automaticLayout(current.manga.id)
val samples = layoutSamples(current)
val key = if (samples.isEmpty()) "" else buildString {
append(AUTOMATIC_LAYOUT_VERSION).append(':').append(layoutGeneration).append(':')
append(repository.source(current.manga.sourceId ?: -1)?.version).append(':')
append(current.manga.genres).append(':')
samples.forEach { append(it.identity()).append(';') }
}
if (key != current.layoutSampleKey) {
layoutDeadlineJob?.cancel()
completedLayoutSamples.clear()
samples.filter { it.identity() in current.pageShapes }.forEach { completedLayoutSamples += it.identity() }
}
val metadataWebtoon = automaticLayoutHasWebtoonMetadata(current.manga.genres)
if (metadataWebtoon && key.isNotEmpty()) layoutDecisions[key] = true
if (key.isNotEmpty() && samples.all { it.identity() in completedLayoutSamples } && key !in layoutDecisions) {
layoutDecisions[key] = automaticWebtoonSample(samples.mapNotNull { current.pageShapes[it.identity()] }, current.pageCount)
}
while (layoutDecisions.size > 8) layoutDecisions.remove(layoutDecisions.keys.first())
val settled = key in layoutDecisions
val fallback = db.personalReaderMode(current.manga.id) ?: db.automaticReaderLayouts.firstOrNull { it.mangaId == current.manga.id }?.fallback ?: db.defaultReaderMode
val pairingOverride = db.personalPageModeList?.firstOrNull { it.mangaId == current.manga.id }?.let { it.pageMode == DbPageMode.DoublePage }
val resolved = if (automatic) resolveAutomaticReaderLayout(fallback, metadataWebtoon || layoutDecisions[key] == true,
current.viewport, pairingOverride = pairingOverride, settled = settled)
else ResolvedReaderLayout(fallback, if (fallback.isRightToLeft()) ReaderDirection.Rtl else ReaderDirection.Ltr, pairingOverride == true)
updateState { it.copy(mode = resolved.mode, doublePage = resolved.pairPages, automaticLayout = automatic,
automaticPairing = automatic && pairingOverride == null, layoutSampleKey = key, layoutSettled = settled,
holdScrollEnabled = db.readerHoldToScroll,
splitPages = db.readerModePreferences(resolved.mode.isPaged()).splitWidePages,
holdScroll = if (db.readerHoldToScroll && it.readerActive && it.mode == resolved.mode && resolved.mode.supportsAutoScroll()) it.holdScroll else ReaderHoldScroll(),
autoScrolling = it.autoScrolling && it.readerActive && resolved.mode.supportsAutoScroll() && (it.autoScrollEnabled || db.readerHoldToScroll)) }
if (!automatic || settled || key.isEmpty()) layoutDeadlineJob?.cancel()
else if (key != current.layoutSampleKey || layoutDeadlineJob?.isActive != true) {
layoutDeadlineJob = viewModelScope.launch { delay(AUTOMATIC_LAYOUT_SAMPLE_TIMEOUT); settleLayout(key) }
}
}
private fun settleLayout(key: String) {
val current = state.value
if (key.isEmpty() || key != current.layoutSampleKey || key in layoutDecisions) return
val sample = layoutSamples(current).mapNotNull { current.pageShapes[it.identity()] }
layoutDecisions[key] = automaticWebtoonSample(sample, current.pageCount)
while (layoutDecisions.size > 8) layoutDecisions.remove(layoutDecisions.keys.first())
refreshLayout()
}
/** Leading source pages of the current chapter; split halves count once. */
private fun layoutSamples(current: ReaderState): List<ReaderStreamItem.Page> =
current.streamItems.asSequence().filterIsInstance<ReaderStreamItem.Page>()
.filter { it.chapter.id == current.chapter.id && it.split != ReaderPageHalf.Second }
.take(AUTOMATIC_LAYOUT_SAMPLE_COUNT).toList()
private fun stepPage(delta: Int) {
val current = state.value
val units = readerDisplayUnits(current.streamItems, current.mode, current.doublePage, current.pageShapes, current.automaticPairing)
if (units.isEmpty()) return
val currentUnit = displayUnitIndexForStreamIndex(units, current.currentStreamIndex)
val targetUnit = currentUnit + delta
if (targetUnit in units.indices) {
onCurrentPageChanged(units[targetUnit].firstStreamIndex, animate = true)
return
}
if (delta > 0) goToNextChapter() else openChapter(current.previousChapter)
}
private fun jumpToPage(index: Int) {
val current = state.value
if (current.pageCount == 0) return
val pageIndex = index.coerceIn(0, current.pageCount - 1)
val streamIndex = streamIndexForChapterPage(
current.streamItems,
current.chapter.id,
pageIndex,
)
if (streamIndex >= 0) onCurrentPageChanged(streamIndex)
}
private fun onCurrentPageChanged(streamIndex: Int, animate: Boolean = false) {
val current = state.value
val clamped = streamIndex.coerceIn(0, current.streamItems.lastIndex.coerceAtLeast(0))
when (val item = current.streamItems.getOrNull(clamped)) {
is ReaderStreamItem.Transition -> {
if (clamped == current.currentStreamIndex) return
val completedIndex = (current.pageCount - 1).coerceAtLeast(0)
updateState {
it.copy(
currentStreamIndex = clamped,
currentPageIndex = completedIndex,
edge = ReaderEdge.AtEnd,
animatePageChange = animate,
)
}
persistProgress(save = true)
}
is ReaderStreamItem.Page -> {
val previousItem = current.streamItems.getOrNull(current.currentStreamIndex) as? ReaderStreamItem.Page
if (previousItem?.identity() != item.identity()) images.close()
if (item.chapter.id != current.chapter.id) {
switchChapterInStream(item, clamped, animate)
return
}
if (
clamped == current.currentStreamIndex &&
item.chapterPageIndex == current.currentPageIndex
) {
return
}
updateState {
it.copy(
currentStreamIndex = clamped,
currentPageIndex = item.chapterPageIndex,
edge = edgeFor(item.chapterPageIndex, it.pageCount),
animatePageChange = animate,
)
}
persistProgress(save = false)
}
null -> Unit
}
}
private fun persistProgress(save: Boolean, readingTimeSeconds: Int = 0) {
val s = state.value
val db = settings.db.value
if (db.isIncognitoFor(s.manga.sourceId)) return
val pageCount = s.pageCount
if (pageCount == 0 || (!save && chapterCompleted)) return
val read = chapterCompleted || readerChapterIsComplete(s.currentPageIndex, pageCount, s.mode)
consumptionObserved = consumptionObserved || readerChapterIsComplete(s.currentPageIndex, pageCount, s.mode)
if (!save && !read) return
val visibleHumanPage = (s.currentPageIndex + 1).coerceAtMost(pageCount)
val newlyCompleted = read && !chapterCompleted
repository.setChaptersRead(
chapterIds = setOf(s.chapter.id),
isRead = read,
lastPageRead = if (read) "1" else visibleHumanPage.toString(),
readingTimeSeconds = readingTimeSeconds,
autoReadDuplicates = newlyCompleted && db.autoReadDuplicateChapters,
)
if (consumptionObserved) repository.recordChapterConsumption(setOf(s.chapter.id))
chapterCompleted = read
}
private fun pauseReading() {
autoScrollWasRunningBeforeSettings = false
updateState { it.copy(readerActive = false, autoScrolling = false, holdScroll = ReaderHoldScroll()) }
if (readingClock.pause()) persistProgress(save = true)
}
private fun resumeReading() {
if (!sessionClosed) {
updateState { it.copy(readerActive = true) }
readingClock.resume()
}
}
private fun closeReadingSession() {
if (sessionClosed) return
updateState { it.copy(readerActive = false, autoScrolling = false, holdScroll = ReaderHoldScroll()) }
layoutDeadlineJob?.cancel()
persistProgress(save = true, readingTimeSeconds = readingClock.finishSeconds())
sessionClosed = true
automationChapterIds.forEach(repository::chapterClosed)
automationChapterIds.clear()
}
private fun activateDownloadPolicy(chapterId: Long) {
// Earlier chapters can remain visible in a continuous stream. Keep their files leased
// until the stream closes instead of deleting images still referenced by its viewport.
if (!automationChapterIds.add(chapterId)) return
repository.chapterOpened(chapterId)
}
private fun goToNextChapter() {
val current = state.value
val target = current.nextChapter ?: return
val transitionIndex = current.streamItems.indexOfFirst { item ->
item is ReaderStreamItem.Transition &&
item.completedChapter.id == current.chapter.id &&
item.nextChapter?.id == target.id
}
val targetIndex = if (transitionIndex >= 0) {
transitionIndex
} else {
streamIndexForChapterPage(current.streamItems, target.id, 0)
}
if (targetIndex >= 0) {
onCurrentPageChanged(targetIndex, animate = true)
} else {
openChapter(target)
}
}
private fun switchChapterInStream(
item: ReaderStreamItem.Page,
streamIndex: Int,
animate: Boolean,
) {
// The finished chapter keeps its own reading time; the clock keeps running for the next.
persistProgress(save = true, readingTimeSeconds = readingClock.takeSeconds())
val chapter = item.chapter
activateDownloadPolicy(chapter.id)
val pages = readerPagesForChapter(state.value.streamItems, chapter.id)
chapterCompleted = chapter.isRead
consumptionObserved = false
historyChapterId = null
updateState {
it.copy(
chapter = chapter,
// Resolved again for this chapter by showChapterSequence below.
previousChapter = null,
nextChapter = null,
load = ReaderLoadState.PagesReady(pages),
currentPageIndex = item.chapterPageIndex,
currentStreamIndex = streamIndex,
animatePageChange = animate,
edge = edgeFor(item.chapterPageIndex, pages.size),
)
}
historyChapterId = chapter.id
persistProgress(save = true)
refreshLayout()
showChapterSequence(chapter.id)
kickNextChapterPreload(chapter)
}
private fun edgeFor(index: Int, count: Int): ReaderEdge = when {
count == 0 -> ReaderEdge.Middle
index <= 0 -> ReaderEdge.AtStart
index >= count - 1 -> ReaderEdge.AtEnd
else -> ReaderEdge.Middle
}
/** Publishes the reading order around [chapterId] once the library index lists that chapter. */
private fun showChapterSequence(chapterId: Long) {
sequenceJob?.cancel()
sequenceJob = viewModelScope.launch {
val manga = state.value.manga
// Wait for index hydration, then keep navigation aligned with preference/read changes.
combine(libraryIndex.index, settings.db) { index, db ->
if (index.chapters(manga.id).none { it.id == chapterId }) null else readingChapterSequence(
manga = manga,
currentChapterId = chapterId,
all = index.chapters(manga.id),
db = db,
downloadedIds = index.downloadedChapterIds,
)
}.flowOn(workDispatcher).distinctUntilChanged()
.collect { all ->
if (all == null || sessionClosed) return@collect
val position = all.indexOfFirst { it.id == chapterId }
val next = all.getOrNull(position + 1)
val before = state.value
val nextChanged = before.chapter.id == chapterId && before.nextChapter?.id != next?.id
if (nextChanged) preloadJob?.cancel()
updateState {
if (it.chapter.id != chapterId) return@updateState it
// Drop only future preloads; keep the current chapter, its page, and earlier content.
val lastCurrentPage = it.streamItems.indexOfLast { item -> item is ReaderStreamItem.Page && item.chapter.id == chapterId }
val items = if (nextChanged && lastCurrentPage >= 0) it.streamItems.take(lastCurrentPage + 1) else it.streamItems
it.copy(
chapterSequence = all,
previousChapter = all.getOrNull(position - 1),
nextChapter = next,
streamItems = items,
currentStreamIndex = if (nextChanged && lastCurrentPage >= 0)
streamIndexForChapterPage(items, chapterId, it.currentPageIndex).coerceAtLeast(0) else it.currentStreamIndex,
)
}
if (nextChanged) kickNextChapterPreload(state.value.chapter)
}
}
}
/** Flushes this session; the route opens [chapter] as a fresh reader entry. */
private fun openChapter(chapter: Chapter?) {
if (chapter == null) return
closeReadingSession()
pageLoadJob?.cancel()
preloadJob?.cancel()
viewModelScope.launch { _effects.send(ReaderEffect.OpenChapter(chapter)) }
}
/** The fresh saved list of [chapter]; downloaded chapters read their files first instead. */
private fun savedPages(chapter: Chapter, sourceId: Long?): List<DbPageUrl> {
if (chapter.archivePath.isNotBlank()) return emptyList()
return chapterPages.savedPages(chapter.id, sourceId).also { if (it.isNotEmpty()) savedListChapterIds += chapter.id }
}
private suspend fun loadLivePages(chapter: Chapter, forceRefresh: Boolean): List<DbPageUrl> {
savedListChapterIds -= chapter.id
val source = state.value.manga.sourceId?.let(repository::source)
return loadPages(source, chapter, forceRefresh)
}
private fun ensurePagesLoaded(chapter: Chapter, restoreResume: Boolean, force: Boolean = false) {
val saved = if (force) emptyList() else savedPages(chapter, state.value.manga.sourceId)
if (saved.isNotEmpty()) {
applyPages(saved, chapter, restoreResume)
return
}
updateState { it.copy(load = ReaderLoadState.PagesLoading) }
pageLoadJob?.cancel()
pageLoadJob = viewModelScope.launch {
catchingNonCancellation { loadLivePages(chapter, forceRefresh = force) }
.onSuccess { pages -> applyPages(pages, chapter, restoreResume) }
.onFailure { throwable ->
val msg = throwable.message.orEmpty().ifBlank { throwable::class.simpleName.orEmpty() }
AppLogger.error("Reader page load failed for ${chapter.name}: $msg")
updateState { it.copy(load = ReaderLoadState.PagesError(msg)) }
}
}
}
private fun chapterInStream(chapterId: Long): Chapter? = state.value.streamItems.firstNotNullOfOrNull { item ->
(item as? ReaderStreamItem.Page)?.chapter?.takeIf { it.id == chapterId }
}
/** Refetches [chapter]'s page list from the source and swaps it in, keeping the reader where it is. */
private fun refreshPages(chapter: Chapter) {
if (refreshJobs[chapter.id]?.isActive == true) return
layoutDeadlineJob?.cancel()
layoutGeneration++
layoutDecisions.clear()
updateState { it.copy(pageShapes = it.pageShapes.filterKeys { identity -> identity.chapterId != chapter.id }) }
refreshLayout()
if (readerPagesForChapter(state.value.streamItems, chapter.id).isEmpty()) {
if (chapter.id == state.value.chapter.id) ensurePagesLoaded(chapter, restoreResume = false, force = true)
return
}
images.invalidateChapter(chapter.id)
refreshJobs[chapter.id] = viewModelScope.launch {
catchingNonCancellation { loadLivePages(chapter, forceRefresh = true) }
.onSuccess { pages -> if (pages.isNotEmpty()) replaceChapterPages(chapter, pages) }
.onFailure { throwable ->
AppLogger.warn("Reader page refresh failed for ${chapter.name}: ${throwable.message.orEmpty()}")
_effects.send(ReaderEffect.ShowMessage("Couldn't refresh pages"))
}
}
}
private fun replaceChapterPages(chapter: Chapter, pages: List<DbPageUrl>) {
updateState { current ->
val items = replaceChapterPagesInStream(current.streamItems, chapter, pages)
val onItem = current.streamItems.getOrNull(current.currentStreamIndex)
val onRefreshedPage = (onItem as? ReaderStreamItem.Page)?.takeIf { it.chapter.id == chapter.id }
val streamIndex = if (onRefreshedPage != null) {
streamIndexForChapterPage(items, chapter.id, onRefreshedPage.chapterPageIndex.coerceAtMost(pages.lastIndex))
} else {
items.indexOf(onItem)
}.coerceAtLeast(0)
if (chapter.id != current.chapter.id) return@updateState current.copy(streamItems = items, currentStreamIndex = streamIndex)
val pageIndex = current.currentPageIndex.coerceAtMost(pages.lastIndex)
current.copy(
load = ReaderLoadState.PagesReady(pages),
streamItems = items,
currentStreamIndex = streamIndex,
currentPageIndex = pageIndex,
edge = edgeFor(pageIndex, pages.size),
)
}
refreshLayout()
}
private fun applyPages(pages: List<DbPageUrl>, chapter: Chapter, restoreResume: Boolean) {
if (restoreResume || pages != state.value.pages) images.invalidateChapter(chapter.id)
val resume = readerResumeIndex(
lastPageRead = chapter.lastPageRead,
pageCount = pages.size,
restoreResume = restoreResume,
incognito = settings.db.value.isIncognitoFor(state.value.manga.sourceId),
alreadyRead = chapter.isRead,
)
updateState {
val streamItems = replaceChapterPagesInStream(it.streamItems, chapter, pages)
val streamIndex = streamIndexForChapterPage(streamItems, chapter.id, resume).coerceAtLeast(0)
it.copy(
load = ReaderLoadState.PagesReady(pages),
currentPageIndex = resume,
currentStreamIndex = streamIndex,
streamItems = streamItems,
edge = edgeFor(resume, pages.size),
)
}
if (historyChapterId != chapter.id) {
historyChapterId = chapter.id
persistProgress(save = true)
}
refreshLayout()
kickNextChapterPreload(chapter)
}
private fun kickNextChapterPreload(chapter: Chapter) {
preloadJob?.cancel()
preloadJob = viewModelScope.launch {
// The next chapter comes from the reading order, which may still be resolving.
val snapshot = state.first { it.chapter.id != chapter.id || it.chapterSequence.any { entry -> entry.id == chapter.id } }
if (snapshot.chapter.id != chapter.id || sessionClosed) return@launch
if (readerPagesForChapter(snapshot.streamItems, chapter.id).isEmpty()) return@launch
val next = snapshot.nextChapter
if (snapshot.streamItems.any {
it is ReaderStreamItem.Transition && it.completedChapter.id == chapter.id ||
next != null && it is ReaderStreamItem.Page && it.chapter.id == next.id
}
) {
return@launch
}
if (next == null) {
appendChapterTransition(chapter, null, emptyList())
return@launch
}
val pages = savedPages(next, snapshot.manga.sourceId).ifEmpty {
catchingNonCancellation { loadLivePages(next, forceRefresh = false) }
.onFailure { throwable ->
AppLogger.warn(
"Reader next-chapter preload failed for ${next.name}: " +
throwable.message.orEmpty(),
)
}
.getOrNull()
.orEmpty()
}
if (pages.isNotEmpty()) appendChapterTransition(chapter, next, pages)
}
}
private fun appendChapterTransition(
chapter: Chapter,
nextChapter: Chapter?,
nextPages: List<DbPageUrl>,
) {
updateState { current ->
if (current.chapter.id != chapter.id || current.nextChapter?.id != nextChapter?.id || sessionClosed) return@updateState current
// Like Mihon, a hidden transition still appears when chapter numbers skip ahead.
val showTransition = settings.db.value.features.reader.alwaysShowChapterTransition || nextChapter == null ||
ChapterRecognition.missingChapterCount(current.manga.name, listOf(chapter, nextChapter)) > 0
current.copy(
streamItems = appendNextChapterToStream(
items = current.streamItems,
completedChapter = chapter,
nextChapter = nextChapter,
mangaTitle = current.manga.name,
nextPages = nextPages,
showTransition = showTransition,
),
)
}
}
}
private fun buildInitialState(manga: Manga, chapter: Chapter, db: DbSettings, cached: List<DbPageUrl>): ReaderState {
val storedMode = db.personalReaderMode(manga.id) ?: db.defaultReaderMode
val autoScroll = db.autoScrollSettings(manga.id)
val streamItems = readerPageItems(chapter, cached)
return ReaderState(
manga = manga,
chapter = chapter,
load = if (cached.isNotEmpty()) ReaderLoadState.PagesReady(cached) else ReaderLoadState.Idle,
streamItems = streamItems,
mode = storedMode,
doublePage = db.personalDoublePage(manga.id),
autoScrollEnabled = autoScroll.autoScroll,
autoScrolling = autoScroll.autoScroll && storedMode.supportsAutoScroll(),
autoScrollOffset = autoScroll.pageOffset.coerceIn(2.0, 30.0),
)
}
internal fun readerResumeIndex(
lastPageRead: String,
pageCount: Int,
restoreResume: Boolean,
incognito: Boolean,
alreadyRead: Boolean = false,
): Int {
if (!restoreResume || incognito || alreadyRead || pageCount <= 0) return 0
return (lastPageRead.toIntOrNull()?.minus(1) ?: 0).coerceIn(0, pageCount - 1)
}
internal fun readerChapterIsComplete(index: Int, pageCount: Int, mode: DbReaderMode): Boolean {
if (pageCount <= 0) return false
return if (mode.isVerticalLike()) {
index + 2 >= pageCount - 1
} else {
index + 2 >= pageCount
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderRoute.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ReaderEntryRoute, ReaderRoute.
The source describes its contract as:
Nav entry for [Route.Reader]. Resolves the title/chapter once per entry (a chapter change is a new entry) and dispatches to the manga reader, anime player or novel reader.
Cross-chapter imports used by this file: YokanRuntime, ProfileSession, Chapter, ItemType, Manga, MissingRoute. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.app.profiles.ProfileSession
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.ui.navigation.MissingRoute
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import eu.friedcutlet.yokan.services.library.sortedChapters
import eu.friedcutlet.yokan.ui.screens.novel.NovelReaderRoute
import eu.friedcutlet.yokan.ui.screens.player.AnimePlayerRoute
import eu.friedcutlet.yokan.ui.screens.together.TogetherPageSync
import eu.friedcutlet.yokan.ui.screens.together.rememberOpenRoomMedia
/**
* Nav entry for [Route.Reader]. Resolves the title/chapter once per entry (a chapter change is a
* new entry) and dispatches to the manga reader, anime player or novel reader.
*/
@Composable
internal fun ReaderEntryRoute(route: Route.Reader, nav: Navigator) {
val owner = remember { YokanRuntime.activeSession }
val settings by owner.settings.db.collectAsStateWithLifecycle()
val resolved = remember(owner, route) {
val repository = owner.repository
repository.manga(route.mangaId)?.let { manga ->
val chapters = sortedChapters(manga, repository.chapters(manga.id), owner.settings.db.value)
val chapter = route.chapterId?.let { id -> chapters.firstOrNull { it.id == id } }
?: chapters.firstOrNull { !it.isRead }
?: chapters.firstOrNull()
chapter?.let { manga to it }
}
}
if (resolved == null) {
MissingRoute("Reader", nav::back)
return
}
val (manga, chapter) = resolved
DiscordPresence(YokanRuntime.discordRpc, settings, manga, chapter)
when (manga.itemType) {
ItemType.Manga -> ReaderRoute(manga, chapter, nav, owner)
ItemType.Anime -> AnimePlayerRoute(manga, chapter, nav, owner)
ItemType.Novel -> NovelReaderRoute(manga, chapter, nav, owner)
}
}
/**
* Route boundary for the manga reader. Resolves [ReaderViewModel] for this entry and translates
* one-shot effects (Exit → back, OpenChapter → a new reader entry, ShowMessage → snackbar).
*/
@Composable
private fun ReaderRoute(manga: Manga, chapter: Chapter, nav: Navigator, owner: ProfileSession) {
val viewModel = viewModel {
ReaderViewModel(
manga,
chapter,
owner.repository,
owner.settings,
owner.libraryIndex,
owner.chapterPages,
loadPages = owner.readerContent::pages,
files = owner.localFiles,
imageHttp = owner.services.http,
)
}
val state by viewModel.state.collectAsStateWithLifecycle()
val settings by owner.settings.db.collectAsStateWithLifecycle()
val snackbarHostState = remember { SnackbarHostState() }
val together = remember(owner) { owner.together }
TogetherPageSync(together, state, viewModel::onEvent, onOpenRoomMedia = rememberOpenRoomMedia(owner, nav))
LifecycleEventEffect(Lifecycle.Event.ON_PAUSE) {
viewModel.onEvent(ReaderEvent.ReadingPaused)
}
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) {
viewModel.onEvent(ReaderEvent.ReadingResumed)
}
// The ViewModel lives as long as the nav entry (onCleared closes the session). Leaving composition
// while the entry stays on the stack (a route pushed on top, the back-gesture preview) only pauses;
// ON_RESUME is replayed when the screen comes back.
DisposableEffect(viewModel) {
onDispose { viewModel.onEvent(ReaderEvent.ReadingPaused) }
}
val lifecycleOwner = LocalLifecycleOwner.current
LaunchedEffect(lifecycleOwner, viewModel) {
lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.effects.collect { effect ->
when (effect) {
ReaderEffect.Exit -> nav.back()
is ReaderEffect.OpenChapter -> nav.navigate(Route.Reader(effect.chapter.mangaId, effect.chapter.id))
is ReaderEffect.ShowMessage -> snackbarHostState.showSnackbar(effect.text)
}
}
}
}
ReaderScreen(
state = state,
settings = settings,
snackbarHostState = snackbarHostState,
onEvent = viewModel::onEvent,
onUpdateSettings = owner.settings::updateDb,
)
}
Check your understanding
Suspend page resolution, switch chapters and complete the old response. It must not replace the current page list or lose the old chapter's final progress. [chapter-content-end]: #
Step 2: implement render modes incrementally
Start with a paged reader and explicit next/previous actions. Add reading direction, continuous vertical and webtoon modes, dual-page/spread/automatic layout and appropriate page ordering. Handle first/last boundaries, transition to adjacent chapters and restoration after dimension/orientation changes.
Implement page keys using chapter/page identity. Add image sizing/quality, prefetch and bounded image work. Preserve a user's reading anchor when pages load with previously unknown dimensions. Continuous mode may retain multiple visible chapter streams; do not close the preceding one just because the nominal current chapter advanced.
Follow the code
Begin with explicit page/chapter keys and a paged layout, then connect continuous/webtoon/spread modes. Layout changes can alter dimensions and page count without changing logical content. Renderer synchronization preserves an anchor while image sizes become known, and continuous mode may retain several visible streams. Request/cache identity includes chapter/page and processing inputs, not just a display index.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderPreferences.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/AutomaticReaderLayout.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderPages.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderRendererSync.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderImageRequests.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderImageWork.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderPreferences.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines DbSettings.personalReaderMode, DbSettings.withPersonalReaderMode, DbSettings.automaticLayout, DbSettings.withPersonalAutomaticLayout, DbSettings.withDefaultReaderLayout, DbSettings.withAutomaticPagePairing, DbSettings.personalDoublePage, DbSettings.withPersonalDoublePage, DbSettings.autoScrollSettings, DbSettings.withAutoScrollSettings.
The source describes its contract as:
The title's own reader mode, or null when it follows the default.
Cross-chapter imports used by this file: DbAutoScrollPages, DbPageMode, DbPersonalPageMode, DbPersonalReaderMode, DbReaderMode, DbSettings. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import eu.friedcutlet.yokan.database.DbAutoScrollPages
import eu.friedcutlet.yokan.database.DbPageMode
import eu.friedcutlet.yokan.database.DbPersonalPageMode
import eu.friedcutlet.yokan.database.DbPersonalReaderMode
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.database.DbSettings
/** The title's own reader mode, or null when it follows the default. */
fun DbSettings.personalReaderMode(mangaId: Long): DbReaderMode? =
personalReaderModeList?.firstOrNull { it.mangaId == mangaId }?.readerMode
fun DbSettings.withPersonalReaderMode(mangaId: Long, mode: DbReaderMode): DbSettings = copy(
automaticReaderLayouts = automaticReaderLayouts.filterNot { it.mangaId == mangaId } + eu.friedcutlet.yokan.database.DbAutomaticReaderLayout(mangaId, false),
personalReaderModeList = personalReaderModeList.orEmpty().filterNot { it.mangaId == mangaId } +
DbPersonalReaderMode(mangaId = mangaId, readerMode = mode),
)
fun DbSettings.automaticLayout(mangaId: Long): Boolean = automaticReaderLayouts.firstOrNull { it.mangaId == mangaId }?.enabled
?: if (personalReaderMode(mangaId) != null) false else automaticReaderLayout
fun DbSettings.withPersonalAutomaticLayout(mangaId: Long): DbSettings = copy(
automaticReaderLayouts = automaticReaderLayouts.filterNot { it.mangaId == mangaId } + eu.friedcutlet.yokan.database.DbAutomaticReaderLayout(mangaId, fallback = personalReaderMode(mangaId)),
)
fun DbSettings.withDefaultReaderLayout(mangaId: Long): DbSettings = copy(
automaticReaderLayouts = automaticReaderLayouts.filterNot { it.mangaId == mangaId },
personalReaderModeList = personalReaderModeList?.filterNot { it.mangaId == mangaId },
)
fun DbSettings.withAutomaticPagePairing(mangaId: Long): DbSettings = copy(
personalPageModeList = personalPageModeList?.filterNot { it.mangaId == mangaId },
)
fun DbSettings.personalDoublePage(mangaId: Long): Boolean =
personalPageModeList?.firstOrNull { it.mangaId == mangaId }?.pageMode == DbPageMode.DoublePage
fun DbSettings.withPersonalDoublePage(mangaId: Long, enabled: Boolean): DbSettings = copy(
personalPageModeList = personalPageModeList.orEmpty().filterNot { it.mangaId == mangaId } +
DbPersonalPageMode(mangaId = mangaId, pageMode = if (enabled) DbPageMode.DoublePage else DbPageMode.OnePage),
)
fun DbSettings.autoScrollSettings(mangaId: Long): DbAutoScrollPages =
autoScrollPages?.firstOrNull { it.mangaId == mangaId } ?: DbAutoScrollPages(mangaId = mangaId)
/** [pageOffset] is clamped to the supported 2–30 range. */
fun DbSettings.withAutoScrollSettings(mangaId: Long, enabled: Boolean, pageOffset: Double): DbSettings = copy(
autoScrollPages = autoScrollPages.orEmpty().filterNot { it.mangaId == mangaId } +
DbAutoScrollPages(mangaId = mangaId, pageOffset = pageOffset.coerceIn(2.0, 30.0), autoScroll = enabled),
)
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/AutomaticReaderLayout.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ReaderDirection, ReaderPageShape, ReaderViewport, ResolvedReaderLayout, automaticWebtoonSample, resolveAutomaticReaderLayout, automaticLayoutHasWebtoonMetadata.
The source describes its contract as:
At least two valid pages for multi-page chapters; mixed samples keep the user's fallback.
Cross-chapter imports used by this file: DbReaderMode. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import eu.friedcutlet.yokan.database.DbReaderMode
enum class ReaderDirection { Ltr, Rtl }
data class ReaderPageShape(val width: Int, val height: Int) {
val valid: Boolean get() = width > 0 && height > 0
val wide: Boolean get() = valid && width.toDouble() / height >= 1.35
val tall: Boolean get() = valid && height.toDouble() / width >= 2.5
}
data class ReaderViewport(val widthDp: Int = 0, val heightDp: Int = 0)
data class ResolvedReaderLayout(val mode: DbReaderMode, val direction: ReaderDirection, val pairPages: Boolean)
internal const val AUTOMATIC_LAYOUT_VERSION = 1
internal const val AUTOMATIC_LAYOUT_SAMPLE_COUNT = 3
internal const val AUTOMATIC_LAYOUT_SAMPLE_TIMEOUT = 1500L
/** At least two valid pages for multi-page chapters; mixed samples keep the user's fallback. */
fun automaticWebtoonSample(sample: List<ReaderPageShape>, chapterPageCount: Int): Boolean {
val valid = sample.filter { it.valid }.take(AUTOMATIC_LAYOUT_SAMPLE_COUNT)
val minimum = if (chapterPageCount == 1) 1 else 2
return valid.size >= minimum && valid.count { it.tall }.toDouble() / valid.size >= 0.75
}
/** Direction comes only from explicit metadata or the fallback, never image aspect or language. */
fun resolveAutomaticReaderLayout(
fallback: DbReaderMode,
webtoon: Boolean,
viewport: ReaderViewport,
explicitDirection: ReaderDirection? = null,
pairingOverride: Boolean? = null,
settled: Boolean = true,
): ResolvedReaderLayout {
val direction = explicitDirection ?: if (fallback.isRightToLeft()) ReaderDirection.Rtl else ReaderDirection.Ltr
val mode = if (webtoon) DbReaderMode.Webtoon else when {
explicitDirection != null && fallback.isHorizontalContinuous() -> if (direction == ReaderDirection.Rtl) DbReaderMode.HorizontalContinuousRtl else DbReaderMode.HorizontalContinuous
explicitDirection != null && (fallback == DbReaderMode.Rtl || fallback == DbReaderMode.Ltr) -> if (direction == ReaderDirection.Rtl) DbReaderMode.Rtl else DbReaderMode.Ltr
else -> fallback
}
val pair = pairingOverride ?: (settled && mode.isPaged() && viewport.widthDp >= 840 && viewport.widthDp > viewport.heightDp)
return ResolvedReaderLayout(mode, direction, pair)
}
internal fun automaticLayoutHasWebtoonMetadata(genres: List<String>): Boolean = genres.any {
it.trim().lowercase() in setOf("webtoon", "long strip", "long-strip")
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderPages.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines PagedReaderPages, VerticalReaderPages, webtoonSidePaddingFraction, HorizontalContinuousPages, ReaderDisplayUnitContent, PageImage, ReaderPageImageLoadState, ReaderPageLoadListener.
The source describes its contract as:
Single page image with the reader's color/blend filter applied. [processing] runs inside Coil's decode: border cropping, the displayed half of a split spread, or a quarter turn for landscape pages; each variant is cached separately. Long-press surfaces the image-actions sheet (save / share / set as cover).
Cross-chapter imports used by this file: DbPageUrl, DbReaderMode, DbSettings. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.pager.VerticalPager
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.IntSize
import coil3.compose.AsyncImage
import coil3.compose.LocalPlatformContext
import coil3.request.ImageRequest
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.readerModePreferences
@Composable
internal fun PagedReaderPages(
settings: DbSettings,
units: List<ReaderDisplayUnit>,
pagerState: PagerState,
mode: DbReaderMode,
zoomStateFor: (ReaderStreamItem.Page) -> ReaderZoomState,
onLoadStateChanged: ReaderPageLoadListener,
colorizedPages: Map<ReaderPageIdentity, ColorizedReaderPage>,
modifier: Modifier = Modifier,
) {
if (mode == DbReaderMode.Vertical) {
VerticalPager(
state = pagerState,
beyondViewportPageCount = 1,
modifier = modifier.fillMaxSize(),
) { index ->
ReaderDisplayUnitContent(
unit = units[index],
mode = mode,
settings = settings,
modifier = Modifier.fillMaxSize(),
zoomStateFor = zoomStateFor,
onLoadStateChanged = onLoadStateChanged,
colorizedPages = colorizedPages,
)
}
} else {
HorizontalPager(
state = pagerState,
reverseLayout = mode == DbReaderMode.Rtl,
beyondViewportPageCount = 1,
modifier = modifier.fillMaxSize(),
) { index ->
ReaderDisplayUnitContent(
unit = units[index],
mode = mode,
settings = settings,
modifier = Modifier.fillMaxSize(),
zoomStateFor = zoomStateFor,
onLoadStateChanged = onLoadStateChanged,
colorizedPages = colorizedPages,
)
}
}
}
@Composable
internal fun VerticalReaderPages(
settings: DbSettings,
units: List<ReaderDisplayUnit>,
mode: DbReaderMode,
doublePage: Boolean,
state: LazyListState,
zoomStateFor: (ReaderStreamItem.Page) -> ReaderZoomState,
onLoadStateChanged: ReaderPageLoadListener,
colorizedPages: Map<ReaderPageIdentity, ColorizedReaderPage>,
modifier: Modifier = Modifier,
) {
BoxWithConstraints(modifier = modifier.fillMaxSize()) {
val sidePadding = maxWidth * webtoonSidePaddingFraction(
percent = settings.webtoonSidePadding,
doublePage = doublePage,
)
LazyColumn(
state = state,
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(
if (settings.showPageGaps && mode != DbReaderMode.Webtoon) 8.dp else 0.dp,
),
) {
items(units, key = ReaderDisplayUnit::firstStreamIndex) { unit ->
val isTransition = unit.items.singleOrNull() is ReaderStreamItem.Transition
ReaderDisplayUnitContent(
unit = unit,
mode = mode,
settings = settings,
modifier = if (isTransition) {
Modifier.fillParentMaxHeight().fillMaxWidth()
} else {
Modifier.fillMaxWidth().padding(horizontal = sidePadding)
},
zoomStateFor = zoomStateFor,
onLoadStateChanged = onLoadStateChanged,
colorizedPages = colorizedPages,
)
}
}
}
}
internal fun webtoonSidePaddingFraction(percent: Int, doublePage: Boolean): Float =
if (doublePage) 0f else percent.coerceIn(0, 50) / 100f
@Composable
internal fun HorizontalContinuousPages(
settings: DbSettings,
units: List<ReaderDisplayUnit>,
mode: DbReaderMode,
state: LazyListState,
zoomStateFor: (ReaderStreamItem.Page) -> ReaderZoomState,
onLoadStateChanged: ReaderPageLoadListener,
colorizedPages: Map<ReaderPageIdentity, ColorizedReaderPage>,
modifier: Modifier = Modifier,
) {
LazyRow(
state = state,
modifier = modifier.fillMaxSize(),
horizontalArrangement = Arrangement.spacedBy(if (settings.showPageGaps) 8.dp else 0.dp),
reverseLayout = mode == DbReaderMode.HorizontalContinuousRtl,
) {
items(units, key = ReaderDisplayUnit::firstStreamIndex) { unit ->
val isTransition = unit.items.singleOrNull() is ReaderStreamItem.Transition
ReaderDisplayUnitContent(
unit = unit,
mode = mode,
settings = settings,
modifier = if (isTransition) {
Modifier.fillParentMaxWidth().fillMaxHeight()
} else {
Modifier.fillMaxHeight()
},
zoomStateFor = zoomStateFor,
onLoadStateChanged = onLoadStateChanged,
colorizedPages = colorizedPages,
)
}
}
}
@Composable
private fun ReaderDisplayUnitContent(
unit: ReaderDisplayUnit,
mode: DbReaderMode,
settings: DbSettings,
modifier: Modifier,
zoomStateFor: (ReaderStreamItem.Page) -> ReaderZoomState,
onLoadStateChanged: ReaderPageLoadListener,
colorizedPages: Map<ReaderPageIdentity, ColorizedReaderPage>,
) {
val transition = unit.items.singleOrNull() as? ReaderStreamItem.Transition
if (transition != null) {
ReaderChapterTransitionPage(
currentChapter = transition.completedChapter,
nextChapter = transition.nextChapter,
mangaTitle = transition.mangaTitle,
vertical = mode == DbReaderMode.Vertical || mode.isVerticalLike(),
isRightToLeft = mode.isRightToLeft(),
modifier = modifier,
)
return
}
val pages = unit.items.mapNotNull { it as? ReaderStreamItem.Page }
val preferences = settings.readerModePreferences(mode.isPaged())
if (pages.size == 1) {
val single = pages.single()
PageImage(
single.page,
modifier,
settings,
mode.isPaged(),
zoomStateFor(single),
onLoadStateChanged,
chapterId = single.chapter.id,
chapterPageIndex = single.chapterPageIndex,
colorizedPages = colorizedPages,
processing = readerPageProcessing(single, mode.isRightToLeft(), preferences),
)
return
}
Row(
modifier = modifier,
horizontalArrangement = Arrangement.spacedBy(
if (settings.showPageGaps && mode != DbReaderMode.Webtoon) 8.dp else 0.dp,
),
) {
pages.forEach { item ->
PageImage(
item.page,
Modifier.weight(1f).then(if (mode.isPaged()) Modifier.fillMaxHeight() else Modifier),
settings,
mode.isPaged(),
zoomStateFor(item),
onLoadStateChanged,
chapterId = item.chapter.id,
chapterPageIndex = item.chapterPageIndex,
colorizedPages = colorizedPages,
processing = readerPageProcessing(item, mode.isRightToLeft(), preferences),
)
}
}
}
/**
* Single page image with the reader's color/blend filter applied.
*
* [processing] runs inside Coil's decode: border cropping, the displayed half of a split
* spread, or a quarter turn for landscape pages; each variant is cached separately.
*
* Long-press surfaces the image-actions sheet (save / share / set as cover).
*/
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun PageImage(
page: DbPageUrl?,
modifier: Modifier,
settings: DbSettings,
paged: Boolean,
zoomState: ReaderZoomState,
onLoadStateChanged: ReaderPageLoadListener,
chapterId: Long? = null,
chapterPageIndex: Int? = null,
colorizedPages: Map<ReaderPageIdentity, ColorizedReaderPage> = emptyMap(),
processing: ReaderPageProcessing = ReaderPageProcessing(),
) {
if (page == null) {
Box(modifier = modifier, contentAlignment = Alignment.Center) { Text("Blank page") }
return
}
val context = LocalPlatformContext.current
val override = if (chapterId != null && chapterPageIndex != null) {
colorizedOverrideFor(page, chapterId, chapterPageIndex, colorizedPages)
} else null
val displayPage = override?.let { page.copy(url = "file://${it.filePath}", headers = null) } ?: page
var retryAttempt by remember(page.url, page.headers, chapterId, override?.revision) { mutableIntStateOf(0) }
var imageLoadState by remember(page.url, page.headers, chapterId, override?.revision, processing, retryAttempt) {
mutableStateOf(ReaderPageImageLoadState.Loading)
}
var viewportSize by remember(page.url, override?.revision) { mutableStateOf(IntSize.Zero) }
var imageSize by remember(page.url, page.headers, chapterId, override?.revision, processing, retryAttempt) {
mutableStateOf(IntSize.Zero)
}
val imageRequest = remember(context, page.url, page.headers, chapterId, override?.revision, processing, retryAttempt) {
ImageRequest.Builder(context)
.readerPageData(displayPage, chapterId, override?.revision ?: 0L)
.applyReaderPageProcessing(processing)
.build()
}
val zoomDurationMillis = doubleTapZoomDurationMillis(settings.doubleTapAnimationSpeed)
val colorFilters = remember(
settings.invertColors,
settings.grayscale,
settings.einkMode,
settings.readerBrightness,
settings.readerContrast,
settings.readerSaturation,
settings.enableCustomColorFilter,
settings.customColorFilter,
settings.colorFilterBlendMode,
) {
buildReaderColorFilters(settings)
}
LaunchedEffect(paged, settings.scaleType, imageSize, viewportSize, zoomState) {
zoomState.applyInitialTransform(
readerInitialTransform(
scaleType = settings.scaleType,
imageSize = imageSize,
viewportSize = viewportSize,
paged = paged,
),
)
}
Box(
modifier = modifier
.background(Color.Black.copy(alpha = 0.08f))
.clipToBounds(),
) {
AsyncImage(
model = imageRequest,
contentDescription = page.fileName ?: page.url,
contentScale = settings.scaleType.toContentScale(paged),
colorFilter = colorFilters.tint,
onLoading = {
imageLoadState = ReaderPageImageLoadState.Loading
onLoadStateChanged(page, chapterId, ReaderPageImageLoadState.Loading, null)
},
onSuccess = { success ->
val intrinsic = success.painter.intrinsicSize
if (intrinsic.width.isFinite() && intrinsic.height.isFinite()) {
imageSize = IntSize(intrinsic.width.toInt(), intrinsic.height.toInt())
}
ReaderPageDownloadProgress.clear(page.url)
imageLoadState = ReaderPageImageLoadState.Ready
onLoadStateChanged(page, chapterId, ReaderPageImageLoadState.Ready, null)
},
onError = { error ->
ReaderPageDownloadProgress.clear(page.url)
imageLoadState = ReaderPageImageLoadState.Error
onLoadStateChanged(page, chapterId, ReaderPageImageLoadState.Error, error.result.throwable)
},
modifier = Modifier
.fillMaxSize()
.onSizeChanged {
viewportSize = it
zoomState.updateViewport(it)
}
.clipToBounds()
.readerSecondaryClickZoom(zoomState, zoomDurationMillis)
.graphicsLayer {
scaleX = zoomState.scale
scaleY = zoomState.scale
translationX = zoomState.offset.x
translationY = zoomState.offset.y
colorFilter = colorFilters.tone
}
.readerZoomGestures(zoomState)
)
when (imageLoadState) {
ReaderPageImageLoadState.Loading -> Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center,
) {
// Determinate ring driven by network bytes, mirroring Mangayomi's
// cumulativeBytesLoaded / expectedTotalBytes placeholder.
val progressFlow = remember(page.url) { ReaderPageDownloadProgress.forUrl(page.url) }
val byteProgress = progressFlow.collectAsStateWithLifecycle(initialValue = null).value
if (byteProgress != null && byteProgress > 0f) {
CircularProgressIndicator(progress = { byteProgress })
} else {
CircularProgressIndicator()
}
}
ReaderPageImageLoadState.Error -> Column(
modifier = Modifier
.fillMaxSize()
.combinedClickable(
onClick = { retryAttempt += 1 },
onLongClick = { retryAttempt += 1 },
)
.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Text(
text = "Couldn't load page",
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.titleMedium,
)
Text(
text = "Tap to retry",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
)
}
ReaderPageImageLoadState.Ready -> Unit
}
}
}
internal enum class ReaderPageImageLoadState {
Loading,
Ready,
Error,
}
/** A page image of `chapterId` changed load state; `error` is why it failed. */
internal typealias ReaderPageLoadListener =
(page: DbPageUrl, chapterId: Long?, state: ReaderPageImageLoadState, error: Throwable?) -> Unit
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderRendererSync.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
Renderer state is a measured UI projection of a logical reading anchor. Preserve its reconciliation guards so changing dimensions does not become an unintended progress jump.
The implementation below defines ReaderRendererSync, LazyListState.scrollTo.
The source describes its contract as:
Keeps the active renderer (pager, vertical or horizontal list) and the ViewModel's stream position in step. A ViewModel move scrolls the renderer, jumping directly on initial content/mode replacement and animating page turns only when [animateTransitions] allows it. A user scroll reports the new position through [onPageChanged], preserving the logical page within a regrouped spread.
Cross-chapter imports used by this file: DbReaderMode. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.pager.PagerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.referentialEqualityPolicy
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import eu.friedcutlet.yokan.database.DbReaderMode
private val ReaderPageTransitionEasing = CubicBezierEasing(0.25f, 0.1f, 0.25f, 1f)
/**
* Keeps the active renderer (pager, vertical or horizontal list) and the ViewModel's stream
* position in step. A ViewModel move scrolls the renderer, jumping directly on initial
* content/mode replacement and animating page turns only when [animateTransitions] allows it.
* A user scroll reports the new position through [onPageChanged], preserving the logical page
* within a regrouped spread.
*/
@Composable
internal fun ReaderRendererSync(
displayUnits: List<ReaderDisplayUnit>,
currentStreamIndex: Int,
animatePageChange: Boolean,
mode: DbReaderMode,
animateTransitions: Boolean,
pagerState: PagerState,
verticalState: LazyListState,
horizontalState: LazyListState,
onPageChanged: (Int) -> Unit,
) {
var lastSynchronizedUnits by remember {
mutableStateOf<List<ReaderDisplayUnit>?>(null, referentialEqualityPolicy())
}
var synchronizingRenderer by remember { mutableStateOf(false) }
var synchronizedMode by remember { mutableStateOf<DbReaderMode?>(null) }
val logicalStreamIndex by rememberUpdatedState(currentStreamIndex)
val rendererIndex: () -> Int = when {
mode.isPaged() -> pagerState::currentPage
mode.isVerticalLike() -> verticalState::firstVisibleItemIndex
else -> horizontalState::firstVisibleItemIndex
}
LaunchedEffect(displayUnits, currentStreamIndex, mode, animateTransitions) {
if (displayUnits.isEmpty()) return@LaunchedEffect
val target = displayUnitIndexForStreamIndex(displayUnits, currentStreamIndex)
val animate = animateTransitions && animatePageChange && lastSynchronizedUnits === displayUnits
if (rendererIndex() != target) {
synchronizingRenderer = true
try {
when {
mode.isPaged() -> if (animate) {
pagerState.animateScrollToPage(
page = target,
animationSpec = tween(
durationMillis = ReaderPageTransitionDurationMillis,
easing = ReaderPageTransitionEasing,
),
)
} else {
pagerState.scrollToPage(target)
}
mode.isVerticalLike() -> verticalState.scrollTo(target, animate)
else -> horizontalState.scrollTo(target, animate)
}
} finally {
synchronizingRenderer = false
}
}
lastSynchronizedUnits = displayUnits
synchronizedMode = mode
}
LaunchedEffect(pagerState, verticalState, horizontalState, displayUnits, mode) {
snapshotFlow(rendererIndex).collect { unitIndex ->
if (!synchronizingRenderer && synchronizedMode == mode && lastSynchronizedUnits == displayUnits) {
readerRendererPageChange(displayUnits, unitIndex, logicalStreamIndex)?.let(onPageChanged)
}
}
}
}
private suspend fun LazyListState.scrollTo(index: Int, animate: Boolean) {
if (animate) animateScrollToItem(index) else scrollToItem(index)
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderImageRequests.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ReaderPagePrefetch, ReaderImageRequestLimiter, intercept, limit, loadReaderPagesBounded, chapterPageCacheKey, ImageRequest.Builder.applyReaderPageProcessing, ImageRequest.Builder.readerPageData, readerPageHeaderFingerprint.
The source describes its contract as:
Starts a cancellable Coil prefetch session for the current reader position. Requests are processed in authority order with the same three-worker bound as Mangayomi. This prevents a large preload window from becoming a burst of simultaneous HTTP requests while still keeping the configured cache warm.
Cross-chapter imports used by this file: DbPageUrl. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.channels.Channel
import coil3.Extras
import coil3.getExtra
import coil3.SingletonImageLoader
import coil3.compose.LocalPlatformContext
import coil3.network.NetworkHeaders
import coil3.network.httpHeaders
import coil3.request.ImageRequest
import coil3.request.CachePolicy
import coil3.intercept.Interceptor
import coil3.request.transformations
import eu.friedcutlet.yokan.database.DbPageUrl
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
/**
* Starts a cancellable Coil prefetch session for the current reader position.
*
* Requests are processed in authority order with the same three-worker bound
* as Mangayomi. This prevents a large preload window from becoming a burst of
* simultaneous HTTP requests while still keeping the configured cache warm.
*/
@Composable
internal fun ReaderPagePrefetch(
items: List<ReaderStreamItem>,
currentStreamIndex: Int,
forwardAmount: Int,
layoutSampleKey: String = "",
sampleChapterId: Long? = null,
onShapeSampled: (String, ReaderPageIdentity, ReaderPageShape?) -> Unit = { _, _, _ -> },
) {
if (items.isEmpty()) return
val context = LocalPlatformContext.current
LaunchedEffect(currentStreamIndex, items, forwardAmount, layoutSampleKey, sampleChapterId) {
val loader = SingletonImageLoader.get(context)
loadReaderPagesBounded(
pages = (readerPrefetchPageItems(
items = items,
currentStreamIndex = currentStreamIndex,
forwardAmount = forwardAmount,
) + items.filterIsInstance<ReaderStreamItem.Page>().filter { it.chapter.id == sampleChapterId && it.split != ReaderPageHalf.Second }
.take(AUTOMATIC_LAYOUT_SAMPLE_COUNT)).distinctBy { it.identity() },
) { pageItem ->
try {
// Warm only the disk/network caches: a target-less request decodes at original size
// without the visible page's transformations, so its bitmap would just evict usable ones.
val result = loader.execute(
ImageRequest.Builder(context)
.readerPageData(pageItem.page, pageItem.chapter.id)
.memoryCachePolicy(CachePolicy.DISABLED)
.build(),
)
val shape = (result as? coil3.request.SuccessResult)?.image?.let { ReaderPageShape(it.width, it.height) }
onShapeSampled(layoutSampleKey, pageItem.identity(), shape)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (_: Throwable) {
onShapeSampled(layoutSampleKey, pageItem.identity(), null)
// Prefetch failures are rendered and retried by the visible page.
}
}
}
}
internal const val READER_PREFETCH_CONCURRENCY = 3
private val ReaderPageRequestExtra = Extras.Key(default = false)
internal class ReaderImageRequestLimiter(
maxConcurrent: Int = READER_PREFETCH_CONCURRENCY,
) : Interceptor {
private val semaphore = Semaphore(maxConcurrent)
override suspend fun intercept(chain: Interceptor.Chain) =
if (chain.request.getExtra(ReaderPageRequestExtra)) {
limit { chain.proceed() }
} else {
chain.proceed()
}
internal suspend fun <T> limit(block: suspend () -> T): T = semaphore.withPermit { block() }
}
internal val ReaderPageRequestLimiter = ReaderImageRequestLimiter()
internal suspend fun <T> loadReaderPagesBounded(
pages: List<T>,
maxConcurrent: Int = READER_PREFETCH_CONCURRENCY,
load: suspend (T) -> Unit,
) {
require(maxConcurrent > 0)
if (pages.isEmpty()) return
coroutineScope {
val queue = Channel<T>(Channel.UNLIMITED)
pages.forEach { queue.trySend(it) }
queue.close()
repeat(minOf(maxConcurrent, pages.size)) {
launch {
for (page in queue) load(page)
}
}
}
}
internal fun chapterPageCacheKey(
chapterId: Long?,
url: String,
headers: Map<String, String>? = null,
): String {
val prefix = if (chapterId != null && chapterId > 0L) "ch_${chapterId}_" else ""
val headerSuffix = headers?.takeIf { it.isNotEmpty() }?.let { "#readerHeaders=${readerPageHeaderFingerprint(it)}" } ?: ""
return "$prefix$url$headerSuffix"
}
/** Explicit memory keys ignore transformations; every processing variant adds its own key extra. */
internal fun ImageRequest.Builder.applyReaderPageProcessing(processing: ReaderPageProcessing): ImageRequest.Builder = apply {
val steps = ArrayList<coil3.transform.Transformation>(3)
if (processing.cropBorders) {
steps += createBorderCropTransformation()
memoryCacheKeyExtra("borderCrop", "true")
}
processing.leftHalf?.let { left ->
steps += createPageHalfTransformation(left)
memoryCacheKeyExtra("pageHalf", if (left) "left" else "right")
}
if (processing.rotation != 0) {
steps += createWidePageRotation(processing.rotation)
memoryCacheKeyExtra("rotateWide", processing.rotation.toString())
}
if (steps.isNotEmpty()) transformations(steps)
}
internal fun ImageRequest.Builder.readerPageData(
page: DbPageUrl,
chapterId: Long? = null,
revision: Long = 0L,
): ImageRequest.Builder = apply {
data(page.url)
extras[ReaderPageRequestExtra] = true
extras[eu.friedcutlet.yokan.ui.image.ImageChapterIdExtra] = chapterId
val headers = page.headers.orEmpty()
val cacheKey = chapterPageCacheKey(chapterId, page.url, headers.takeIf { it.isNotEmpty() }) + "#revision=$revision"
memoryCacheKey(cacheKey)
diskCacheKey(cacheKey)
if (headers.isNotEmpty()) {
val networkHeaders = NetworkHeaders.Builder().apply {
headers.forEach { (name, value) -> set(name, value) }
}.build()
httpHeaders(networkHeaders)
}
}
internal fun readerPageHeaderFingerprint(headers: Map<String, String>): String {
var hash = 14695981039346656037uL
headers.entries
.sortedWith(compareBy({ it.key.lowercase() }, { it.key }, { it.value }))
.forEach { (name, value) ->
for (character in name.lowercase()) {
hash = (hash xor character.code.toULong()) * 1099511628211uL
}
hash = (hash xor 0uL) * 1099511628211uL
for (character in value) {
hash = (hash xor character.code.toULong()) * 1099511628211uL
}
hash = (hash xor 0xFFuL) * 1099511628211uL
}
return hash.toString(16)
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderImageWork.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ReaderImageWork, open, close, setAsCover, export, openColorizer, closeColorizer, importModel, removeModel, selectCrop and 19 further declarations.
The source describes its contract as:
Image actions of one reader session: resolving page bytes, export/share/save, custom cover, the panel colorizer and its session cache. [ReaderViewModel] owns [scope] and the state; [state], [update] and [emit] reach them.
Cross-chapter imports used by this file: YokanRepository, DbPageUrl, LocalFileService, pickFile, HttpRequest, AppLogger. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.colorization.PanelColorizer
import eu.friedcutlet.yokan.services.colorization.PanelCrop
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.files.pickFile
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.logging.AppLogger
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.compose.resources.getString
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.colorizer_export_failed
import yokan.composeapp.generated.resources.picture_saved
/**
* Image actions of one reader session: resolving page bytes, export/share/save, custom cover,
* the panel colorizer and its session cache. [ReaderViewModel] owns [scope] and the state;
* [state], [update] and [emit] reach them.
*/
internal class ReaderImageWork(
private val scope: CoroutineScope,
private val workDispatcher: CoroutineDispatcher,
private val localFiles: LocalFileService,
private val imageHttp: HttpService,
private val repository: YokanRepository,
panelColorizer: Lazy<PanelColorizer>,
private val saveImagesInTitleFolder: () -> Boolean,
private val state: () -> ReaderState,
private val update: ((ReaderState) -> ReaderState) -> Unit,
private val emit: suspend (ReaderEffect) -> Unit,
) {
private val panelColorizer by panelColorizer
private var imageActionJob: Job? = null
private var imageActionsGeneration = 0
private var imageActionItem: ReaderStreamItem.Page? = null
private var colorizerJob: Job? = null
private var colorizerGeneration = 0
private val colorizedRevisions = mutableMapOf<ReaderPageIdentity, Long>()
private var colorizedSessionPath: String? = null
fun open(item: ReaderStreamItem.Page) {
val page = item.page
if (page.url.isBlank()) return
imageActionsGeneration++
val generation = imageActionsGeneration
imageActionItem = item
imageActionJob?.cancel()
imageActionJob = scope.launch {
val identity = item.identity()
if (!isCurrentReaderPage(identity)) return@launch
val override = state().colorizedPages[identity]
val bytes = if (override != null) readOverride(override) else resolvePageBytes(page)
if (generation != imageActionsGeneration || !isCurrentReaderPage(identity) || bytes == null) return@launch
val originalBytes = if (override != null) resolvePageBytes(page) else bytes
if (generation != imageActionsGeneration || !isCurrentReaderPage(identity) || originalBytes == null) return@launch
val pageIndex = item.chapterPageIndex + 1
val imageFormat = readerImageFormat(bytes)
val fileName = readerImageFileName(
mangaTitle = state().manga.name,
chapterTitle = item.chapter.name,
pageIndex = pageIndex,
extension = imageFormat.extension,
)
val originalFileName = readerImageFileName(
mangaTitle = state().manga.name,
chapterTitle = item.chapter.name,
pageIndex = pageIndex,
extension = readerImageFormat(originalBytes).extension,
)
update {
val unit = readerDisplayUnits(it.streamItems, it.mode, it.doublePage, it.pageShapes, it.automaticPairing)
.firstOrNull { candidate -> item in candidate.items }
it.copy(
imageActionsTarget = ResolvedReaderImage(
item = item,
page = page,
bytes = bytes,
originalBytes = originalBytes,
fileName = fileName,
originalFileName = originalFileName,
mimeType = imageFormat.mimeType,
spreadPartner = unit?.items?.filterIsInstance<ReaderStreamItem.Page>()
?.takeIf { pages -> pages.size == 2 }?.firstOrNull { other -> other != item },
),
)
}
}
}
/** Drops the action target and any colorizer work on it. */
fun close() {
cancelWork()
update { it.copy(imageActionsTarget = null, colorizer = ReaderColorizerState()) }
}
fun setAsCover() {
val target = state().imageActionsTarget ?: return
if (target.bytes.size >= MAX_COVER_BYTES) {
scope.launch { emit(ReaderEffect.ShowMessage("Cover image must be smaller than 5 MB")) }
return
}
scope.launch {
repository.setMangaCustomCover(state().manga.id, target.bytes) ?: return@launch
emit(ReaderEffect.ShowMessage("Cover updated"))
update { it.copy(imageActionsTarget = null) }
}
}
fun export(export: ReaderImageExport, spread: Boolean) {
val target = state().imageActionsTarget ?: return
scope.launch {
val image = if (spread) mergedSpread(target) else Triple(target.bytes, target.fileName, target.mimeType)
val done = image != null && when (export) {
ReaderImageExport.Save -> saveImageToGallery(image.first, image.second, image.third, imageFolder())
ReaderImageExport.Share -> shareImage(image.first, image.second, image.third)
ReaderImageExport.Copy -> copyImageToClipboard(image.first, image.second, image.third)
}
val message = when (export) {
ReaderImageExport.Save -> if (done) "Picture saved" else "Save failed"
ReaderImageExport.Share -> if (done) null else "Share failed"
ReaderImageExport.Copy -> if (done) "Image copied" else "Copy failed"
}
message?.let { emit(ReaderEffect.ShowMessage(it)) }
}
}
fun openColorizer() = update { current ->
current.copy(
colorizer = ReaderColorizerState(
open = true,
supported = panelColorizer.supported,
modelInstalled = panelColorizer.installed(),
hasAppliedColorization = current.imageActionsTarget?.let { target ->
target.item.identity() in current.colorizedPages
} == true,
),
)
}
fun closeColorizer() {
colorizerGeneration++
colorizerJob?.cancel()
update { it.copy(colorizer = ReaderColorizerState()) }
}
fun importModel() = runColorizerWork(ColorizerWork.Importing, ColorizerError.ImportFailed) {
val path = pickFile(listOf("onnx")) ?: return@runColorizerWork
panelColorizer.importModel(path)
update { it.copy(colorizer = it.colorizer.copy(modelInstalled = true)) }
}
fun removeModel() = runColorizerWork(ColorizerWork.Importing, ColorizerError.RemoveFailed) {
panelColorizer.removeModel()
update { it.copy(colorizer = it.colorizer.copy(modelInstalled = false, preview = null)) }
}
fun selectCrop(crop: PanelCrop) {
if (!crop.valid() || state().colorizer.work != ColorizerWork.Idle) return
update { it.copy(colorizer = it.colorizer.copy(crop = crop, preview = null, error = null)) }
}
fun toggleOriginal() = update { it.copy(colorizer = it.colorizer.copy(showOriginal = !it.colorizer.showOriginal)) }
fun colorize() {
val source = state().imageActionsTarget ?: return
val crop = state().colorizer.crop
val identity = source.item.identity()
val generationAtStart = imageActionsGeneration
val workGeneration = colorizerGeneration + 1
runColorizerWork(ColorizerWork.Colorizing, ColorizerError.InferenceFailed) {
// A later edit starts from the displayed derivative, not the source page.
val bytes = panelColorizer.colorizePage(source.bytes, crop)
if (!canApplyColorizationResult(generationAtStart, imageActionsGeneration, identity, state().streamItems) || workGeneration != colorizerGeneration) return@runColorizerWork
val revision = (colorizedRevisions[identity] ?: 0L) + 1
val path = readerColorizedCachePath(colorizedCacheDirectory(), identity, revision)
withContext(workDispatcher) { localFiles.writeBytes(path, bytes) }
if (!canApplyColorizationResult(generationAtStart, imageActionsGeneration, identity, state().streamItems) || workGeneration != colorizerGeneration) {
localFiles.deleteRecursively(path)
return@runColorizerWork
}
val previousPath = state().colorizedPages[identity]?.filePath
colorizedRevisions[identity] = revision
update {
val target = it.imageActionsTarget?.takeIf { target -> target.item.identity() == identity }
if (target == null) it else it.copy(
colorizedPages = it.colorizedPages + (identity to ColorizedReaderPage(identity, revision, path)),
imageActionsTarget = target.copy(bytes = bytes, mimeType = "image/png", fileName = colorizedFileName()),
colorizer = it.colorizer.copy(preview = bytes, showOriginal = false, hasAppliedColorization = true),
)
}
previousPath?.let(localFiles::deleteRecursively)
}
}
fun restoreOriginal() {
val target = state().imageActionsTarget ?: return
val identity = target.item.identity()
val override = state().colorizedPages[identity] ?: return
localFiles.deleteRecursively(override.filePath)
update {
val current = it.imageActionsTarget?.takeIf { action -> action.item.identity() == identity }
it.copy(
colorizedPages = it.colorizedPages - identity,
imageActionsTarget = current?.copy(
bytes = current.originalBytes,
fileName = current.originalFileName,
mimeType = restoredReaderImageMimeType(current),
),
colorizer = it.colorizer.copy(preview = null, showOriginal = true, hasAppliedColorization = false),
)
}
}
fun saveColorized() {
val bytes = state().colorizer.preview ?: return
val name = colorizedFileName()
scope.launch {
val saved = saveImageToGallery(bytes, name, "image/png", imageFolder())
emit(ReaderEffect.ShowMessage(getString(if (saved) Res.string.picture_saved else Res.string.colorizer_export_failed)))
}
}
fun shareColorized() {
val bytes = state().colorizer.preview ?: return
if (!shareImage(bytes, colorizedFileName(), "image/png")) scope.launch {
emit(ReaderEffect.ShowMessage(getString(Res.string.colorizer_export_failed)))
}
}
/** Drops colorized derivatives of [chapterId], whose page list changed. */
fun invalidateChapter(chapterId: Long) {
if (imageActionItem?.chapter?.id == chapterId || state().imageActionsTarget?.item?.chapter?.id == chapterId) cancelWork()
state().colorizedPages.filterKeys { it.chapterId == chapterId }.values.forEach { localFiles.deleteRecursively(it.filePath) }
update { current ->
val target = current.imageActionsTarget?.takeUnless { it.item.chapter.id == chapterId }
current.copy(
colorizedPages = current.colorizedPages.filterKeys { it.chapterId != chapterId },
imageActionsTarget = target,
colorizer = if (target == null) ReaderColorizerState() else current.colorizer,
)
}
}
fun cancel() {
imageActionJob?.cancel()
colorizerJob?.cancel()
imageActionJob = null
}
/** Deletes this session's colorized cache; throws when files remain so cleanup retries. */
fun deleteCache() {
colorizedSessionPath?.let { path ->
check(localFiles.deleteRecursively(path) || !localFiles.exists(path)) { "Reader cache cleanup failed" }
}
colorizedSessionPath = null
}
private fun cancelWork() {
imageActionsGeneration++
imageActionJob?.cancel()
imageActionItem = null
colorizerGeneration++
colorizerJob?.cancel()
}
private fun runColorizerWork(work: ColorizerWork, error: ColorizerError, block: suspend () -> Unit) {
if (!state().colorizer.open || state().colorizer.work != ColorizerWork.Idle) return
update { it.copy(colorizer = it.colorizer.copy(work = work, error = null)) }
val generation = ++colorizerGeneration
colorizerJob = scope.launch {
try { block() }
catch (cancelled: CancellationException) { throw cancelled }
catch (failure: Exception) {
AppLogger.warn("Panel colorization failed: ${failure.message}")
if (generation == colorizerGeneration) {
update { it.copy(colorizer = it.colorizer.copy(error = error)) }
}
} finally {
// A dismissed panel may have been replaced while a native call was finishing.
if (generation == colorizerGeneration && state().colorizer.work == work) update { it.copy(colorizer = it.colorizer.copy(work = ColorizerWork.Idle)) }
}
}
}
private fun colorizedCacheDirectory(): String = colorizedSessionPath ?:
"${localFiles.cacheRoot.trimEnd('/')}/reader-colorized/${nextReaderSessionId()}".also { colorizedSessionPath = it }
private fun isCurrentReaderPage(identity: ReaderPageIdentity): Boolean =
canApplyColorizationResult(imageActionsGeneration, imageActionsGeneration, identity, state().streamItems)
private fun colorizedFileName() = state().imageActionsTarget?.originalFileName.orEmpty().substringBeforeLast('.') + "-colorized.png"
private fun imageFolder(): String? = state().manga.name.takeIf { saveImagesInTitleFolder() }?.let(::readerImageFolderName)
private suspend fun readOverride(override: ColorizedReaderPage): ByteArray? =
catchingNonCancellation { withContext(workDispatcher) { localFiles.readBytes(override.filePath) } }.getOrNull()
/** The spread as displayed: reading order, mirrored for right-to-left modes. */
private suspend fun mergedSpread(target: ResolvedReaderImage): Triple<ByteArray, String, String>? {
val partner = target.spreadPartner ?: return null
val partnerBytes = state().colorizedPages[partner.identity()]?.let { readOverride(it) }
?: resolvePageBytes(partner.page) ?: return null
val partnerFirst = partner.chapterPageIndex < target.item.chapterPageIndex
val (first, second) = if (partnerFirst) partnerBytes to target.bytes else target.bytes to partnerBytes
val (left, right) = if (state().mode.isRightToLeft()) second to first else first to second
val merged = catchingNonCancellation { withContext(workDispatcher) { mergeSpreadImages(left, right) } }.getOrNull() ?: return null
val firstPage = minOf(partner.chapterPageIndex, target.item.chapterPageIndex) + 1
val name = readerImageFileName(state().manga.name, target.item.chapter.name, firstPage, "jpg")
.removeSuffix(".jpg") + "-${firstPage + 1}.jpg"
return Triple(merged, name, "image/jpeg")
}
private suspend fun resolvePageBytes(page: DbPageUrl): ByteArray? {
val localPath = page.url.removePrefix("file://")
if (page.url.startsWith("file://") || localFiles.exists(localPath)) {
return catchingNonCancellation {
withContext(workDispatcher) { localFiles.readBytes(localPath) }
}.getOrElse {
emit(ReaderEffect.ShowMessage("Image could not be read"))
null
}
}
val response = catchingNonCancellation {
imageHttp.request(HttpRequest(url = page.url, method = "GET", headers = page.headers.orEmpty()))
}.getOrNull() ?: run {
emit(ReaderEffect.ShowMessage("Download failed"))
return null
}
if (response.statusCode !in 200..299) {
emit(ReaderEffect.ShowMessage("Download failed (${response.statusCode})"))
return null
}
return response.bodyBytes
}
}
private fun nextReaderSessionId(): Long = readerSessionCounter++
private var readerSessionCounter = 0L
internal fun restoredReaderImageMimeType(target: ResolvedReaderImage): String =
readerImageFormat(target.originalBytes).mimeType
private const val MAX_COVER_BYTES = 5 * 1024 * 1024
Check your understanding
Rotate or change layout while an image is loading. Check that the same logical page remains anchored and visible earlier chapters keep their protection leases. [chapter-content-end]: #
Step 3: add gestures and chrome
Implement tap zones, swipe, zoom/pan, hold scrolling, auto-scroll, long-press actions and controls overlays in independently testable policies. Gesture arbitration must distinguish scroll/zoom/actions and respect direction/preferences. Add bottom bar, page numbers, progress, page download indicators and settings sheets. Avoid repeated progress writes on every transient pixel change.
Use ReaderSystemUi for orientation, bars, brightness/keep-awake and restore them on exit. Respect device capabilities, TV controls, e-ink and reduced motion. Share reading-time accounting through ReadingSessionClock, preserving incognito behavior.
Follow the code
Gesture handlers arbitrate taps, scroll, pan/zoom, hold and automatic movement using the active reading direction/preferences. Build them as policies before attaching visual chrome. Controls and settings dispatch callbacks into the owner rather than writing arbitrary progress from composition. System UI actuals acquire brightness/orientation/keep-awake behavior and restore prior state on exit.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderGestures.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderZoom.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderScreen.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderSystemUi.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderAutoScroll.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderBottomBar.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderHoldScroll.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderOverlays.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderPageDownloadProgress.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderSettingsSheet.ktcomposeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderSystemUi.android.ktcomposeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderSystemUi.desktop.ktcomposeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderSystemUi.ios.ktcomposeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderSystemUi.wasm.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderGestures.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines TapNavLayout, fromIndex, TapZoneAction, Prev, Next, ToggleChrome, computeTapAction, sideAction, Modifier.readerTapZones, readerKeyEventHandler and 4 further declarations.
The source describes its contract as:
Six navigation layouts mirroring the Flutter
reader_gesture_handler.dart(which mirrors Mihon). Index lives inDbReaderModePreferences.navigationLayout. 0 Default 3-column + top/bottom strips 1 L-shaped top-left = prev, bottom-right = next, rest = chrome 2 Kindle top = chrome, bottom split (left = prev, right = next) 3 Edge thin strips at left/right for prev/next, middle = chrome 4 Right/Left left half = prev, right half = next 5 Disabled whole surface only toggles chrome For RTL modes, only left/right zone semantics are flipped; Default's top/bottom actions remain previous/next.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEvent
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.isShiftPressed
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.PointerInputScope
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.IntSize
/**
* Six navigation layouts mirroring the Flutter `reader_gesture_handler.dart`
* (which mirrors Mihon). Index lives in `DbReaderModePreferences.navigationLayout`.
*
* 0 Default 3-column + top/bottom strips
* 1 L-shaped top-left = prev, bottom-right = next, rest = chrome
* 2 Kindle top = chrome, bottom split (left = prev, right = next)
* 3 Edge thin strips at left/right for prev/next, middle = chrome
* 4 Right/Left left half = prev, right half = next
* 5 Disabled whole surface only toggles chrome
*
* For RTL modes, only left/right zone semantics are flipped; Default's
* top/bottom actions remain previous/next.
*/
internal enum class TapNavLayout {
Default, LShaped, Kindle, Edge, RightLeft, Disabled;
companion object {
fun fromIndex(i: Int): TapNavLayout = entries.getOrNull(i) ?: Default
}
}
internal sealed interface TapZoneAction {
data object Prev : TapZoneAction
data object Next : TapZoneAction
data object ToggleChrome : TapZoneAction
}
/**
* Maps a tap offset within the reader viewport to a navigation action. Pure
* function — no Compose state — so it's trivially testable.
*
* `xRatio` / `yRatio` are normalized in [0, 1]. Zone fractions match the
* Flutter implementation: Default uses 2:5:2 vertically, L-shaped corners
* use quarter-height rows, Kindle reserves the top quarter for chrome, and
* Edge uses 1:5:1 columns.
*/
internal fun computeTapAction(
layout: TapNavLayout,
offset: Offset,
size: IntSize,
usePageTapZones: Boolean,
isRightToLeft: Boolean = false,
hasImageError: Boolean = false,
): TapZoneAction {
if (!usePageTapZones) return TapZoneAction.ToggleChrome
if (size.width <= 0 || size.height <= 0) return TapZoneAction.ToggleChrome
val x = (offset.x / size.width).coerceIn(0f, 1f)
val y = (offset.y / size.height).coerceIn(0f, 1f)
fun sideAction(action: TapZoneAction): TapZoneAction =
if (!isRightToLeft) action else when (action) {
TapZoneAction.Prev -> TapZoneAction.Next
TapZoneAction.Next -> TapZoneAction.Prev
TapZoneAction.ToggleChrome -> TapZoneAction.ToggleChrome
}
return when (layout) {
TapNavLayout.Default -> when {
y < 2f / 9f -> if (hasImageError) TapZoneAction.ToggleChrome else TapZoneAction.Prev
y > 7f / 9f -> if (hasImageError) TapZoneAction.ToggleChrome else TapZoneAction.Next
x < 1f / 3f -> sideAction(TapZoneAction.Prev)
x > 2f / 3f -> sideAction(TapZoneAction.Next)
else -> TapZoneAction.ToggleChrome
}
TapNavLayout.LShaped -> when {
y < 0.25f && x < 1f / 3f -> sideAction(TapZoneAction.Prev)
y > 0.75f && x > 2f / 3f -> sideAction(TapZoneAction.Next)
else -> TapZoneAction.ToggleChrome
}
TapNavLayout.Kindle -> when {
y < 0.25f -> TapZoneAction.ToggleChrome
x < 0.5f -> sideAction(TapZoneAction.Prev)
else -> sideAction(TapZoneAction.Next)
}
TapNavLayout.Edge -> when {
x < 1f / 7f -> sideAction(TapZoneAction.Prev)
x > 6f / 7f -> sideAction(TapZoneAction.Next)
else -> TapZoneAction.ToggleChrome
}
TapNavLayout.RightLeft ->
sideAction(if (x < 0.5f) TapZoneAction.Prev else TapZoneAction.Next)
TapNavLayout.Disabled -> TapZoneAction.ToggleChrome
}
}
/**
* Single full-screen tap detector. Applied to the Box that contains the
* page renderer — does NOT replace the page renderer's own pointer input,
* so HorizontalPager swipes and LazyList scrolling continue to work
* (`detectTapGestures` cancels on drag and parent + child pointerInputs
* coexist via Compose's gesture pass system).
*
* Single tap → zone-mapped action via [computeTapAction].
* Double tap → delegated to the page renderer (zoom) while suppressing two single taps.
*/
@Composable
internal fun Modifier.readerTapZones(
layout: TapNavLayout,
usePageTapZones: Boolean,
hasImageError: Boolean,
isRightToLeft: Boolean,
onToggleChrome: () -> Unit,
onPreviousPage: () -> Unit,
onNextPage: () -> Unit,
onDoubleTap: (Offset, IntSize) -> Unit,
onLongPress: (Offset, IntSize) -> Unit,
longPressImageActions: Boolean = true,
): Modifier {
val layoutRef by rememberUpdatedState(layout)
val zonesRef by rememberUpdatedState(usePageTapZones)
val rtlRef by rememberUpdatedState(isRightToLeft)
val errorRef by rememberUpdatedState(hasImageError)
val toggleRef by rememberUpdatedState(onToggleChrome)
val prevRef by rememberUpdatedState(onPreviousPage)
val nextRef by rememberUpdatedState(onNextPage)
val doubleRef by rememberUpdatedState(onDoubleTap)
val longPressRef by rememberUpdatedState(onLongPress)
return this.then(
Modifier.pointerInput(longPressImageActions) {
detectTapGestures(
onTap = { offset ->
when (computeTapAction(layoutRef, offset, size, zonesRef, rtlRef, errorRef)) {
TapZoneAction.Prev -> prevRef()
TapZoneAction.Next -> nextRef()
TapZoneAction.ToggleChrome -> toggleRef()
}
},
onDoubleTap = { offset -> doubleRef(offset, size) },
onLongPress = if (longPressImageActions) ({ offset -> longPressRef(offset, size) }) else null,
)
},
)
}
/**
* Keyboard handler — direct port of `ReaderKeyboardHandler` from the Flutter
* implementation. Mounted on a stable focused ancestor of the Scaffold so it
* fires regardless of which chrome element currently owns focus (Slider, IconButton, etc.).
*
* With [volumeKeys], hardware volume down/up turn to the next/previous page (swapped by
* [invertVolumeKeys]); both key edges are consumed so the system volume stays unchanged.
*/
internal fun readerKeyEventHandler(
isRightToLeft: Boolean,
onBack: () -> Unit,
onFullscreen: () -> Unit,
onPreviousPage: () -> Unit,
onNextPage: () -> Unit,
onPreviousChapter: () -> Unit,
onNextChapter: () -> Unit,
volumeKeys: Boolean = false,
invertVolumeKeys: Boolean = false,
): (KeyEvent) -> Boolean = handler@{ event ->
val volumeStep = readerVolumeKeyStep(event.key, volumeKeys, invertVolumeKeys)
if (volumeStep != 0) {
if (event.type == KeyEventType.KeyDown) {
if (volumeStep > 0) onNextPage() else onPreviousPage()
}
return@handler true
}
if (event.type != KeyEventType.KeyDown) return@handler false
when (event.key) {
Key.F11 -> { onFullscreen(); true }
Key.Escape, Key.Backspace -> { onBack(); true }
Key.DirectionUp -> { onPreviousPage(); true }
Key.DirectionDown, Key.Spacebar -> { onNextPage(); true }
Key.DirectionLeft -> { if (isRightToLeft) onNextPage() else onPreviousPage(); true }
Key.DirectionRight -> { if (isRightToLeft) onPreviousPage() else onNextPage(); true }
Key.N -> { onNextChapter(); true }
Key.P -> { onPreviousChapter(); true }
Key.PageDown -> { onNextChapter(); true }
Key.PageUp -> { onPreviousChapter(); true }
Key.ShiftLeft -> if (event.isShiftPressed) { onPreviousChapter(); true } else false
Key.ShiftRight -> if (event.isShiftPressed) { onNextChapter(); true } else false
else -> false
}
}
/** Page step for a hardware volume key: +1 next, -1 previous, 0 when not handled. */
internal fun readerVolumeKeyStep(key: Key, enabled: Boolean, invert: Boolean): Int {
if (!enabled) return 0
val step = when (key) {
Key.VolumeDown -> 1
Key.VolumeUp -> -1
else -> return 0
}
return if (invert) -step else step
}
internal fun Modifier.readerKeyEvents(
isRightToLeft: Boolean,
volumeKeys: Boolean,
invertVolumeKeys: Boolean,
onBack: () -> Unit,
onFullscreen: () -> Unit,
onPreviousPage: () -> Unit,
onNextPage: () -> Unit,
onPreviousChapter: () -> Unit,
onNextChapter: () -> Unit,
): Modifier = onPreviewKeyEvent(
readerKeyEventHandler(
isRightToLeft = isRightToLeft,
onBack = onBack,
onFullscreen = onFullscreen,
onPreviousPage = onPreviousPage,
onNextPage = onNextPage,
onPreviousChapter = onPreviousChapter,
onNextChapter = onNextChapter,
volumeKeys = volumeKeys,
invertVolumeKeys = invertVolumeKeys,
),
)
/**
* Mouse-wheel page nav. Only active in paged modes (Ltr/Rtl + double-page);
* continuous modes let the lazy lists handle wheel naturally.
*
* `vertical.scrollDelta > 0` is wheel-down → next page. The caller resolves
* RTL before passing callbacks.
*/
@Composable
internal fun Modifier.readerMouseWheelNav(
enabled: Boolean,
onPreviousPage: () -> Unit,
onNextPage: () -> Unit,
): Modifier {
val prev by rememberUpdatedState(onPreviousPage)
val next by rememberUpdatedState(onNextPage)
return if (!enabled) this else this.then(
Modifier.pointerInput(Unit) { handleMouseWheel(prev, next) }
)
}
private suspend fun PointerInputScope.handleMouseWheel(onPrev: () -> Unit, onNext: () -> Unit) {
awaitPointerEventScope {
while (true) {
val event = awaitPointerEvent()
if (event.type != PointerEventType.Scroll) continue
val change = event.changes.firstOrNull() ?: continue
val deltaY = change.scrollDelta.y
if (deltaY > 0f) onNext() else if (deltaY < 0f) onPrev()
change.consume()
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderZoom.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ReaderZoomState, updateViewport, applyInitialTransform, transform, toggleZoom, fling, Modifier.readerZoomGestures, Modifier.readerSecondaryClickZoom, doubleTapZoomOffset, constrainZoomOffset and 1 further declarations.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.VectorConverter
import androidx.compose.animation.core.animate
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.exponentialDecay
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.calculateCentroid
import androidx.compose.foundation.gestures.calculatePan
import androidx.compose.foundation.gestures.calculateZoom
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.isSecondaryPressed
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.util.VelocityTracker
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.Velocity
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
internal class ReaderZoomState {
var scale by mutableFloatStateOf(1f)
private set
var offset by mutableStateOf(Offset.Zero)
private set
var lastPointerPosition by mutableStateOf(Offset.Zero)
internal set
private var viewportSize by mutableStateOf(IntSize.Zero)
fun updateViewport(size: IntSize) {
viewportSize = size
offset = constrainZoomOffset(offset, scale, viewportSize)
}
fun applyInitialTransform(transform: ReaderInitialTransform) {
scale = transform.scale.coerceIn(MIN_ZOOM, MAX_ZOOM)
offset = constrainZoomOffset(transform.offset, scale, viewportSize)
}
fun transform(centroid: Offset, pan: Offset, zoomChange: Float) {
val oldScale = scale
val newScale = (oldScale * zoomChange).coerceIn(MIN_ZOOM, MAX_ZOOM)
val center = viewportSize.centerOffset()
val ratio = newScale / oldScale
val transformed = offset * ratio + pan + (centroid - center) * (1f - ratio)
scale = newScale
offset = if (newScale == MIN_ZOOM) {
Offset.Zero
} else {
constrainZoomOffset(transformed, newScale, viewportSize)
}
}
suspend fun toggleZoom(tapPosition: Offset, durationMillis: Int) {
val targetScale = if (scale > MIN_ZOOM + 0.01f) MIN_ZOOM else DOUBLE_TAP_ZOOM
val targetOffset = if (targetScale == MIN_ZOOM) {
Offset.Zero
} else {
doubleTapZoomOffset(tapPosition, targetScale, viewportSize)
}
val startScale = scale
val startOffset = offset
animate(
initialValue = 0f,
targetValue = 1f,
animationSpec = tween(durationMillis, easing = ReaderZoomEasing),
) { progress, _ ->
scale = startScale + (targetScale - startScale) * progress
offset = Offset(
x = startOffset.x + (targetOffset.x - startOffset.x) * progress,
y = startOffset.y + (targetOffset.y - startOffset.y) * progress,
)
}
}
suspend fun fling(velocity: Velocity) {
if (scale <= MIN_ZOOM) return
val animation = Animatable(offset, Offset.VectorConverter)
animation.animateDecay(
initialVelocity = Offset(velocity.x, velocity.y),
animationSpec = exponentialDecay(),
) {
val constrained = constrainZoomOffset(value, scale, viewportSize)
offset = constrained
}
}
}
internal fun Modifier.readerZoomGestures(state: ReaderZoomState): Modifier = pointerInput(state) {
coroutineScope {
var flingJob: Job? = null
awaitEachGesture {
flingJob?.cancel()
val velocityTracker = VelocityTracker()
var handled = false
val firstDown = awaitFirstDown(requireUnconsumed = false)
state.lastPointerPosition = firstDown.position
do {
val event = awaitPointerEvent(PointerEventPass.Main)
event.changes.firstOrNull { it.pressed && !it.previousPressed }?.let {
state.lastPointerPosition = it.position
}
val pressedCount = event.changes.count { it.pressed }
val zoomChange = event.calculateZoom()
if (pressedCount > 0 && (pressedCount > 1 || state.scale > MIN_ZOOM)) {
val centroid = event.calculateCentroid(useCurrent = true)
velocityTracker.addPosition(event.changes.first().uptimeMillis, centroid)
state.transform(
centroid = centroid,
pan = event.calculatePan(),
zoomChange = zoomChange,
)
handled = true
event.changes.forEach { it.consume() }
}
} while (event.changes.any { it.pressed })
if (handled && state.scale > MIN_ZOOM) {
val velocity = velocityTracker.calculateVelocity()
flingJob = launch { state.fling(velocity) }
}
}
}
}
internal fun Modifier.readerSecondaryClickZoom(
state: ReaderZoomState,
durationMillis: Int,
): Modifier = pointerInput(state, durationMillis) {
coroutineScope {
val animationScope = this
var animationJob: Job? = null
awaitPointerEventScope {
while (true) {
val event = awaitPointerEvent(PointerEventPass.Main)
if (event.type == PointerEventType.Press && event.buttons.isSecondaryPressed) {
val position = event.changes.firstOrNull()?.position ?: continue
state.lastPointerPosition = position
event.changes.forEach { it.consume() }
animationJob?.cancel()
animationJob = animationScope.launch {
state.toggleZoom(position, durationMillis)
}
}
}
}
}
}
internal fun doubleTapZoomOffset(
tapPosition: Offset,
targetScale: Float,
viewportSize: IntSize,
): Offset {
val center = viewportSize.centerOffset()
return constrainZoomOffset(
offset = (center - tapPosition) * (targetScale - 1f),
scale = targetScale,
viewportSize = viewportSize,
)
}
internal fun constrainZoomOffset(offset: Offset, scale: Float, viewportSize: IntSize): Offset {
if (scale <= MIN_ZOOM || viewportSize.width <= 0 || viewportSize.height <= 0) return Offset.Zero
val maxX = viewportSize.width * (scale - 1f) / 2f
val maxY = viewportSize.height * (scale - 1f) / 2f
return Offset(offset.x.coerceIn(-maxX, maxX), offset.y.coerceIn(-maxY, maxY))
}
private fun IntSize.centerOffset(): Offset = Offset(width / 2f, height / 2f)
internal const val MIN_ZOOM = 1f
private const val DOUBLE_TAP_ZOOM = 2f
internal const val MAX_ZOOM = 8f
private val ReaderZoomEasing = CubicBezierEasing(0.25f, 0.1f, 0.25f, 1f)
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ReaderGestureTarget, readerGestureTarget, ReaderScreen, ReaderLoadingOverlay, ReaderErrorOverlay, EinkFlash.
The source describes its contract as:
Stateless reader screen. Renders [ReaderState] and dispatches user input through [onEvent]. All async loading, persistence, and chapter navigation live in [ReaderViewModel] — this composable just paints + forwards. Layout: a single full-screen [Box] with three layers, bottom-to-top: 1. Page surface (paged / vertical / horizontal continuous renderers). 2. Tap / mouse / keyboard gesture handler. 3. Overlay bars (top app bar + bottom slider/actions card) gated by [ReaderState.chromeVisible] via [ReaderOverlayBars]. The settings + image-actions modal bottom sheets are siblings so they overlay everything and survive chrome-visibility changes.
Cross-chapter imports used by this file: DbSettings, einkFullRefreshDue, openSystemBrowser, EmptyState. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.graphics.Color
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalWindowInfo
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.readerModePreferences
import eu.friedcutlet.yokan.database.withReaderModePreferences
import eu.friedcutlet.yokan.database.einkFullRefreshDue
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import androidx.compose.material.icons.filled.BrokenImage
import eu.friedcutlet.yokan.ui.components.EmptyState
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.pager.PagerState
internal data class ReaderGestureTarget(
val item: ReaderStreamItem.Page,
val localOffset: Offset,
) {
val page get() = item.page
}
internal fun readerGestureTarget(
unit: ReaderDisplayUnit?,
offset: Offset,
size: IntSize,
): ReaderGestureTarget? {
val pages = unit?.items.orEmpty().filterIsInstance<ReaderStreamItem.Page>()
if (pages.isEmpty()) return null
if (pages.size == 1 || size.width <= 0) return ReaderGestureTarget(pages.first(), offset)
val pageWidth = size.width.toFloat() / pages.size
val pageIndex = (offset.x / pageWidth).toInt().coerceIn(0, pages.lastIndex)
return ReaderGestureTarget(
item = pages[pageIndex],
localOffset = Offset(offset.x - pageWidth * pageIndex, offset.y),
)
}
/**
* Stateless reader screen. Renders [ReaderState] and dispatches user input
* through [onEvent]. All async loading, persistence, and chapter navigation
* live in [ReaderViewModel] — this composable just paints + forwards.
*
* Layout: a single full-screen [Box] with three layers, bottom-to-top:
* 1. Page surface (paged / vertical / horizontal continuous renderers).
* 2. Tap / mouse / keyboard gesture handler.
* 3. Overlay bars (top app bar + bottom slider/actions card) gated by
* [ReaderState.chromeVisible] via [ReaderOverlayBars].
*
* The settings + image-actions modal bottom sheets are siblings so they
* overlay everything and survive chrome-visibility changes.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun ReaderScreen(
state: ReaderState,
settings: DbSettings,
snackbarHostState: SnackbarHostState,
onEvent: (ReaderEvent) -> Unit,
onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit,
) {
val density = LocalDensity.current
val displayUnits = remember(state.streamItems, state.mode, state.doublePage, state.pageShapes, state.automaticPairing) {
readerDisplayUnits(state.streamItems, state.mode, state.doublePage, state.pageShapes, state.automaticPairing)
}
val pagerState: PagerState = rememberPagerState(pageCount = displayUnits::size)
val verticalState: LazyListState = rememberLazyListState()
val horizontalState: LazyListState = rememberLazyListState()
val focusRequester = remember { FocusRequester() }
val gestureScope = rememberCoroutineScope()
val zoomStates = remember(state.chapter.id) { mutableMapOf<String, ReaderZoomState>() }
// Split halves of one source page zoom independently.
val zoomStateFor = remember(zoomStates) {
{ item: ReaderStreamItem.Page ->
zoomStates.getOrPut("${item.page.url}#${item.split}") { ReaderZoomState() }
}
}
val modePreferences = settings.readerModePreferences(state.mode.isPaged())
val failedImageUrls = remember(state.chapter.id) { mutableStateMapOf<String, Boolean>() }
val onImageLoadStateChanged: ReaderPageLoadListener = remember(failedImageUrls, onEvent) {
{ page, chapterId, loadState, error ->
if (loadState == ReaderPageImageLoadState.Error) {
failedImageUrls[page.url] = true
if (chapterId != null && error != null) onEvent(ReaderEvent.PageImageFailed(chapterId, error))
} else {
failedImageUrls.remove(page.url)
}
}
}
LaunchedEffect(focusRequester) { focusRequester.requestFocus() }
ReaderRendererSync(
displayUnits = displayUnits,
currentStreamIndex = state.currentStreamIndex,
animatePageChange = state.animatePageChange,
mode = state.mode,
animateTransitions = modePreferences.animatePageTransitions && !settings.einkMode,
pagerState = pagerState,
verticalState = verticalState,
horizontalState = horizontalState,
onPageChanged = { onEvent(ReaderEvent.CurrentPageChanged(it)) },
)
val chromeVisible = state.chromeVisible || settings.alwaysShowChrome
ApplyReaderSystemUi(
fullscreen = settings.fullScreenReader,
keepScreenOn = settings.keepScreenOnReader,
chromeVisible = chromeVisible,
)
val windowFocused = LocalWindowInfo.current.isWindowFocused
LaunchedEffect(windowFocused) {
if (!windowFocused) onEvent(ReaderEvent.InterruptScrolling)
}
val holding = state.holdScroll.phase != ReaderHoldPhase.Idle
val autoScrollPlaying = (state.autoScrolling || state.holdScroll.phase == ReaderHoldPhase.Scrolling) &&
state.readerActive && windowFocused && !state.overlayOpen
val scrollSpeed = if (holding) state.holdScroll.speed else state.autoScrollOffset.toFloat()
val endOfContent = (state.streamItems.lastOrNull() as? ReaderStreamItem.Transition)?.let { it.nextChapter == null } == true
if (state.mode.isVerticalLike()) {
DriveAutoScroll(verticalState, autoScrollPlaying, scrollSpeed, endOfContent) { onEvent(ReaderEvent.InterruptScrolling) }
}
if (state.mode.isHorizontalContinuous()) {
DriveAutoScroll(horizontalState, autoScrollPlaying, scrollSpeed, endOfContent) { onEvent(ReaderEvent.InterruptScrolling) }
}
// Coil prefetch for current, forward, and recent pages across chapter boundaries.
ReaderPagePrefetch(
items = state.streamItems,
currentStreamIndex = state.currentStreamIndex,
forwardAmount = settings.pagePreloadAmount,
layoutSampleKey = state.layoutSampleKey,
sampleChapterId = state.chapter.id.takeIf { state.automaticLayout && !state.layoutSettled },
onShapeSampled = { key, identity, shape -> onEvent(ReaderEvent.PageShapeSampled(key, identity, shape)) },
)
val rtl = state.mode.isRightToLeft()
val pageOneBased = (state.currentPageIndex + 1).coerceAtLeast(1)
val pageLabel = readerPageLabel(
page = pageOneBased,
pageCount = state.pageCount,
doublePage = displayUnits.getOrNull(displayUnitIndexForStreamIndex(displayUnits, state.currentStreamIndex))?.items?.size == 2,
)
val currentUnitIndex = displayUnitIndexForStreamIndex(displayUnits, state.currentStreamIndex)
val currentDisplayUnit = displayUnits.getOrNull(currentUnitIndex)
val currentPages = currentDisplayUnit?.items.orEmpty().filterIsInstance<ReaderStreamItem.Page>()
val zoomed = currentPages.any { zoomStateFor(it).scale > 1.01f }
LaunchedEffect(zoomed) {
if (zoomed) onEvent(ReaderEvent.InterruptScrolling)
}
val holdAvailable = state.holdScrollEnabled && state.mode.supportsAutoScroll() && state.readerActive &&
windowFocused && !zoomed && !state.overlayOpen && currentPages.isNotEmpty()
val hasImageError = currentDisplayUnit
?.items
.orEmpty()
.mapNotNull { (it as? ReaderStreamItem.Page)?.page }
.any { page -> failedImageUrls[page.url] == true }
Box(
modifier = Modifier
.fillMaxSize()
.onSizeChanged { size -> onEvent(ReaderEvent.ViewportChanged(ReaderViewport((size.width / density.density).toInt(), (size.height / density.density).toInt()))) }
.background(settings.backgroundColor.toColor(eu.friedcutlet.yokan.ui.theme.LocalYokanScaffoldColor.current))
.focusRequester(focusRequester)
.focusable()
.readerKeyEvents(
isRightToLeft = rtl,
volumeKeys = settings.features.reader.volumeKeyNavigation,
invertVolumeKeys = settings.features.reader.invertVolumeKeys,
onBack = { onEvent(ReaderEvent.Back) },
onFullscreen = { onEvent(ReaderEvent.ToggleFullscreen) },
onPreviousPage = { onEvent(ReaderEvent.PreviousPage) },
onNextPage = { onEvent(ReaderEvent.NextPage) },
onPreviousChapter = { onEvent(ReaderEvent.PreviousChapter) },
onNextChapter = { onEvent(ReaderEvent.NextChapter) },
),
) {
// ── Layer 1: page surface ──────────────────────────────────────────
Box(
modifier = Modifier
.fillMaxSize()
// Layer 2 (gestures) is composed onto the same Box so tap/wheel
// events flow through the pages first and only bubble out when
// unhandled by the pager/lazy list.
.readerTapZones(
layout = TapNavLayout.fromIndex(modePreferences.navigationLayout),
usePageTapZones = modePreferences.usePageTapZones,
hasImageError = hasImageError,
isRightToLeft = rtl,
onToggleChrome = { onEvent(ReaderEvent.ToggleChrome) },
onPreviousPage = { onEvent(ReaderEvent.PreviousPage) },
onNextPage = { onEvent(ReaderEvent.NextPage) },
onDoubleTap = { offset, size ->
readerGestureTarget(currentDisplayUnit, offset, size)?.let { target ->
gestureScope.launch {
zoomStateFor(target.item).toggleZoom(
target.localOffset,
doubleTapZoomDurationMillis(settings.doubleTapAnimationSpeed),
)
}
}
},
longPressImageActions = !holdAvailable,
onLongPress = { offset, size ->
readerGestureTarget(currentDisplayUnit, offset, size)?.let { target ->
onEvent(ReaderEvent.OpenImageActions(target.item))
}
},
)
.readerHoldScroll(
enabled = holdAvailable,
mode = state.mode,
viewport = state.viewport,
density = density.density,
canStart = { offset -> readerGestureTarget(currentDisplayUnit, offset, IntSize.Zero)?.let {
zoomStateFor(it.item).scale <= 1.01f
} == true },
onStart = { onEvent(ReaderEvent.BeginHoldScroll(it)) },
onSpeed = { id, distance -> onEvent(ReaderEvent.HoldScrollSpeed(id, distance)) },
onStop = { onEvent(ReaderEvent.EndHoldScroll(it)) },
)
.readerMouseWheelNav(
enabled = state.mode.isPaged(),
onPreviousPage = { onEvent(ReaderEvent.PreviousPage) },
onNextPage = { onEvent(ReaderEvent.NextPage) },
),
) {
when {
displayUnits.isNotEmpty() -> when {
state.mode.isVerticalLike() ->
VerticalReaderPages(
settings,
displayUnits,
state.mode,
state.doublePage,
verticalState,
zoomStateFor,
onImageLoadStateChanged,
state.colorizedPages,
)
state.mode.isHorizontalContinuous() ->
HorizontalContinuousPages(
settings,
displayUnits,
state.mode,
horizontalState,
zoomStateFor,
onImageLoadStateChanged,
state.colorizedPages,
)
else ->
PagedReaderPages(
settings,
displayUnits,
pagerState,
state.mode,
zoomStateFor,
onImageLoadStateChanged,
state.colorizedPages,
)
}
else -> EmptyState(
icon = Icons.Filled.BrokenImage,
title = "No pages available",
modifier = Modifier.fillMaxSize(),
)
}
// Loading + error overlays.
when (val load = state.load) {
ReaderLoadState.PagesLoading, ReaderLoadState.Idle -> {
if (state.pages.isEmpty()) ReaderLoadingOverlay()
}
is ReaderLoadState.PagesError -> ReaderErrorOverlay(
message = load.message,
onRetry = { onEvent(ReaderEvent.Retry) },
)
is ReaderLoadState.PagesReady -> Unit
}
}
EinkFlash(state.currentStreamIndex, settings.einkMode, settings.einkRefreshEveryPages)
// ── Floating helpers visible only when chrome is hidden ────────────
if (!chromeVisible && settings.showPagesNumber && state.pageCount > 0) {
ReaderPageIndicatorPill(
currentLabel = pageLabel,
total = state.pageCount,
)
}
ReaderHoldScrollIndicator(state.holdScroll)
ReaderAutoScrollFab(
visible = (state.autoScrollEnabled || state.holdScrollEnabled) &&
state.mode.supportsAutoScroll() &&
!chromeVisible,
isPlaying = state.autoScrolling || holding,
onToggle = { onEvent(ReaderEvent.ToggleAutoScroll) },
)
// Full chapter-boundary interstitials are part of the reader stream.
// ── Layer 3: animated top + bottom overlay bars. ───────────────────
ReaderOverlayBars(
visible = chromeVisible,
topBar = {
ReaderTopBar(
mangaTitle = state.manga.name,
chapterTitle = state.chapter.name,
isBookmarked = state.chapter.isBookmarked,
showWebAction = !state.manga.isLocalArchive && state.manga.link.isNotBlank(),
showRefreshAction = !state.manga.isLocalArchive,
onBack = { onEvent(ReaderEvent.Back) },
onChapterList = { onEvent(ReaderEvent.OpenChapterList) },
showImageActions = currentPages.isNotEmpty(),
onOpenMenu = { onEvent(ReaderEvent.InterruptScrolling) },
onImageActions = { currentPages.firstOrNull()?.let { onEvent(ReaderEvent.OpenImageActions(it)) } },
onToggleBookmark = { onEvent(ReaderEvent.ToggleBookmark) },
onRefreshPages = { onEvent(ReaderEvent.RefreshPages) },
onWeb = {
if (state.manga.link.isNotBlank()) openSystemBrowser(state.manga.link)
},
)
},
bottomBar = {
ReaderBottomBar(
page = pageOneBased,
pageCount = state.pageCount,
showPageNumbers = settings.showPagesNumber,
canGoPrevious = state.canGoPreviousChapter,
canGoNext = state.canGoNextChapter,
mode = state.mode,
doublePage = state.doublePage,
cropBorders = modePreferences.cropBorders,
onMode = { onEvent(ReaderEvent.ChangeMode(it)) },
onDoublePage = { onEvent(ReaderEvent.ToggleDoublePage) },
onCropBorders = { onUpdateSettings { db -> db.withReaderModePreferences(state.mode.isPaged()) { it.copy(cropBorders = !it.cropBorders) } } },
onPreviousChapter = { onEvent(ReaderEvent.PreviousChapter) },
onNextChapter = { onEvent(ReaderEvent.NextChapter) },
onJumpToPage = { onEvent(ReaderEvent.JumpToPage(it)) },
onOpenSettings = { onEvent(ReaderEvent.OpenSettingsSheet) },
)
},
)
// ── Snackbars float above everything. ─────────────────────────────
SnackbarHost(
hostState = snackbarHostState,
modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 200.dp),
)
}
if (state.chapterListOpen) {
ReaderChapterListDialog(
chapters = state.chapterSequence,
currentChapterId = state.chapter.id,
onDismiss = { onEvent(ReaderEvent.CloseChapterList) },
onSelect = { onEvent(ReaderEvent.SelectChapter(it)) },
)
}
// ── Sheets siblings so they overlay the reader entirely. ──────────────
ReaderSettingsSheet(
visible = state.settingsSheetOpen,
settings = settings,
onUpdateSettings = onUpdateSettings,
currentMode = state.mode,
automaticLayout = state.automaticLayout,
doublePage = state.doublePage,
automaticPairing = state.automaticPairing,
onAutomatic = { onEvent(ReaderEvent.AutomaticLayout) },
onDefaultLayout = { onEvent(ReaderEvent.DefaultLayout) },
onAutomaticPairing = { onEvent(ReaderEvent.AutomaticPagePairing) },
autoScrollEnabled = state.autoScrollEnabled,
autoScrollOffset = state.autoScrollOffset,
onModeChange = { onEvent(ReaderEvent.ChangeMode(it)) },
onAutoScrollEnabledChange = { onEvent(ReaderEvent.SetAutoScrollEnabled(it)) },
onAutoScrollOffsetChange = { onEvent(ReaderEvent.SetAutoScrollOffset(it)) },
onDismiss = { onEvent(ReaderEvent.CloseSettingsSheet) },
)
ReaderImageActionsSheet(
target = state.imageActionsTarget.takeUnless { state.colorizer.open },
onDismiss = { onEvent(ReaderEvent.CloseImageActions) },
onExport = { export, spread -> onEvent(ReaderEvent.ExportResolvedImage(export, spread)) },
onSetCover = { onEvent(ReaderEvent.SetResolvedImageAsCover) },
onColorize = { onEvent(ReaderEvent.OpenColorizer) },
)
PanelColorizerSheet(state.imageActionsTarget, state.colorizer, onEvent)
}
@Composable
private fun ReaderLoadingOverlay() {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
CircularProgressIndicator()
Text("Loading pages…", style = MaterialTheme.typography.bodyMedium)
}
}
}
@Composable
private fun ReaderErrorOverlay(message: String, onRetry: () -> Unit) {
Box(modifier = Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(
text = "Couldn't load pages",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.error,
)
Text(
text = message,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
TextButton(onClick = onRetry) {
Icon(Icons.Filled.Refresh, contentDescription = null)
Text(" Retry")
}
}
}
}
/** E-ink: flashes black every N page turns so the panel does a full refresh and clears ghosting. */
@Composable
private fun EinkFlash(currentStreamIndex: Int, einkMode: Boolean, refreshEveryPages: Int) {
var flashing by remember { mutableStateOf(false) }
var pageTurns by remember { mutableStateOf(0) }
LaunchedEffect(currentStreamIndex, einkMode) {
if (!einkMode) return@LaunchedEffect
pageTurns++
if (!einkFullRefreshDue(pageTurns, refreshEveryPages)) return@LaunchedEffect
try {
flashing = true
delay(EinkFlashMillis)
} finally {
flashing = false
}
}
if (flashing) Box(Modifier.fillMaxSize().background(Color.Black))
}
/** Long enough for an e-paper controller to treat the black frame as a full refresh. */
private const val EinkFlashMillis = 120L
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderSystemUi.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ReaderSystemUiPreferences, ReaderSystemUiController, apply, reset, createReaderSystemUiController, ApplyReaderSystemUi.
Cross-chapter imports used by this file: YokanRuntime. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import eu.friedcutlet.yokan.app.YokanRuntime
data class ReaderSystemUiPreferences(
val fullscreen: Boolean,
val keepScreenOn: Boolean,
val chromeVisible: Boolean = false,
) {
val hideMobileSystemBars: Boolean get() = fullscreen && !chromeVisible
}
interface ReaderSystemUiController {
fun apply(preferences: ReaderSystemUiPreferences)
fun reset()
}
expect fun createReaderSystemUiController(): ReaderSystemUiController
@Composable
fun ApplyReaderSystemUi(
fullscreen: Boolean,
keepScreenOn: Boolean,
chromeVisible: Boolean = false,
) {
val controller = remember { YokanRuntime.readerSystemUi }
LaunchedEffect(controller, fullscreen, keepScreenOn, chromeVisible) {
controller.apply(ReaderSystemUiPreferences(fullscreen, keepScreenOn, chromeVisible))
}
DisposableEffect(controller) {
onDispose(controller::reset)
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderAutoScroll.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines BoxScope.ReaderHoldScrollIndicator, BoxScope.ReaderAutoScrollFab, DriveAutoScroll.
The source describes its contract as:
Floating play/pause FAB shown in continuous modes (vertical, webtoon, horizontal continuous). Mirrors the Flutter
auto_scroll_button.dart. Auto-scroll itself is driven by [DriveAutoScroll] below — kept separate so the FAB stays a pure render-only composable.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.tween
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.foundation.gestures.animateScrollBy
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.MaterialTheme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.isActive
import kotlinx.coroutines.flow.first
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.reader_scroll_pause
import yokan.composeapp.generated.resources.reader_scroll_play
import yokan.composeapp.generated.resources.reader_hold_speed
import yokan.composeapp.generated.resources.reader_hold_paused
import kotlin.math.roundToInt
@Composable
internal fun BoxScope.ReaderHoldScrollIndicator(hold: ReaderHoldScroll) {
if (hold.phase == ReaderHoldPhase.Idle) return
Surface(
modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 64.dp),
shape = RoundedCornerShape(50),
color = MaterialTheme.colorScheme.secondaryContainer,
) {
val multiplier = (hold.speed / hold.baseSpeed.coerceAtLeast(2f) * 10f).roundToInt() / 10f
Text(
text = if (hold.phase == ReaderHoldPhase.Holding) stringResource(Res.string.reader_hold_paused)
else stringResource(Res.string.reader_hold_speed, multiplier.toString()),
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
style = MaterialTheme.typography.labelLarge,
)
}
}
/**
* Floating play/pause FAB shown in continuous modes (vertical, webtoon,
* horizontal continuous). Mirrors the Flutter `auto_scroll_button.dart`.
*
* Auto-scroll itself is driven by [DriveAutoScroll] below — kept separate so
* the FAB stays a pure render-only composable.
*/
@Composable
internal fun BoxScope.ReaderAutoScrollFab(
visible: Boolean,
isPlaying: Boolean,
onToggle: () -> Unit,
bottomPadding: Dp = 108.dp,
) {
AnimatedVisibility(
visible = visible,
enter = scaleIn(),
exit = scaleOut(),
modifier = Modifier.align(Alignment.BottomEnd).padding(end = 18.dp, bottom = bottomPadding),
) {
FloatingActionButton(onClick = onToggle) {
if (isPlaying) Icon(Icons.Filled.Pause, contentDescription = stringResource(Res.string.reader_scroll_pause))
else Icon(Icons.Filled.PlayArrow, contentDescription = stringResource(Res.string.reader_scroll_play))
}
}
}
/**
* One frame-driven controller for ordinary and temporary hold scrolling. Speed changes
* do not restart it. At a loading boundary it suspends until the extent changes; at the
* confirmed final transition it relinquishes ownership. The old loop advanced one offset
* over a 100 ms animation after a 100 ms delay, hence five offsets per second.
*/
@Composable
internal fun DriveAutoScroll(
state: LazyListState,
isPlaying: Boolean,
pageOffset: Float,
endOfContent: Boolean = false,
onFinished: () -> Unit = {},
) {
val playing by rememberUpdatedState(isPlaying)
val offset by rememberUpdatedState(pageOffset.coerceIn(0f, 60f))
val terminal by rememberUpdatedState(endOfContent)
val finished by rememberUpdatedState(onFinished)
LaunchedEffect(state, isPlaying) {
if (!playing) return@LaunchedEffect
try {
var previous = withFrameNanos { it }
while (playing) {
if (!state.canScrollForward) {
if (terminal && state.layoutInfo.totalItemsCount > 0) {
finished()
break
}
snapshotFlow { state.canScrollForward || (terminal && state.layoutInfo.totalItemsCount > 0) || !playing }.first { it }
previous = withFrameNanos { it }
continue
}
if (offset <= 0f) {
snapshotFlow { offset > 0f || !playing }.first { it }
previous = withFrameNanos { it }
continue
}
val now = withFrameNanos { it }
val seconds = ((now - previous) / 1_000_000_000f).coerceIn(0f, 0.05f)
if (playing) state.scrollBy(offset * 5f * seconds)
previous = now
}
} catch (cancelled: CancellationException) {
// A user drag can interrupt the list's scroll mutation while this effect is
// still active. Disposing/replacing the effect must not stop a newer controller.
if (currentCoroutineContext().isActive) finished()
throw cancelled
}
}
}
/** ScrollState counterpart used by the continuous novel reader. */
@Composable
internal fun DriveAutoScroll(
state: ScrollState,
isPlaying: Boolean,
pageOffset: Float,
) {
val playing by rememberUpdatedState(isPlaying)
val offset by rememberUpdatedState(pageOffset.coerceIn(2f, 30f))
LaunchedEffect(state, playing, offset) {
if (!playing) return@LaunchedEffect
while (playing) {
delay(100L)
if (!playing) break
if (state.value < state.maxValue && state.maxValue != Int.MAX_VALUE) {
state.animateScrollBy(
value = offset,
animationSpec = tween(durationMillis = 100, easing = LinearEasing),
)
}
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderBottomBar.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ReaderBottomBar, readerPageLabel, ReaderModeMenu, modeIcon.
The source describes its contract as:
Reader bottom bar — Material 3 surface containing two stacked rows: 1. Slider row: prev-chapter, page slider, next-chapter, page counter. 2. Action row: reading-mode menu, crop-borders toggle, double-page toggle, settings. The slider tracks its drag state locally so the seek doesn't fight the pager's own scroll callbacks — we commit on release.
Cross-chapter imports used by this file: DbReaderMode. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.MenuBook
import androidx.compose.material.icons.filled.CropFree
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.SkipNext
import androidx.compose.material.icons.filled.SkipPrevious
import androidx.compose.material.icons.filled.ViewArray
import androidx.compose.material.icons.filled.ViewDay
import androidx.compose.material.icons.filled.Wallpaper
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconToggleButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.graphics.vector.ImageVector
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbReaderMode
/**
* Reader bottom bar — Material 3 surface containing two stacked rows:
*
* 1. Slider row: prev-chapter, page slider, next-chapter, page counter.
* 2. Action row: reading-mode menu, crop-borders toggle, double-page
* toggle, settings.
*
* The slider tracks its drag state locally so the seek doesn't fight the
* pager's own scroll callbacks — we commit on release.
*/
@Composable
internal fun ReaderBottomBar(
page: Int, // 1-based for display
pageCount: Int,
showPageNumbers: Boolean,
canGoPrevious: Boolean,
canGoNext: Boolean,
mode: DbReaderMode,
doublePage: Boolean,
cropBorders: Boolean,
onMode: (DbReaderMode) -> Unit,
onDoublePage: () -> Unit,
onCropBorders: () -> Unit,
onPreviousChapter: () -> Unit,
onNextChapter: () -> Unit,
onJumpToPage: (Int) -> Unit, // 0-based
onOpenSettings: () -> Unit,
) {
var dragValue by remember(page) { mutableStateOf<Float?>(null) }
val displayPage = dragValue?.toInt()?.plus(1)?.coerceAtMost(pageCount) ?: page.coerceAtMost(pageCount)
val sliderMax = (pageCount - 1).coerceAtLeast(0).toFloat()
val total = pageCount.coerceAtLeast(1)
val displayLabel = readerPageLabel(
page = displayPage,
pageCount = pageCount,
doublePage = doublePage && !mode.isHorizontalContinuous(),
)
Surface(
tonalElevation = 3.dp,
shadowElevation = 8.dp,
color = MaterialTheme.colorScheme.surface,
// MUI-style top-rounded sheet so the bar reads as a panel that lifts
// off the page rather than a rectangular bar pinned to the edge.
shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp),
modifier = Modifier.fillMaxWidth(),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 10.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
// Row 1 — prev-chapter, slider with current/total labels, next-chapter.
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth(),
) {
eu.friedcutlet.yokan.ui.components.TooltipIconButton(
tooltip = "Previous chapter",
icon = Icons.Filled.SkipPrevious,
onClick = onPreviousChapter,
enabled = canGoPrevious,
)
Text(
text = displayLabel,
style = MaterialTheme.typography.labelMedium,
textAlign = TextAlign.End,
modifier = Modifier.widthIn(min = 28.dp).padding(end = 4.dp),
)
Slider(
value = (dragValue ?: (page - 1).coerceAtLeast(0).toFloat()).coerceIn(0f, sliderMax.coerceAtLeast(0f)),
onValueChange = { dragValue = it },
onValueChangeFinished = {
val target = dragValue?.toInt() ?: return@Slider
dragValue = null
onJumpToPage(target.coerceIn(0, (pageCount - 1).coerceAtLeast(0)))
},
valueRange = 0f..sliderMax,
steps = (pageCount - 2).coerceAtLeast(0),
enabled = pageCount > 1,
modifier = Modifier.weight(1f),
)
Text(
text = total.toString(),
style = MaterialTheme.typography.labelMedium,
modifier = Modifier.widthIn(min = 28.dp).padding(start = 4.dp),
)
eu.friedcutlet.yokan.ui.components.TooltipIconButton(
tooltip = "Next chapter",
icon = Icons.Filled.SkipNext,
onClick = onNextChapter,
enabled = canGoNext,
)
}
// Optional page count pill centred under the slider — much easier
// to read against the page art than the previous bare label.
if (showPageNumbers && pageCount > 0) {
Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Surface(
shape = RoundedCornerShape(50),
color = MaterialTheme.colorScheme.surfaceContainerHighest,
) {
Text(
text = "$displayLabel / $total",
modifier = Modifier.padding(horizontal = 10.dp, vertical = 3.dp),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
// Row 2 — mode menu / crop / double-page / settings.
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceAround,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 4.dp),
) {
ReaderModeMenu(mode = mode, onMode = onMode)
IconToggleButton(
checked = cropBorders,
onCheckedChange = { onCropBorders() },
) {
Icon(Icons.Filled.CropFree, contentDescription = "Crop borders")
}
IconToggleButton(
checked = doublePage,
onCheckedChange = { onDoublePage() },
) {
Icon(Icons.AutoMirrored.Filled.MenuBook, contentDescription = "Double page")
}
eu.friedcutlet.yokan.ui.components.TooltipIconButton(
tooltip = "Reader settings",
icon = Icons.Filled.Settings,
onClick = onOpenSettings,
)
}
Spacer(Modifier.width(0.dp))
}
}
}
internal fun readerPageLabel(page: Int, pageCount: Int, doublePage: Boolean): String {
val total = pageCount.coerceAtLeast(1)
val first = page.coerceIn(1, total)
if (!doublePage) return first.toString()
val second = (first + 1).coerceAtMost(total)
return if (second == first) first.toString() else "$first-$second"
}
/**
* Reading-mode picker — a single icon that opens a dropdown of the available
* [DbReaderMode] values. The icon reflects the active mode family (paged vs.
* webtoon vs. vertical-strip) so users get a visual cue without opening the
* menu.
*/
@Composable
private fun ReaderModeMenu(mode: DbReaderMode, onMode: (DbReaderMode) -> Unit) {
var expanded by remember { mutableStateOf(false) }
Box {
IconButton(onClick = { expanded = true }) {
Icon(modeIcon(mode), contentDescription = "Reading mode")
}
DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
DbReaderMode.entries.forEach { candidate ->
DropdownMenuItem(
text = { Text(candidate.label()) },
leadingIcon = { Icon(modeIcon(candidate), contentDescription = null) },
onClick = {
expanded = false
onMode(candidate)
},
)
}
}
}
}
private fun modeIcon(mode: DbReaderMode): ImageVector = when (mode) {
DbReaderMode.Ltr, DbReaderMode.Rtl -> Icons.Filled.ViewArray
DbReaderMode.Webtoon -> Icons.Filled.Wallpaper
DbReaderMode.Vertical,
DbReaderMode.VerticalContinuous,
DbReaderMode.HorizontalContinuous,
DbReaderMode.HorizontalContinuousRtl -> Icons.Filled.ViewDay
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderHoldScroll.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ReaderHoldPhase, ReaderHoldScroll, readerHoldSpeed, readerHoldDistance, Modifier.readerHoldScroll.
The source describes its contract as:
Finger movement against the forward reading axis accelerates forward scrolling.
Cross-chapter imports used by this file: DbReaderMode. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import eu.friedcutlet.yokan.database.DbReaderMode
import kotlin.math.abs
import kotlin.math.sign
enum class ReaderHoldPhase { Idle, Holding, Scrolling }
data class ReaderHoldScroll(
val gestureId: Long? = null,
val baseSpeed: Float = 0f,
val speed: Float = 0f,
) {
val phase: ReaderHoldPhase get() = when {
gestureId == null -> ReaderHoldPhase.Idle
speed <= 0f -> ReaderHoldPhase.Holding
else -> ReaderHoldPhase.Scrolling
}
}
internal fun readerHoldSpeed(base: Float, distanceDp: Float): Float {
val fallback = if (base.isFinite()) base.coerceIn(2f, 30f) else 10f
if (!distanceDp.isFinite()) return fallback
val adjusted = sign(distanceDp) * (abs(distanceDp) - 12f).coerceAtLeast(0f) / 6f
return (fallback + adjusted).coerceIn(0f, 60f)
}
/** Finger movement against the forward reading axis accelerates forward scrolling. */
internal fun readerHoldDistance(mode: DbReaderMode, origin: Offset, position: Offset): Float = when {
mode.isHorizontalContinuous() && mode.isRightToLeft() -> position.x - origin.x
mode.isHorizontalContinuous() -> origin.x - position.x
else -> origin.y - position.y
}
/**
* Observes without consuming until a stationary, single-pointer long press wins.
* Main/Final passes reject gestures consumed by child scrolling/zoom; after ownership,
* Initial consumes speed drags before children can turn them into swipes or zoom.
*/
@Composable
internal fun Modifier.readerHoldScroll(
enabled: Boolean,
mode: DbReaderMode,
viewport: ReaderViewport,
density: Float,
canStart: (Offset) -> Boolean,
onStart: (Long) -> Unit,
onSpeed: (Long, Float) -> Unit,
onStop: (Long) -> Unit,
): Modifier {
val canStartRef by rememberUpdatedState(canStart)
val startRef by rememberUpdatedState(onStart)
val speedRef by rememberUpdatedState(onSpeed)
val stopRef by rememberUpdatedState(onStop)
if (!enabled) return this
return pointerInput(enabled, mode, viewport, density) {
awaitEachGesture {
// This modifier sits inside readerTapZones: children get first refusal,
// then we observe the down before the outer tap detector consumes it.
val down = awaitFirstDown(requireUnconsumed = true, pass = PointerEventPass.Main)
if (!canStartRef(down.position)) return@awaitEachGesture
var candidate = true
val completed = withTimeoutOrNull(viewConfiguration.longPressTimeoutMillis) {
while (candidate) {
val event = awaitPointerEvent(PointerEventPass.Main)
val change = event.changes.singleOrNull()
candidate = change != null && change.id == down.id && change.pressed && !change.isConsumed &&
(change.position - down.position).getDistance() <= viewConfiguration.touchSlop
if (candidate) {
candidate = awaitPointerEvent(PointerEventPass.Final).changes.none { it.isConsumed }
}
}
true
}
if (completed != null || !candidate || !canStartRef(down.position)) return@awaitEachGesture
val id = down.uptimeMillis
startRef(id)
try {
currentEvent.changes.forEach { it.consume() }
while (true) {
val event = awaitPointerEvent(PointerEventPass.Initial)
val change = event.changes.singleOrNull()
if (change == null) {
event.changes.firstOrNull { it.id == down.id }?.consume()
break
}
if (change.id != down.id || change.isConsumed) break
change.consume()
if (!change.pressed) break
speedRef(id, readerHoldDistance(mode, down.position, change.position) / density)
}
} finally {
stopRef(id)
}
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderOverlays.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ReaderTopBar, ReaderChapterListDialog, BoxScope.ReaderOverlayBars, BoxScope.ReaderPageIndicatorPill, ReaderChapterTransitionPage, TransitionHeading, TransitionChapterCard.
The source describes its contract as:
Reader top app bar — back / title / chapter-list / bookmark / refresh / web actions. Title is a two-line label: bold manga name + smaller chapter subtitle. The bookmark icon swaps between filled/outline mirroring [isBookmarked]. The refresh and web buttons are hidden for local-archive chapters since they have no source page list or remote URL.
Cross-chapter imports used by this file: Chapter, GlobalStatusAccessButton. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandVertically
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.FormatListBulleted
import androidx.compose.material.icons.automirrored.filled.MenuBook
import androidx.compose.material.icons.automirrored.filled.NavigateNext
import androidx.compose.material.icons.filled.Bookmark
import androidx.compose.material.icons.filled.BookmarkBorder
import androidx.compose.material.icons.filled.CheckCircleOutline
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.Public
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_back
import yokan.composeapp.generated.resources.ui_close
import yokan.composeapp.generated.resources.reader_image_actions
import yokan.composeapp.generated.resources.reader_refresh_pages
import yokan.composeapp.generated.resources.reader_open_web
import yokan.composeapp.generated.resources.reader_actions_menu
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.ui.status.GlobalStatusAccessButton
/**
* Reader top app bar — back / title / chapter-list / bookmark / refresh / web actions.
*
* Title is a two-line label: bold manga name + smaller chapter subtitle.
* The bookmark icon swaps between filled/outline mirroring [isBookmarked].
* The refresh and web buttons are hidden for local-archive chapters since they
* have no source page list or remote URL.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun ReaderTopBar(
mangaTitle: String,
chapterTitle: String,
isBookmarked: Boolean,
showWebAction: Boolean,
showRefreshAction: Boolean,
onBack: () -> Unit,
onChapterList: () -> Unit,
onToggleBookmark: () -> Unit,
onRefreshPages: () -> Unit,
onWeb: () -> Unit,
showImageActions: Boolean,
onImageActions: () -> Unit,
onOpenMenu: () -> Unit,
) {
var menuOpen by remember { mutableStateOf(false) }
TopAppBar(
title = {
Column {
Text(
text = mangaTitle,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = chapterTitle,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
},
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.action_back))
}
},
actions = {
GlobalStatusAccessButton()
IconButton(onClick = onChapterList) {
Icon(
Icons.AutoMirrored.Filled.FormatListBulleted,
contentDescription = "Chapter list",
)
}
IconButton(onClick = onToggleBookmark) {
Icon(
imageVector = if (isBookmarked) Icons.Filled.Bookmark else Icons.Filled.BookmarkBorder,
contentDescription = if (isBookmarked) "Remove bookmark" else "Bookmark",
)
}
Box {
IconButton(onClick = { onOpenMenu(); menuOpen = true }) {
Icon(Icons.Filled.MoreVert, contentDescription = stringResource(Res.string.reader_actions_menu))
}
DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) {
if (showImageActions) DropdownMenuItem(
text = { Text(stringResource(Res.string.reader_image_actions)) },
onClick = { menuOpen = false; onImageActions() },
)
if (showRefreshAction) DropdownMenuItem(
text = { Text(stringResource(Res.string.reader_refresh_pages)) },
onClick = { menuOpen = false; onRefreshPages() },
)
if (showWebAction) DropdownMenuItem(
text = { Text(stringResource(Res.string.reader_open_web)) },
onClick = { menuOpen = false; onWeb() },
)
}
}
},
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.94f),
),
)
}
@Composable
internal fun ReaderChapterListDialog(
chapters: List<Chapter>,
currentChapterId: Long,
onDismiss: () -> Unit,
onSelect: (Chapter) -> Unit,
) {
val currentIndex = remember(chapters, currentChapterId) {
chapters.indexOfFirst { it.id == currentChapterId }.coerceAtLeast(0)
}
val listState = rememberLazyListState(
initialFirstVisibleItemIndex = (currentIndex - 2).coerceAtLeast(0),
)
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false),
) {
Surface(
modifier = Modifier.fillMaxWidth(0.85f).fillMaxHeight(0.8f),
shape = RoundedCornerShape(20.dp),
tonalElevation = 8.dp,
) {
Column {
Row(
modifier = Modifier.fillMaxWidth().padding(start = 20.dp, end = 8.dp, top = 8.dp, bottom = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.MenuBook,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
)
Spacer(Modifier.width(12.dp))
Text(
text = "Chapters",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold,
modifier = Modifier.weight(1f),
)
IconButton(onClick = onDismiss) {
Icon(Icons.Filled.Close, contentDescription = stringResource(Res.string.ui_close))
}
}
HorizontalDivider(color = MaterialTheme.colorScheme.primary.copy(alpha = 0.2f))
LazyColumn(
state = listState,
modifier = Modifier.fillMaxSize(),
contentPadding = androidx.compose.foundation.layout.PaddingValues(12.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
items(chapters, key = Chapter::id) { chapter ->
val current = chapter.id == currentChapterId
Surface(
onClick = {
if (!current) onSelect(chapter)
},
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(12.dp),
color = if (current) {
MaterialTheme.colorScheme.primary.copy(alpha = 0.15f)
} else {
Color.Transparent
},
border = if (current) {
BorderStroke(1.5.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.4f))
} else {
null
},
) {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Box(
Modifier
.width(4.dp)
.height(48.dp)
.clip(RoundedCornerShape(2.dp))
.background(
if (chapter.isRead) {
MaterialTheme.colorScheme.onSurface.copy(alpha = 0.25f)
} else {
MaterialTheme.colorScheme.primary
},
),
)
Spacer(Modifier.width(12.dp))
Column(Modifier.weight(1f)) {
Text(
text = chapter.name,
style = MaterialTheme.typography.bodyMedium,
fontWeight = if (current) FontWeight.Bold else FontWeight.Medium,
color = if (chapter.isRead) {
MaterialTheme.colorScheme.onSurface.copy(alpha = 0.45f)
} else {
MaterialTheme.colorScheme.onSurface
},
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
listOf(chapter.scanlator, chapter.dateUpload)
.filter(String::isNotBlank)
.joinToString(" · ")
.takeIf(String::isNotBlank)
?.let { metadata ->
Spacer(Modifier.height(4.dp))
Text(
text = metadata,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
if (chapter.isBookmarked) {
Icon(
Icons.Filled.Bookmark,
contentDescription = "Bookmarked",
tint = MaterialTheme.colorScheme.primary,
)
}
}
}
}
}
}
}
}
}
/**
* Expands and collapses reader chrome height over the authority's 300 ms ease
* curve. The bars stay pinned to their respective screen edges while content
* is clipped by the size transition.
*/
@Composable
internal fun BoxScope.ReaderOverlayBars(
visible: Boolean,
topBar: @Composable () -> Unit,
bottomBar: @Composable () -> Unit,
) {
val eink = eu.friedcutlet.yokan.ui.theme.LocalEinkMode.current
AnimatedVisibility(
visible = visible,
enter = if (eink) EnterTransition.None else expandVertically(
animationSpec = tween(300, easing = ReaderChromeEasing),
expandFrom = Alignment.Top,
),
exit = if (eink) ExitTransition.None else shrinkVertically(
animationSpec = tween(300, easing = ReaderChromeEasing),
shrinkTowards = Alignment.Top,
),
modifier = Modifier.align(Alignment.TopCenter),
) {
topBar()
}
AnimatedVisibility(
visible = visible,
enter = if (eink) EnterTransition.None else expandVertically(
animationSpec = tween(300, easing = ReaderChromeEasing),
expandFrom = Alignment.Bottom,
),
exit = if (eink) ExitTransition.None else shrinkVertically(
animationSpec = tween(300, easing = ReaderChromeEasing),
shrinkTowards = Alignment.Bottom,
),
modifier = Modifier.align(Alignment.BottomCenter),
) {
bottomBar()
}
}
private val ReaderChromeEasing = CubicBezierEasing(0.25f, 0.1f, 0.25f, 1f)
/**
* Floating page indicator pill at bottom-center, shown when chrome is hidden.
* Mirrors the Flutter behavior — when the user dismisses the bars they still
* want to know where they are. Gated by `DbSettings.showPagesNumber` upstream.
*/
@Composable
internal fun BoxScope.ReaderPageIndicatorPill(currentLabel: String, total: Int) {
Box(
modifier = Modifier
.align(Alignment.BottomCenter)
.padding(bottom = 18.dp)
.clip(RoundedCornerShape(percent = 50))
.background(Color.Black.copy(alpha = 0.55f))
.padding(horizontal = 14.dp, vertical = 6.dp),
) {
Text(
text = "$currentLabel / $total",
color = Color.White,
style = MaterialTheme.typography.labelMedium,
)
}
}
@Composable
internal fun ReaderChapterTransitionPage(
currentChapter: Chapter,
nextChapter: Chapter?,
mangaTitle: String,
vertical: Boolean,
isRightToLeft: Boolean,
modifier: Modifier = Modifier,
) {
Box(
modifier = modifier.background(MaterialTheme.colorScheme.surface),
contentAlignment = Alignment.Center,
) {
if (vertical) {
Column(
modifier = Modifier.fillMaxWidth().widthIn(max = 480.dp).padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
TransitionHeading()
Spacer(Modifier.height(20.dp))
TransitionChapterCard("Chapter completed", currentChapter.name, primary = false)
Spacer(Modifier.height(16.dp))
Icon(
imageVector = if (nextChapter == null) {
Icons.Filled.CheckCircleOutline
} else {
Icons.Filled.KeyboardArrowDown
},
contentDescription = null,
modifier = Modifier.size(32.dp),
tint = MaterialTheme.colorScheme.primary,
)
Spacer(Modifier.height(16.dp))
if (nextChapter != null) {
TransitionChapterCard("Next chapter", nextChapter.name, primary = true)
} else {
TransitionChapterCard("End of manga", mangaTitle, primary = true)
}
Spacer(Modifier.height(20.dp))
Text(
text = if (nextChapter != null) {
"Continue to the next chapter"
} else {
"Return to the chapter list"
},
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
style = MaterialTheme.typography.bodyMedium,
)
}
} else {
Column(
modifier = Modifier.fillMaxSize().padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
TransitionHeading()
Spacer(Modifier.height(20.dp))
Row(
modifier = Modifier.fillMaxWidth().widthIn(max = 600.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
val currentCard: @Composable () -> Unit = {
TransitionChapterCard("Chapter completed", currentChapter.name, primary = false)
}
val nextCard: @Composable () -> Unit = {
if (nextChapter != null) {
TransitionChapterCard("Next chapter", nextChapter.name, primary = true)
} else {
TransitionChapterCard("End of manga", mangaTitle, primary = true)
}
}
if (isRightToLeft) {
Box(Modifier.weight(1f)) { nextCard() }
Icon(Icons.AutoMirrored.Filled.NavigateNext, contentDescription = null)
Box(Modifier.weight(1f)) { currentCard() }
} else {
Box(Modifier.weight(1f)) { currentCard() }
Icon(Icons.AutoMirrored.Filled.NavigateNext, contentDescription = null)
Box(Modifier.weight(1f)) { nextCard() }
}
}
Spacer(Modifier.height(16.dp))
Text(
text = if (nextChapter != null) {
"Continue to the next chapter"
} else {
"Return to the chapter list"
},
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
style = MaterialTheme.typography.bodyMedium,
)
}
}
}
}
@Composable
private fun TransitionHeading() {
Icon(
Icons.AutoMirrored.Filled.MenuBook,
contentDescription = null,
modifier = Modifier.size(48.dp),
tint = MaterialTheme.colorScheme.primary,
)
Spacer(Modifier.height(20.dp))
Text(
text = "End of chapter",
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
)
}
@Composable
private fun TransitionChapterCard(
label: String,
chapterName: String,
primary: Boolean,
) {
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(12.dp),
color = if (primary) {
MaterialTheme.colorScheme.primaryContainer
} else {
MaterialTheme.colorScheme.surfaceVariant
},
tonalElevation = if (primary) 2.dp else 0.dp,
) {
Column(Modifier.padding(16.dp)) {
Text(
label,
style = MaterialTheme.typography.labelMedium,
color = if (primary) {
MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.8f)
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
)
Spacer(Modifier.height(4.dp))
Text(
chapterName,
style = MaterialTheme.typography.titleMedium,
color = if (primary) {
MaterialTheme.colorScheme.onPrimaryContainer
} else {
MaterialTheme.colorScheme.onSurface
},
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderPageDownloadProgress.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ReaderPageDownloadProgress, forUrl, report, clear, clearAll.
The source describes its contract as:
Byte-level download progress for images loaded through Coil, keyed by URL. Mangayomi surfaces
ImageChunkEvent.cumulativeBytesLoaded / expectedTotalByteson every reader page placeholder; Coil has no progress API, so the shared [eu.friedcutlet.yokan.ui.image.ProfileImageHttpClient] taps Ktor'sonDownloadcallback instead and this registry fans the ratio out to the composables that render the placeholder.
package eu.friedcutlet.yokan.ui.screens.reader
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
/**
* Byte-level download progress for images loaded through Coil, keyed by URL.
*
* Mangayomi surfaces `ImageChunkEvent.cumulativeBytesLoaded / expectedTotalBytes`
* on every reader page placeholder; Coil has no progress API, so the shared
* [eu.friedcutlet.yokan.ui.image.ProfileImageHttpClient] taps Ktor's `onDownload` callback instead and this
* registry fans the ratio out to the composables that render the placeholder.
*/
object ReaderPageDownloadProgress {
private const val MAX_TRACKED = 128
private val state = MutableStateFlow<Map<String, Float>>(emptyMap())
val progress: StateFlow<Map<String, Float>> get() = state
fun forUrl(url: String): Flow<Float?> = state.map { it[url] }.distinctUntilChanged()
fun report(url: String, receivedBytes: Long, totalBytes: Long?) {
if (totalBytes == null || totalBytes <= 0L) return
val ratio = (receivedBytes.toFloat() / totalBytes.toFloat()).coerceIn(0f, 1f)
state.update { current ->
if (ratio >= 1f) {
return@update if (url in current) current - url else current
}
// Check before copying: most chunks leave the displayed percent unchanged.
val previous = current[url]
if (previous != null && (previous * 100).toInt() == (ratio * 100).toInt()) return@update current
buildMap {
putAll(current)
put(url, ratio)
if (size > MAX_TRACKED) keys.take(size - MAX_TRACKED).forEach(::remove)
}
}
}
fun clear(url: String) {
state.update { current -> if (url in current) current - url else current }
}
fun clearAll() { state.update { emptyMap() } }
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderSettingsSheet.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ReaderSettingsSheet, ReaderTab, GeneralTab, FilterTab, SectionLabel, BooleanRow, SliderRow, FilterChipRow, DbScaleType.label, formatPercent.
The source describes its contract as:
In-reader settings sheet. Direct port of the Flutter
reader_settings_modal.dartstructure: three tabs (Reader / General / Filter). Each control persists itsDbSettingschange throughonUpdateSettings; the reader observes the stored settings, so changes show immediately and survive across sessions. Some controls (reader mode, double-page) also live in the bottom bar for convenience — that's intentional, mirroring the Flutter UI.
Cross-chapter imports used by this file: DbBackgroundColor, DbColorFilterBlendMode, DbCustomColorFilter, DbReaderMode, DbScaleType, DbSettings. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.SecondaryTabRow
import androidx.compose.material3.Slider
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbBackgroundColor
import eu.friedcutlet.yokan.database.DbColorFilterBlendMode
import eu.friedcutlet.yokan.database.DbCustomColorFilter
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.database.DbScaleType
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbReaderModePreferences
import eu.friedcutlet.yokan.database.readerModePreferences
import eu.friedcutlet.yokan.database.withReaderModePreferences
import eu.friedcutlet.yokan.ui.formatDecimal
import eu.friedcutlet.yokan.ui.components.compactSheetWidth
/**
* In-reader settings sheet. Direct port of the Flutter
* `reader_settings_modal.dart` structure: three tabs (Reader / General /
* Filter). Each control persists its `DbSettings` change through
* `onUpdateSettings`; the reader observes the stored settings, so changes
* show immediately and survive across sessions.
*
* Some controls (reader mode, double-page) also live in the bottom bar for
* convenience — that's intentional, mirroring the Flutter UI.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun ReaderSettingsSheet(
visible: Boolean,
settings: DbSettings,
onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit,
currentMode: DbReaderMode,
automaticLayout: Boolean,
doublePage: Boolean,
automaticPairing: Boolean,
onAutomatic: () -> Unit,
onDefaultLayout: () -> Unit,
onAutomaticPairing: () -> Unit,
autoScrollEnabled: Boolean,
autoScrollOffset: Double,
onModeChange: (DbReaderMode) -> Unit,
onAutoScrollEnabledChange: (Boolean) -> Unit,
onAutoScrollOffsetChange: (Double) -> Unit,
onDismiss: () -> Unit,
) {
if (!visible) return
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = false)
var tab by remember { mutableIntStateOf(0) }
val tabs = listOf("Reader", "General", "Filter")
ModalBottomSheet(
onDismissRequest = onDismiss,
modifier = Modifier.compactSheetWidth(),
sheetState = sheetState,
) {
Column(
Modifier
.fillMaxWidth()
.heightIn(min = 320.dp)
.padding(bottom = 24.dp),
) {
Text(
text = "Reader settings",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp),
)
SecondaryTabRow(selectedTabIndex = tab) {
tabs.forEachIndexed { index, title ->
Tab(
selected = tab == index,
onClick = { tab = index },
text = { Text(title) },
)
}
}
Box(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(horizontal = 20.dp, vertical = 12.dp)) {
when (tab) {
0 -> ReaderTab(
settings = settings,
onUpdateSettings = onUpdateSettings,
currentMode = currentMode,
automaticLayout = automaticLayout,
doublePage = doublePage,
automaticPairing = automaticPairing,
onAutomatic = onAutomatic,
onDefaultLayout = onDefaultLayout,
onAutomaticPairing = onAutomaticPairing,
autoScrollEnabled = autoScrollEnabled,
autoScrollOffset = autoScrollOffset,
onModeChange = onModeChange,
onAutoScrollEnabledChange = onAutoScrollEnabledChange,
onAutoScrollOffsetChange = onAutoScrollOffsetChange,
)
1 -> GeneralTab(settings, onUpdateSettings, currentMode.isPaged())
else -> FilterTab(settings, onUpdateSettings)
}
}
}
}
}
@Composable
private fun ReaderTab(
settings: DbSettings,
onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit,
currentMode: DbReaderMode,
automaticLayout: Boolean,
doublePage: Boolean,
automaticPairing: Boolean,
onAutomatic: () -> Unit,
onDefaultLayout: () -> Unit,
onAutomaticPairing: () -> Unit,
autoScrollEnabled: Boolean,
autoScrollOffset: Double,
onModeChange: (DbReaderMode) -> Unit,
onAutoScrollEnabledChange: (Boolean) -> Unit,
onAutoScrollOffsetChange: (Double) -> Unit,
) {
Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
SectionLabel("Reading mode")
Text(stringResource(Res.string.reader_layout_resolved, currentMode.label(), stringResource(if (doublePage) Res.string.reader_layout_two_pages else Res.string.reader_layout_one_page)))
Text(stringResource(Res.string.reader_layout_help), style = MaterialTheme.typography.bodySmall)
FilterChipRow {
FilterChip(selected = automaticLayout, onClick = onAutomatic, label = { Text(stringResource(Res.string.reader_layout_automatic)) })
DbReaderMode.entries.forEach { mode ->
FilterChip(
selected = !automaticLayout && currentMode == mode,
onClick = { onModeChange(mode) },
label = { Text(mode.label()) },
)
}
}
TextButton(onDefaultLayout) { Text(stringResource(Res.string.reader_layout_default)) }
if (automaticLayout) TextButton(onAutomaticPairing, enabled = !automaticPairing) {
Text(stringResource(Res.string.reader_layout_auto_pairing))
}
SectionLabel("Scale type")
FilterChipRow {
DbScaleType.entries.forEach { type ->
FilterChip(
selected = settings.scaleType == type,
onClick = { onUpdateSettings { it.copy(scaleType = type) } },
label = { Text(type.label()) },
)
}
}
SectionLabel("Background")
FilterChipRow {
DbBackgroundColor.entries.forEach { color ->
FilterChip(
selected = settings.backgroundColor == color,
onClick = { onUpdateSettings { it.copy(backgroundColor = color) } },
label = { Text(color.name) },
)
}
}
BooleanRow(
label = "Show page gaps",
value = settings.showPageGaps,
onChange = { v -> onUpdateSettings { it.copy(showPageGaps = v) } },
)
BooleanRow(
label = "Fullscreen",
value = settings.fullScreenReader,
onChange = { v -> onUpdateSettings { it.copy(fullScreenReader = v) } },
)
BooleanRow(
label = "Always show chrome",
value = settings.alwaysShowChrome,
onChange = { v -> onUpdateSettings { it.copy(alwaysShowChrome = v) } },
)
BooleanRow(
label = "Keep screen on",
value = settings.keepScreenOnReader,
onChange = { v -> onUpdateSettings { it.copy(keepScreenOnReader = v) } },
)
if (currentMode.supportsAutoScroll()) {
SliderRow(
label = "Webtoon side padding",
value = settings.webtoonSidePadding.toFloat(),
valueRange = 0f..50f,
steps = 49,
valueLabel = "${settings.webtoonSidePadding.coerceIn(0, 50)}%",
onChange = { value ->
onUpdateSettings {
it.copy(webtoonSidePadding = value.toInt().coerceIn(0, 50))
}
},
)
}
BooleanRow(
label = stringResource(Res.string.reader_hold_to_scroll),
value = settings.readerHoldToScroll,
onChange = { value -> onUpdateSettings { it.copy(readerHoldToScroll = value) } },
)
Text(stringResource(Res.string.reader_hold_help), style = MaterialTheme.typography.bodySmall)
if (currentMode.supportsAutoScroll()) {
BooleanRow(
label = stringResource(Res.string.reader_scroll_enabled),
value = autoScrollEnabled,
onChange = onAutoScrollEnabledChange,
)
if (autoScrollEnabled || settings.readerHoldToScroll) {
SliderRow(
label = stringResource(Res.string.reader_scroll_speed),
value = autoScrollOffset.toFloat(),
valueRange = 2f..30f,
steps = 27,
valueLabel = formatDecimal(autoScrollOffset, 1),
onChange = { onAutoScrollOffsetChange(it.toDouble()) },
)
}
}
}
}
@Composable
private fun GeneralTab(settings: DbSettings, onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit, paged: Boolean) {
val modePreferences = settings.readerModePreferences(paged)
val updateMode: ((DbReaderModePreferences) -> DbReaderModePreferences) -> Unit = { transform ->
onUpdateSettings { it.withReaderModePreferences(paged, transform) }
}
Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
Text(
if (paged) "Tap zones and page processing apply to paged modes." else "Tap zones and page processing apply to continuous modes.",
style = MaterialTheme.typography.bodySmall,
)
SectionLabel("Tap zones")
BooleanRow(
label = "Use page tap zones",
value = modePreferences.usePageTapZones,
onChange = { v -> updateMode { it.copy(usePageTapZones = v) } },
)
FilterChipRow {
val labels = listOf("Default", "L-shape", "Kindle", "Edge", "R/L", "Disabled")
labels.forEachIndexed { index, label ->
FilterChip(
selected = modePreferences.navigationLayout == index,
onClick = { updateMode { it.copy(navigationLayout = index) } },
label = { Text(label) },
)
}
}
SectionLabel("Page processing")
BooleanRow(
label = "Animate page transitions",
value = modePreferences.animatePageTransitions,
onChange = { v -> updateMode { it.copy(animatePageTransitions = v) } },
)
BooleanRow(
label = "Crop borders",
value = modePreferences.cropBorders,
onChange = { v -> updateMode { it.copy(cropBorders = v) } },
)
BooleanRow(
label = "Split wide pages",
value = modePreferences.splitWidePages,
onChange = { v -> updateMode { it.copy(splitWidePages = v) } },
)
if (modePreferences.splitWidePages) BooleanRow(
label = "Invert split order",
value = modePreferences.invertSplit,
onChange = { v -> updateMode { it.copy(invertSplit = v) } },
)
BooleanRow(
label = "Rotate wide pages to fit",
value = modePreferences.rotateWidePages,
onChange = { v -> updateMode { it.copy(rotateWidePages = v) } },
)
if (modePreferences.rotateWidePages) BooleanRow(
label = "Invert rotation",
value = modePreferences.invertRotation,
onChange = { v -> updateMode { it.copy(invertRotation = v) } },
)
SectionLabel("Display")
BooleanRow(
label = "Show page numbers",
value = settings.showPagesNumber,
onChange = { v -> onUpdateSettings { it.copy(showPagesNumber = v) } },
)
BooleanRow(
label = "Grayscale",
value = settings.grayscale,
onChange = { v -> onUpdateSettings { it.copy(grayscale = v) } },
)
BooleanRow(
label = "Invert colors",
value = settings.invertColors,
onChange = { v -> onUpdateSettings { it.copy(invertColors = v) } },
)
SectionLabel("Tone")
SliderRow(
label = "Brightness",
value = settings.readerBrightness.toFloat(),
valueRange = -1f..1f,
steps = 19,
valueLabel = formatPercent(settings.readerBrightness),
onChange = { v -> onUpdateSettings { it.copy(readerBrightness = v.toDouble()) } },
)
SliderRow(
label = "Contrast",
value = settings.readerContrast.toFloat(),
valueRange = 0f..2f,
steps = 19,
valueLabel = "${formatDecimal(settings.readerContrast, 2)}x",
onChange = { v -> onUpdateSettings { it.copy(readerContrast = v.toDouble()) } },
)
SliderRow(
label = "Saturation",
value = settings.readerSaturation.toFloat(),
valueRange = 0f..2f,
steps = 19,
valueLabel = "${formatDecimal(settings.readerSaturation, 2)}x",
onChange = { v -> onUpdateSettings { it.copy(readerSaturation = v.toDouble()) } },
)
}
}
@Composable
private fun FilterTab(settings: DbSettings, onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit) {
Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
BooleanRow(
label = "Enable custom color filter",
value = settings.enableCustomColorFilter,
onChange = { v -> onUpdateSettings { it.copy(enableCustomColorFilter = v) } },
)
val custom = settings.customColorFilter ?: DbCustomColorFilter()
SliderRow(
label = "Red",
value = (custom.r ?: 0).toFloat(),
valueRange = 0f..255f,
steps = 0,
valueLabel = "${custom.r ?: 0}",
onChange = { v -> onUpdateSettings { it.copy(customColorFilter = custom.copy(r = v.toInt())) } },
)
SliderRow(
label = "Green",
value = (custom.g ?: 0).toFloat(),
valueRange = 0f..255f,
steps = 0,
valueLabel = "${custom.g ?: 0}",
onChange = { v -> onUpdateSettings { it.copy(customColorFilter = custom.copy(g = v.toInt())) } },
)
SliderRow(
label = "Blue",
value = (custom.b ?: 0).toFloat(),
valueRange = 0f..255f,
steps = 0,
valueLabel = "${custom.b ?: 0}",
onChange = { v -> onUpdateSettings { it.copy(customColorFilter = custom.copy(b = v.toInt())) } },
)
SliderRow(
label = "Alpha",
value = (custom.a ?: 0).toFloat(),
valueRange = 0f..255f,
steps = 0,
valueLabel = "${custom.a ?: 0}",
onChange = { v -> onUpdateSettings { it.copy(customColorFilter = custom.copy(a = v.toInt())) } },
)
SectionLabel("Blend mode")
FilterChipRow {
DbColorFilterBlendMode.entries.forEach { mode ->
FilterChip(
selected = settings.colorFilterBlendMode == mode,
onClick = { onUpdateSettings { it.copy(colorFilterBlendMode = mode) } },
label = { Text(mode.name) },
)
}
}
}
}
@Composable
private fun SectionLabel(text: String) {
Text(
text = text,
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.primary,
)
}
@Composable
private fun BooleanRow(label: String, value: Boolean, onChange: (Boolean) -> Unit) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
Text(label, modifier = Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium)
Checkbox(checked = value, onCheckedChange = onChange)
}
}
@Composable
private fun SliderRow(
label: String,
value: Float,
valueRange: ClosedFloatingPointRange<Float>,
steps: Int,
valueLabel: String,
onChange: (Float) -> Unit,
) {
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
Text(label, modifier = Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium)
Text(valueLabel, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Slider(
value = value.coerceIn(valueRange.start, valueRange.endInclusive),
onValueChange = onChange,
valueRange = valueRange,
steps = steps,
)
}
}
@Composable
private fun FilterChipRow(content: @Composable () -> Unit) {
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) { content() }
}
private fun DbScaleType.label(): String = when (this) {
DbScaleType.FitScreen -> "Fit screen"
DbScaleType.Stretch -> "Stretch"
DbScaleType.FitWidth -> "Fit width"
DbScaleType.FitHeight -> "Fit height"
DbScaleType.OriginalSize -> "Original"
DbScaleType.SmartFit -> "Smart fit"
}
private fun formatPercent(v: Double): String {
val pct = (v * 100).toInt()
return if (pct >= 0) "+$pct%" else "$pct%"
}
Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderSystemUi.android.kt
Create this path in your reconstruction project. Source set: androidMain. Exact file download.
The implementation below defines createReaderSystemUiController, AndroidReaderSystemUiController, apply, reset, applyKeepScreenOn, applyFullscreen.
Cross-chapter imports used by this file: AndroidForegroundActivity, MainActivity. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import eu.friedcutlet.yokan.AndroidForegroundActivity
import android.app.Activity
import android.os.Build
import android.view.View
import android.view.Window
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.view.WindowManager
import eu.friedcutlet.yokan.MainActivity
actual fun createReaderSystemUiController(): ReaderSystemUiController = AndroidReaderSystemUiController()
private class AndroidReaderSystemUiController : ReaderSystemUiController {
override fun apply(preferences: ReaderSystemUiPreferences) {
val activity = AndroidForegroundActivity.activity ?: return
val window = activity.window ?: return
activity.runOnUiThread {
applyKeepScreenOn(window, preferences.keepScreenOn)
applyFullscreen(window, preferences.hideMobileSystemBars)
}
}
override fun reset() {
val activity = AndroidForegroundActivity.activity ?: return
val window = activity.window ?: return
activity.runOnUiThread {
applyKeepScreenOn(window, false)
applyFullscreen(window, false)
}
}
private fun applyKeepScreenOn(window: Window, enabled: Boolean) {
if (enabled) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
private fun applyFullscreen(window: Window, enabled: Boolean) {
// The window is always edge-to-edge (enableEdgeToEdge in MainActivity);
// never re-fit the decor here — only toggle system bar visibility.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val controller = window.insetsController ?: return
if (enabled) {
controller.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
controller.hide(WindowInsets.Type.systemBars())
} else {
controller.show(WindowInsets.Type.systemBars())
}
} else {
@Suppress("DEPRECATION")
val hideFlags = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_FULLSCREEN)
@Suppress("DEPRECATION")
val layoutFlags = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
// Keep layout flags (edge-to-edge) and any appearance bits like
// SYSTEM_UI_FLAG_LIGHT_STATUS_BAR set by enableEdgeToEdge.
@Suppress("DEPRECATION")
window.decorView.systemUiVisibility = if (enabled) {
window.decorView.systemUiVisibility or layoutFlags or hideFlags
} else {
(window.decorView.systemUiVisibility or layoutFlags) and hideFlags.inv()
}
}
}
}
Write composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderSystemUi.desktop.kt
Create this path in your reconstruction project. Source set: desktopMain. Exact file download.
The implementation below defines createReaderSystemUiController, DesktopReaderSystemUiController, apply, reset, applyFullscreen, locateFrame.
Cross-chapter imports used by this file: DesktopSession. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import eu.friedcutlet.yokan.services.scheduling.DesktopSession
import java.awt.Frame
import java.awt.GraphicsEnvironment
import java.awt.Toolkit
import java.awt.event.WindowEvent
import javax.swing.JFrame
actual fun createReaderSystemUiController(): ReaderSystemUiController = DesktopReaderSystemUiController()
private class DesktopReaderSystemUiController : ReaderSystemUiController {
private var previousExtendedState: Int = Frame.NORMAL
private var previousMaximized: Boolean = false
// keepScreenOn has no portable JVM wake-lock API, so desktop only handles fullscreen.
override fun apply(preferences: ReaderSystemUiPreferences) {
val frame = locateFrame() ?: return
applyFullscreen(frame, preferences.fullscreen)
}
override fun reset() {
val frame = locateFrame() ?: return
applyFullscreen(frame, false)
}
private fun applyFullscreen(frame: Frame, enabled: Boolean) {
val device = GraphicsEnvironment.getLocalGraphicsEnvironment().defaultScreenDevice
if (enabled) {
previousExtendedState = frame.extendedState
previousMaximized = (frame.extendedState and Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH
if (device.isFullScreenSupported && device.fullScreenWindow == null) {
runCatching { device.fullScreenWindow = frame }
} else {
frame.extendedState = Frame.MAXIMIZED_BOTH
}
} else {
if (device.fullScreenWindow === frame) {
runCatching { device.fullScreenWindow = null }
}
frame.extendedState = if (previousMaximized) Frame.MAXIMIZED_BOTH else previousExtendedState
}
Toolkit.getDefaultToolkit().sync()
if (frame is JFrame) {
frame.dispatchEvent(WindowEvent(frame, WindowEvent.WINDOW_STATE_CHANGED))
}
}
private fun locateFrame(): Frame? = DesktopSession.frame ?: Frame.getFrames().firstOrNull { it.isVisible }
}
Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderSystemUi.ios.kt
Create this path in your reconstruction project. Source set: iosMain. Exact file download.
The implementation below defines IosReaderSystemUiBridge, register, unregister, setFullscreen, createReaderSystemUiController, IosReaderSystemUiController, apply, reset.
package eu.friedcutlet.yokan.ui.screens.reader
import platform.UIKit.UIApplication
object IosReaderSystemUiBridge {
private var fullscreenHandler: ((Boolean) -> Unit)? = null
private var fullscreen: Boolean = false
fun register(fullscreenHandler: (Boolean) -> Unit) {
this.fullscreenHandler = fullscreenHandler
fullscreenHandler(fullscreen)
}
fun unregister() {
fullscreenHandler = null
}
internal fun setFullscreen(enabled: Boolean) {
fullscreen = enabled
fullscreenHandler?.invoke(enabled)
}
}
actual fun createReaderSystemUiController(): ReaderSystemUiController = IosReaderSystemUiController()
private class IosReaderSystemUiController : ReaderSystemUiController {
override fun apply(preferences: ReaderSystemUiPreferences) {
UIApplication.sharedApplication.setIdleTimerDisabled(preferences.keepScreenOn)
IosReaderSystemUiBridge.setFullscreen(preferences.hideMobileSystemBars)
}
override fun reset() {
UIApplication.sharedApplication.setIdleTimerDisabled(false)
IosReaderSystemUiBridge.setFullscreen(false)
}
}
Write composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderSystemUi.wasm.kt
Create this path in your reconstruction project. Source set: wasmJsMain. Exact file download.
The implementation below defines createReaderSystemUiController, WasmReaderSystemUiController, apply, reset.
package eu.friedcutlet.yokan.ui.screens.reader
actual fun createReaderSystemUiController(): ReaderSystemUiController = WasmReaderSystemUiController
private object WasmReaderSystemUiController : ReaderSystemUiController {
override fun apply(preferences: ReaderSystemUiPreferences) = Unit
override fun reset() = Unit
}
Check your understanding
Combine zoom, vertical scroll and tap zones at a chapter boundary. Confirm each gesture has one intended action and closing the reader restores platform UI state. [chapter-content-end]: #
Step 4: persist progress and completion correctly
Save last page/read state/history on meaningful transitions and awaited cleanup. Preserve page units. Notify download automation only on actual consumption completion. Do not update history/tracking under incognito where the reference suppresses it. Chapter switches, back navigation and profile retirement all need final-save tests.
Follow the code
Follow the progress-saving methods already written in ReaderViewModel and ReaderRuntime, then their repository calls. A chapter/page event saves the correct unit and respects incognito; a transient render remeasurement is not consumption. Completion notifies automation only when the policy recognizes a real transition. Navigation and profile retirement must await final saves before closing the database. ReadingSessionClock from chapter 10 supplies shared time accounting.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/DiscordPresence.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/DiscordPresence.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines DiscordPresence.
The source describes its contract as:
Publishes Discord Rich Presence for the reader/player session and returns to idle on exit (Mangayomi's per-view RPC calls). Privacy rules live in the shared presence builder.
Cross-chapter imports used by this file: DbSettings, Chapter, ItemType, Manga, DiscordPresenceRequest, DiscordRpcService. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.discord.DiscordPresenceRequest
import eu.friedcutlet.yokan.services.discord.DiscordRpcService
/**
* Publishes Discord Rich Presence for the reader/player session and returns to idle on exit
* (Mangayomi's per-view RPC calls). Privacy rules live in the shared presence builder.
*/
@Composable
internal fun DiscordPresence(rpc: DiscordRpcService, settings: DbSettings, manga: Manga, chapter: Chapter) {
DisposableEffect(rpc, manga.id, chapter.id, settings.enableDiscordRpc, settings.incognitoMode, settings.features.discord) {
val title = manga.name
if (settings.enableDiscordRpc && !title.isNullOrBlank()) {
val request = DiscordPresenceRequest(
title = title,
detail = chapter.name,
coverUrl = manga.imageUrl,
watching = manga.itemType == ItemType.Anime,
sourceId = manga.sourceId,
categoryIds = manga.categories,
)
runCatching { rpc.showActivity(settings, request) }
}
onDispose {
if (settings.enableDiscordRpc) runCatching { rpc.showIdle(settings) }
}
}
}
Check your understanding
Exit during a pending save and switch profiles. Verify the final write targets the departing owner and finishes before its storage closes; no automatic history is created under incognito. [chapter-content-end]: #
Step 5: add processing and image actions
Implement border crop, spread merge, filters and page-processing cache keys in shared and platform-specific code. A transformed image must remain associated with its source identity and processing options. Rebuild export/share/set-cover/crop/colorize/restore-original actions through ReaderImageWork and platform file/image services; cancellation must not publish an obsolete result to the next page.
For colorization, implement EXIF orientation, PanelColorizer contracts and LocalColorizationQueue first, then Android/desktop ONNX and iOS native bridge implementations. Preserve model/session caching, bounded allocations, queue ownership and output/cache recovery from tests. The model binary/runtime is an external dependency; the guide's coverage ledger inventories the host code, not generated weights. Show progress/cancel/error and preserve original pages.
Follow the code
Processing receives a stable page identity and options, then publishes only if that identity is still current. Cache keys distinguish original, crop/filter and colorized output. Image export/share/set-cover actions use the file/image services instead of writing platform paths from UI code. Colorization adds EXIF handling, queue ownership and platform model/session lifecycle; native inference limits and cancellation protect memory and the original page.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/colorization/ExifOrientation.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/colorization/PanelColorizer.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/colorization/LocalColorizationQueue.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderImageActions.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/PanelColorizerSheet.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/colorization/ColorizerPlatform.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/BorderCropTransformation.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ImageSharing.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderColorFilters.ktcomposeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/colorization/ColorizerPlatform.android.ktcomposeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/BorderCropTransformation.android.ktcomposeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ImageSharing.android.ktcomposeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/SpreadMerge.android.ktcomposeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/colorization/ColorizerPlatform.desktop.ktcomposeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ImageSharing.desktop.ktcomposeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/colorization/ColorizerPlatform.ios.ktcomposeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ImageSharing.ios.ktcomposeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/colorization/OnnxPanelInference.ktcomposeApp/src/skikoMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/BorderCropTransformation.skiko.ktcomposeApp/src/skikoMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/SpreadMerge.skiko.ktcomposeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/colorization/ColorizerPlatform.wasm.ktcomposeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ImageSharing.wasm.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/colorization/ExifOrientation.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines jpegExifOrientation, parseTiffOrientation, u16, u32, orientedDimensions, orientPixels.
The source describes its contract as:
Reads the JPEG EXIF orientation (1 when absent, malformed, or unsupported).
package eu.friedcutlet.yokan.services.colorization
/** Reads the JPEG EXIF orientation (1 when absent, malformed, or unsupported). */
internal fun jpegExifOrientation(bytes: ByteArray): Int {
if (bytes.size < 4 || bytes[0] != 0xff.toByte() || bytes[1] != 0xd8.toByte()) return 1
var offset = 2
while (offset + 4 <= bytes.size && bytes[offset] == 0xff.toByte()) {
while (offset < bytes.size && bytes[offset] == 0xff.toByte()) offset++
if (offset >= bytes.size) return 1
val marker = bytes[offset++].toInt() and 0xff
if (marker == 0xda || marker == 0xd9) return 1
if (marker in 0xd0..0xd7 || marker == 0x01) continue
if (offset + 2 > bytes.size) return 1
val length = u16(bytes, offset, littleEndian = false)
if (length < 2 || length > bytes.size - offset) return 1
val data = offset + 2
val end = offset + length
if (marker == 0xe1 && end - data >= 14 &&
bytes[data] == 'E'.code.toByte() && bytes[data + 1] == 'x'.code.toByte() &&
bytes[data + 2] == 'i'.code.toByte() && bytes[data + 3] == 'f'.code.toByte() &&
bytes[data + 4] == 0.toByte() && bytes[data + 5] == 0.toByte()
) return parseTiffOrientation(bytes, data + 6, end)
offset = end
}
return 1
}
private fun parseTiffOrientation(bytes: ByteArray, start: Int, end: Int): Int {
if (start + 8 > end) return 1
val littleEndian = when {
bytes[start] == 'I'.code.toByte() && bytes[start + 1] == 'I'.code.toByte() -> true
bytes[start] == 'M'.code.toByte() && bytes[start + 1] == 'M'.code.toByte() -> false
else -> return 1
}
if (u16(bytes, start + 2, littleEndian) != 42) return 1
val ifdOffset = u32(bytes, start + 4, littleEndian)
if (ifdOffset > (end - start).toLong()) return 1
val ifd = start + ifdOffset.toInt()
if (ifd + 2 > end) return 1
val count = u16(bytes, ifd, littleEndian)
for (index in 0 until count) {
val entry = ifd + 2 + index * 12
if (entry + 12 > end) return 1
if (u16(bytes, entry, littleEndian) == 0x0112 &&
u16(bytes, entry + 2, littleEndian) == 3 && u32(bytes, entry + 4, littleEndian) == 1L
) {
return u16(bytes, entry + 8, littleEndian).takeIf { it in 1..8 } ?: 1
}
}
return 1
}
private fun u16(bytes: ByteArray, offset: Int, littleEndian: Boolean): Int {
val first = bytes[offset].toInt() and 0xff
val second = bytes[offset + 1].toInt() and 0xff
return if (littleEndian) first or (second shl 8) else (first shl 8) or second
}
private fun u32(bytes: ByteArray, offset: Int, littleEndian: Boolean): Long {
val first = u16(bytes, offset, littleEndian).toLong()
val second = u16(bytes, offset + 2, littleEndian).toLong()
return if (littleEndian) first or (second shl 16) else (first shl 16) or second
}
internal fun orientedDimensions(width: Int, height: Int, orientation: Int): Pair<Int, Int> =
if (orientation in 5..8) height to width else width to height
/** Applies EXIF orientation to decoded ARGB pixels without resampling. */
internal fun orientPixels(width: Int, height: Int, argb: IntArray, orientation: Int): PanelPixels {
require(width > 0 && height > 0 && argb.size.toLong() == width.toLong() * height)
if (orientation !in 2..8) return PanelPixels(width, height, argb)
val (outWidth, outHeight) = orientedDimensions(width, height, orientation)
val output = IntArray(argb.size)
for (y in 0 until height) for (x in 0 until width) {
val (outX, outY) = when (orientation) {
2 -> width - 1 - x to y
3 -> width - 1 - x to height - 1 - y
4 -> x to height - 1 - y
5 -> y to x
6 -> height - 1 - y to x
7 -> height - 1 - y to width - 1 - x
else -> y to width - 1 - x // 8: 90° counter-clockwise
}
output[outY * outWidth + outX] = argb[y * width + x]
}
return PanelPixels(outWidth, outHeight, output)
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/colorization/PanelColorizer.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines MangaColorizerModel, PanelCrop, valid, PanelPixels, PanelColorizer, installed, importModel, removeModel, colorize, colorizePage and 13 further declarations.
The source describes its contract as:
The supported export is pinned so untrusted/arbitrary ONNX graphs are never executed.
Cross-chapter imports used by this file: sha256, LocalFileService, createPlatformLocalFileService. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.colorization
import eu.friedcutlet.yokan.util.sha256
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.files.createPlatformLocalFileService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlin.coroutines.coroutineContext
import kotlin.math.roundToInt
/** The supported export is pinned so untrusted/arbitrary ONNX graphs are never executed. */
object MangaColorizerModel {
const val fileName = "manga-colorize-fp16.onnx"
const val sizeBytes = 61_650_260
const val sha256Hex = "39660d0047ea6f1a0ddee6aa89054997f95ea566f4d56ff762f66dbcf1a1a7ef"
const val sourceUrl = "https://huggingface.co/Faridzar/manga-colorization-v2-onnx/tree/5515e06d31b08ffd107af686cba5e98e95e8d4cf"
const val maxInputLongEdge = 512
}
data class PanelCrop(val left: Float = 0f, val top: Float = 0f, val right: Float = 1f, val bottom: Float = 1f) {
fun valid(): Boolean = left.isFinite() && top.isFinite() && right.isFinite() && bottom.isFinite() &&
left >= 0f && top >= 0f && right <= 1f && bottom <= 1f && right - left >= .02f && bottom - top >= .02f
}
internal data class PanelPixels(val width: Int, val height: Int, val argb: IntArray) {
init { require(width in 1..4096 && height in 1..4096 && width.toLong() * height <= 8_000_000 && argb.size.toLong() == width.toLong() * height) }
}
// Process-wide gate: even overlapping readers/imports cannot load two native sessions.
private val colorizerGate = Mutex()
class PanelColorizer internal constructor(
private val files: LocalFileService,
private val platform: ColorizerPlatform,
private val validateModel: (ByteArray) -> Boolean = ::isSupportedColorizerModel,
) {
constructor() : this(createPlatformLocalFileService(), createColorizerPlatform())
val supported: Boolean get() = platform.supported
private val modelPath get() = "${files.downloadRoot.trimEnd('/')}/colorizer/${MangaColorizerModel.fileName}"
private val legacyModelPath get() = "${files.cacheRoot.trimEnd('/')}/colorizer/${MangaColorizerModel.fileName}"
fun installed(): Boolean = supported && (files.exists(modelPath) || files.exists(legacyModelPath))
suspend fun importModel(path: String) = withContext(Dispatchers.Default) {
colorizerGate.withLock {
check(supported)
val bytes = platform.readModel(path)
require(validateModel(bytes)) { "Use the supported manga-colorize-fp16.onnx export." }
coroutineContext.ensureActive()
val temporary = "$modelPath.partial"
try {
files.writeBytes(temporary, bytes)
check(files.promote(temporary, modelPath)) { "Could not store the model." }
} finally { files.deleteRecursively(temporary) }
}
}
suspend fun removeModel() = withContext(Dispatchers.Default) {
colorizerGate.withLock {
platform.release()
val currentRemoved = !files.exists(modelPath) || files.deleteRecursively(modelPath)
val legacyRemoved = !files.exists(legacyModelPath) || files.deleteRecursively(legacyModelPath)
check(currentRemoved && legacyRemoved)
}
}
suspend fun colorize(source: ByteArray, crop: PanelCrop): ByteArray = withContext(Dispatchers.Default) {
require(source.size in 1..25_000_000 && crop.valid()) { "Image is too large or panel selection is invalid." }
colorizerGate.withLock {
check(ensureModelAvailable()) { "Import the colorization model first." }
val original = cropPanel(platform.decode(source), crop)
val input = panelModelInput(original)
coroutineContext.ensureActive()
// Only the pinned graph may reach the native runtime: the cached copy is verified whenever
// the platform loads it, not on every panel while it stays loaded.
val rgb = platform.infer(modelPath, input) {
platform.readModel(modelPath).also { check(validateModel(it)) { "Reimport the supported model." } }
}
coroutineContext.ensureActive()
platform.encode(applyPanelRgb(original, input, rgb))
}
}
/** Returns the original page with only the selected normalized rectangle colorized. */
suspend fun colorizePage(source: ByteArray, crop: PanelCrop): ByteArray = withContext(Dispatchers.Default) {
require(source.size in 1..25_000_000 && crop.valid()) { "Image is too large or panel selection is invalid." }
colorizerGate.withLock {
check(ensureModelAvailable()) { "Import the colorization model first." }
val page = platform.decodeFullPage(source)
val bounds = panelBounds(page, crop)
val selected = cropPanel(page, crop)
val input = panelModelInput(selected)
coroutineContext.ensureActive()
val rgb = platform.infer(modelPath, input) {
platform.readModel(modelPath).also { check(validateModel(it)) { "Reimport the supported model." } }
}
coroutineContext.ensureActive()
platform.encode(compositePanel(page, applyPanelRgb(selected, input, rgb), bounds))
}
}
/** Migrates the verified pre-downloadRoot model only after the new copy is verified in place. */
private suspend fun ensureModelAvailable(): Boolean {
if (!supported) return false
if (files.exists(modelPath)) {
val persistentIsValid = try {
validateModel(platform.readModel(modelPath))
} catch (_: Exception) {
false
}
if (persistentIsValid) return true
}
if (!files.exists(legacyModelPath)) return false
val legacyBytes = platform.readModel(legacyModelPath)
check(validateModel(legacyBytes)) { "The stored colorization model is invalid. Reimport the supported model." }
coroutineContext.ensureActive()
val temporary = "$modelPath.partial"
try {
// A corrupt persistent copy may shadow the valid legacy cache after an interrupted migration.
if (files.exists(modelPath)) check(files.deleteRecursively(modelPath)) { "Could not replace the invalid stored colorization model." }
files.writeBytes(temporary, legacyBytes)
check(files.promote(temporary, modelPath)) { "Could not migrate the stored colorization model." }
val promotedIsValid = try {
validateModel(platform.readModel(modelPath))
} catch (failure: Exception) {
files.deleteRecursively(modelPath)
throw failure
}
if (!promotedIsValid) {
files.deleteRecursively(modelPath)
error("The stored colorization model could not be migrated safely.")
}
coroutineContext.ensureActive()
files.deleteRecursively(legacyModelPath)
return true
} finally {
files.deleteRecursively(temporary)
}
}
}
internal fun isSupportedColorizerModel(bytes: ByteArray): Boolean = bytes.size == MangaColorizerModel.sizeBytes &&
sha256(bytes).toHexString() == MangaColorizerModel.sha256Hex
internal fun cropPanel(image: PanelPixels, crop: PanelCrop): PanelPixels {
val bounds = panelBounds(image, crop)
val left = bounds.left
val top = bounds.top
val right = bounds.right
val bottom = bounds.bottom
val width = right - left
val pixels = IntArray(width * (bottom - top))
for (y in top until bottom) image.argb.copyInto(pixels, (y - top) * width, y * image.width + left, y * image.width + right)
return PanelPixels(width, bottom - top, pixels)
}
internal data class PanelBounds(val left: Int, val top: Int, val right: Int, val bottom: Int)
internal fun panelBounds(image: PanelPixels, crop: PanelCrop): PanelBounds {
require(crop.valid())
val left = (crop.left * image.width).toInt().coerceIn(0, image.width - 1)
val top = (crop.top * image.height).toInt().coerceIn(0, image.height - 1)
return PanelBounds(
left, top,
(crop.right * image.width).roundToInt().coerceIn(left + 1, image.width),
(crop.bottom * image.height).roundToInt().coerceIn(top + 1, image.height),
)
}
internal fun compositePanel(page: PanelPixels, colored: PanelPixels, bounds: PanelBounds): PanelPixels {
require(colored.width == bounds.right - bounds.left && colored.height == bounds.bottom - bounds.top)
val result = page.argb.copyOf()
for (y in bounds.top until bounds.bottom) {
colored.argb.copyInto(result, y * page.width + bounds.left, (y - bounds.top) * colored.width, (y - bounds.top + 1) * colored.width)
}
return PanelPixels(page.width, page.height, result)
}
internal data class PanelModelInput(
val values: FloatArray,
val width: Int,
val height: Int,
val contentLeft: Int,
val contentTop: Int,
val contentWidth: Int,
val contentHeight: Int,
) {
init {
require(width >= 32 && height >= 32 && width % 32 == 0 && height % 32 == 0)
require(maxOf(width, height) <= MangaColorizerModel.maxInputLongEdge)
require(values.size == 5 * width * height)
require(contentLeft >= 0 && contentTop >= 0)
require(contentWidth in 1..width - contentLeft && contentHeight in 1..height - contentTop)
}
}
// Preserve aspect ratio in dynamic 32px blocks; the unused input is white with no hints.
internal fun panelModelInput(image: PanelPixels): PanelModelInput {
val scale = MangaColorizerModel.maxInputLongEdge.toFloat() / maxOf(image.width, image.height)
fun paddedDimension(value: Int): Int =
(((value * scale).roundToInt().coerceAtLeast(1) + 31) / 32).coerceIn(1, 16) * 32
val width = paddedDimension(image.width)
val height = paddedDimension(image.height)
val plane = width * height
val contentScale = minOf(width.toFloat() / image.width, height.toFloat() / image.height)
val contentWidth = (image.width * contentScale).roundToInt().coerceIn(1, width)
val contentHeight = (image.height * contentScale).roundToInt().coerceIn(1, height)
val contentLeft = (width - contentWidth) / 2
val contentTop = (height - contentHeight) / 2
return PanelModelInput(FloatArray(5 * plane).also { input ->
input.fill(1f, 0, plane)
val xScale = contentWidth.toFloat() / image.width
val yScale = contentHeight.toFloat() / image.height
for (y in 0 until contentHeight) for (x in 0 until contentWidth) {
val left = (x / xScale).toInt().coerceAtMost(image.width - 1)
val top = (y / yScale).toInt().coerceAtMost(image.height - 1)
val right = ((x + 1) / xScale).roundToInt().coerceIn(left + 1, image.width)
val bottom = ((y + 1) / yScale).roundToInt().coerceIn(top + 1, image.height)
var sum = 0f
for (sy in top until bottom) for (sx in left until right) sum += luminance(image.argb[sy * image.width + sx])
input[(contentTop + y) * width + contentLeft + x] = sum / ((right - left) * (bottom - top))
}
}, width, height, contentLeft, contentTop, contentWidth, contentHeight)
}
private fun luminance(pixel: Int): Float {
val alpha = (pixel ushr 24 and 255) / 255f
val luma = ((pixel ushr 16 and 255) * .299f + (pixel ushr 8 and 255) * .587f + (pixel and 255) * .114f) / 255f
return luma * alpha + 1f - alpha
}
/** Upsample RGB output while keeping near-black ink and near-white bubbles neutral. */
internal fun applyPanelRgb(image: PanelPixels, input: PanelModelInput, rgb: FloatArray): PanelPixels {
val plane = input.width * input.height
require(rgb.size == 3 * plane && rgb.all(Float::isFinite)) { "Invalid colorizer output." }
val xScale = input.contentWidth.toFloat() / image.width
val yScale = input.contentHeight.toFloat() / image.height
fun sample(channel: Int, x: Float, y: Float): Float {
val x0 = x.toInt().coerceIn(0, input.width - 1); val y0 = y.toInt().coerceIn(0, input.height - 1)
val x1 = (x0 + 1).coerceAtMost(input.width - 1); val y1 = (y0 + 1).coerceAtMost(input.height - 1)
val fx = x - x0; val fy = y - y0; val start = channel * plane
val a = rgb[start + y0 * input.width + x0] * (1 - fx) + rgb[start + y0 * input.width + x1] * fx
val b = rgb[start + y1 * input.width + x0] * (1 - fx) + rgb[start + y1 * input.width + x1] * fx
return (a * (1 - fy) + b * fy).coerceIn(0f, 1f)
}
val result = IntArray(image.argb.size)
for (y in 0 until image.height) for (x in 0 until image.width) {
val r = sample(0, input.contentLeft + x * xScale, input.contentTop + y * yScale); val g = sample(1, input.contentLeft + x * xScale, input.contentTop + y * yScale); val b = sample(2, input.contentLeft + x * xScale, input.contentTop + y * yScale)
val index = y * image.width + x
val luma = luminance(image.argb[index])
val preserve = maxOf(
((.12f - luma) / .12f).coerceIn(0f, 1f),
((luma - .92f) / .08f).coerceIn(0f, 1f),
)
fun channel(value: Float) = ((value * (1 - preserve) + luma * preserve).coerceIn(0f, 1f) * 255).roundToInt()
result[index] = (255 shl 24) or (channel(r) shl 16) or (channel(g) shl 8) or channel(b)
}
return PanelPixels(image.width, image.height, result)
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/colorization/LocalColorizationQueue.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The queue owns inference work and its output lifecycle. Keep cancellation, bounded allocations and original-file recovery separate from the UI sheet that reports progress.
The implementation below defines ColorizationJobState, ColorizationJob, LocalColorizationQueue, start, enqueue, pause, resume, cancel, retry, close and 47 further declarations.
The source describes its contract as:
Durable, serialized, single-worker colorization of local archives.
Cross-chapter imports used by this file: DbChapter, DbPageUrl, YokanDatabase, sha256, LocalArchiveService, LocalFileService. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.colorization
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.util.sha256
import eu.friedcutlet.yokan.services.files.LocalArchiveService
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.library.LocalLibraryService
import eu.friedcutlet.yokan.services.files.effectiveLocalLibraryFolders
import eu.friedcutlet.yokan.services.files.resolveConfiguredLocalArchivePath
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import dev.whyoleg.cryptography.DelicateCryptographyApi
import dev.whyoleg.cryptography.random.CryptographyRandom
enum class ColorizationJobState { Queued, Running, Paused, Blocked, Publishing, Completed, Cancelled }
data class ColorizationJob(
val id: String,
val sourceMangaId: Long,
val sourceTitle: String,
val cloneTitle: String,
val state: ColorizationJobState,
val donePages: Int,
val totalPages: Int,
val currentChapter: String?,
val error: String? = null,
)
/** Durable, serialized, single-worker colorization of local archives. */
class LocalColorizationQueue(
private val database: YokanDatabase,
private val files: LocalFileService,
private val archives: LocalArchiveService,
private val colorizer: PanelColorizer,
private val localLibrary: LocalLibraryService,
private val scope: CoroutineScope,
) {
private val json = Json { ignoreUnknownKeys = false; encodeDefaults = true }
private val lock = Mutex()
private val workerGate = Mutex()
private val manifests = linkedMapOf<String, QueueManifest>()
private val _jobs = MutableStateFlow<List<ColorizationJob>>(emptyList())
val jobs: StateFlow<List<ColorizationJob>> = _jobs.asStateFlow()
val supported: Boolean get() = colorizer.supported
private var started = false
private var worker: Job? = null
private var activeJobId: String? = null
fun start() {
scope.launch(Dispatchers.Default) {
try {
ensureStarted()
} catch (failure: Throwable) {
if (failure is CancellationException) throw failure
AppLogger.error("[colorization] queue initialization failed: ${failure.message ?: failure::class.simpleName}")
}
}
}
suspend fun enqueue(mangaId: Long): ColorizationJob {
ensureStarted()
lock.withLock {
manifests.values.firstOrNull { it.sourceMangaId == mangaId && it.state in ACTIVE_STATES }?.let { return it.toJob() }
}
check(colorizer.supported) { "Colorization is not supported on this platform." }
check(colorizer.installed()) { "Import the colorization model first." }
val manga = database.manga(mangaId)?.takeIf { it.isLocalArchive && !it.source.equals("torrent", true) }
?: error("Only local, non-torrent titles can be colorized.")
val chapters = database.chapters(mangaId)
require(chapters.isNotEmpty()) { "This local title has no chapters." }
chapters.forEach { chapter -> chapterLocator(chapter) }
val title = manga.name?.takeIf(String::isNotBlank) ?: "Untitled"
lock.withLock {
manifests.values.firstOrNull { it.sourceMangaId == mangaId && it.state in ACTIVE_STATES }?.let { return it.toJob() }
val id = randomId()
val manifest = QueueManifest(
id = id,
sourceMangaId = manga.id,
sourceTitle = title,
cloneTitle = "$title (Colorized)",
state = ColorizationJobState.Queued,
chapters = chapters.map { QueueChapter(chapterId = it.id, locator = chapterLocator(it), title = it.name ?: "Chapter") },
)
persist(manifest)
manifests[id] = manifest
publishJobs()
launchWorkerLocked()
return manifest.toJob()
}
}
suspend fun pause(jobId: String) {
val task = lock.withLock {
val current = required(jobId)
check(!current.publicationCommitted) { "Publication is committed; this job cannot be paused." }
if (current.state !in setOf(ColorizationJobState.Queued, ColorizationJobState.Running)) return
persist(current.copy(state = ColorizationJobState.Paused, error = null))
manifests[jobId] = current.copy(state = ColorizationJobState.Paused, error = null)
publishJobs()
worker?.takeIf { activeJobId == jobId }
}
task?.cancelAndJoin()
lock.withLock { if (worker === task) worker = null; launchWorkerLocked() }
}
suspend fun resume(jobId: String) {
lock.withLock {
val current = required(jobId)
require(current.state == ColorizationJobState.Paused) { "Only paused jobs can resume." }
save(current.copy(state = ColorizationJobState.Queued, error = null))
launchWorkerLocked()
}
}
suspend fun cancel(jobId: String) {
val task = lock.withLock {
val current = required(jobId)
if (current.state == ColorizationJobState.Completed || current.state == ColorizationJobState.Cancelled) return
check(!current.publicationCommitted) { "Publication is committed; this job cannot be cancelled." }
val cancelled = current.copy(state = ColorizationJobState.Cancelled, error = null)
persist(cancelled)
manifests[jobId] = cancelled
publishJobs()
worker?.takeIf { activeJobId == jobId }
}
task?.cancelAndJoin()
val state = lock.withLock {
if (worker === task) worker = null
required(jobId)
}
if (state.state == ColorizationJobState.Cancelled) deleteOwnedStage(state)
lock.withLock { launchWorkerLocked() }
}
suspend fun retry(jobId: String) {
lock.withLock {
val current = required(jobId)
require(current.state == ColorizationJobState.Blocked) { "Only blocked jobs can be retried." }
save(current.copy(state = if (current.publicationCommitted) ColorizationJobState.Publishing else ColorizationJobState.Queued, error = null))
launchWorkerLocked()
}
}
fun close() {
worker?.cancel()
}
private suspend fun ensureStarted() {
lock.withLock {
if (started) return
val root = manifestRoot
files.listFiles(root).filter { it.name.endsWith(".json") }.forEach { entry ->
val decoded = try {
json.decodeFromString<QueueManifest>(files.readBytesBounded(entry.path, MAX_MANIFEST_BYTES.toLong()).decodeToString())
} catch (failure: Exception) {
if (failure is CancellationException) throw failure
AppLogger.warn("[colorization] cannot restore ${entry.name}; leaving it untouched: ${failure.message.orEmpty()}")
return@forEach
}
if (!decoded.id.matches(Regex("[a-f0-9]{32}")) || entry.name != "${decoded.id}.json") {
AppLogger.warn("[colorization] invalid manifest identity in ${entry.name}; leaving it untouched")
return@forEach
}
if (decoded.version != MANIFEST_VERSION) {
val blocked = decoded.copy(state = ColorizationJobState.Blocked, error = "Unsupported colorization manifest version ${decoded.version}.")
persist(blocked)
manifests[blocked.id] = blocked
return@forEach
}
val recovered = when (decoded.state) {
ColorizationJobState.Running -> decoded.copy(state = if (decoded.publicationCommitted) ColorizationJobState.Publishing else ColorizationJobState.Queued)
ColorizationJobState.Publishing -> decoded.copy(state = if (decoded.publicationCommitted) ColorizationJobState.Publishing else ColorizationJobState.Queued)
else -> decoded
}
val value = recovered
persist(value)
manifests[value.id] = value
}
started = true
publishJobs()
launchWorkerLocked()
}
}
private fun launchWorkerLocked() {
if (worker?.isActive == true) return
if (manifests.values.none(::isRunnable)) return
worker = scope.launch(Dispatchers.Default) {
try {
workerGate.withLock {
while (true) {
val next = lock.withLock {
val queued = manifests.values.firstOrNull(::isRunnable) ?: return@withLock null
if (queued.state == ColorizationJobState.Queued) save(queued.copy(state = ColorizationJobState.Running, error = null))
activeJobId = queued.id
queued
} ?: break
try {
process(next.id)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (failure: Throwable) {
lock.withLock {
manifests[next.id]?.takeIf { it.state in setOf(ColorizationJobState.Running, ColorizationJobState.Publishing) }
?.let { save(it.copy(state = ColorizationJobState.Blocked, error = failure.message ?: "Colorization failed.")) }
}
} finally {
lock.withLock { if (activeJobId == next.id) activeJobId = null }
}
}
}
} finally {
lock.withLock {
if (worker === currentCoroutineContext()[Job]) worker = null
activeJobId = null
launchWorkerLocked()
}
}
}
}
private suspend fun process(jobId: String) {
var manifest = lock.withLock { required(jobId) }
if (manifest.publicationCommitted) {
finishPublication(jobId)
return
}
check(colorizer.supported) { "Colorization is not supported on this platform." }
check(colorizer.installed()) { "Import the colorization model first." }
val manga = database.manga(manifest.sourceMangaId)?.takeIf { it.isLocalArchive && !it.source.equals("torrent", true) }
?: error("The source title is no longer a local archive.")
val chapters = database.chapters(manga.id)
check(chapters.map(DbChapter::id) == manifest.chapters.map(QueueChapter::chapterId)) { "The source chapter inventory changed." }
val stage = stagePath(manifest)
ensureOwnedPath(stage, downloadRoot)
for ((chapterIndex, chapter) in chapters.withIndex()) {
currentCoroutineContext().ensureActive()
manifest = runningJob(jobId)
val locator = chapterLocator(chapter)
val stored = manifest.chapters[chapterIndex]
check(locator == stored.locator) { "Source chapter path changed." }
val pageInventory = resolvePages(locator)
check(pageInventory.isNotEmpty()) { "Chapter '${chapter.name.orEmpty()}' has no local pages." }
val sourceHashes = pageInventory.map { page ->
hash(readPage(page.url))
}
val fingerprint = inventoryFingerprint(pageInventory.map { it.url }, sourceHashes)
var saved = stored.copy(pageCount = pageInventory.size, fingerprint = fingerprint)
if (stored.pageCount != 0 && (stored.pageCount != pageInventory.size || stored.fingerprint != fingerprint)) {
updateRunning(jobId) { it.copy(donePages = 0) }
error("Source chapter '${chapter.name.orEmpty()}' changed since colorization began.")
}
val chapterDir = "$stage/${chapterFolderName(chapterIndex, stored.title.ifBlank { "Chapter" })}"
ensureOwnedPath(chapterDir, stage)
val existingCbz = "$chapterDir.cbz"
if (saved.packaged) {
ensureOwnedPath(existingCbz, stage)
if (verifyPackage(existingCbz, saved)) {
if (files.exists(chapterDir)) check(files.deleteRecursively(chapterDir)) { "Could not remove temporary chapter pages." }
updateRunning(jobId) { current -> current.copy(currentChapter = chapter.name ?: "Chapter") }
continue
}
if (files.exists(existingCbz)) check(files.deleteRecursively(existingCbz)) { "Could not remove corrupt chapter package." }
if (chapterCheckpointsValid(chapterDir, saved, sourceHashes)) {
saved = saved.copy(packaged = false, artifactSize = 0, artifactFingerprint = "")
} else {
val invalidated = saved.copy(packaged = false, artifactSize = 0, artifactFingerprint = "", checkpoints = emptyList())
saved = invalidated
updateRunning(jobId) { current ->
val chaptersWithoutInvalidArtifact = current.chapters.toMutableList().also { it[chapterIndex] = invalidated }
current.copy(chapters = chaptersWithoutInvalidArtifact, donePages = doneCount(current.copy(chapters = chaptersWithoutInvalidArtifact)))
}
error("Packaged chapter '${chapter.name.orEmpty()}' is corrupt and verified page checkpoints are unavailable.")
}
}
saved = saved.copy(checkpoints = saved.checkpoints.filter { checkpoint ->
checkpoint.pageIndex in pageInventory.indices && validCheckpoint(
"$chapterDir/${(checkpoint.pageIndex + 1).toString().padStart(6, '0')}.png",
checkpoint,
sourceHashes[checkpoint.pageIndex],
)
})
val chapterState = saved
manifest = updateRunning(jobId) { current ->
val chaptersWithCurrent = current.chapters.toMutableList().also { it[chapterIndex] = chapterState }
current.copy(
chapters = chaptersWithCurrent,
currentChapter = chapter.name ?: "Chapter",
totalPages = chaptersWithCurrent.sumOf { it.pageCount },
donePages = doneCount(current.copy(chapters = chaptersWithCurrent)),
)
}
for ((pageIndex, pageEntry) in pageInventory.withIndex()) {
currentCoroutineContext().ensureActive()
manifest = runningJob(jobId)
val pageCheckpoint = manifest.chapters[chapterIndex].checkpoints.firstOrNull { it.pageIndex == pageIndex }
val outputPath = "$chapterDir/${(pageIndex + 1).toString().padStart(6, '0')}.png"
ensureOwnedPath(outputPath, stage)
val source = readPage(pageEntry.url)
check(hash(source) == sourceHashes[pageIndex]) { "Source chapter '${chapter.name.orEmpty()}' changed during colorization." }
if (pageCheckpoint != null && validCheckpoint(outputPath, pageCheckpoint, sourceHashes[pageIndex])) continue
if (pageCheckpoint != null && files.exists(outputPath)) files.deleteRecursively(outputPath)
require(source.isSupportedImage()) { "A chapter page is not a supported image." }
val output = colorizer.colorizePage(source, PanelCrop())
check(output.isPng()) { "Colorizer returned a non-PNG page." }
files.writeBytes(outputPath, output)
val checkpoint = QueuePage(pageIndex, sourceHashes[pageIndex], hash(output), output.size)
updateRunning(jobId) { current ->
val chapterState = current.chapters[chapterIndex]
val checkpoints = (chapterState.checkpoints.filterNot { it.pageIndex == pageIndex } + checkpoint).sortedBy { it.pageIndex }
val updatedChapter = chapterState.copy(checkpoints = checkpoints)
current.copy(
chapters = current.chapters.toMutableList().also { it[chapterIndex] = updatedChapter },
donePages = doneCount(current.copy(chapters = current.chapters.toMutableList().also { it[chapterIndex] = updatedChapter })),
totalPages = current.chapters.sumOf { it.pageCount },
)
}
}
val chapterMeta = json.encodeToString(ChapterOutputMetadata(jobId)).encodeToByteArray()
files.writeBytes("$chapterDir/metadata.json", chapterMeta)
val cbz = archives.zipDirectoryToCbz(chapterDir, deleteSource = false)
?: error("Could not package chapter '${chapter.name.orEmpty()}'.")
ensureOwnedPath(cbz, stage)
val expected = runningJob(jobId).chapters[chapterIndex]
val artifactSize = files.directorySize(cbz)
check(artifactSize in 1..MAX_ARCHIVE_VERIFY_BYTES.toLong()) { "Packaged chapter exceeds the verification size limit." }
verifyPackageContents(cbz, expected)
val artifactFingerprint = packageFingerprint(artifactSize, expected)
manifest = updateRunning(jobId) { current ->
current.copy(chapters = current.chapters.toMutableList().also {
it[chapterIndex] = it[chapterIndex].copy(packaged = true, artifactSize = artifactSize, artifactFingerprint = artifactFingerprint)
})
}
check(files.deleteRecursively(chapterDir)) { "Could not remove temporary chapter pages." }
}
manifest = runningJob(jobId)
check(manifest.chapters.all { it.packaged && it.pageCount > 0 }) { "Not all chapters were packaged." }
files.writeBytes("$stage/metadata.json", json.encodeToString(CloneMetadata(manifest.cloneTitle, manifest.id)).encodeToByteArray())
manifest = lock.withLock {
val current = required(jobId)
check(current.state == ColorizationJobState.Running) { "Job was stopped before publication." }
val publishing = current.copy(state = ColorizationJobState.Publishing, publicationCommitted = true, error = null)
save(publishing)
publishing
}
finishPublication(jobId)
}
private suspend fun finishPublication(jobId: String) {
val manifest = lock.withLock { required(jobId) }
check(manifest.publicationCommitted) { "Publication has not been committed." }
val destination = finalPath(manifest)
ensureOwnedPath(destination, downloadRoot)
ensureOwnedPath(stagePath(manifest), downloadRoot)
if (files.exists(destination)) {
check(ownedFinal(manifest, destination)) { "The colorized destination exists but is not owned by this job." }
verifyTitlePackages(destination, manifest)
} else {
verifyTitlePackages(stagePath(manifest), manifest)
check(files.publishDirectoryIfAbsent(stagePath(manifest), destination)) { "Could not atomically publish colorized title." }
verifyTitlePackages(destination, manifest)
}
try {
localLibrary.reconcile()
} catch (failure: Throwable) {
if (failure is CancellationException) throw failure
throw IllegalStateException("The clone was published, but local library reconciliation failed: ${failure.message ?: "unknown error"}", failure)
}
updateJob(jobId) { current -> current.copy(state = ColorizationJobState.Completed, error = null) }
}
private fun resolvePages(locator: String): List<DbPageUrl> {
val suffixAt = locator.indexOf('#')
val archiveLocator = if (suffixAt < 0) locator else locator.substring(0, suffixAt)
val resolved = resolveConfiguredLocalArchivePath(archiveLocator, files, database.settings())
require(isLocalLocator(resolved)) { "Remote chapter sources are not supported." }
val roots = effectiveLocalLibraryFolders(database.settings(), files)
val configured = roots.any { folder ->
if (folder.path.startsWith("content://")) {
resolved == folder.path || resolved.startsWith(folder.path.trimEnd('/') + "/")
} else {
isWithinCanonicalRoot(resolved, folder.path)
}
}
require(configured) { "The source chapter is outside configured local-library roots." }
val pages = if (resolved.isDirectImage()) {
listOf(DbPageUrl(resolved, resolved.substringAfterLast('/')))
} else {
archives.listPagesStrict(resolved)
}
return pages
}
private fun readPage(path: String): ByteArray {
require(isLocalLocator(path)) { "Remote page acquisition is not supported." }
val bytes = files.readBytesBounded(path, MAX_SOURCE_BYTES.toLong())
require(bytes.size in 1..MAX_SOURCE_BYTES) { "Source page is empty or exceeds 25 MB." }
require(bytes.isSupportedImage()) { "A chapter page is not a supported image." }
return bytes
}
private fun verifyPackage(path: String, chapter: QueueChapter): Boolean = try {
val size = files.directorySize(path)
if (!files.exists(path) || size !in 1..MAX_ARCHIVE_VERIFY_BYTES.toLong() || size != chapter.artifactSize ||
chapter.artifactFingerprint != packageFingerprint(size, chapter)
) {
false
} else {
verifyPackageContents(path, chapter)
true
}
} catch (_: Exception) { false }
private fun verifyTitlePackages(root: String, manifest: QueueManifest) {
ensureOwnedPath(root, downloadRoot)
manifest.chapters.forEachIndexed { index, chapter ->
check(chapter.packaged) { "A chapter is not marked as packaged." }
val path = "$root/${chapterFolderName(index, chapter.title.ifBlank { "Chapter" })}.cbz"
ensureOwnedPath(path, root)
check(verifyPackage(path, chapter)) { "Packaged chapter '${chapter.title}' failed publication verification." }
}
}
private fun packageFingerprint(size: Long, chapter: QueueChapter): String = hash(buildString {
append(size).append(':').append(chapter.pageCount).append('\n')
chapter.checkpoints.sortedBy { it.pageIndex }.forEach { checkpoint ->
append(checkpoint.pageIndex).append(':').append(checkpoint.outputSize).append(':').append(checkpoint.outputHash).append('\n')
}
}.encodeToByteArray())
private fun verifyPackageContents(path: String, chapter: QueueChapter) {
val pages = archives.listPagesStrict(path)
check(pages.size == chapter.pageCount) { "Packaged chapter page count did not validate." }
val expected = chapter.checkpoints.sortedBy { it.pageIndex }
check(expected.size == chapter.pageCount) { "Packaged chapter checkpoints are incomplete." }
pages.forEachIndexed { index, page ->
val bytes = files.readBytesBounded(page.url, MAX_OUTPUT_PAGE_BYTES.toLong())
check(bytes.size == expected[index].outputSize && hash(bytes) == expected[index].outputHash) {
"Packaged chapter page ${index + 1} failed hash validation."
}
}
}
private fun chapterCheckpointsValid(directory: String, chapter: QueueChapter, sourceHashes: List<String>): Boolean = runCatching {
chapter.checkpoints.size == chapter.pageCount && chapter.checkpoints.sortedBy { it.pageIndex }.all { checkpoint ->
checkpoint.pageIndex in sourceHashes.indices && validCheckpoint(
"$directory/${(checkpoint.pageIndex + 1).toString().padStart(6, '0')}.png",
checkpoint,
sourceHashes[checkpoint.pageIndex],
)
}
}.getOrDefault(false)
private fun validCheckpoint(path: String, checkpoint: QueuePage, sourceHash: String): Boolean {
if (checkpoint.sourceHash != sourceHash || !files.exists(path)) return false
return runCatching {
ensureOwnedPath(path, downloadRoot)
val output = files.readBytesBounded(path, MAX_OUTPUT_PAGE_BYTES.toLong())
output.size == checkpoint.outputSize && hash(output) == checkpoint.outputHash && output.isPng()
}.getOrDefault(false)
}
private fun ownedFinal(manifest: QueueManifest, path: String): Boolean {
return runCatching {
ensureOwnedPath(path, downloadRoot)
if (!files.exists(path)) false else {
val metadata = json.decodeFromString<CloneMetadata>(files.readBytesBounded("$path/metadata.json", MAX_METADATA_BYTES.toLong()).decodeToString())
metadata.colorizationJobId == manifest.id && metadata.name == manifest.cloneTitle
}
}.getOrDefault(false)
}
private fun deleteOwnedStage(manifest: QueueManifest) {
val path = stagePath(manifest)
if (files.exists(path)) {
ensureOwnedPath(path, downloadRoot)
files.deleteRecursively(path)
}
}
private suspend fun save(value: QueueManifest) {
persist(value)
manifests[value.id] = value
publishJobs()
}
private suspend fun runningJob(id: String): QueueManifest = lock.withLock {
required(id).also { check(it.state == ColorizationJobState.Running) { "Colorization job is no longer running." } }
}
private suspend fun updateRunning(id: String, transform: (QueueManifest) -> QueueManifest): QueueManifest = lock.withLock {
val current = required(id)
check(current.state == ColorizationJobState.Running) { "Colorization job was paused or cancelled." }
val updated = transform(current)
save(updated)
updated
}
private suspend fun updateJob(id: String, transform: (QueueManifest) -> QueueManifest): QueueManifest = lock.withLock {
val updated = transform(required(id))
save(updated)
updated
}
private fun persist(value: QueueManifest) {
val path = manifestPath(value.id)
ensureOwnedPath(path, manifestRoot)
val temp = "$path.${randomId()}.tmp"
files.writeBytes(temp, json.encodeToString(value).encodeToByteArray())
check(files.atomicReplaceFile(temp, path)) { "Could not atomically save colorization job." }
}
private fun publishJobs() {
_jobs.value = manifests.values.map(QueueManifest::toJob)
}
private fun required(id: String): QueueManifest = manifests[id] ?: error("Colorization job not found.")
private fun isRunnable(manifest: QueueManifest): Boolean = manifest.state == ColorizationJobState.Queued ||
(manifest.state == ColorizationJobState.Publishing && manifest.publicationCommitted)
private fun finalPath(manifest: QueueManifest): String = "$downloadRoot/local/${safeSegment(manifest.sourceTitle)}-${manifest.id}"
private fun stagePath(manifest: QueueManifest): String = "$downloadRoot/local/.colorizer-${manifest.id}.partial"
private fun manifestPath(id: String): String = "$manifestRoot/$id.json"
private val downloadRoot get() = files.downloadRoot.trimEnd('/', '\\')
private val manifestRoot get() = "$downloadRoot/colorizer/jobs"
private fun ensureOwnedPath(path: String, root: String) {
val canonicalRoot = files.canonicalPath(root) ?: error("Could not validate app-owned storage path.")
val canonicalPath = files.canonicalPath(path) ?: error("Could not validate storage path.")
check(canonicalPath == canonicalRoot || canonicalPath.startsWith(canonicalRoot.trimEnd('/', '\\') + "/")) {
"Storage path escaped its owned root."
}
}
private fun isWithinCanonicalRoot(path: String, root: String): Boolean {
val canonicalRoot = files.canonicalPath(root) ?: return false
val canonicalPath = files.canonicalPath(path) ?: return false
return canonicalPath == canonicalRoot || canonicalPath.startsWith(canonicalRoot.trimEnd('/', '\\') + "/")
}
private fun chapterLocator(chapter: DbChapter): String {
val path = chapter.archivePath.ifBlank { chapter.url }
require(path.isNotBlank() && isLocalLocator(path)) { "Remote or missing chapter sources are not supported." }
return path
}
private fun safeSegment(value: String): String = value.replace(Regex("[^A-Za-z0-9 ._-]"), "_")
.trim().trim('.').take(100).ifBlank { "Colorized" }
private fun chapterFolderName(index: Int, title: String): String =
"${(index + 1).toString().padStart(4, '0')}-${safeSegment(title).take(80)}"
private fun doneCount(value: QueueManifest): Int = value.chapters.sumOf { chapter ->
if (chapter.packaged) chapter.pageCount else chapter.checkpoints.count { checkpoint -> checkpoint.pageIndex in 0 until chapter.pageCount }
}
@OptIn(DelicateCryptographyApi::class)
private fun randomId(): String = CryptographyRandom.Default.nextBytes(16).toHexString()
private fun hash(bytes: ByteArray): String = sha256(bytes).toHexString()
private fun inventoryFingerprint(paths: List<String>, hashes: List<String>): String =
hash((paths.zip(hashes).joinToString("\n") { (path, digest) -> "${path.substringAfterLast('/')}:$digest" }).encodeToByteArray())
private fun isLocalLocator(value: String): Boolean =
!value.startsWith("http://", true) && !value.startsWith("https://", true) &&
(value.startsWith("content://", true) || value.startsWith("file:", true) || !value.contains("://"))
private fun String.isDirectImage(): Boolean = hasImageExtension() ||
files.mimeType(this)?.startsWith("image/", ignoreCase = true) == true
private fun String.hasImageExtension(): Boolean = substringBefore('#').substringAfterLast('.').lowercase() in
setOf("png", "jpg", "jpeg", "gif", "webp", "bmp", "avif")
private fun ByteArray.isSupportedImage(): Boolean =
starts(0x89, 0x50, 0x4e, 0x47) || starts(0xff, 0xd8, 0xff) || starts(0x47, 0x49, 0x46, 0x38) ||
(size >= 12 && ascii(0, "RIFF") && ascii(8, "WEBP")) || (size >= 12 && (ascii(4, "ftypavif") || ascii(4, "ftypavis")))
private fun ByteArray.isPng(): Boolean = starts(0x89, 0x50, 0x4e, 0x47)
private fun ByteArray.starts(vararg values: Int): Boolean = size >= values.size && values.indices.all { this[it].toInt() and 255 == values[it] }
private fun ByteArray.ascii(offset: Int, text: String): Boolean = size >= offset + text.length &&
text.indices.all { this[offset + it].toInt() and 255 == text[it].code }
@Serializable
private data class QueueManifest(
val version: Int = 2,
val id: String,
val sourceMangaId: Long,
val sourceTitle: String,
val cloneTitle: String,
val state: ColorizationJobState,
val chapters: List<QueueChapter>,
val donePages: Int = 0,
val totalPages: Int = 0,
val currentChapter: String? = null,
val error: String? = null,
val publicationCommitted: Boolean = false,
) {
fun toJob() = ColorizationJob(id, sourceMangaId, sourceTitle, cloneTitle, state, donePages, totalPages, currentChapter, error)
}
@Serializable
private data class QueueChapter(
val chapterId: Long,
val locator: String,
val title: String,
val pageCount: Int = 0,
val fingerprint: String = "",
val checkpoints: List<QueuePage> = emptyList(),
val packaged: Boolean = false,
val artifactSize: Long = 0,
val artifactFingerprint: String = "",
)
@Serializable
private data class QueuePage(val pageIndex: Int, val sourceHash: String, val outputHash: String, val outputSize: Int)
@Serializable
private data class CloneMetadata(val name: String, val colorizationJobId: String)
@Serializable
private data class ChapterOutputMetadata(val colorizationJobId: String)
private companion object {
const val MANIFEST_VERSION = 2
const val MAX_SOURCE_BYTES = 25_000_000
const val MAX_METADATA_BYTES = 65_536
const val MAX_OUTPUT_PAGE_BYTES = 100_000_000
const val MAX_ARCHIVE_VERIFY_BYTES = 512_000_000
const val MAX_MANIFEST_BYTES = 8_000_000
val ACTIVE_STATES = setOf(ColorizationJobState.Queued, ColorizationJobState.Running, ColorizationJobState.Paused, ColorizationJobState.Publishing)
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderImageActions.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ReaderImageActionsSheet.
The source describes its contract as:
Actions for image bytes resolved at long-press time. Save, share and copy reuse the exact rendered source payload; a two-page spread can also be exported merged. Setting a cover requires confirmation.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Palette
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.colorizer_title
import yokan.composeapp.generated.resources.ok
import androidx.compose.material.icons.filled.Bookmark
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.ui.components.compactSheetWidth
/**
* Actions for image bytes resolved at long-press time. Save, share and copy reuse
* the exact rendered source payload; a two-page spread can also be exported merged.
* Setting a cover requires confirmation.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun ReaderImageActionsSheet(
target: ResolvedReaderImage?,
onDismiss: () -> Unit,
onExport: (ReaderImageExport, spread: Boolean) -> Unit,
onSetCover: () -> Unit,
onColorize: () -> Unit,
) {
target ?: return
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = false)
var confirmingCover by remember(target) { mutableStateOf(false) }
ModalBottomSheet(
onDismissRequest = onDismiss,
modifier = Modifier.compactSheetWidth(),
sheetState = sheetState,
) {
Column(Modifier.fillMaxWidth().padding(bottom = 16.dp)) {
Text(
text = "Page actions",
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(start = 20.dp, top = 8.dp, bottom = 4.dp),
)
ListItem(
modifier = Modifier.clickable(onClick = onColorize),
headlineContent = { Text(stringResource(Res.string.colorizer_title)) },
leadingContent = { Icon(Icons.Filled.Palette, contentDescription = null) },
)
ListItem(
modifier = Modifier.clickable { onExport(ReaderImageExport.Save, false) },
headlineContent = { Text("Save image") },
leadingContent = { Icon(Icons.Filled.Download, contentDescription = null) },
)
ListItem(
modifier = Modifier.clickable { onExport(ReaderImageExport.Share, false) },
headlineContent = { Text("Share image") },
leadingContent = { Icon(Icons.Filled.Share, contentDescription = null) },
)
ListItem(
modifier = Modifier.clickable { onExport(ReaderImageExport.Copy, false) },
headlineContent = { Text("Copy image") },
leadingContent = { Icon(Icons.Filled.ContentCopy, contentDescription = null) },
)
if (target.spreadPartner != null) {
ListItem(
modifier = Modifier.clickable { onExport(ReaderImageExport.Save, true) },
headlineContent = { Text("Save both pages") },
leadingContent = { Icon(Icons.Filled.Download, contentDescription = null) },
)
ListItem(
modifier = Modifier.clickable { onExport(ReaderImageExport.Share, true) },
headlineContent = { Text("Share both pages") },
leadingContent = { Icon(Icons.Filled.Share, contentDescription = null) },
)
ListItem(
modifier = Modifier.clickable { onExport(ReaderImageExport.Copy, true) },
headlineContent = { Text("Copy both pages") },
leadingContent = { Icon(Icons.Filled.ContentCopy, contentDescription = null) },
)
}
ListItem(
modifier = Modifier.clickable { confirmingCover = true },
headlineContent = { Text("Set as cover") },
leadingContent = { Icon(Icons.Filled.Bookmark, contentDescription = null) },
)
}
}
if (confirmingCover) {
AlertDialog(
onDismissRequest = { confirmingCover = false },
text = { Text("Use this as cover art?") },
dismissButton = {
TextButton(onClick = { confirmingCover = false }) { Text(stringResource(Res.string.action_cancel)) }
},
confirmButton = {
TextButton(
onClick = {
confirmingCover = false
onSetCover()
},
) { Text(stringResource(Res.string.ok)) }
},
)
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/PanelColorizerSheet.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines panelColorizerPreviewBytes, PanelColorizerSheet, PanelSelectionImage, PanelBoundSlider.
Cross-chapter imports used by this file: openSystemBrowser. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import coil3.compose.AsyncImage
import coil3.compose.LocalPlatformContext
import coil3.request.ImageRequest
import coil3.request.CachePolicy
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.contentDescription
import eu.friedcutlet.yokan.services.colorization.MangaColorizerModel
import eu.friedcutlet.yokan.services.colorization.PanelCrop
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import eu.friedcutlet.yokan.ui.components.compactSheetWidth
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
internal fun panelColorizerPreviewBytes(
target: ResolvedReaderImage,
preview: ByteArray?,
showOriginal: Boolean,
): ByteArray = preview?.takeUnless { showOriginal } ?: if (showOriginal) target.originalBytes else target.bytes
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun PanelColorizerSheet(target: ResolvedReaderImage?, state: ReaderColorizerState, onEvent: (ReaderEvent) -> Unit) {
if (!state.open || target == null) return
val busy = state.work != ColorizerWork.Idle
var showBounds by remember(target) { mutableStateOf(false) }
ModalBottomSheet(
onDismissRequest = { onEvent(ReaderEvent.CloseColorizer) },
modifier = Modifier.compactSheetWidth(),
sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),
) {
Column(
Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(horizontal = 20.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(stringResource(Res.string.colorizer_title), style = MaterialTheme.typography.titleLarge)
Text(stringResource(Res.string.colorizer_intro), style = MaterialTheme.typography.bodySmall)
if (state.hasAppliedColorization) {
OutlinedButton(
onClick = { onEvent(ReaderEvent.RestoreOriginalColorizedPage) },
modifier = Modifier.fillMaxWidth(),
enabled = !busy,
) {
Text(stringResource(Res.string.colorizer_restore_original))
}
}
if (!state.supported) {
Text(stringResource(Res.string.colorizer_web_unavailable))
} else {
if (!state.modelInstalled) {
Text(stringResource(Res.string.colorizer_import_help), style = MaterialTheme.typography.bodyMedium)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
TextButton(onClick = { openSystemBrowser(MangaColorizerModel.sourceUrl) }, enabled = !busy) {
Text(stringResource(Res.string.colorizer_model_source))
}
OutlinedButton(onClick = { onEvent(ReaderEvent.ImportColorizerModel) }, enabled = !busy) {
Text(stringResource(Res.string.colorizer_import))
}
}
} else {
Text(stringResource(Res.string.colorizer_crop_hint), style = MaterialTheme.typography.bodySmall)
val preview = state.preview
val showingResult = preview != null && !state.showOriginal
PanelSelectionImage(
bytes = panelColorizerPreviewBytes(target, preview, state.showOriginal),
crop = if (showingResult) PanelCrop() else state.crop,
editable = !busy && !showingResult,
showSelection = !showingResult,
onCrop = { onEvent(ReaderEvent.SelectPanelCrop(it)) },
)
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
TextButton(enabled = !busy, onClick = { onEvent(ReaderEvent.SelectPanelCrop(PanelCrop())) }) {
Text(stringResource(Res.string.colorizer_whole_page))
}
if (preview != null) {
TextButton(onClick = { onEvent(ReaderEvent.ToggleColorizerOriginal) }, enabled = !busy) {
Text(stringResource(if (state.showOriginal) Res.string.colorizer_show_result else Res.string.colorizer_show_original))
}
}
}
TextButton(onClick = { showBounds = !showBounds }, enabled = !busy) {
Text(stringResource(Res.string.colorizer_adjust_bounds))
}
if (showBounds && !busy) {
val crop = state.crop
PanelBoundSlider(stringResource(Res.string.colorizer_bounds_left), crop.left, { onEvent(ReaderEvent.SelectPanelCrop(crop.copy(left = it.coerceAtMost(crop.right - .02f)))) })
PanelBoundSlider(stringResource(Res.string.colorizer_bounds_right), crop.right, { onEvent(ReaderEvent.SelectPanelCrop(crop.copy(right = it.coerceAtLeast(crop.left + .02f)))) })
PanelBoundSlider(stringResource(Res.string.colorizer_bounds_top), crop.top, { onEvent(ReaderEvent.SelectPanelCrop(crop.copy(top = it.coerceAtMost(crop.bottom - .02f)))) })
PanelBoundSlider(stringResource(Res.string.colorizer_bounds_bottom), crop.bottom, { onEvent(ReaderEvent.SelectPanelCrop(crop.copy(bottom = it.coerceAtLeast(crop.top + .02f)))) })
}
Button(
onClick = { onEvent(ReaderEvent.ColorizePanel) },
modifier = Modifier.fillMaxWidth(),
enabled = !busy,
) { Text(stringResource(Res.string.colorizer_run)) }
if (preview != null) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(onClick = { onEvent(ReaderEvent.SaveColorizedPanel) }, enabled = !busy) {
Text(stringResource(Res.string.colorizer_save))
}
OutlinedButton(onClick = { onEvent(ReaderEvent.ShareColorizedPanel) }, enabled = !busy) {
Text(stringResource(Res.string.colorizer_share))
}
}
}
TextButton(onClick = { onEvent(ReaderEvent.RemoveColorizerModel) }, enabled = !busy) {
Text(stringResource(Res.string.colorizer_remove_model))
}
}
if (busy) {
LinearProgressIndicator(Modifier.fillMaxWidth())
Text(stringResource(if (state.work == ColorizerWork.Importing) Res.string.colorizer_importing else Res.string.colorizer_running))
}
state.error?.let { error ->
Text(
stringResource(when (error) {
ColorizerError.ImportFailed -> Res.string.colorizer_import_error
ColorizerError.InferenceFailed -> Res.string.colorizer_inference_error
ColorizerError.RemoveFailed -> Res.string.colorizer_remove_error
}),
color = MaterialTheme.colorScheme.error,
)
}
}
TextButton(onClick = { onEvent(ReaderEvent.CloseColorizer) }, modifier = Modifier.align(Alignment.End)) {
Text(stringResource(if (busy) Res.string.action_cancel else Res.string.ui_close))
}
}
}
}
@Composable
private fun PanelSelectionImage(bytes: ByteArray, crop: PanelCrop, editable: Boolean, showSelection: Boolean, onCrop: (PanelCrop) -> Unit) {
var aspect by remember(bytes) { mutableStateOf(1f) }
val currentOnCrop by rememberUpdatedState(onCrop)
val color = MaterialTheme.colorScheme.primary
val context = LocalPlatformContext.current
val request = remember(bytes, context) { ImageRequest.Builder(context).data(bytes).size(800, 800).memoryCachePolicy(CachePolicy.DISABLED).diskCachePolicy(CachePolicy.DISABLED).build() }
BoxWithConstraints(Modifier.fillMaxWidth().height(300.dp), contentAlignment = Alignment.Center) {
val width = minOf(maxWidth, maxHeight * aspect)
val height = width / aspect
Box(Modifier.size(width, height).pointerInput(editable) {
if (editable) {
var start = Offset.Zero
detectDragGestures(
onDragStart = { start = it },
onDrag = { change, _ ->
change.consume()
val end = change.position
val selection = PanelCrop(
(minOf(start.x, end.x) / size.width).coerceIn(0f, 1f),
(minOf(start.y, end.y) / size.height).coerceIn(0f, 1f),
(maxOf(start.x, end.x) / size.width).coerceIn(0f, 1f),
(maxOf(start.y, end.y) / size.height).coerceIn(0f, 1f),
)
if (selection.valid()) currentOnCrop(selection)
},
)
}
}) {
AsyncImage(
model = request,
contentDescription = stringResource(Res.string.colorizer_preview),
contentScale = ContentScale.FillBounds,
modifier = Modifier.fillMaxSize(),
onSuccess = { result -> aspect = (result.result.image.width.toFloat() / result.result.image.height).coerceIn(.01f, 100f) },
)
if (showSelection) Canvas(Modifier.fillMaxSize()) {
drawRect(color, Offset(crop.left * size.width, crop.top * size.height),
Size((crop.right - crop.left) * size.width, (crop.bottom - crop.top) * size.height), style = Stroke(2.dp.toPx()))
}
}
}
}
@Composable
private fun PanelBoundSlider(label: String, value: Float, onChange: (Float) -> Unit) {
Text(label)
Slider(value, onChange, modifier = Modifier.semantics { contentDescription = label })
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/colorization/ColorizerPlatform.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ColorizerPlatform, readModel, decode, decodeFullPage, encode, infer, release, createColorizerPlatform.
The source describes its contract as:
Platform image codec and pinned-model inference behind [PanelColorizer].
package eu.friedcutlet.yokan.services.colorization
/** Platform image codec and pinned-model inference behind [PanelColorizer]. */
internal interface ColorizerPlatform {
val supported: Boolean get() = true
fun readModel(path: String): ByteArray
fun decode(bytes: ByteArray): PanelPixels
/** Decodes without resizing and rejects pages exceeding the full-page bounds. */
fun decodeFullPage(bytes: ByteArray): PanelPixels
fun encode(image: PanelPixels): ByteArray
/**
* Runs the model stored at [modelPath]. Implementations may keep it loaded between calls, but
* must call [verifiedModel] (reads and verifies the pinned graph) every time the native runtime
* (re)loads the model, preferably loading the returned bytes rather than the file again.
*/
fun infer(modelPath: String, input: PanelModelInput, verifiedModel: () -> ByteArray): FloatArray
/** Unloads a model [infer] kept loaded; called when the stored model is removed. */
fun release() {}
}
internal expect fun createColorizerPlatform(): ColorizerPlatform
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/BorderCropTransformation.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines ImageCropBounds, detectBorderCropBounds, createBorderCropTransformation, createPageHalfTransformation, createWidePageRotation.
The source describes its contract as:
Finds the same non-transparent, non-white, non-black content bounds as Mangayomi's Rust image cropper. A null result means the source should be returned unchanged because it is empty or already fills the bitmap.
package eu.friedcutlet.yokan.ui.screens.reader
import coil3.transform.Transformation
internal data class ImageCropBounds(
val left: Int,
val top: Int,
val rightExclusive: Int,
val bottomExclusive: Int,
) {
val width: Int get() = rightExclusive - left
val height: Int get() = bottomExclusive - top
}
/**
* Finds the same non-transparent, non-white, non-black content bounds as
* Mangayomi's Rust image cropper. A null result means the source should be
* returned unchanged because it is empty or already fills the bitmap.
*/
internal inline fun detectBorderCropBounds(
width: Int,
height: Int,
pixelAt: (x: Int, y: Int) -> Int,
): ImageCropBounds? {
if (width <= 0 || height <= 0) return null
var left = width
var top = height
var right = -1
var bottom = -1
for (y in 0 until height) {
for (x in 0 until width) {
val pixel = pixelAt(x, y)
val alpha = pixel ushr 24 and 0xFF
val red = (pixel ushr 16 and 0xFF) + 1
val green = (pixel ushr 8 and 0xFF) + 2
val blue = (pixel and 0xFF) + 3
if (alpha == 0) continue
if (red > 0xAA && green > 0xAA && blue > 0xAA) continue
if (red < 0x05 && green < 0x05 && blue < 0x05) continue
if (x < left) left = x
if (x > right) right = x
if (y < top) top = y
if (y > bottom) bottom = y
}
}
if (right < left || bottom < top) return null
if (left == 0 && top == 0 && right == width - 1 && bottom == height - 1) return null
return ImageCropBounds(left, top, right + 1, bottom + 1)
}
internal expect fun createBorderCropTransformation(): Transformation
/** Keeps the [left] or right half of the decoded page (the right half takes an odd middle column). */
internal expect fun createPageHalfTransformation(left: Boolean): Transformation
/** Turns landscape bitmaps by [degrees] (±90); portrait bitmaps pass through unchanged. */
internal expect fun createWidePageRotation(degrees: Int): Transformation
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ImageSharing.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines shareImage, saveImageToGallery, copyImageToClipboard, mergeSpreadImages, String.safeSharedFileName, readerImageFolderName, SpreadLayout, spreadLayout.
The source describes its contract as:
Opens the platform share UI for in-memory image data.
package eu.friedcutlet.yokan.ui.screens.reader
/** Opens the platform share UI for in-memory image data. */
expect fun shareImage(bytes: ByteArray, fileName: String, mimeType: String): Boolean
/**
* Saves in-memory image data to the platform's user-visible picture library, inside a
* [folder] (album on iOS) below Yokan's own location when one is given.
*/
expect suspend fun saveImageToGallery(bytes: ByteArray, fileName: String, mimeType: String, folder: String?): Boolean
/** Places the image on the system clipboard. */
expect suspend fun copyImageToClipboard(bytes: ByteArray, fileName: String, mimeType: String): Boolean
/**
* Two decoded pages side by side at a common height, encoded as JPEG; null for animated,
* undecodable or oversized inputs.
*/
internal expect suspend fun mergeSpreadImages(left: ByteArray, right: ByteArray): ByteArray?
internal fun String.safeSharedFileName(): String =
replace(Regex("[^A-Za-z0-9._-]+"), "_").trim('_').ifBlank { "yokan-cover.jpg" }
/** A title as a single path segment: path separators and reserved characters are replaced. */
internal fun readerImageFolderName(title: String): String =
title.replace(Regex("[\\\\/:*?\"<>|\\x00-\\x1F]+"), "_").trim().trim('.').take(100).trim().ifBlank { "Untitled" }
/** Side-by-side pixel layout shared by every platform's spread merge. */
internal data class SpreadLayout(val width: Int, val height: Int, val leftWidth: Int, val rightWidth: Int)
/** Scales both pages to the taller page's height; null when the result would exceed the decode budget. */
internal fun spreadLayout(leftWidth: Int, leftHeight: Int, rightWidth: Int, rightHeight: Int): SpreadLayout? {
if (leftWidth <= 0 || leftHeight <= 0 || rightWidth <= 0 || rightHeight <= 0) return null
val height = maxOf(leftHeight, rightHeight)
val scaledLeft = (leftWidth.toLong() * height / leftHeight).toInt().coerceAtLeast(1)
val scaledRight = (rightWidth.toLong() * height / rightHeight).toInt().coerceAtLeast(1)
val width = scaledLeft.toLong() + scaledRight
if (width * height > eu.friedcutlet.yokan.services.download.MaxSplitImagePixels) return null
return SpreadLayout(width.toInt(), height, scaledLeft, scaledRight)
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderColorFilters.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines DbBackgroundColor.toColor, DbScaleType.toContentScale, ReaderInitialTransform, readerInitialTransform, ReaderColorFilters, buildReaderColorFilters, composeColorMatrix, identityMatrix, invertMatrix, grayscaleMatrix and 5 further declarations.
Cross-chapter imports used by this file: DbBackgroundColor, DbColorFilterBlendMode, DbScaleType, DbSettings. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.ColorMatrix
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.IntSize
import eu.friedcutlet.yokan.database.DbBackgroundColor
import eu.friedcutlet.yokan.database.DbColorFilterBlendMode
import eu.friedcutlet.yokan.database.DbScaleType
import eu.friedcutlet.yokan.database.DbSettings
// ── Filter helpers ──
// Schema mirrors `DbSettings`: invertColors / grayscale toggles, readerBrightness /
// readerContrast / readerSaturation continuous knobs, enableCustomColorFilter +
// customColorFilter (a/r/g/b) tint with `colorFilterBlendMode` blend mode.
internal fun DbBackgroundColor.toColor(themeBackground: Color): Color = when (this) {
DbBackgroundColor.Black -> Color.Black
DbBackgroundColor.White -> Color.White
DbBackgroundColor.Grey -> Color(0xFF1B1B1B)
DbBackgroundColor.Automatic -> themeBackground
}
internal fun DbScaleType.toContentScale(paged: Boolean): ContentScale = when (this) {
DbScaleType.FitScreen -> ContentScale.Fit
DbScaleType.Stretch -> ContentScale.Crop
DbScaleType.FitWidth -> if (paged) ContentScale.Fit else ContentScale.FillWidth
DbScaleType.FitHeight -> if (paged) ContentScale.Fit else ContentScale.FillHeight
DbScaleType.OriginalSize -> ContentScale.Crop
DbScaleType.SmartFit -> ContentScale.Fit
}
internal data class ReaderInitialTransform(
val scale: Float = MIN_ZOOM,
val offset: Offset = Offset.Zero,
)
internal fun readerInitialTransform(
scaleType: DbScaleType,
imageSize: IntSize,
viewportSize: IntSize,
paged: Boolean,
): ReaderInitialTransform {
if (!paged ||
imageSize.width <= 0 ||
imageSize.height <= 0 ||
viewportSize.width <= 0 ||
viewportSize.height <= 0
) {
return ReaderInitialTransform()
}
val imageAspect = imageSize.width.toFloat() / imageSize.height
val viewportAspect = viewportSize.width.toFloat() / viewportSize.height
return when {
scaleType == DbScaleType.FitWidth && imageAspect < viewportAspect -> {
val scale = (viewportAspect / imageAspect).coerceAtMost(MAX_ZOOM)
ReaderInitialTransform(
scale = scale,
offset = Offset(y = viewportSize.height * (scale - 1f) / 2f, x = 0f),
)
}
scaleType == DbScaleType.FitHeight && imageAspect > viewportAspect -> {
val scale = (imageAspect / viewportAspect).coerceAtMost(MAX_ZOOM)
ReaderInitialTransform(
scale = scale,
offset = Offset(x = viewportSize.width * (scale - 1f) / 2f, y = 0f),
)
}
else -> ReaderInitialTransform()
}
}
internal data class ReaderColorFilters(
val tone: ColorFilter?,
val tint: ColorFilter?,
)
internal fun buildReaderColorFilters(settings: DbSettings): ReaderColorFilters {
val tone = composeColorMatrix(settings)?.let(ColorFilter::colorMatrix)
val custom = settings.takeIf { it.enableCustomColorFilter }?.customColorFilter
val blend = settings.colorFilterBlendMode.toBlendMode()
val tint = if (custom != null && blend != null) {
val color = Color(
red = (custom.r ?: 0).coerceIn(0, 255) / 255f,
green = (custom.g ?: 0).coerceIn(0, 255) / 255f,
blue = (custom.b ?: 0).coerceIn(0, 255) / 255f,
alpha = (custom.a ?: 0).coerceIn(0, 255) / 255f,
)
ColorFilter.tint(color, blend)
} else {
null
}
return ReaderColorFilters(tone = tone, tint = tint)
}
private fun composeColorMatrix(settings: DbSettings): ColorMatrix? {
// E-paper shows grays only; mapping color here keeps the panel's own dithering predictable.
val grayscale = settings.grayscale || settings.einkMode
if (!settings.invertColors &&
!grayscale &&
settings.readerBrightness == 0.0 &&
settings.readerContrast == 1.0 &&
settings.readerSaturation == 1.0
) return null
var current = identityMatrix()
if (settings.readerSaturation != 1.0) current = multiply(saturationMatrix(settings.readerSaturation.toFloat()), current)
if (settings.readerContrast != 1.0) current = multiply(contrastMatrix(settings.readerContrast.toFloat()), current)
if (settings.readerBrightness != 0.0) current = multiply(brightnessMatrix(settings.readerBrightness.toFloat()), current)
if (grayscale) current = multiply(grayscaleMatrix(), current)
if (settings.invertColors) current = multiply(invertMatrix(), current)
return ColorMatrix(current)
}
private fun identityMatrix(): FloatArray = floatArrayOf(
1f, 0f, 0f, 0f, 0f,
0f, 1f, 0f, 0f, 0f,
0f, 0f, 1f, 0f, 0f,
0f, 0f, 0f, 1f, 0f,
)
private fun invertMatrix(): FloatArray = floatArrayOf(
-1f, 0f, 0f, 0f, 255f,
0f, -1f, 0f, 0f, 255f,
0f, 0f, -1f, 0f, 255f,
0f, 0f, 0f, 1f, 0f,
)
private fun grayscaleMatrix(): FloatArray {
val lr = 0.2126f
val lg = 0.7152f
val lb = 0.0722f
return floatArrayOf(
lr, lg, lb, 0f, 0f,
lr, lg, lb, 0f, 0f,
lr, lg, lb, 0f, 0f,
0f, 0f, 0f, 1f, 0f,
)
}
private fun brightnessMatrix(value: Float): FloatArray {
val t = value * 255f
return floatArrayOf(
1f, 0f, 0f, 0f, t,
0f, 1f, 0f, 0f, t,
0f, 0f, 1f, 0f, t,
0f, 0f, 0f, 1f, 0f,
)
}
private fun contrastMatrix(value: Float): FloatArray {
val t = 128f * (1f - value)
return floatArrayOf(
value, 0f, 0f, 0f, t,
0f, value, 0f, 0f, t,
0f, 0f, value, 0f, t,
0f, 0f, 0f, 1f, 0f,
)
}
private fun saturationMatrix(value: Float): FloatArray {
val lr = 0.2126f
val lg = 0.7152f
val lb = 0.0722f
return floatArrayOf(
lr * (1 - value) + value, lg * (1 - value), lb * (1 - value), 0f, 0f,
lr * (1 - value), lg * (1 - value) + value, lb * (1 - value), 0f, 0f,
lr * (1 - value), lg * (1 - value), lb * (1 - value) + value, 0f, 0f,
0f, 0f, 0f, 1f, 0f,
)
}
private fun multiply(a: FloatArray, b: FloatArray): FloatArray {
val result = FloatArray(20)
for (i in 0..3) {
for (j in 0..4) {
var sum = 0f
for (k in 0..3) sum += a[i * 5 + k] * b[k * 5 + j]
if (j == 4) sum += a[i * 5 + 4]
result[i * 5 + j] = sum
}
}
return result
}
private fun DbColorFilterBlendMode.toBlendMode(): BlendMode? = when (this) {
DbColorFilterBlendMode.None -> null
DbColorFilterBlendMode.Multiply -> BlendMode.Multiply
DbColorFilterBlendMode.Screen -> BlendMode.Screen
DbColorFilterBlendMode.Overlay -> BlendMode.Overlay
DbColorFilterBlendMode.ColorDodge -> BlendMode.ColorDodge
DbColorFilterBlendMode.Lighten -> BlendMode.Lighten
DbColorFilterBlendMode.ColorBurn -> BlendMode.ColorBurn
DbColorFilterBlendMode.Darken -> BlendMode.Darken
DbColorFilterBlendMode.Difference -> BlendMode.Difference
DbColorFilterBlendMode.Saturation -> BlendMode.Saturation
DbColorFilterBlendMode.SoftLight -> BlendMode.Softlight
DbColorFilterBlendMode.Plus -> BlendMode.Plus
DbColorFilterBlendMode.Exclusion -> BlendMode.Exclusion
}
Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/colorization/ColorizerPlatform.android.kt
Create this path in your reconstruction project. Source set: androidMain. Exact file download.
The implementation below defines createColorizerPlatform, readModel, infer, release, decode, decodeFullPage, encode.
Cross-chapter imports used by this file: AndroidAppContext. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.colorization
import eu.friedcutlet.yokan.AndroidAppContext
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import java.io.ByteArrayOutputStream
import java.io.File
internal actual fun createColorizerPlatform(): ColorizerPlatform = object : ColorizerPlatform {
override fun readModel(path: String): ByteArray {
val stream = if (path.startsWith("content://")) {
checkNotNull(AndroidAppContext.appContext).contentResolver.openInputStream(Uri.parse(path))
} else File(path.removePrefix("file://")).inputStream()
return readBoundedModel(checkNotNull(stream))
}
override fun infer(modelPath: String, input: PanelModelInput, verifiedModel: () -> ByteArray) =
inferPanel(modelPath, input, verifiedModel)
override fun release() = releasePanelSession()
override fun decode(bytes: ByteArray): PanelPixels {
val orientation = jpegExifOrientation(bytes)
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
require(options.outWidth > 0 && options.outHeight > 0) { "Unsupported image format." }
var sample = 1
val longestSide = maxOf(options.outWidth, options.outHeight).toLong()
while ((longestSide + sample - 1) / sample > 1600) sample *= 2
options.inJustDecodeBounds = false
options.inSampleSize = sample
options.inPreferredConfig = Bitmap.Config.ARGB_8888
val image = checkNotNull(BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options))
try {
val pixels = IntArray(image.width * image.height)
image.getPixels(pixels, 0, image.width, 0, 0, image.width, image.height)
return orientPixels(image.width, image.height, pixels, orientation)
} finally { image.recycle() }
}
override fun decodeFullPage(bytes: ByteArray): PanelPixels {
val orientation = jpegExifOrientation(bytes)
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
require(bounds.outWidth > 0 && bounds.outHeight > 0) { "Unsupported or corrupt image." }
val (orientedWidth, orientedHeight) = orientedDimensions(bounds.outWidth, bounds.outHeight, orientation)
require(orientedWidth <= 4096 && orientedHeight <= 4096 && orientedWidth.toLong() * orientedHeight <= 8_000_000) {
"Full-page colorization supports images up to 4096 pixels per edge and 8 million pixels."
}
val options = BitmapFactory.Options().apply { inPreferredConfig = Bitmap.Config.ARGB_8888 }
val image = checkNotNull(BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)) { "Unsupported or corrupt image." }
try {
val pixels = IntArray(image.width * image.height)
image.getPixels(pixels, 0, image.width, 0, 0, image.width, image.height)
return orientPixels(image.width, image.height, pixels, orientation)
} finally { image.recycle() }
}
override fun encode(image: PanelPixels): ByteArray {
val bitmap = Bitmap.createBitmap(image.argb, image.width, image.height, Bitmap.Config.ARGB_8888)
try { return ByteArrayOutputStream().use { check(bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)); it.toByteArray() } }
finally { bitmap.recycle() }
}
}
Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/BorderCropTransformation.android.kt
Create this path in your reconstruction project. Source set: androidMain. Exact file download.
The implementation below defines createBorderCropTransformation, AndroidBorderCropTransformation, transform, createPageHalfTransformation, AndroidPageHalfTransformation, createWidePageRotation, AndroidWidePageRotation.
package eu.friedcutlet.yokan.ui.screens.reader
import android.graphics.Bitmap
import android.graphics.Matrix
import coil3.size.Size
import coil3.transform.Transformation
internal actual fun createBorderCropTransformation(): Transformation = AndroidBorderCropTransformation
private object AndroidBorderCropTransformation : Transformation() {
override val cacheKey: String = "yokan-border-crop-v1"
override suspend fun transform(input: Bitmap, size: Size): Bitmap {
val bounds = detectBorderCropBounds(input.width, input.height, input::getPixel) ?: return input
return Bitmap.createBitmap(input, bounds.left, bounds.top, bounds.width, bounds.height)
}
}
internal actual fun createPageHalfTransformation(left: Boolean): Transformation = AndroidPageHalfTransformation(left)
private class AndroidPageHalfTransformation(private val left: Boolean) : Transformation() {
override val cacheKey: String = "yokan-page-half-${if (left) "left" else "right"}-v1"
override suspend fun transform(input: Bitmap, size: Size): Bitmap {
val half = input.width / 2
if (half == 0) return input
return if (left) Bitmap.createBitmap(input, 0, 0, half, input.height)
else Bitmap.createBitmap(input, half, 0, input.width - half, input.height)
}
}
internal actual fun createWidePageRotation(degrees: Int): Transformation = AndroidWidePageRotation(degrees)
private class AndroidWidePageRotation(private val degrees: Int) : Transformation() {
override val cacheKey: String = "yokan-rotate-wide-$degrees-v1"
override suspend fun transform(input: Bitmap, size: Size): Bitmap {
if (input.width <= input.height) return input
return Bitmap.createBitmap(input, 0, 0, input.width, input.height, Matrix().apply { setRotate(degrees.toFloat()) }, true)
}
}
Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ImageSharing.android.kt
Create this path in your reconstruction project. Source set: androidMain. Exact file download.
The implementation below defines shareImage, saveImageToGallery, copyImageToClipboard, sharedImageUri.
The source describes its contract as:
Below API 29 MediaStore has no relative path, so images there land in the default Pictures location.
Cross-chapter imports used by this file: AndroidAppContext. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import eu.friedcutlet.yokan.AndroidAppContext
import android.content.ClipData
import android.content.ClipboardManager
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.core.content.FileProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
actual fun shareImage(bytes: ByteArray, fileName: String, mimeType: String): Boolean {
if (bytes.isEmpty()) return false
val context = AndroidAppContext.appContext ?: return false
return runCatching {
val uri = sharedImageUri(context, bytes, fileName)
val sendIntent = Intent(Intent.ACTION_SEND).apply {
type = mimeType
putExtra(Intent.EXTRA_STREAM, uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
val chooser = Intent.createChooser(sendIntent, "Share cover").apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
context.startActivity(chooser)
true
}.getOrDefault(false)
}
/** Below API 29 MediaStore has no relative path, so images there land in the default Pictures location. */
actual suspend fun saveImageToGallery(
bytes: ByteArray,
fileName: String,
mimeType: String,
folder: String?,
): Boolean = withContext(Dispatchers.IO) {
if (bytes.isEmpty()) return@withContext false
val context = AndroidAppContext.appContext ?: return@withContext false
val resolver = context.contentResolver
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, fileName.safeSharedFileName())
put(MediaStore.Images.Media.MIME_TYPE, mimeType)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
put(MediaStore.Images.Media.RELATIVE_PATH, listOfNotNull(Environment.DIRECTORY_PICTURES, "Yokan", folder).joinToString("/"))
put(MediaStore.Images.Media.IS_PENDING, 1)
}
}
val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
?: return@withContext false
runCatching {
resolver.openOutputStream(uri)?.use { it.write(bytes) }
?: error("Unable to open gallery output")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
resolver.update(
uri,
ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) },
null,
null,
)
}
true
}.getOrElse {
resolver.delete(uri, null, null)
false
}
}
actual suspend fun copyImageToClipboard(bytes: ByteArray, fileName: String, mimeType: String): Boolean {
if (bytes.isEmpty()) return false
val context = AndroidAppContext.appContext ?: return false
// Clipboard readers receive a temporary grant for the FileProvider URI.
val uri = withContext(Dispatchers.IO) { runCatching { sharedImageUri(context, bytes, fileName) }.getOrNull() } ?: return false
return runCatching {
val clipboard = context.getSystemService(ClipboardManager::class.java) ?: return false
clipboard.setPrimaryClip(ClipData.newUri(context.contentResolver, fileName, uri))
true
}.getOrDefault(false)
}
private fun sharedImageUri(context: Context, bytes: ByteArray, fileName: String): Uri {
val directory = File(context.cacheDir, "shared-images").apply { mkdirs() }
val image = File(directory, fileName.safeSharedFileName()).apply { writeBytes(bytes) }
return FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", image)
}
Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/SpreadMerge.android.kt
Create this path in your reconstruction project. Source set: androidMain. Exact file download.
The implementation below defines mergeSpreadImages, decodeSpreadPage.
The source describes its contract as:
Same limits as tall-image splitting: bounded input, still image, upright EXIF orientation.
package eu.friedcutlet.yokan.ui.screens.reader
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.media.ExifInterface
import eu.friedcutlet.yokan.services.download.MaxSplitImageBytes
import eu.friedcutlet.yokan.services.download.MaxSplitImagePixels
import eu.friedcutlet.yokan.services.download.mayBeAnimatedImage
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
internal actual suspend fun mergeSpreadImages(left: ByteArray, right: ByteArray): ByteArray? {
val first = decodeSpreadPage(left) ?: return null
try {
val second = decodeSpreadPage(right) ?: return null
try {
val layout = spreadLayout(first.width, first.height, second.width, second.height) ?: return null
val output = Bitmap.createBitmap(layout.width, layout.height, Bitmap.Config.ARGB_8888)
try {
val paint = Paint(Paint.FILTER_BITMAP_FLAG)
Canvas(output).apply {
drawColor(Color.WHITE)
drawBitmap(first, null, Rect(0, 0, layout.leftWidth, layout.height), paint)
drawBitmap(second, null, Rect(layout.leftWidth, 0, layout.width, layout.height), paint)
}
return ByteArrayOutputStream().use { out ->
check(output.compress(Bitmap.CompressFormat.JPEG, 90, out))
out.toByteArray()
}
} finally { output.recycle() }
} finally { second.recycle() }
} finally { first.recycle() }
}
/** Same limits as tall-image splitting: bounded input, still image, upright EXIF orientation. */
private fun decodeSpreadPage(bytes: ByteArray): Bitmap? {
if (bytes.size > MaxSplitImageBytes || bytes.mayBeAnimatedImage()) return null
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
if (bounds.outWidth <= 0 || bounds.outHeight <= 0 || bounds.outWidth.toLong() * bounds.outHeight > MaxSplitImagePixels) return null
if (bytes.size >= 2 && bytes[0] == 0xff.toByte() && bytes[1] == 0xd8.toByte()) {
val orientation = ByteArrayInputStream(bytes).use { ExifInterface(it).getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) }
if (orientation != ExifInterface.ORIENTATION_NORMAL && orientation != ExifInterface.ORIENTATION_UNDEFINED) return null
}
return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}
Write composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/colorization/ColorizerPlatform.desktop.kt
Create this path in your reconstruction project. Source set: desktopMain. Exact file download.
The implementation below defines createColorizerPlatform, readModel, infer, release, decode, decodeFullPage, encode.
package eu.friedcutlet.yokan.services.colorization
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
import kotlin.math.ceil
internal actual fun createColorizerPlatform(): ColorizerPlatform = object : ColorizerPlatform {
override fun readModel(path: String) = readBoundedModel(File(path.removePrefix("file://")).inputStream())
override fun infer(modelPath: String, input: PanelModelInput, verifiedModel: () -> ByteArray) =
inferPanel(modelPath, input, verifiedModel)
override fun release() = releasePanelSession()
override fun decode(bytes: ByteArray): PanelPixels {
val orientation = jpegExifOrientation(bytes)
ImageIO.createImageInputStream(ByteArrayInputStream(bytes)).use { stream ->
val readers = ImageIO.getImageReaders(stream)
require(readers.hasNext()) { "Unsupported image format. Use PNG or JPEG." }
val reader = readers.next()
try {
reader.input = stream
val sample = ceil(maxOf(reader.getWidth(0), reader.getHeight(0)) / 1600.0).toInt().coerceAtLeast(1)
val params = reader.defaultReadParam.apply { setSourceSubsampling(sample, sample, 0, 0) }
val image = reader.read(0, params)
try {
return orientPixels(
image.width, image.height,
image.getRGB(0, 0, image.width, image.height, null, 0, image.width), orientation,
)
} finally { image.flush() }
} finally { reader.dispose() }
}
}
override fun decodeFullPage(bytes: ByteArray): PanelPixels {
val orientation = jpegExifOrientation(bytes)
ImageIO.createImageInputStream(ByteArrayInputStream(bytes)).use { stream ->
val readers = ImageIO.getImageReaders(stream)
require(readers.hasNext()) { "Unsupported or corrupt image." }
val reader = readers.next()
try {
reader.input = stream
val width = reader.getWidth(0)
val height = reader.getHeight(0)
require(width > 0 && height > 0) { "Unsupported or corrupt image." }
val (orientedWidth, orientedHeight) = orientedDimensions(width, height, orientation)
require(orientedWidth <= 4096 && orientedHeight <= 4096 && orientedWidth.toLong() * orientedHeight <= 8_000_000) {
"Full-page colorization supports images up to 4096 pixels per edge and 8 million pixels."
}
val image = checkNotNull(reader.read(0)) { "Unsupported or corrupt image." }
try {
return orientPixels(
image.width, image.height,
image.getRGB(0, 0, image.width, image.height, null, 0, image.width), orientation,
)
}
finally { image.flush() }
} finally { reader.dispose() }
}
}
override fun encode(image: PanelPixels): ByteArray {
val bitmap = BufferedImage(image.width, image.height, BufferedImage.TYPE_INT_ARGB)
try {
bitmap.setRGB(0, 0, image.width, image.height, image.argb, 0, image.width)
return ByteArrayOutputStream().use { check(ImageIO.write(bitmap, "png", it)); it.toByteArray() }
} finally { bitmap.flush() }
}
}
Write composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ImageSharing.desktop.kt
Create this path in your reconstruction project. Source set: desktopMain. Exact file download.
The implementation below defines shareImage, saveImageToGallery, copyImageToClipboard, ImageTransferable, getTransferDataFlavors, isDataFlavorSupported, getTransferData.
package eu.friedcutlet.yokan.ui.screens.reader
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.awt.Desktop
import java.awt.Image
import java.awt.Toolkit
import java.awt.datatransfer.DataFlavor
import java.awt.datatransfer.Transferable
import java.awt.datatransfer.UnsupportedFlavorException
import java.io.File
import javax.imageio.ImageIO
actual fun shareImage(bytes: ByteArray, fileName: String, mimeType: String): Boolean {
if (bytes.isEmpty()) return false
return runCatching {
val directory = File(System.getProperty("java.io.tmpdir"), "yokan-shared-images").apply { mkdirs() }
val image = File(directory, fileName.safeSharedFileName()).apply { writeBytes(bytes) }
if (!Desktop.isDesktopSupported() || !Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) return false
Desktop.getDesktop().open(image)
true
}.getOrDefault(false)
}
actual suspend fun saveImageToGallery(
bytes: ByteArray,
fileName: String,
mimeType: String,
folder: String?,
): Boolean = withContext(Dispatchers.IO) {
if (bytes.isEmpty()) return@withContext false
runCatching {
val root = File(System.getProperty("user.home"), "Pictures/Yokan")
val directory = (if (folder == null) root else File(root, folder)).apply { mkdirs() }
File(directory, fileName.safeSharedFileName()).writeBytes(bytes)
true
}.getOrDefault(false)
}
actual suspend fun copyImageToClipboard(bytes: ByteArray, fileName: String, mimeType: String): Boolean = withContext(Dispatchers.IO) {
// ImageIO lacks WebP/AVIF; Skia normalizes every reader format to PNG first.
val image = readerImageAsPng(bytes)?.let { png -> runCatching { ImageIO.read(png.inputStream()) }.getOrNull() }
?: return@withContext false
runCatching {
Toolkit.getDefaultToolkit().systemClipboard.setContents(ImageTransferable(image), null)
true
}.getOrDefault(false)
}
private class ImageTransferable(private val image: Image) : Transferable {
override fun getTransferDataFlavors(): Array<DataFlavor> = arrayOf(DataFlavor.imageFlavor)
override fun isDataFlavorSupported(flavor: DataFlavor): Boolean = flavor == DataFlavor.imageFlavor
override fun getTransferData(flavor: DataFlavor): Any =
if (flavor == DataFlavor.imageFlavor) image else throw UnsupportedFlavorException(flavor)
}
Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/colorization/ColorizerPlatform.ios.kt
Create this path in your reconstruction project. Source set: iosMain. Exact file download.
The implementation below defines createColorizerPlatform, readModel, decode, decodeFullPage, encode, infer, NSData.toPanelBytes.
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class, kotlinx.cinterop.BetaInteropApi::class)
package eu.friedcutlet.yokan.services.colorization
import eu.friedcutlet.yokan.colorizerbridge.YokanDecodePanel
import eu.friedcutlet.yokan.colorizerbridge.YokanDecodePanelFullPage
import eu.friedcutlet.yokan.colorizerbridge.YokanEncodePanel
import eu.friedcutlet.yokan.colorizerbridge.YokanInferPanel
import kotlinx.cinterop.*
import platform.Foundation.*
import platform.posix.memcpy
internal actual fun createColorizerPlatform(): ColorizerPlatform = object : ColorizerPlatform {
override fun readModel(path: String): ByteArray {
val attributes = NSFileManager.defaultManager.attributesOfItemAtPath(path, null)
val size = (attributes?.get(NSFileSize) as? NSNumber)?.longLongValue
require(size == MangaColorizerModel.sizeBytes.toLong()) { "Use the supported model file." }
// Mapped (clean, evictable) pages instead of a second 60 MB resident copy; the pool frees the
// autoreleased NSData before decode and inference run.
return autoreleasepool {
checkNotNull(NSData.dataWithContentsOfFile(path, NSDataReadingMappedIfSafe, null)).toPanelBytes()
}
}
override fun decode(bytes: ByteArray): PanelPixels = memScoped {
val width = alloc<IntVar>(); val height = alloc<IntVar>()
// Borrow the pinned source instead of copying up to 25 MB; the bridge only reads it during the call.
val rgba = autoreleasepool {
bytes.usePinned {
val data = NSData.create(bytesNoCopy = it.addressOf(0), length = bytes.size.toULong(), freeWhenDone = false)
YokanDecodePanel(data, 1600, width.ptr, height.ptr)?.toPanelBytes()
}
}
checkNotNull(rgba) { "Unsupported image format." }
val pixels = IntArray(width.value * height.value) { index ->
val offset = index * 4
(255 shl 24) or ((rgba[offset].toInt() and 255) shl 16) or
((rgba[offset + 1].toInt() and 255) shl 8) or (rgba[offset + 2].toInt() and 255)
}
PanelPixels(width.value, height.value, pixels)
}
override fun decodeFullPage(bytes: ByteArray): PanelPixels = memScoped {
val width = alloc<IntVar>(); val height = alloc<IntVar>(); val failure = alloc<IntVar>()
val rgba = autoreleasepool {
bytes.usePinned {
val data = NSData.create(bytesNoCopy = it.addressOf(0), length = bytes.size.toULong(), freeWhenDone = false)
YokanDecodePanelFullPage(data, width.ptr, height.ptr, failure.ptr)?.toPanelBytes()
}
}
if (rgba == null) {
if (failure.value == 2) throw IllegalArgumentException("Full-page colorization supports images up to 4096 pixels per edge and 8 million pixels.")
throw IllegalArgumentException("Unsupported or corrupt image.")
}
val pixelCount = width.value.toLong() * height.value
check(width.value in 1..4096 && height.value in 1..4096 && pixelCount <= 8_000_000 && rgba.size.toLong() == pixelCount * 4) {
"Unsupported or corrupt image."
}
PanelPixels(width.value, height.value, IntArray(pixelCount.toInt()) { index ->
val offset = index * 4
((rgba[offset + 3].toInt() and 255) shl 24) or ((rgba[offset].toInt() and 255) shl 16) or
((rgba[offset + 1].toInt() and 255) shl 8) or (rgba[offset + 2].toInt() and 255)
})
}
override fun encode(image: PanelPixels): ByteArray = image.argb.usePinned {
checkNotNull(YokanEncodePanel(it.addressOf(0).reinterpret(), image.width, image.height)).toPanelBytes()
}
override fun infer(modelPath: String, input: PanelModelInput, verifiedModel: () -> ByteArray): FloatArray {
// The bridge loads the file on every call, so the stored copy is verified on every call too.
verifiedModel()
val output = FloatArray(3 * input.width * input.height)
input.values.usePinned { source -> output.usePinned { destination ->
check(YokanInferPanel(modelPath, source.addressOf(0), destination.addressOf(0), input.width, input.height)) { "Local model inference failed." }
} }
return output
}
}
private fun NSData.toPanelBytes(): ByteArray = ByteArray(length.toInt()).also { output ->
if (output.isNotEmpty()) output.usePinned { memcpy(it.addressOf(0), bytes, length) }
}
Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ImageSharing.ios.kt
Create this path in your reconstruction project. Source set: iosMain. Exact file download.
The implementation below defines shareImage, saveImageToGallery, copyImageToClipboard, photoLibraryReadWriteAccess, ByteArray.toNSData, imageSharePresenter.
The source describes its contract as:
A [folder] becomes a Photos album of that name, which needs read-write library access to find.
@file:OptIn(kotlinx.cinterop.BetaInteropApi::class, kotlinx.cinterop.ExperimentalForeignApi::class)
package eu.friedcutlet.yokan.ui.screens.reader
import kotlin.coroutines.resume
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.usePinned
import kotlinx.coroutines.suspendCancellableCoroutine
import platform.Foundation.NSData
import platform.Foundation.NSMutableArray
import platform.Foundation.NSPredicate
import platform.Foundation.NSTemporaryDirectory
import platform.Foundation.NSURL
import platform.Foundation.create
import platform.Foundation.writeToFile
import platform.Photos.PHAccessLevelReadWrite
import platform.Photos.PHAssetCollection
import platform.Photos.PHAssetCollectionChangeRequest
import platform.Photos.PHAssetCollectionSubtypeAny
import platform.Photos.PHAssetCollectionTypeAlbum
import platform.Photos.PHAssetCreationRequest
import platform.Photos.PHAssetResourceTypePhoto
import platform.Photos.PHAuthorizationStatusAuthorized
import platform.Photos.PHAuthorizationStatusLimited
import platform.Photos.PHAuthorizationStatusNotDetermined
import platform.Photos.PHFetchOptions
import platform.Photos.PHPhotoLibrary
import platform.UIKit.UIImage
import platform.UIKit.UIImageWriteToSavedPhotosAlbum
import platform.UIKit.UIActivityViewController
import platform.UIKit.UIApplication
import platform.UIKit.UIPasteboard
import platform.UIKit.UISceneActivationStateForegroundActive
import platform.UIKit.UIViewController
import platform.UIKit.UIWindow
import platform.UIKit.popoverPresentationController
import platform.UIKit.UIWindowScene
actual fun shareImage(bytes: ByteArray, fileName: String, mimeType: String): Boolean {
if (bytes.isEmpty()) return false
val presenter = imageSharePresenter() ?: return false
val safeName = fileName.safeSharedFileName()
val path = "${NSTemporaryDirectory().trimEnd('/')}/$safeName"
if (!bytes.toNSData().writeToFile(path, atomically = true)) return false
val controller = UIActivityViewController(
activityItems = listOf(NSURL.fileURLWithPath(path)),
applicationActivities = null,
)
controller.popoverPresentationController()?.sourceView = presenter.view
presenter.presentViewController(controller, animated = true, completion = null)
return true
}
/** A [folder] becomes a Photos album of that name, which needs read-write library access to find. */
actual suspend fun saveImageToGallery(bytes: ByteArray, fileName: String, mimeType: String, folder: String?): Boolean {
if (bytes.isEmpty()) return false
val data = bytes.toNSData()
if (folder == null) {
UIImageWriteToSavedPhotosAlbum(UIImage(data = data), null, null, null)
return true
}
if (!photoLibraryReadWriteAccess()) return false
return suspendCancellableCoroutine { continuation ->
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
val asset = PHAssetCreationRequest.creationRequestForAsset()
asset.addResourceWithType(PHAssetResourceTypePhoto, data = data, options = null)
val placeholder = asset.placeholderForCreatedAsset ?: return@performChanges
val options = PHFetchOptions().apply { predicate = NSPredicate.predicateWithFormat("title == %@", argumentArray = listOf(folder)) }
val album = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionTypeAlbum, PHAssetCollectionSubtypeAny, options)
.firstObject as? PHAssetCollection
val request = album?.let { PHAssetCollectionChangeRequest.changeRequestForAssetCollection(it) }
?: PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(folder)
request.addAssets(NSMutableArray().apply { addObject(placeholder) })
}) { success, _ -> if (continuation.isActive) continuation.resume(success) }
}
}
actual suspend fun copyImageToClipboard(bytes: ByteArray, fileName: String, mimeType: String): Boolean {
if (bytes.isEmpty()) return false
val image = UIImage.imageWithData(bytes.toNSData()) ?: return false
UIPasteboard.generalPasteboard.image = image
return true
}
private suspend fun photoLibraryReadWriteAccess(): Boolean {
val current = PHPhotoLibrary.authorizationStatusForAccessLevel(PHAccessLevelReadWrite)
val status = if (current != PHAuthorizationStatusNotDetermined) current else suspendCancellableCoroutine { continuation ->
PHPhotoLibrary.requestAuthorizationForAccessLevel(PHAccessLevelReadWrite) { granted -> if (continuation.isActive) continuation.resume(granted) }
}
return status == PHAuthorizationStatusAuthorized || status == PHAuthorizationStatusLimited
}
private fun ByteArray.toNSData(): NSData = usePinned { pinned ->
NSData.create(bytes = pinned.addressOf(0), length = size.toULong())
}
private fun imageSharePresenter(): UIViewController? {
val activeWindows = UIApplication.sharedApplication.connectedScenes
.filterIsInstance<UIWindowScene>()
.filter { scene -> scene.activationState == UISceneActivationStateForegroundActive }
.flatMap { scene -> scene.windows }
.filterIsInstance<UIWindow>()
val window = activeWindows.firstOrNull { candidate -> candidate.isKeyWindow() }
?: activeWindows.firstOrNull()
?: return null
var current = window.rootViewController
while (current?.presentedViewController != null) current = current.presentedViewController
return current
}
Write composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/colorization/OnnxPanelInference.kt
Create this path in your reconstruction project. Source set: jvmCommonMain. Exact file download.
The implementation below defines readBoundedModel, inferPanel, releasePanelSession, ModelSessionCache, use, release, releaseLocked.
The source describes its contract as:
Keeps the session of the model last used open, so consecutive panels skip reading, verifying and loading it again. The session closes [idleTimeout] after its last use, or on [release].
package eu.friedcutlet.yokan.services.colorization
import ai.onnxruntime.OnnxTensor
import ai.onnxruntime.OrtEnvironment
import ai.onnxruntime.OrtSession
import java.io.InputStream
import java.nio.FloatBuffer
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.job
import kotlinx.coroutines.launch
internal fun readBoundedModel(stream: InputStream): ByteArray = stream.use {
val bytes = ByteArray(MangaColorizerModel.sizeBytes)
var offset = 0
while (offset < bytes.size) {
val read = it.read(bytes, offset, bytes.size - offset)
require(read > 0) { "The selected model has an unsupported size." }
offset += read
}
require(it.read() == -1) { "The selected model is too large." }
bytes
}
// ponytail: one process-wide session (only the pinned model exists), closed after a minute without
// panels so its native weights don't stay resident; raise the timeout if colorizing in slow bursts.
@OptIn(DelicateCoroutinesApi::class)
private val panelSessions = ModelSessionCache(GlobalScope, idleTimeout = 1.minutes) { model ->
OrtSession.SessionOptions().use { options ->
options.setIntraOpNumThreads(1)
options.setInterOpNumThreads(1)
options.setExecutionMode(OrtSession.SessionOptions.ExecutionMode.SEQUENTIAL)
// FP16 graph optimization can temporarily expand weights past 1 GB on CPU.
options.setOptimizationLevel(OrtSession.SessionOptions.OptLevel.NO_OPT)
options.addConfigEntry("session.disable_prepacking", "1")
options.setCPUArenaAllocator(false)
options.setMemoryPatternOptimization(false)
// The session copies what it needs from the options, which can be released right away.
OrtEnvironment.getEnvironment().createSession(model, options)
}
}
internal fun inferPanel(modelPath: String, input: PanelModelInput, verifiedModel: () -> ByteArray): FloatArray {
require(input.values.size == 5 * input.width * input.height)
return panelSessions.use(modelPath, verifiedModel) { session ->
OnnxTensor.createTensor(
OrtEnvironment.getEnvironment(),
FloatBuffer.wrap(input.values),
longArrayOf(1, 5, input.height.toLong(), input.width.toLong()),
).use { tensor ->
session.run(mapOf("input" to tensor), setOf("rgb")).use { result ->
val output = result[0] as? OnnxTensor ?: error("Invalid colorizer output.")
require(output.info.shape.contentEquals(longArrayOf(1, 3, input.height.toLong(), input.width.toLong())))
FloatArray(3 * input.width * input.height).also { output.floatBuffer.get(it) }
}
}
}
}
internal fun releasePanelSession() = panelSessions.release()
/**
* Keeps the session of the model last used open, so consecutive panels skip reading, verifying and
* loading it again. The session closes [idleTimeout] after its last use, or on [release].
*/
internal class ModelSessionCache<S : AutoCloseable>(
private val scope: CoroutineScope,
private val idleTimeout: Duration,
private val open: (model: ByteArray) -> S,
) {
private val lock = Any()
private var modelPath: String? = null
private var session: S? = null
private var idleClose: Job? = null
fun <R> use(modelPath: String, loadModel: () -> ByteArray, block: (S) -> R): R = synchronized(lock) {
idleClose?.cancel()
val current = session?.takeIf { this.modelPath == modelPath } ?: run {
releaseLocked()
open(loadModel()).also {
session = it
this.modelPath = modelPath
}
}
try {
block(current)
} finally {
idleClose = scope.launch {
delay(idleTimeout)
// A use that started after this timer fired replaced it; only the latest timer closes.
synchronized(lock) { if (idleClose === coroutineContext.job) releaseLocked() }
}
}
}
fun release() = synchronized(lock) { releaseLocked() }
private fun releaseLocked() {
idleClose?.cancel()
idleClose = null
session?.close()
session = null
modelPath = null
}
}
Write composeApp/src/skikoMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/BorderCropTransformation.skiko.kt
Create this path in your reconstruction project. Source set: skikoMain. Exact file download.
The implementation below defines createBorderCropTransformation, SkiaBorderCropTransformation, transform, createPageHalfTransformation, SkiaPageHalfTransformation, createWidePageRotation, SkiaWidePageRotation, Bitmap.subset.
package eu.friedcutlet.yokan.ui.screens.reader
import coil3.Bitmap
import coil3.size.Size
import coil3.transform.Transformation
import org.jetbrains.skia.Canvas
import org.jetbrains.skia.IRect
import org.jetbrains.skia.Image
import org.jetbrains.skia.ImageInfo
internal actual fun createBorderCropTransformation(): Transformation = SkiaBorderCropTransformation
private object SkiaBorderCropTransformation : Transformation() {
override val cacheKey: String = "yokan-border-crop-v1"
override suspend fun transform(input: Bitmap, size: Size): Bitmap {
val bounds = detectBorderCropBounds(input.width, input.height, input::getColor) ?: return input
return input.subset(IRect.makeLTRB(bounds.left, bounds.top, bounds.rightExclusive, bounds.bottomExclusive))
}
}
internal actual fun createPageHalfTransformation(left: Boolean): Transformation = SkiaPageHalfTransformation(left)
private class SkiaPageHalfTransformation(private val left: Boolean) : Transformation() {
override val cacheKey: String = "yokan-page-half-${if (left) "left" else "right"}-v1"
override suspend fun transform(input: Bitmap, size: Size): Bitmap {
val half = input.width / 2
if (half == 0) return input
return input.subset(if (left) IRect.makeLTRB(0, 0, half, input.height) else IRect.makeLTRB(half, 0, input.width, input.height))
}
}
internal actual fun createWidePageRotation(degrees: Int): Transformation = SkiaWidePageRotation(degrees)
private class SkiaWidePageRotation(private val degrees: Int) : Transformation() {
override val cacheKey: String = "yokan-rotate-wide-$degrees-v1"
override suspend fun transform(input: Bitmap, size: Size): Bitmap {
if (input.width <= input.height) return input
val output = Bitmap()
check(output.allocPixels(ImageInfo(input.imageInfo.colorInfo, input.height, input.width))) { "Unable to allocate rotated page" }
val image = Image.makeFromBitmap(input)
val canvas = Canvas(output)
try {
// Clockwise: (x, y) -> (height - y, x); counter-clockwise: (x, y) -> (y, width - x).
if (degrees > 0) canvas.translate(input.height.toFloat(), 0f) else canvas.translate(0f, input.width.toFloat())
canvas.rotate(degrees.toFloat())
canvas.drawImage(image, 0f, 0f)
} finally {
canvas.close()
image.close()
}
return output
}
}
private fun Bitmap.subset(bounds: IRect): Bitmap = Bitmap().also { result ->
check(extractSubset(result, bounds)) { "Unable to crop image to $bounds" }
}
Write composeApp/src/skikoMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/SpreadMerge.skiko.kt
Create this path in your reconstruction project. Source set: skikoMain. Exact file download.
The implementation below defines mergeSpreadImages, readerImageAsPng, decodeSpreadPage, Image.encodeOnce.
The source describes its contract as:
PNG copy of any decodable still image; the format every clipboard accepts.
package eu.friedcutlet.yokan.ui.screens.reader
import eu.friedcutlet.yokan.services.download.MaxSplitImageBytes
import eu.friedcutlet.yokan.services.download.MaxSplitImagePixels
import eu.friedcutlet.yokan.services.download.mayBeAnimatedImage
import org.jetbrains.skia.Codec
import org.jetbrains.skia.Color
import org.jetbrains.skia.Data
import org.jetbrains.skia.EncodedImageFormat
import org.jetbrains.skia.EncodedOrigin
import org.jetbrains.skia.FilterMipmap
import org.jetbrains.skia.FilterMode
import org.jetbrains.skia.Image
import org.jetbrains.skia.MipmapMode
import org.jetbrains.skia.Rect
import org.jetbrains.skia.Surface
internal actual suspend fun mergeSpreadImages(left: ByteArray, right: ByteArray): ByteArray? {
val first = decodeSpreadPage(left) ?: return null
try {
val second = decodeSpreadPage(right) ?: return null
try {
val layout = spreadLayout(first.width, first.height, second.width, second.height) ?: return null
val surface = Surface.makeRasterN32Premul(layout.width, layout.height)
try {
val sampling = FilterMipmap(FilterMode.LINEAR, MipmapMode.NONE)
surface.canvas.clear(Color.WHITE)
surface.canvas.drawImageRect(first, Rect.makeWH(first.width.toFloat(), first.height.toFloat()),
Rect.makeWH(layout.leftWidth.toFloat(), layout.height.toFloat()), sampling, null, true)
surface.canvas.drawImageRect(second, Rect.makeWH(second.width.toFloat(), second.height.toFloat()),
Rect.makeXYWH(layout.leftWidth.toFloat(), 0f, layout.rightWidth.toFloat(), layout.height.toFloat()), sampling, null, true)
return surface.makeImageSnapshot().encodeOnce(EncodedImageFormat.JPEG, 90)
} finally { surface.close() }
} finally { second.close() }
} finally { first.close() }
}
/** PNG copy of any decodable still image; the format every clipboard accepts. */
internal fun readerImageAsPng(bytes: ByteArray): ByteArray? =
runCatching { Image.makeFromEncoded(bytes) }.getOrNull()?.encodeOnce(EncodedImageFormat.PNG)
/** Same limits as tall-image splitting: bounded input, still image, upright EXIF orientation. */
private fun decodeSpreadPage(bytes: ByteArray): Image? {
if (bytes.size > MaxSplitImageBytes || bytes.mayBeAnimatedImage()) return null
val data = Data.makeFromBytes(bytes)
try {
val codec = runCatching { Codec.makeFromData(data) }.getOrNull() ?: return null
try {
if (codec.encodedOrigin != EncodedOrigin.TOP_LEFT || codec.width.toLong() * codec.height > MaxSplitImagePixels) return null
} finally { codec.close() }
} finally { data.close() }
return runCatching { Image.makeFromEncoded(bytes) }.getOrNull()
}
private fun Image.encodeOnce(format: EncodedImageFormat, quality: Int = 100): ByteArray? = try {
encodeToData(format, quality)?.let { data -> try { data.bytes } finally { data.close() } }
} finally { close() }
Write composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/colorization/ColorizerPlatform.wasm.kt
Create this path in your reconstruction project. Source set: wasmJsMain. Exact file download.
The implementation below defines createColorizerPlatform, readModel, decode, decodeFullPage, encode, infer.
package eu.friedcutlet.yokan.services.colorization
internal actual fun createColorizerPlatform(): ColorizerPlatform = object : ColorizerPlatform {
override val supported = false
override fun readModel(path: String): ByteArray = error("Local colorization is unavailable on web.")
override fun decode(bytes: ByteArray): PanelPixels = error("Unavailable on web.")
override fun decodeFullPage(bytes: ByteArray): PanelPixels = error("Unavailable on web.")
override fun encode(image: PanelPixels): ByteArray = error("Unavailable on web.")
override fun infer(modelPath: String, input: PanelModelInput, verifiedModel: () -> ByteArray): FloatArray =
error("Unavailable on web.")
}
Write composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ImageSharing.wasm.kt
Create this path in your reconstruction project. Source set: wasmJsMain. Exact file download.
The implementation below defines shareImage, saveImageToGallery, copyImageToClipboard, writeClipboardPng.
The source describes its contract as:
Browsers choose the download directory; a title folder cannot be created, so [folder] is not applied.
Cross-chapter imports used by this file: triggerBrowserDownload. Keep those contracts available as you connect this step.
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class, kotlin.io.encoding.ExperimentalEncodingApi::class)
package eu.friedcutlet.yokan.ui.screens.reader
import eu.friedcutlet.yokan.services.system.triggerBrowserDownload
import kotlin.io.encoding.Base64
import kotlin.js.JsAny
import kotlin.js.Promise
import kotlinx.coroutines.await
actual fun shareImage(bytes: ByteArray, fileName: String, mimeType: String): Boolean {
if (bytes.isEmpty()) return false
// ponytail: navigator.share is async and needs a user gesture; a plain
// download covers the "get the image out" intent.
return triggerBrowserDownload(bytes, fileName, mimeType)
}
/** Browsers choose the download directory; a title folder cannot be created, so [folder] is not applied. */
actual suspend fun saveImageToGallery(bytes: ByteArray, fileName: String, mimeType: String, folder: String?): Boolean {
if (bytes.isEmpty()) return false
return triggerBrowserDownload(bytes, fileName, mimeType)
}
/** The async Clipboard API only guarantees `image/png`, so other formats are re-encoded first. */
actual suspend fun copyImageToClipboard(bytes: ByteArray, fileName: String, mimeType: String): Boolean {
val png = readerImageAsPng(bytes) ?: return false
return runCatching { writeClipboardPng(Base64.encode(png)).await<JsAny?>() }.isSuccess
}
private fun writeClipboardPng(base64: String): Promise<JsAny?> = js(
"""
(async () => {
if (!navigator.clipboard || !navigator.clipboard.write || typeof ClipboardItem === 'undefined') {
throw new Error('Clipboard images are not supported');
}
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
await navigator.clipboard.write([new ClipboardItem({ 'image/png': new Blob([bytes], { type: 'image/png' }) })]);
return null;
})()
""",
)
Check your understanding
Begin colorization, change chapter and finish the old job. The result can remain in its owned cache where allowed, but must not replace a page or cover in the new chapter. [chapter-content-end]: #
Recreate the tests and verify the chapter
Recreate reader sequence/runtime/retirement/progress, gesture/layout and processing/colorization fixtures. Run rendering and image tests on their applicable desktop/skiko/platform targets. Then test large, rotated, tall and AVIF pages with real devices/backends; test-only fake images do not establish decoder/native model availability.
These are source tests to reproduce and run in your reconstruction. Their inclusion here is not a claim that application/native/device tests were executed while writing the guide.
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/colorization/ExifOrientationTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ExifOrientationTest, jpegWithOrientation, short, int.
Read the setup, action and assertions in these cases before implementing their production paths:
transformsAsymmetricGridForEveryExifOrientationparsesOrientationFromBothTiffByteOrders
package eu.friedcutlet.yokan.services.colorization
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
class ExifOrientationTest {
@Test fun transformsAsymmetricGridForEveryExifOrientation() {
val source = intArrayOf(1, 2, 3, 4, 5, 6)
val expected = mapOf(
1 to ((2 to 3) to intArrayOf(1, 2, 3, 4, 5, 6)),
2 to ((2 to 3) to intArrayOf(2, 1, 4, 3, 6, 5)),
3 to ((2 to 3) to intArrayOf(6, 5, 4, 3, 2, 1)),
4 to ((2 to 3) to intArrayOf(5, 6, 3, 4, 1, 2)),
5 to ((3 to 2) to intArrayOf(1, 3, 5, 2, 4, 6)),
6 to ((3 to 2) to intArrayOf(5, 3, 1, 6, 4, 2)),
7 to ((3 to 2) to intArrayOf(6, 4, 2, 5, 3, 1)),
8 to ((3 to 2) to intArrayOf(2, 4, 6, 1, 3, 5)),
)
for ((orientation, expectedPixels) in expected) {
val (dimensions, pixels) = expectedPixels
val actual = orientPixels(2, 3, source, orientation)
assertEquals(dimensions.first, actual.width)
assertEquals(dimensions.second, actual.height)
assertContentEquals(pixels, actual.argb)
}
}
@Test fun parsesOrientationFromBothTiffByteOrders() {
assertEquals(6, jpegExifOrientation(jpegWithOrientation(6, littleEndian = true)))
assertEquals(2, jpegExifOrientation(jpegWithOrientation(2, littleEndian = false)))
assertEquals(1, jpegExifOrientation(byteArrayOf(1, 2, 3)))
}
private fun jpegWithOrientation(orientation: Int, littleEndian: Boolean): ByteArray {
val payload = byteArrayOf(
'E'.code.toByte(), 'x'.code.toByte(), 'i'.code.toByte(), 'f'.code.toByte(), 0, 0,
if (littleEndian) 'I'.code.toByte() else 'M'.code.toByte(),
if (littleEndian) 'I'.code.toByte() else 'M'.code.toByte(),
*short(42, littleEndian), *int(8, littleEndian),
*short(1, littleEndian),
*short(0x0112, littleEndian), *short(3, littleEndian), *int(1, littleEndian),
*short(orientation, littleEndian), 0, 0,
*int(0, littleEndian),
)
val segmentLength = payload.size + 2
return byteArrayOf(0xff.toByte(), 0xd8.toByte(), 0xff.toByte(), 0xe1.toByte()) +
byteArrayOf((segmentLength shr 8).toByte(), segmentLength.toByte()) + payload +
byteArrayOf(0xff.toByte(), 0xd9.toByte())
}
private fun short(value: Int, littleEndian: Boolean) = if (littleEndian) {
byteArrayOf(value.toByte(), (value shr 8).toByte())
} else byteArrayOf((value shr 8).toByte(), value.toByte())
private fun int(value: Int, littleEndian: Boolean) = if (littleEndian) {
byteArrayOf(value.toByte(), (value shr 8).toByte(), (value shr 16).toByte(), (value shr 24).toByte())
} else byteArrayOf((value shr 24).toByte(), (value shr 16).toByte(), (value shr 8).toByte(), value.toByte())
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/colorization/PanelColorizerTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines PanelColorizerTest, FakePlatform, readModel, decode, decodeFullPage, encode, infer, ColorizerFiles, readBytes, promote.
Read the setup, action and assertions in these cases before implementing their production paths:
cropsUseNormalizedBoundsAndRejectEmptyOrNonFiniteRegionsinputHasWhitePaddingAndZeroHintsWithoutStretchingpreservesBlackInkAndWhiteBubblesWhileRenderingPredictedRgbfailedImportKeepsExistingModelAndFailedPromotionRemovesTemporaryFileinvalidCachedGraphNeverReachesInferencemigratesOnlyVerifiedLegacyModelAndRetainsPinnedHashcorruptPromotedModelIsRemovedAndLegacyMigrationCanRetrycolorizePagePreservesOutsidePixelsAndEarlierSelections
package eu.friedcutlet.yokan.services.colorization
import eu.friedcutlet.yokan.services.files.*
import kotlin.test.*
import kotlinx.coroutines.test.runTest
class PanelColorizerTest {
@Test fun cropsUseNormalizedBoundsAndRejectEmptyOrNonFiniteRegions() {
val image = PanelPixels(4, 2, IntArray(8) { it })
val crop = cropPanel(image, PanelCrop(.25f, 0f, .75f, 1f))
assertEquals(2, crop.width)
assertContentEquals(intArrayOf(1, 2, 5, 6), crop.argb)
assertFalse(PanelCrop(left = Float.NaN).valid())
assertFalse(PanelCrop(left = .5f, right = .5f).valid())
assertFailsWith<IllegalArgumentException> { cropPanel(image, PanelCrop(right = 2f)) }
}
@Test fun inputHasWhitePaddingAndZeroHintsWithoutStretching() {
val input = panelModelInput(PanelPixels(2, 1, intArrayOf(0xff000000.toInt(), 0xffffffff.toInt())))
assertEquals(512, input.width)
assertEquals(256, input.height)
assertEquals(0f, input.values[0])
assertEquals(1f, input.values[input.width - 1])
assertTrue(input.values.drop(input.width * input.height).all { it == 0f })
val wide = panelModelInput(PanelPixels(1000, 500, IntArray(500_000) { 0xff808080.toInt() }))
assertEquals(512, wide.width)
assertEquals(256, wide.height)
assertEquals(5 * wide.width * wide.height, wide.values.size)
}
@Test fun preservesBlackInkAndWhiteBubblesWhileRenderingPredictedRgb() {
val input = panelModelInput(PanelPixels(3, 1, intArrayOf(0xff000000.toInt(), 0xff808080.toInt(), 0xffffffff.toInt())))
val plane = input.width * input.height
val rgb = FloatArray(3 * plane) { if (it < plane) 1f else 0f }
val source = PanelPixels(3, 1, intArrayOf(0xff000000.toInt(), 0xff808080.toInt(), 0xffffffff.toInt()))
val output = applyPanelRgb(source, input, rgb)
assertEquals(source.argb[0], output.argb[0])
assertEquals(source.argb[2], output.argb[2])
assertTrue((output.argb[1] ushr 16 and 255) > (output.argb[1] and 255))
rgb[0] = Float.NaN
assertFailsWith<IllegalArgumentException> { applyPanelRgb(source, input, rgb) }
}
@Test fun failedImportKeepsExistingModelAndFailedPromotionRemovesTemporaryFile() = runTest {
val files = ColorizerFiles()
val platform = FakePlatform(files)
val colorizer = PanelColorizer(files, platform) { it.contentEquals(byteArrayOf(1)) }
platform.imported = byteArrayOf(1)
colorizer.importModel("import")
assertTrue(colorizer.installed())
platform.imported = byteArrayOf(2)
assertFailsWith<IllegalArgumentException> { colorizer.importModel("import") }
assertTrue(colorizer.installed())
colorizer.removeModel()
files.failPromotion = true
platform.imported = byteArrayOf(1)
assertFailsWith<IllegalStateException> { colorizer.importModel("import") }
assertFalse(colorizer.installed())
assertTrue(files.files.isEmpty())
}
@Test fun invalidCachedGraphNeverReachesInference() = runTest {
val files = ColorizerFiles()
val platform = FakePlatform(files)
val colorizer = PanelColorizer(files, platform) { it.contentEquals(byteArrayOf(1)) }
colorizer.importModel("import")
files.files.keys.toList().forEach { files.files[it] = byteArrayOf(2) }
assertFailsWith<IllegalStateException> { colorizer.colorize(byteArrayOf(1), PanelCrop()) }
assertEquals(0, platform.runs)
}
@Test fun migratesOnlyVerifiedLegacyModelAndRetainsPinnedHash() = runTest {
assertEquals(61_650_260, MangaColorizerModel.sizeBytes)
assertEquals("39660d0047ea6f1a0ddee6aa89054997f95ea566f4d56ff762f66dbcf1a1a7ef", MangaColorizerModel.sha256Hex)
val files = ColorizerFiles()
val platform = FakePlatform(files)
val colorizer = PanelColorizer(files, platform) { it.contentEquals(byteArrayOf(1)) }
val legacyPath = "/cache/colorizer/${MangaColorizerModel.fileName}"
val currentPath = "/downloads/colorizer/${MangaColorizerModel.fileName}"
files.files[legacyPath] = byteArrayOf(1)
assertTrue(colorizer.installed())
colorizer.colorize(byteArrayOf(1), PanelCrop())
assertContentEquals(byteArrayOf(1), files.files[currentPath])
assertFalse(files.exists(legacyPath))
colorizer.removeModel()
files.files[legacyPath] = byteArrayOf(1)
files.failPromotion = true
assertFailsWith<IllegalStateException> { colorizer.colorize(byteArrayOf(1), PanelCrop()) }
assertContentEquals(byteArrayOf(1), files.files[legacyPath])
assertFalse(files.exists(currentPath))
files.failPromotion = false
files.files[legacyPath] = byteArrayOf(2)
assertFailsWith<IllegalStateException> { colorizer.colorize(byteArrayOf(1), PanelCrop()) }
assertContentEquals(byteArrayOf(2), files.files[legacyPath])
assertFalse(files.exists(currentPath))
assertEquals(1, platform.runs)
}
@Test fun corruptPromotedModelIsRemovedAndLegacyMigrationCanRetry() = runTest {
val files = ColorizerFiles()
val platform = FakePlatform(files)
val colorizer = PanelColorizer(files, platform) { it.contentEquals(byteArrayOf(1)) }
val legacyPath = "/cache/colorizer/${MangaColorizerModel.fileName}"
val currentPath = "/downloads/colorizer/${MangaColorizerModel.fileName}"
files.files[legacyPath] = byteArrayOf(1)
files.corruptNextPromotion = true
assertFailsWith<IllegalStateException> { colorizer.colorize(byteArrayOf(1), PanelCrop()) }
assertFalse(files.exists(currentPath))
assertContentEquals(byteArrayOf(1), files.files[legacyPath])
colorizer.colorize(byteArrayOf(1), PanelCrop())
assertContentEquals(byteArrayOf(1), files.files[currentPath])
assertFalse(files.exists(legacyPath))
assertEquals(1, platform.runs)
}
@Test fun colorizePagePreservesOutsidePixelsAndEarlierSelections() = runTest {
val files = ColorizerFiles()
val platform = FakePlatform(files)
val colorizer = PanelColorizer(files, platform) { it.contentEquals(byteArrayOf(1)) }
colorizer.importModel("import")
val original = IntArray(16) { 0xff808080.toInt() }
original[2] = 0x40804020
original[3] = 0x00804020
val initial = platform.encode(PanelPixels(4, 4, original))
val first = colorizer.colorizePage(initial, PanelCrop(0f, 0f, .5f, .5f))
val afterFirst = platform.decodeFullPage(first)
assertEquals(original[2], afterFirst.argb[2])
assertEquals(original[3], afterFirst.argb[3])
assertNotEquals(original[0], afterFirst.argb[0])
val second = colorizer.colorizePage(first, PanelCrop(.5f, .5f, 1f, 1f))
val afterSecond = platform.decodeFullPage(second)
assertEquals(afterFirst.argb[0], afterSecond.argb[0])
assertEquals(afterFirst.argb[2], afterSecond.argb[2])
assertEquals(afterFirst.argb[3], afterSecond.argb[3])
assertNotEquals(original[15], afterSecond.argb[15])
assertEquals(4, afterSecond.width)
assertEquals(4, afterSecond.height)
}
private class FakePlatform(val files: ColorizerFiles) : ColorizerPlatform {
var imported = byteArrayOf(1)
var runs = 0
override fun readModel(path: String) = if (path == "import") imported else files.readBytes(path)
override fun decode(bytes: ByteArray) = PanelPixels(1, 1, intArrayOf(-1))
override fun decodeFullPage(bytes: ByteArray): PanelPixels {
if (bytes.firstOrNull() != 0x50.toByte()) return PanelPixels(4, 4, IntArray(16) { 0xff808080.toInt() })
val width = bytes[1].toInt() and 255
val height = bytes[2].toInt() and 255
return PanelPixels(width, height, IntArray(width * height) { index ->
val offset = 3 + index * 4
(bytes[offset].toInt() shl 24) or ((bytes[offset + 1].toInt() and 255) shl 16) or
((bytes[offset + 2].toInt() and 255) shl 8) or (bytes[offset + 3].toInt() and 255)
})
}
override fun encode(image: PanelPixels) = ByteArray(3 + image.argb.size * 4).also { bytes ->
bytes[0] = 0x50
bytes[1] = image.width.toByte()
bytes[2] = image.height.toByte()
image.argb.forEachIndexed { index, pixel ->
val offset = 3 + index * 4
bytes[offset] = (pixel ushr 24).toByte()
bytes[offset + 1] = (pixel ushr 16).toByte()
bytes[offset + 2] = (pixel ushr 8).toByte()
bytes[offset + 3] = pixel.toByte()
}
}
override fun infer(modelPath: String, input: PanelModelInput, verifiedModel: () -> ByteArray): FloatArray {
verifiedModel()
runs++
val plane = input.width * input.height
return FloatArray(3 * plane).also { it.fill(1f, 2 * plane, 3 * plane) }
}
}
private class ColorizerFiles : MemoryFiles() {
var failPromotion = false
var corruptNextPromotion = false
override fun readBytes(path: String) = checkNotNull(files[path])
override fun promote(sourcePath: String, targetPath: String): Boolean {
if (failPromotion || !super.promote(sourcePath, targetPath)) return false
if (corruptNextPromotion) {
corruptNextPromotion = false
files[targetPath] = byteArrayOf(2)
}
return true
}
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/AutomaticReaderLayoutTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines AutomaticReaderLayoutTest.
Read the setup, action and assertions in these cases before implementing their production paths:
tallPatternsAreConservativeAndDoNotInferDirectionfallbackMetadataAndViewportAreIndependentupgradeManualOverridesAutomaticAndResetRoundTripRemainCompatibleautomaticPairingKeepsSpreadsAndUnknownPagesSingleWithoutMovingTheirIndexes
Cross-chapter imports used by this file: Chapter. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.Chapter
import kotlinx.serialization.json.Json
import kotlin.test.*
class AutomaticReaderLayoutTest {
@Test fun tallPatternsAreConservativeAndDoNotInferDirection() {
val tall = ReaderPageShape(800, 4000)
val normal = ReaderPageShape(800, 1200)
assertTrue(automaticWebtoonSample(listOf(tall, tall, tall), 30))
assertFalse(automaticWebtoonSample(listOf(tall, normal, normal), 30))
assertFalse(automaticWebtoonSample(listOf(tall), 30))
assertTrue(automaticWebtoonSample(listOf(tall), 1))
assertFalse(automaticWebtoonSample(listOf(ReaderPageShape(0, 1)), 1))
val result = resolveAutomaticReaderLayout(DbReaderMode.Rtl, true, ReaderViewport(1280, 800))
assertEquals(DbReaderMode.Webtoon, result.mode)
assertEquals(ReaderDirection.Rtl, result.direction)
assertFalse(result.pairPages)
}
@Test fun fallbackMetadataAndViewportAreIndependent() {
assertEquals(DbReaderMode.Rtl, resolveAutomaticReaderLayout(DbReaderMode.Rtl, false, ReaderViewport()).mode)
assertEquals(DbReaderMode.Ltr, resolveAutomaticReaderLayout(DbReaderMode.Rtl, false, ReaderViewport(), ReaderDirection.Ltr).mode)
assertEquals(DbReaderMode.VerticalContinuous, resolveAutomaticReaderLayout(DbReaderMode.VerticalContinuous, false, ReaderViewport(1280, 800)).mode)
assertTrue(resolveAutomaticReaderLayout(DbReaderMode.Rtl, false, ReaderViewport(1280, 800)).pairPages)
assertFalse(resolveAutomaticReaderLayout(DbReaderMode.Rtl, false, ReaderViewport(800, 1280)).pairPages)
assertFalse(resolveAutomaticReaderLayout(DbReaderMode.Rtl, false, ReaderViewport(1280, 800), settled = false).pairPages)
assertFalse(resolveAutomaticReaderLayout(DbReaderMode.Rtl, false, ReaderViewport(1280, 800), pairingOverride = false).pairPages)
assertTrue(automaticLayoutHasWebtoonMetadata(listOf("Long strip")))
assertFalse(automaticLayoutHasWebtoonMetadata(listOf("Manhwa", "Manga")))
}
@Test fun upgradeManualOverridesAutomaticAndResetRoundTripRemainCompatible() {
val legacy = Json.decodeFromString<DbSettings>("""{"defaultReaderMode":"Rtl","personalReaderModeList":[{"mangaId":5,"readerMode":"Ltr"}]}""")
assertFalse(legacy.automaticLayout(5))
val global = legacy.copy(automaticReaderLayout = true)
assertFalse(global.automaticLayout(5))
assertTrue(global.automaticLayout(6))
val title = global.withPersonalAutomaticLayout(5).withPersonalDoublePage(5, false)
assertTrue(title.automaticLayout(5))
assertEquals(DbReaderMode.Ltr, title.personalReaderMode(5))
assertFalse(title.personalDoublePage(5))
val restored = Json.decodeFromString<DbSettings>(Json.encodeToString(title))
assertEquals(title, restored)
assertFalse(restored.withPersonalReaderMode(5, DbReaderMode.Rtl).automaticLayout(5))
assertTrue(restored.withDefaultReaderLayout(5).automaticLayout(5))
assertTrue(restored.withAutomaticPagePairing(5).personalPageModeList.orEmpty().none { it.mangaId == 5L })
}
@Test fun automaticPairingKeepsSpreadsAndUnknownPagesSingleWithoutMovingTheirIndexes() {
val chapter = Chapter(1, 1, "Chapter 1", "/1")
val items = readerPageItems(chapter, (0..4).map { DbPageUrl("/$it") })
val shapes = items.filterIsInstance<ReaderStreamItem.Page>().take(4).associate {
it.identity() to if (it.chapterPageIndex == 2) ReaderPageShape(1800, 1000) else ReaderPageShape(800, 1200)
}
val units = readerDisplayUnits(items, DbReaderMode.Rtl, true, shapes, true)
assertEquals(listOf(0..1, 2..2, 3..3, 4..4), units.map { it.streamIndexes })
assertEquals(1, displayUnitIndexForStreamIndex(units, 2))
assertEquals(listOf(0, 1, 2, 3, 4), units.flatMap { it.streamIndexes.toList() })
assertEquals(listOf(0..1, 2..3, 4..4), readerDisplayUnits(items, DbReaderMode.Rtl, true).map { it.streamIndexes })
// Resuming page 2 and pairing it with page 1 must not persist page 1 on a renderer echo.
assertNull(readerRendererPageChange(units, 0, 1))
assertEquals(2, readerRendererPageChange(units, 1, 1))
assertNull(readerRendererPageChange(units, -1, 1))
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ChapterReadingSequenceTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ChapterReadingSequenceTest, filteredSequenceSortsAscendingAndCollapsesDuplicateScanlations, filteredOutOrCollapsedCurrentChapterBridgesIntoSelectedSequenceWithoutReplayingDuplicates, playerAndReaderSelectTheSameReleasesAndBridgeOnlyTheOpenedAlternate, chapter.
Read the setup, action and assertions in these cases before implementing their production paths:
filteredSequenceSortsAscendingAndCollapsesDuplicateScanlationsfilteredOutOrCollapsedCurrentChapterBridgesIntoSelectedSequenceWithoutReplayingDuplicatesplayerAndReaderSelectTheSameReleasesAndBridgeOnlyTheOpenedAlternate
Cross-chapter imports used by this file: Chapter, Manga, ItemType, Status, DbSettings, DbChapterReleasePreference. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Status
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbChapterReleasePreference
import eu.friedcutlet.yokan.database.DbFilterScanlator
import eu.friedcutlet.yokan.database.DbSortChapter
import eu.friedcutlet.yokan.ui.screens.player.playerEpisodeSequence
import kotlin.test.Test
import kotlin.test.assertEquals
import eu.friedcutlet.yokan.services.library.readingChapterSequence
import eu.friedcutlet.yokan.services.library.resolveReadingChapterSequence
class ChapterReadingSequenceTest {
@Test
fun filteredSequenceSortsAscendingAndCollapsesDuplicateScanlations() {
val all = listOf(
chapter(3, "Chapter 3"),
chapter(1, "Chapter 1 - Group A"),
chapter(2, "Chapter 2"),
chapter(4, "Ch. 1 - Group B"),
)
val sequence = resolveReadingChapterSequence(
mangaTitle = "Fixture",
currentChapterId = 2,
filteredChapters = all,
allChapters = all,
)
assertEquals(listOf(1L, 2L, 3L), sequence.map(Chapter::id))
}
@Test
fun filteredOutOrCollapsedCurrentChapterBridgesIntoSelectedSequenceWithoutReplayingDuplicates() {
val all = listOf(
chapter(3, "Chapter 3"),
chapter(1, "Chapter 1 - Group A"),
chapter(2, "Chapter 2"),
chapter(4, "Ch. 1 - Group B"),
)
val filteredOut = resolveReadingChapterSequence(
mangaTitle = "Fixture",
currentChapterId = 3,
filteredChapters = all.filterNot { it.id == 3L },
allChapters = all,
)
val collapsedDuplicate = resolveReadingChapterSequence(
mangaTitle = "Fixture",
currentChapterId = 4,
filteredChapters = all,
allChapters = all,
)
assertEquals(listOf(1L, 2L, 3L), filteredOut.map(Chapter::id))
assertEquals(listOf(4L, 2L, 3L), collapsedDuplicate.map(Chapter::id))
}
@Test
fun playerAndReaderSelectTheSameReleasesAndBridgeOnlyTheOpenedAlternate() {
val manga = Manga(
id = 100, name = "Fixture", link = "/fixture", description = "",
status = Status.Ongoing, itemType = ItemType.Anime, source = "Fixture", lang = "en",
dateAddedMillis = 0, lastUpdateMillis = 0,
)
val all = listOf(
chapter(1, "Episode 1").copy(scanlator = "A"),
chapter(4, "Episode 1").copy(scanlator = "B"),
chapter(2, "Episode 2").copy(scanlator = "B"),
chapter(5, "Episode 2").copy(scanlator = "A"),
chapter(3, "Episode 3").copy(scanlator = "Hidden"),
)
val settings = DbSettings(
chapterReleasePreferences = listOf(DbChapterReleasePreference(scanlatorPriority = listOf("b"), skipDuplicateReleases = true)),
filterScanlatorList = listOf(DbFilterScanlator(mangaId = 100, scanlators = listOf("hidden"))),
)
assertEquals(listOf(1L, 2L), readingChapterSequence(manga, 1, all, settings, emptySet()).map(Chapter::id))
assertEquals(listOf(2L, 1L), playerEpisodeSequence(manga, 1, all, settings, emptySet()).map(Chapter::id))
val changed = settings.copy(
chapterReleasePreferences = listOf(DbChapterReleasePreference(scanlatorPriority = listOf("a"), skipDuplicateReleases = true)),
sortChapterList = listOf(DbSortChapter(mangaId = 100, reverse = true)),
)
assertEquals(listOf(1L, 5L), playerEpisodeSequence(manga, 1, all, changed, emptySet()).map(Chapter::id))
}
private fun chapter(id: Long, name: String) = Chapter(
id = id,
mangaId = 100,
name = name,
url = "/chapter/$id",
)
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderColorizedPageTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ReaderColorizedPageTest, overrideSelectsOnlyTheSameSourcePageAcrossReaderLayouts, cacheRevisionAndSourceIdentityChangeTheOwnedFileKey, staleResultsAreRejected, restoringAColorizedPageShowsTheSourceImageAndDeletesItsDerivative, originalComparisonAndRestoreUseTheSourceImageAndMimeType, List.
Read the setup, action and assertions in these cases before implementing their production paths:
overrideSelectsOnlyTheSameSourcePageAcrossReaderLayoutscacheRevisionAndSourceIdentityChangeTheOwnedFileKeystaleResultsAreRejectedrestoringAColorizedPageShowsTheSourceImageAndDeletesItsDerivativeoriginalComparisonAndRestoreUseTheSourceImageAndMimeType
Cross-chapter imports used by this file: DefaultYokanRepository, DbPageUrl, DbReaderMode, InMemoryYokanDatabase, seedDatabaseSnapshot, Chapter. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.testManga
import eu.friedcutlet.yokan.services.files.MemoryFiles
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
class ReaderColorizedPageTest {
private val chapter = Chapter(50, 5, "Chapter", "/chapter")
private val pages = List(4) { ReaderStreamItem.Page(chapter, DbPageUrl("https://example.test/$it.jpg"), it) }
private val identity = pages[1].identity()
private val override = ColorizedReaderPage(identity, 3, "/cache/page-3.png")
private val overrides = mapOf(identity to override)
@Test
fun overrideSelectsOnlyTheSameSourcePageAcrossReaderLayouts() {
for (mode in listOf(
DbReaderMode.Ltr,
DbReaderMode.Rtl,
DbReaderMode.Vertical,
DbReaderMode.VerticalContinuous,
DbReaderMode.HorizontalContinuousRtl,
)) {
val units = readerDisplayUnits(pages, mode, doublePage = true)
assertTrue(units.flattenPages().any { colorizedOverrideFor(it.page, it.chapter.id, it.chapterPageIndex, overrides) == override })
pages.filterNot { it.identity() == identity }.forEach { page ->
assertNull(colorizedOverrideFor(page.page, page.chapter.id, page.chapterPageIndex, overrides))
}
}
}
@Test
fun cacheRevisionAndSourceIdentityChangeTheOwnedFileKey() {
val first = readerColorizedCachePath("/cache/reader-session", identity, 1)
val second = readerColorizedCachePath("/cache/reader-session", identity, 2)
val changedSource = pages[1].copy(page = pages[1].page.copy(url = "https://example.test/replaced.jpg")).identity()
assertNotEquals(first, second)
assertNotEquals(first, readerColorizedCachePath("/cache/reader-session", changedSource, 1))
}
@Test
fun staleResultsAreRejected() {
assertTrue(canApplyColorizationResult(8, 8, identity, pages))
assertFalse(canApplyColorizationResult(7, 8, identity, pages))
assertFalse(canApplyColorizationResult(8, 8, identity, pages.filterNot { it.identity() == identity }))
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun restoringAColorizedPageShowsTheSourceImageAndDeletesItsDerivative() = runTest {
val jpeg = byteArrayOf(0xFF.toByte(), 0xD8.toByte(), 0xFF.toByte())
val png = byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47)
val files = MemoryFiles().apply { writeBytes(override.filePath, png) }
val state = MutableStateFlow(
ReaderState(
manga = testManga(5),
chapter = chapter,
mode = DbReaderMode.Ltr,
streamItems = pages,
imageActionsTarget = ResolvedReaderImage(pages[1], pages[1].page, png, jpeg, "page-colorized.png", "page.jpg", "image/png"),
colorizedPages = overrides,
colorizer = ReaderColorizerState(open = true, preview = png, hasAppliedColorization = true),
),
)
val work = ReaderImageWork(
scope = backgroundScope,
workDispatcher = UnconfinedTestDispatcher(testScheduler),
localFiles = files,
imageHttp = { error("restoring needs no network") },
repository = DefaultYokanRepository(InMemoryYokanDatabase(seedDatabaseSnapshot())),
panelColorizer = lazy { error("restoring needs no colorizer") },
saveImagesInTitleFolder = { false },
state = { state.value },
update = { transform -> state.update(transform) },
emit = {},
)
work.restoreOriginal()
val restored = state.value
assertContentEquals(jpeg, restored.imageActionsTarget?.bytes)
assertEquals("page.jpg", restored.imageActionsTarget?.fileName)
assertEquals("image/jpeg", restored.imageActionsTarget?.mimeType)
assertTrue(restored.colorizedPages.isEmpty())
assertTrue(restored.colorizer.showOriginal)
assertFalse(restored.colorizer.hasAppliedColorization)
assertFalse(override.filePath in files.paths)
}
@Test
fun originalComparisonAndRestoreUseTheSourceImageAndMimeType() {
val jpeg = byteArrayOf(0xFF.toByte(), 0xD8.toByte(), 0xFF.toByte())
val png = byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47)
val target = ResolvedReaderImage(pages[1], pages[1].page, png, jpeg, "colored.png", "original.jpg", "image/png")
assertContentEquals(jpeg, panelColorizerPreviewBytes(target, png, showOriginal = true))
assertEquals("image/jpeg", restoredReaderImageMimeType(target))
}
private fun List<ReaderDisplayUnit>.flattenPages(): List<ReaderStreamItem.Page> =
flatMap { unit -> unit.items.filterIsInstance<ReaderStreamItem.Page>() }
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderGesturesTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ReaderGesturesTest, lShapedCornersUseQuarterHeightRows, kindleReservesOnlyTopQuarterForChrome, edgeLayoutUsesOneSeventhSideStrips, rtlFlipsSidesButNotDefaultTopAndBottom, defaultTopAndBottomStopNavigatingWhileCurrentImageFailed, disabledPageZonesAlwaysToggleChrome, action.
Read the setup, action and assertions in these cases before implementing their production paths:
lShapedCornersUseQuarterHeightRowskindleReservesOnlyTopQuarterForChromeedgeLayoutUsesOneSeventhSideStripsrtlFlipsSidesButNotDefaultTopAndBottomdefaultTopAndBottomStopNavigatingWhileCurrentImageFaileddisabledPageZonesAlwaysToggleChrome
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.unit.IntSize
import kotlin.test.Test
import kotlin.test.assertEquals
class ReaderGesturesTest {
private val viewport = IntSize(width = 700, height = 400)
@Test
fun lShapedCornersUseQuarterHeightRows() {
assertEquals(TapZoneAction.Prev, action(TapNavLayout.LShaped, 100f, 50f))
assertEquals(TapZoneAction.ToggleChrome, action(TapNavLayout.LShaped, 100f, 150f))
assertEquals(TapZoneAction.Next, action(TapNavLayout.LShaped, 650f, 350f))
}
@Test
fun kindleReservesOnlyTopQuarterForChrome() {
assertEquals(TapZoneAction.ToggleChrome, action(TapNavLayout.Kindle, 100f, 50f))
assertEquals(TapZoneAction.Prev, action(TapNavLayout.Kindle, 100f, 150f))
assertEquals(TapZoneAction.Next, action(TapNavLayout.Kindle, 600f, 150f))
}
@Test
fun edgeLayoutUsesOneSeventhSideStrips() {
assertEquals(TapZoneAction.Prev, action(TapNavLayout.Edge, 80f, 200f))
assertEquals(TapZoneAction.ToggleChrome, action(TapNavLayout.Edge, 110f, 200f))
assertEquals(TapZoneAction.Next, action(TapNavLayout.Edge, 620f, 200f))
}
@Test
fun rtlFlipsSidesButNotDefaultTopAndBottom() {
assertEquals(TapZoneAction.Prev, action(TapNavLayout.Default, 350f, 20f, rtl = true))
assertEquals(TapZoneAction.Next, action(TapNavLayout.Default, 350f, 380f, rtl = true))
assertEquals(TapZoneAction.Next, action(TapNavLayout.Default, 50f, 200f, rtl = true))
assertEquals(TapZoneAction.Prev, action(TapNavLayout.Default, 650f, 200f, rtl = true))
assertEquals(TapZoneAction.Next, action(TapNavLayout.RightLeft, 50f, 200f, rtl = true))
}
@Test
fun defaultTopAndBottomStopNavigatingWhileCurrentImageFailed() {
assertEquals(
TapZoneAction.ToggleChrome,
computeTapAction(
layout = TapNavLayout.Default,
offset = Offset(350f, 20f),
size = viewport,
usePageTapZones = true,
hasImageError = true,
),
)
assertEquals(
TapZoneAction.Prev,
computeTapAction(
layout = TapNavLayout.Default,
offset = Offset(50f, 200f),
size = viewport,
usePageTapZones = true,
hasImageError = true,
),
)
}
@Test
fun disabledPageZonesAlwaysToggleChrome() {
assertEquals(
TapZoneAction.ToggleChrome,
computeTapAction(
layout = TapNavLayout.RightLeft,
offset = Offset(10f, 10f),
size = viewport,
usePageTapZones = false,
isRightToLeft = true,
),
)
}
private fun action(layout: TapNavLayout, x: Float, y: Float, rtl: Boolean = false): TapZoneAction =
computeTapAction(
layout = layout,
offset = Offset(x, y),
size = viewport,
usePageTapZones = true,
isRightToLeft = rtl,
)
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderHoldScrollTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ReaderHoldScrollTest.
Read the setup, action and assertions in these cases before implementing their production paths:
deadZoneBoundsAndZeroNeverReverseScrollingspeedGestureFollowsVerticalAndHorizontalReadingDirectionsoptInPersistsWithoutExtendingSerializedReaderEnums
Cross-chapter imports used by this file: DbReaderMode, DbSettings. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.ui.geometry.Offset
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.database.DbSettings
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class ReaderHoldScrollTest {
@Test fun deadZoneBoundsAndZeroNeverReverseScrolling() {
assertEquals(10f, readerHoldSpeed(10f, 0f))
assertEquals(10f, readerHoldSpeed(10f, 12f))
assertEquals(10f, readerHoldSpeed(10f, -12f))
assertEquals(15f, readerHoldSpeed(10f, 42f))
assertEquals(5f, readerHoldSpeed(10f, -42f))
assertEquals(0f, readerHoldSpeed(10f, -1000f))
assertEquals(60f, readerHoldSpeed(10f, 1000f))
assertEquals(10f, readerHoldSpeed(10f, Float.NaN))
assertEquals(ReaderHoldPhase.Idle, ReaderHoldScroll().phase)
assertEquals(ReaderHoldPhase.Holding, ReaderHoldScroll(1, 10f, 0f).phase)
assertEquals(ReaderHoldPhase.Scrolling, ReaderHoldScroll(1, 10f, 15f).phase)
}
@Test fun speedGestureFollowsVerticalAndHorizontalReadingDirections() {
val origin = Offset(100f, 100f)
assertEquals(40f, readerHoldDistance(DbReaderMode.Webtoon, origin, Offset(300f, 60f)))
assertEquals(-40f, readerHoldDistance(DbReaderMode.VerticalContinuous, origin, Offset(100f, 140f)))
assertEquals(40f, readerHoldDistance(DbReaderMode.HorizontalContinuous, origin, Offset(60f, 300f)))
assertEquals(40f, readerHoldDistance(DbReaderMode.HorizontalContinuousRtl, origin, Offset(140f, 300f)))
assertEquals(-40f, readerHoldDistance(DbReaderMode.HorizontalContinuousRtl, origin, Offset(60f, 100f)))
}
@Test fun optInPersistsWithoutExtendingSerializedReaderEnums() {
assertFalse(Json.decodeFromString<DbSettings>("""{"defaultReaderMode":"Webtoon"}""").readerHoldToScroll)
val settings = DbSettings(readerHoldToScroll = true, defaultReaderMode = DbReaderMode.HorizontalContinuousRtl)
assertEquals(settings, Json.decodeFromString<DbSettings>(Json.encodeToString(settings)))
assertTrue(settings.readerHoldToScroll)
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderPageDownloadProgressTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ReaderPageDownloadProgressTest, unchangedPercentKeepsTheSameSnapshot, concurrentDownloadsDoNotLoseEachOthersProgress, pageSubscriberDoesNotReceiveOtherPagesUpdates, tearDown, reportsRatioAndClearsOnCompletion, ignoresUnknownTotalsAndSupportsExplicitClear.
Read the setup, action and assertions in these cases before implementing their production paths:
unchangedPercentKeepsTheSameSnapshotconcurrentDownloadsDoNotLoseEachOthersProgresspageSubscriberDoesNotReceiveOtherPagesUpdatesreportsRatioAndClearsOnCompletionignoresUnknownTotalsAndSupportsExplicitClear
package eu.friedcutlet.yokan.ui.screens.reader
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.flow.toList
class ReaderPageDownloadProgressTest {
@Test
fun unchangedPercentKeepsTheSameSnapshot() {
ReaderPageDownloadProgress.report("page", 501, 1_000)
val snapshot = ReaderPageDownloadProgress.progress.value
ReaderPageDownloadProgress.report("page", 509, 1_000)
assertSame(snapshot, ReaderPageDownloadProgress.progress.value)
}
@Test
fun concurrentDownloadsDoNotLoseEachOthersProgress() = runTest {
(0 until 100).map { index ->
launch(Dispatchers.Default) { ReaderPageDownloadProgress.report("page-$index", 50, 100) }
}.joinAll()
repeat(100) { assertEquals(0.5f, ReaderPageDownloadProgress.progress.value["page-$it"]) }
}
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
@Test
fun pageSubscriberDoesNotReceiveOtherPagesUpdates() = runTest {
val values = mutableListOf<Float?>()
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
ReaderPageDownloadProgress.forUrl("watched").toList(values)
}
ReaderPageDownloadProgress.report("other", 10, 100)
ReaderPageDownloadProgress.report("watched", 25, 100)
ReaderPageDownloadProgress.report("other", 50, 100)
ReaderPageDownloadProgress.clear("watched")
assertEquals(listOf(null, 0.25f, null), values)
}
@AfterTest
fun tearDown() {
ReaderPageDownloadProgress.progress.value.keys.forEach(ReaderPageDownloadProgress::clear)
}
@Test
fun reportsRatioAndClearsOnCompletion() {
ReaderPageDownloadProgress.report("https://example/page1.jpg", receivedBytes = 250, totalBytes = 1_000)
assertEquals(0.25f, ReaderPageDownloadProgress.progress.value["https://example/page1.jpg"])
ReaderPageDownloadProgress.report("https://example/page1.jpg", receivedBytes = 1_000, totalBytes = 1_000)
assertNull(ReaderPageDownloadProgress.progress.value["https://example/page1.jpg"])
}
@Test
fun ignoresUnknownTotalsAndSupportsExplicitClear() {
ReaderPageDownloadProgress.report("https://example/page2.jpg", receivedBytes = 10, totalBytes = null)
ReaderPageDownloadProgress.report("https://example/page2.jpg", receivedBytes = 10, totalBytes = 0)
assertNull(ReaderPageDownloadProgress.progress.value["https://example/page2.jpg"])
ReaderPageDownloadProgress.report("https://example/page3.jpg", receivedBytes = 900, totalBytes = 1_000)
ReaderPageDownloadProgress.clear("https://example/page3.jpg")
assertNull(ReaderPageDownloadProgress.progress.value["https://example/page3.jpg"])
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderPageHeadersTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ReaderPageHeadersTest, pageCacheRoundTripsPageHeadersAndReadsLegacyUserAgentEntries, requestCacheFingerprintIsOrderIndependentAndHeaderSensitive, chapterPageCacheKeyIsChapterIsolatedToPreventCollision.
Read the setup, action and assertions in these cases before implementing their production paths:
pageCacheRoundTripsPageHeadersAndReadsLegacyUserAgentEntriesrequestCacheFingerprintIsOrderIndependentAndHeaderSensitivechapterPageCacheKeyIsChapterIsolatedToPreventCollision
Cross-chapter imports used by this file: DefaultYokanRepository, DbChapterPageUrls, DbPageUrl, InMemoryYokanDatabase, seedDatabaseSnapshot. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.DbChapterPageUrls
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
class ReaderPageHeadersTest {
@Test
fun pageCacheRoundTripsPageHeadersAndReadsLegacyUserAgentEntries() {
val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
val repository = DefaultYokanRepository(database)
val headers = mapOf(
"Referer" to "https://example.com/chapter",
"X-Reader" to "Yokan",
)
repository.cachePageUrls(
chapterId = 42L,
chapterUrl = "/chapter/42",
pageUrls = listOf(DbPageUrl("https://example.com/page.jpg", headers = headers)),
)
assertEquals(headers, repository.pageUrls(42L).single().headers)
val legacyDatabase = InMemoryYokanDatabase(
seedDatabaseSnapshot().copy(
pageCache = listOf(
DbChapterPageUrls(
chapterId = 7L,
urls = listOf("https://example.com/legacy.jpg"),
headers = listOf("Legacy Agent"),
),
),
),
)
assertEquals(
mapOf("User-Agent" to "Legacy Agent"),
DefaultYokanRepository(legacyDatabase).pageUrls(7L).single().headers,
)
}
@Test
fun requestCacheFingerprintIsOrderIndependentAndHeaderSensitive() {
val first = readerPageHeaderFingerprint(mapOf("Referer" to "a", "Authorization" to "b"))
val reordered = readerPageHeaderFingerprint(mapOf("Authorization" to "b", "Referer" to "a"))
val changed = readerPageHeaderFingerprint(mapOf("Referer" to "a", "Authorization" to "c"))
assertEquals(first, reordered)
assertNotEquals(first, changed)
}
@Test
fun chapterPageCacheKeyIsChapterIsolatedToPreventCollision() {
val url = "https://example.com/001.jpg"
val keyCh1 = chapterPageCacheKey(chapterId = 101L, url = url)
val keyCh2 = chapterPageCacheKey(chapterId = 202L, url = url)
val keyNoCh = chapterPageCacheKey(chapterId = null, url = url)
assertEquals("ch_101_https://example.com/001.jpg", keyCh1)
assertEquals("ch_202_https://example.com/001.jpg", keyCh2)
assertEquals("https://example.com/001.jpg", keyNoCh)
assertNotEquals(keyCh1, keyCh2)
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderProcessingTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ReaderProcessingTest, wideSplitKeepsTheReaderOnTheSameSourcePageAndCollapsesBack, splitHalvesStayWhileShapesAreForgottenAndUnchangedStreamsAreReused, splitHalvesFollowDirectionAndInversionWhileRotationYieldsToSplitting, splitHalvesNeverPairIntoADoublePageSpread, hiddenTransitionsChainChaptersDirectlyButTheSeriesEndKeepsItsCard, skipReadDropsReadChaptersButNeverTheOpenOne, untouchedModeGroupsFollowLegacyGlobalsAndEditingOneLeavesTheOther, volumeKeysTurnPagesOnlyWhenEnabledAndSwapWhenInverted, titleFoldersAreSingleSegmentsAndSpreadsShareTheTallerHeight.
Read the setup, action and assertions in these cases before implementing their production paths:
wideSplitKeepsTheReaderOnTheSameSourcePageAndCollapsesBacksplitHalvesStayWhileShapesAreForgottenAndUnchangedStreamsAreReusedsplitHalvesFollowDirectionAndInversionWhileRotationYieldsToSplittingsplitHalvesNeverPairIntoADoublePageSpreadhiddenTransitionsChainChaptersDirectlyButTheSeriesEndKeepsItsCardskipReadDropsReadChaptersButNeverTheOpenOneuntouchedModeGroupsFollowLegacyGlobalsAndEditingOneLeavesTheOthervolumeKeysTurnPagesOnlyWhenEnabledAndSwapWhenInvertedtitleFoldersAreSingleSegmentsAndSpreadsShareTheTallerHeight
Cross-chapter imports used by this file: DbPageUrl, DbReaderMode, DbReaderModePreferences, DbSettings, Chapter, resolveReadingChapterSequence. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.ui.input.key.Key
import eu.friedcutlet.yokan.database.DatabaseJson
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.database.DbReaderModePreferences
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.readerModePreferences
import eu.friedcutlet.yokan.database.withReaderModePreferences
import eu.friedcutlet.yokan.domain.Chapter
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
import eu.friedcutlet.yokan.services.library.resolveReadingChapterSequence
class ReaderProcessingTest {
private val chapter = Chapter(1, 1, "Chapter 1", "/1")
private val next = Chapter(2, 1, "Chapter 2", "/2")
private val pages = readerPageItems(chapter, List(4) { DbPageUrl("https://example.test/$it.jpg") })
private val landscape = ReaderPageShape(2000, 1400)
private val portrait = ReaderPageShape(1000, 1400)
@Test
fun wideSplitKeepsTheReaderOnTheSameSourcePageAndCollapsesBack() {
val stream = pages + ReaderStreamItem.Transition(chapter, null, "Title")
val shapes = mapOf(pages[1].identity() to landscape, pages[2].identity() to portrait)
// Current on page 3: the split page before it shifts it by one.
val (split, index) = splitWidePagesInStream(stream, 2, shapes, enabled = true)
assertEquals(listOf(null, ReaderPageHalf.First, ReaderPageHalf.Second, null, null, null), split.map { (it as? ReaderStreamItem.Page)?.split })
assertEquals(listOf(0, 1, 1, 2, 3), split.filterIsInstance<ReaderStreamItem.Page>().map { it.chapterPageIndex })
assertEquals(3, index)
assertTrue(split.last() is ReaderStreamItem.Transition)
assertEquals(pages.map { it.page }, readerPagesForChapter(split, chapter.id))
// The second half collapses onto its whole page; nothing else moves.
val (collapsed, collapsedIndex) = splitWidePagesInStream(split, 2, shapes, enabled = false)
assertEquals(stream, collapsed)
assertEquals(1, collapsedIndex)
}
@Test
fun splitHalvesStayWhileShapesAreForgottenAndUnchangedStreamsAreReused() {
val (split, _) = splitWidePagesInStream(pages, 0, mapOf(pages[0].identity() to landscape), enabled = true)
val (again, index) = splitWidePagesInStream(split, 1, emptyMap(), enabled = true)
assertSame(split, again)
assertEquals(1, index)
assertSame(pages, splitWidePagesInStream(pages, 0, mapOf(pages[0].identity() to landscape), enabled = false).first)
}
@Test
fun splitHalvesFollowDirectionAndInversionWhileRotationYieldsToSplitting() {
val first = pages[0].copy(split = ReaderPageHalf.First)
val second = pages[0].copy(split = ReaderPageHalf.Second)
val split = DbReaderModePreferences(splitWidePages = true, rotateWidePages = true)
assertEquals(true, readerPageProcessing(first, rightToLeft = false, split).leftHalf)
assertEquals(false, readerPageProcessing(second, rightToLeft = false, split).leftHalf)
assertEquals(false, readerPageProcessing(first, rightToLeft = true, split).leftHalf)
assertEquals(true, readerPageProcessing(first, rightToLeft = true, split.copy(invertSplit = true)).leftHalf)
assertEquals(0, readerPageProcessing(first, rightToLeft = false, split).rotation)
val rotate = DbReaderModePreferences(rotateWidePages = true, cropBorders = true)
assertEquals(ReaderPageProcessing(cropBorders = true, rotation = 90), readerPageProcessing(pages[0], false, rotate))
assertEquals(-90, readerPageProcessing(pages[0], false, rotate.copy(invertRotation = true)).rotation)
assertNull(readerPageProcessing(pages[0], false, DbReaderModePreferences()).leftHalf)
}
@Test
fun splitHalvesNeverPairIntoADoublePageSpread() {
val (split, _) = splitWidePagesInStream(pages, 0, mapOf(pages[1].identity() to landscape), enabled = true)
val units = readerDisplayUnits(split, DbReaderMode.Ltr, doublePage = true)
assertEquals(listOf(listOf(0), listOf(1), listOf(1), listOf(2, 3)), units.map { unit ->
unit.items.map { (it as ReaderStreamItem.Page).chapterPageIndex }
})
}
@Test
fun hiddenTransitionsChainChaptersDirectlyButTheSeriesEndKeepsItsCard() {
val nextPages = listOf(DbPageUrl("https://example.test/n.jpg"))
val chained = appendNextChapterToStream(pages, chapter, next, "Title", nextPages, showTransition = false)
assertEquals(pages.size + 1, chained.size)
assertTrue(chained.none { it is ReaderStreamItem.Transition })
assertSame(chained, appendNextChapterToStream(chained, chapter, next, "Title", nextPages, showTransition = false))
assertTrue(appendNextChapterToStream(pages, chapter, null, "Title", emptyList(), showTransition = false).last() is ReaderStreamItem.Transition)
}
@Test
fun skipReadDropsReadChaptersButNeverTheOpenOne() {
val all = listOf(
Chapter(1, 1, "Chapter 1", "/1", isRead = true),
Chapter(2, 1, "Chapter 2", "/2", isRead = true),
Chapter(3, 1, "Chapter 3", "/3"),
)
assertEquals(listOf(1L, 2L, 3L), resolveReadingChapterSequence("Title", 2, all, all).map(Chapter::id))
assertEquals(listOf(2L, 3L), resolveReadingChapterSequence("Title", 2, all, all, skipRead = true).map(Chapter::id))
}
@Test
fun untouchedModeGroupsFollowLegacyGlobalsAndEditingOneLeavesTheOther() {
val legacy = DatabaseJson.decodeFromString(DbSettings.serializer(), """{"cropBorders":true,"usePageTapZones":false,"readerNavigationLayout":3,"animatePageTransitions":false}""")
val expected = DbReaderModePreferences(cropBorders = true, animatePageTransitions = false, usePageTapZones = false, navigationLayout = 3)
assertEquals(expected, legacy.readerModePreferences(paged = true))
assertEquals(expected, legacy.readerModePreferences(paged = false))
val edited = legacy.withReaderModePreferences(paged = false) { it.copy(splitWidePages = true, cropBorders = false) }
assertEquals(expected.copy(splitWidePages = true, cropBorders = false), edited.readerModePreferences(paged = false))
assertEquals(expected, edited.readerModePreferences(paged = true))
assertNull(edited.features.reader.paged)
val restored = DatabaseJson.decodeFromString(DbSettings.serializer(), DatabaseJson.encodeToString(DbSettings.serializer(), edited))
assertEquals(edited.features.reader, restored.features.reader)
}
@Test
fun volumeKeysTurnPagesOnlyWhenEnabledAndSwapWhenInverted() {
assertEquals(1, readerVolumeKeyStep(Key.VolumeDown, enabled = true, invert = false))
assertEquals(-1, readerVolumeKeyStep(Key.VolumeUp, enabled = true, invert = false))
assertEquals(-1, readerVolumeKeyStep(Key.VolumeDown, enabled = true, invert = true))
assertEquals(0, readerVolumeKeyStep(Key.VolumeDown, enabled = false, invert = false))
assertEquals(0, readerVolumeKeyStep(Key.Spacebar, enabled = true, invert = false))
}
@Test
fun titleFoldersAreSingleSegmentsAndSpreadsShareTheTallerHeight() {
assertEquals("One_ Piece_ Vol_2", readerImageFolderName("One: Piece? Vol/2"))
assertEquals("ワンピース", readerImageFolderName("ワンピース"))
assertEquals("Untitled", readerImageFolderName("..."))
assertEquals(SpreadLayout(width = 300, height = 200, leftWidth = 100, rightWidth = 200), spreadLayout(50, 100, 200, 200))
assertNull(spreadLayout(6000, 3000, 6000, 3000))
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderRuntimeTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ReaderRuntimeTest, onlyGoneOrUnresolvableImageUrlsCountAsDeadLinks, http, verticalUsesPagedRendererWhileContinuousModesUseLists, doubleTapZoomKeepsTappedContentUnderTheFingerAndClampsPan, pinchZoomPansWithinBoundsAndReturningToOneResetsPan, borderCropFindsNonBorderPixelsAndLeavesEmptyOrFullImagesAlone, incognitoStartsAtFirstPageWhileNormalModeRestoresProgress, completedChaptersRestartAndCompletionUsesModeThresholds, continuousDoublePageKeepsEachChapterCoverSoloThenPairsRemainingPages and 14 further declarations.
Read the setup, action and assertions in these cases before implementing their production paths:
onlyGoneOrUnresolvableImageUrlsCountAsDeadLinksverticalUsesPagedRendererWhileContinuousModesUseListsdoubleTapZoomKeepsTappedContentUnderTheFingerAndClampsPanpinchZoomPansWithinBoundsAndReturningToOneResetsPanborderCropFindsNonBorderPixelsAndLeavesEmptyOrFullImagesAloneincognitoStartsAtFirstPageWhileNormalModeRestoresProgresscompletedChaptersRestartAndCompletionUsesModeThresholdscontinuousDoublePageKeepsEachChapterCoverSoloThenPairsRemainingPagesnextChapterAppendIsIdempotentAndKeepsTransitionPageSoloprefetchUsesConfiguredForwardWindowThenTwoRecentPagesAcrossChaptersprefetchNeverStartsMoreThanThreeImageRequestsAtOnceallReaderImageRequestsShareTheThreeRequestLimitreaderGestureTargetsTheTappedPageWithoutAnImageClickLayerdoubleTapZoomSpeedMatchesAuthorityDurationsdoublePageProgressLabelsDescribeAndClampSpreadsresolvedImageActionsUseByteAccurateTypesAndAuthorityStyleNames- The remaining 3 cases are included in the complete listing below.
Cross-chapter imports used by this file: DbColorFilterBlendMode, DbCustomColorFilter, DbPageUrl, DbReaderMode, DbScaleType, DbSettings. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.IntSize
import eu.friedcutlet.yokan.database.DbColorFilterBlendMode
import eu.friedcutlet.yokan.database.DbCustomColorFilter
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.database.DbScaleType
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Manga
import coil3.network.HttpException
import coil3.network.NetworkResponse
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
class ReaderRuntimeTest {
@Test
fun onlyGoneOrUnresolvableImageUrlsCountAsDeadLinks() {
fun http(code: Int) = HttpException(NetworkResponse(code = code))
listOf(401, 403, 404, 410).forEach { assertTrue(isDeadPageLink(http(it)), "HTTP $it") }
listOf(408, 429, 500, 503).forEach { assertFalse(isDeadPageLink(http(it)), "HTTP $it is transient") }
assertTrue(isDeadPageLink(IllegalStateException("fetch failed", UnknownHostException())), "wrapped DNS failure")
assertTrue(
isDeadPageLink(Exception("Exception in http request: Error Domain=NSURLErrorDomain Code=-1003 \"A server with the specified hostname could not be found.\"")),
)
assertFalse(isDeadPageLink(Exception("Error Domain=NSURLErrorDomain Code=-1001 \"The request timed out.\"")))
assertFalse(isDeadPageLink(IllegalStateException("decode failed")))
}
@Test
fun verticalUsesPagedRendererWhileContinuousModesUseLists() {
assertTrue(DbReaderMode.Vertical.isPaged())
assertFalse(DbReaderMode.Vertical.isVerticalLike())
assertTrue(DbReaderMode.VerticalContinuous.isVerticalLike())
assertFalse(DbReaderMode.VerticalContinuous.isPaged())
assertTrue(DbReaderMode.Webtoon.isVerticalLike())
assertFalse(DbReaderMode.Webtoon.isPaged())
}
@Test
fun doubleTapZoomKeepsTappedContentUnderTheFingerAndClampsPan() {
val viewport = IntSize(width = 100, height = 80)
assertEquals(Offset.Zero, doubleTapZoomOffset(Offset(50f, 40f), 2f, viewport))
assertEquals(Offset(25f, 0f), doubleTapZoomOffset(Offset(25f, 40f), 2f, viewport))
assertEquals(Offset(50f, -40f), constrainZoomOffset(Offset(500f, -500f), 2f, viewport))
}
@Test
fun pinchZoomPansWithinBoundsAndReturningToOneResetsPan() {
val state = ReaderZoomState()
state.updateViewport(IntSize(width = 100, height = 80))
state.transform(centroid = Offset(50f, 40f), pan = Offset(10f, -5f), zoomChange = 2f)
assertEquals(2f, state.scale)
assertEquals(Offset(10f, -5f), state.offset)
state.transform(centroid = Offset(50f, 40f), pan = Offset.Zero, zoomChange = 0.1f)
assertEquals(1f, state.scale)
assertEquals(Offset.Zero, state.offset)
}
@Test
fun borderCropFindsNonBorderPixelsAndLeavesEmptyOrFullImagesAlone() {
val width = 5
val height = 4
val pixels = IntArray(width * height) { 0xFFFFFFFF.toInt() }
pixels[1 + width] = 0xFF808080.toInt()
pixels[3 + width * 2] = 0xFF204060.toInt()
assertEquals(
ImageCropBounds(left = 1, top = 1, rightExclusive = 4, bottomExclusive = 3),
detectBorderCropBounds(width, height) { x, y -> pixels[x + y * width] },
)
assertNull(detectBorderCropBounds(2, 2) { _, _ -> 0x00000000 })
assertNull(detectBorderCropBounds(2, 2) { _, _ -> 0xFF808080.toInt() })
}
@Test
fun incognitoStartsAtFirstPageWhileNormalModeRestoresProgress() {
assertEquals(
0,
readerResumeIndex(lastPageRead = "5", pageCount = 10, restoreResume = true, incognito = true),
)
assertEquals(
4,
readerResumeIndex(lastPageRead = "5", pageCount = 10, restoreResume = true, incognito = false),
)
assertEquals(
9,
readerResumeIndex(lastPageRead = "99", pageCount = 10, restoreResume = true, incognito = false),
)
}
@Test
fun completedChaptersRestartAndCompletionUsesModeThresholds() {
assertEquals(
0,
readerResumeIndex(
lastPageRead = "5",
pageCount = 10,
restoreResume = true,
incognito = false,
alreadyRead = true,
),
)
assertFalse(readerChapterIsComplete(index = 7, pageCount = 10, mode = DbReaderMode.Vertical))
assertTrue(readerChapterIsComplete(index = 8, pageCount = 10, mode = DbReaderMode.Vertical))
assertFalse(readerChapterIsComplete(index = 6, pageCount = 10, mode = DbReaderMode.VerticalContinuous))
assertTrue(readerChapterIsComplete(index = 7, pageCount = 10, mode = DbReaderMode.VerticalContinuous))
}
@Test
fun continuousDoublePageKeepsEachChapterCoverSoloThenPairsRemainingPages() {
val chapter = chapter(1)
val items = readerPageItems(chapter, pages(6))
val units = readerDisplayUnits(items, DbReaderMode.VerticalContinuous, doublePage = true)
assertEquals(listOf(0..0, 1..2, 3..4, 5..5), units.map { it.streamIndexes })
repeat(items.size) { streamIndex ->
val unitIndex = displayUnitIndexForStreamIndex(units, streamIndex)
assertTrue(streamIndex in units[unitIndex].streamIndexes)
}
}
@Test
fun nextChapterAppendIsIdempotentAndKeepsTransitionPageSolo() {
val current = chapter(1)
val next = chapter(2)
val currentItems = readerPageItems(current, pages(3))
val stream = appendNextChapterToStream(
items = currentItems,
completedChapter = current,
nextChapter = next,
mangaTitle = "Manga",
nextPages = pages(2),
)
assertEquals(6, stream.size)
assertEquals(current, (stream[3] as ReaderStreamItem.Transition).completedChapter)
assertEquals(next, (stream[3] as ReaderStreamItem.Transition).nextChapter)
assertEquals(4, streamIndexForChapterPage(stream, next.id, pageIndex = 0))
assertEquals(
stream,
appendNextChapterToStream(stream, current, next, "Manga", pages(2)),
)
val pagedUnits = readerDisplayUnits(stream, DbReaderMode.Ltr, doublePage = true)
assertEquals(listOf(0..1, 2..2, 3..3, 4..5), pagedUnits.map { it.streamIndexes })
assertTrue(pagedUnits.single { it.firstStreamIndex == 3 }.items.single() is ReaderStreamItem.Transition)
val endStream = appendNextChapterToStream(
items = currentItems,
completedChapter = current,
nextChapter = null,
mangaTitle = "Manga",
nextPages = emptyList(),
)
assertEquals(4, endStream.size)
assertNull((endStream.last() as ReaderStreamItem.Transition).nextChapter)
}
@Test
fun prefetchUsesConfiguredForwardWindowThenTwoRecentPagesAcrossChapters() {
val current = chapter(1)
val next = chapter(2)
val firstPages = List(4) { DbPageUrl("https://example.com/first-$it.jpg") }
val nextPages = List(3) { DbPageUrl("https://example.com/next-$it.jpg") }
val stream = appendNextChapterToStream(
items = readerPageItems(current, firstPages),
completedChapter = current,
nextChapter = next,
mangaTitle = "Manga",
nextPages = nextPages,
)
assertEquals(
listOf(
firstPages[2],
firstPages[3],
nextPages[0],
nextPages[1],
firstPages[1],
firstPages[0],
),
readerPrefetchPages(
items = stream,
currentStreamIndex = 2,
forwardAmount = 4,
),
)
assertEquals(
listOf(firstPages[3], firstPages[2]),
readerPrefetchPages(
items = stream,
currentStreamIndex = 4,
forwardAmount = 0,
),
)
}
@Test
fun prefetchNeverStartsMoreThanThreeImageRequestsAtOnce() = runTest {
val pages = pages(8)
val started = Channel<DbPageUrl>(Channel.UNLIMITED)
val release = Channel<Unit>(Channel.UNLIMITED)
var active = 0
var peak = 0
var completed = 0
val prefetch = launch {
loadReaderPagesBounded(pages) { page ->
active += 1
peak = maxOf(peak, active)
started.send(page)
release.receive()
completed += 1
active -= 1
}
}
repeat(READER_PREFETCH_CONCURRENCY) { started.receive() }
assertEquals(READER_PREFETCH_CONCURRENCY, peak)
assertTrue(started.tryReceive().isFailure)
repeat(pages.size) { release.send(Unit) }
prefetch.join()
assertEquals(pages.size, completed)
}
@Test
fun allReaderImageRequestsShareTheThreeRequestLimit() = runTest {
val limiter = ReaderImageRequestLimiter()
val started = Channel<Int>(Channel.UNLIMITED)
val release = Channel<Unit>(Channel.UNLIMITED)
var active = 0
var peak = 0
val requests = List(8) { request ->
launch {
limiter.limit {
active += 1
peak = maxOf(peak, active)
started.send(request)
release.receive()
active -= 1
}
}
}
repeat(READER_PREFETCH_CONCURRENCY) { started.receive() }
assertEquals(READER_PREFETCH_CONCURRENCY, peak)
assertTrue(started.tryReceive().isFailure)
repeat(requests.size) { release.send(Unit) }
requests.forEach { it.join() }
}
@Test
fun readerGestureTargetsTheTappedPageWithoutAnImageClickLayer() {
val pages = pages(2)
val unit = ReaderDisplayUnit(
streamIndexes = 0..1,
items = readerPageItems(chapter(1), pages),
)
assertEquals(
ReaderGestureTarget(unit.items[0] as ReaderStreamItem.Page, Offset(25f, 60f)),
readerGestureTarget(unit, Offset(25f, 60f), IntSize(200, 100)),
)
assertEquals(
ReaderGestureTarget(unit.items[1] as ReaderStreamItem.Page, Offset(50f, 60f)),
readerGestureTarget(unit, Offset(150f, 60f), IntSize(200, 100)),
)
}
@Test
fun doubleTapZoomSpeedMatchesAuthorityDurations() {
assertEquals(10, doubleTapZoomDurationMillis(0))
assertEquals(800, doubleTapZoomDurationMillis(1))
assertEquals(200, doubleTapZoomDurationMillis(2))
assertEquals(200, doubleTapZoomDurationMillis(3))
}
@Test
fun doublePageProgressLabelsDescribeAndClampSpreads() {
assertEquals("3", readerPageLabel(page = 3, pageCount = 8, doublePage = false))
assertEquals("3-4", readerPageLabel(page = 3, pageCount = 8, doublePage = true))
assertEquals("8", readerPageLabel(page = 8, pageCount = 8, doublePage = true))
assertEquals("1-2", readerPageLabel(page = 0, pageCount = 8, doublePage = true))
}
@Test
fun resolvedImageActionsUseByteAccurateTypesAndAuthorityStyleNames() {
assertEquals(
ReaderImageFormat("image/png", "png"),
readerImageFormat(byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47)),
)
assertEquals(
ReaderImageFormat("image/jpeg", "jpg"),
readerImageFormat(byteArrayOf(0xFF.toByte(), 0xD8.toByte(), 0xFF.toByte())),
)
assertEquals(
ReaderImageFormat("image/webp", "webp"),
readerImageFormat("RIFF0000WEBP".encodeToByteArray()),
)
assertEquals(
"Ma_ga Chapter (1) - 3.png",
readerImageFileName("Mañga", "Chapter (1)", 3, "png"),
)
}
@Test
fun toneEnhancementAndCustomTintRemainActiveTogether() {
val filters = buildReaderColorFilters(
DbSettings(
invertColors = true,
readerContrast = 1.2,
enableCustomColorFilter = true,
customColorFilter = DbCustomColorFilter(a = 128, r = 40, g = 80, b = 120),
colorFilterBlendMode = DbColorFilterBlendMode.Multiply,
),
)
assertNotNull(filters.tone)
assertNotNull(filters.tint)
}
@Test
fun scaleModesMatchAuthorityFitAndPagedAlignmentSemantics() {
assertEquals(ContentScale.Crop, DbScaleType.Stretch.toContentScale(paged = true))
assertEquals(ContentScale.Crop, DbScaleType.OriginalSize.toContentScale(paged = false))
assertEquals(ContentScale.Fit, DbScaleType.FitWidth.toContentScale(paged = true))
assertEquals(ContentScale.FillWidth, DbScaleType.FitWidth.toContentScale(paged = false))
assertEquals(
ReaderInitialTransform(scale = 2f, offset = Offset(0f, 100f)),
readerInitialTransform(
scaleType = DbScaleType.FitWidth,
imageSize = IntSize(100, 200),
viewportSize = IntSize(200, 200),
paged = true,
),
)
assertEquals(
ReaderInitialTransform(scale = 2f, offset = Offset(100f, 0f)),
readerInitialTransform(
scaleType = DbScaleType.FitHeight,
imageSize = IntSize(200, 100),
viewportSize = IntSize(200, 200),
paged = true,
),
)
assertEquals(
ReaderInitialTransform(),
readerInitialTransform(
scaleType = DbScaleType.FitWidth,
imageSize = IntSize(100, 200),
viewportSize = IntSize(200, 200),
paged = false,
),
)
}
@Test
fun webtoonPaddingUsesClampedViewportPercentAndDisablesForSpreads() {
assertEquals(0.25f, webtoonSidePaddingFraction(percent = 25, doublePage = false))
assertEquals(0.5f, webtoonSidePaddingFraction(percent = 80, doublePage = false))
assertEquals(0f, webtoonSidePaddingFraction(percent = 25, doublePage = true))
}
private fun chapter(id: Long): Chapter = Chapter(
id = id,
mangaId = 10,
name = "Chapter $id",
url = "/chapter/$id",
)
private fun pages(count: Int): List<DbPageUrl> =
List(count) { index -> DbPageUrl(url = "https://example.com/page-$index.jpg") }
}
/** Named like the JVM's, which the reader recognises by name on every platform. */
private class UnknownHostException : Exception("img.example: nodename nor servname provided")
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderSystemUiPreferencesTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ReaderSystemUiPreferencesTest, mobileBarsFollowFullscreenSettingAndChromeVisibility.
Read the setup, action and assertions in these cases before implementing their production paths:
mobileBarsFollowFullscreenSettingAndChromeVisibility
package eu.friedcutlet.yokan.ui.screens.reader
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class ReaderSystemUiPreferencesTest {
@Test
fun mobileBarsFollowFullscreenSettingAndChromeVisibility() {
assertTrue(
ReaderSystemUiPreferences(
fullscreen = true,
keepScreenOn = true,
chromeVisible = false,
).hideMobileSystemBars,
)
assertFalse(
ReaderSystemUiPreferences(
fullscreen = true,
keepScreenOn = true,
chromeVisible = true,
).hideMobileSystemBars,
)
assertFalse(
ReaderSystemUiPreferences(
fullscreen = false,
keepScreenOn = true,
chromeVisible = false,
).hideMobileSystemBars,
)
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderViewModelStreamTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ReaderViewModelStreamTest, holdTakesOverWithoutPersistingSpeedAndReleaseNeverResumesOrdinaryScrolling, chapterListOverlayStopsScrollingAndBlocksHoldUntilClosed, holdStopsForDialogsBackgroundModeChangesAndDisabledPreference, accessiblePlayPauseWorksWithoutAutomaticStartupAndHoldSurvivesContinuousChapterEntry, automaticLayoutFallsBackAtDeadlineAndResolvesPreloadedChapterIndependently, automaticLayoutSamplesOnceAndKeepsLogicalPageAcrossRotationAndManualOverride, tallCachedSamplesResolveWebtoonAndStaleIdentityEventsAreIgnored, navigationRespondsToReleasePriorityChangesWithoutChangingTheOpenAlternate, setUp and 9 further declarations.
Read the setup, action and assertions in these cases before implementing their production paths:
holdTakesOverWithoutPersistingSpeedAndReleaseNeverResumesOrdinaryScrollingchapterListOverlayStopsScrollingAndBlocksHoldUntilClosedholdStopsForDialogsBackgroundModeChangesAndDisabledPreferenceaccessiblePlayPauseWorksWithoutAutomaticStartupAndHoldSurvivesContinuousChapterEntryautomaticLayoutFallsBackAtDeadlineAndResolvesPreloadedChapterIndependentlyautomaticLayoutSamplesOnceAndKeepsLogicalPageAcrossRotationAndManualOverridetallCachedSamplesResolveWebtoonAndStaleIdentityEventsAreIgnorednavigationRespondsToReleasePriorityChangesWithoutChangingTheOpenAlternatechoosingAnotherChapterFlushesTheSessionAndReopeningResumesTherecachedNextChapterAppendsAndBecomesActiveInPlaceautoScrollPreferencePersistsAndSettingsSheetPausesOnlyTheRunningSessionaDeadImageLinkOnASavedListRefreshesItOnceInPlace
Cross-chapter imports used by this file: DefaultYokanRepository, LibraryIndexStore, SettingsStore, DbAutoScrollPages, DbChapter, DbItemType. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Job
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.DbAutoScrollPages
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.services.extensions.ChapterPageResolver
import eu.friedcutlet.yokan.services.extensions.PageListRuntimeFactory
import eu.friedcutlet.yokan.services.files.NoFiles
import coil3.network.HttpException
import coil3.network.NetworkResponse
import eu.friedcutlet.yokan.domain.Chapter
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
@OptIn(ExperimentalCoroutinesApi::class)
class ReaderViewModelStreamTest {
@Test
fun holdTakesOverWithoutPersistingSpeedAndReleaseNeverResumesOrdinaryScrolling() = runTest {
val db = fixtureDatabase(listOf(FIRST_CHAPTER_ID), settings = {
it.copy(readerHoldToScroll = true, defaultReaderMode = DbReaderMode.Webtoon)
})
val repository = DefaultYokanRepository(db)
repository.cachePageUrls(FIRST_CHAPTER_ID, "/1", pages("hold", 5))
val vm = viewModel(db, repository, backgroundScope, repository.chapter(FIRST_CHAPTER_ID))
vm.state.first { it.holdScrollEnabled && it.pages.isNotEmpty() }
vm.onEvent(ReaderEvent.SetAutoScrollEnabled(true))
val savedSettings = db.settings()
vm.onEvent(ReaderEvent.BeginHoldScroll(1))
assertFalse(vm.state.value.autoScrolling)
assertEquals(ReaderHoldPhase.Scrolling, vm.state.value.holdScroll.phase)
vm.onEvent(ReaderEvent.HoldScrollSpeed(1, 42f))
assertEquals(15f, vm.state.value.holdScroll.speed)
vm.onEvent(ReaderEvent.HoldScrollSpeed(1, -1000f))
assertEquals(ReaderHoldPhase.Holding, vm.state.value.holdScroll.phase)
vm.onEvent(ReaderEvent.HoldScrollSpeed(1, 1000f))
assertEquals(60f, vm.state.value.holdScroll.speed)
assertEquals(savedSettings, db.settings())
assertEquals(10.0, vm.state.value.autoScrollOffset)
vm.onEvent(ReaderEvent.EndHoldScroll(1))
assertFalse(vm.state.value.autoScrolling)
assertEquals(ReaderHoldPhase.Idle, vm.state.value.holdScroll.phase)
vm.onEvent(ReaderEvent.HoldScrollSpeed(1, 42f))
assertEquals(ReaderHoldPhase.Idle, vm.state.value.holdScroll.phase)
vm.onEvent(ReaderEvent.BeginHoldScroll(2))
vm.onEvent(ReaderEvent.EndHoldScroll(1))
assertEquals(2L, vm.state.value.holdScroll.gestureId)
vm.onEvent(ReaderEvent.InterruptScrolling)
assertEquals(ReaderHoldPhase.Idle, vm.state.value.holdScroll.phase)
}
@Test
fun chapterListOverlayStopsScrollingAndBlocksHoldUntilClosed() = runTest {
val db = fixtureDatabase(listOf(FIRST_CHAPTER_ID), settings = {
it.copy(readerHoldToScroll = true, defaultReaderMode = DbReaderMode.Webtoon)
})
val repository = DefaultYokanRepository(db)
repository.cachePageUrls(FIRST_CHAPTER_ID, "/1", pages("list", 5))
val vm = viewModel(db, repository, backgroundScope, repository.chapter(FIRST_CHAPTER_ID))
vm.state.first { it.holdScrollEnabled && it.pages.isNotEmpty() }
vm.onEvent(ReaderEvent.SetAutoScrollEnabled(true))
vm.onEvent(ReaderEvent.OpenChapterList)
vm.onEvent(ReaderEvent.BeginHoldScroll(1))
assertTrue(vm.state.value.chapterListOpen)
assertTrue(vm.state.value.overlayOpen)
assertFalse(vm.state.value.autoScrolling)
assertEquals(ReaderHoldPhase.Idle, vm.state.value.holdScroll.phase)
vm.onEvent(ReaderEvent.CloseChapterList)
vm.onEvent(ReaderEvent.BeginHoldScroll(2))
assertFalse(vm.state.value.overlayOpen)
assertEquals(ReaderHoldPhase.Scrolling, vm.state.value.holdScroll.phase)
}
@Test
fun holdStopsForDialogsBackgroundModeChangesAndDisabledPreference() = runTest {
val db = fixtureDatabase(listOf(FIRST_CHAPTER_ID), settings = {
it.copy(readerHoldToScroll = true, defaultReaderMode = DbReaderMode.VerticalContinuous)
})
val repository = DefaultYokanRepository(db)
repository.cachePageUrls(FIRST_CHAPTER_ID, "/1", pages("interrupt", 5))
val vm = viewModel(db, repository, backgroundScope, repository.chapter(FIRST_CHAPTER_ID))
vm.state.first { it.holdScrollEnabled && it.pages.isNotEmpty() }
vm.onEvent(ReaderEvent.BeginHoldScroll(1))
vm.onEvent(ReaderEvent.OpenSettingsSheet)
vm.onEvent(ReaderEvent.BeginHoldScroll(2))
assertEquals(ReaderHoldPhase.Idle, vm.state.value.holdScroll.phase)
vm.onEvent(ReaderEvent.CloseSettingsSheet)
assertFalse(vm.state.value.autoScrolling)
vm.onEvent(ReaderEvent.BeginHoldScroll(3))
vm.onEvent(ReaderEvent.ReadingPaused)
assertFalse(vm.state.value.readerActive)
vm.onEvent(ReaderEvent.BeginHoldScroll(4))
assertEquals(ReaderHoldPhase.Idle, vm.state.value.holdScroll.phase)
vm.onEvent(ReaderEvent.ReadingResumed)
assertTrue(vm.state.value.readerActive)
assertFalse(vm.state.value.autoScrolling)
vm.onEvent(ReaderEvent.BeginHoldScroll(5))
vm.onEvent(ReaderEvent.ChangeMode(DbReaderMode.Ltr))
assertEquals(ReaderHoldPhase.Idle, vm.state.value.holdScroll.phase)
vm.onEvent(ReaderEvent.BeginHoldScroll(6))
assertEquals(ReaderHoldPhase.Idle, vm.state.value.holdScroll.phase)
vm.onEvent(ReaderEvent.ChangeMode(DbReaderMode.Webtoon))
vm.onEvent(ReaderEvent.BeginHoldScroll(7))
db.updateSettings(db.settings().copy(readerHoldToScroll = false))
vm.state.first { !it.holdScrollEnabled }
assertEquals(ReaderHoldPhase.Idle, vm.state.value.holdScroll.phase)
vm.onEvent(ReaderEvent.BeginHoldScroll(8))
assertEquals(ReaderHoldPhase.Idle, vm.state.value.holdScroll.phase)
db.updateSettings(db.settings().copy(readerHoldToScroll = true))
vm.onEvent(ReaderEvent.ChangeMode(DbReaderMode.HorizontalContinuous))
vm.onEvent(ReaderEvent.AutomaticLayout)
val sampling = vm.state.first { it.automaticLayout && it.holdScrollEnabled }
vm.onEvent(ReaderEvent.BeginHoldScroll(9))
assertEquals(ReaderHoldPhase.Scrolling, vm.state.value.holdScroll.phase)
sampling.streamItems.filterIsInstance<ReaderStreamItem.Page>().take(3).forEach {
vm.onEvent(ReaderEvent.PageShapeSampled(sampling.layoutSampleKey, it.identity(), ReaderPageShape(800, 4000)))
}
assertEquals(DbReaderMode.Webtoon, vm.state.value.mode)
assertEquals(ReaderHoldPhase.Idle, vm.state.value.holdScroll.phase)
vm.onEvent(ReaderEvent.BeginHoldScroll(10))
vm.onEvent(ReaderEvent.Back)
assertFalse(vm.state.value.readerActive)
vm.onEvent(ReaderEvent.BeginHoldScroll(11))
assertEquals(ReaderHoldPhase.Idle, vm.state.value.holdScroll.phase)
}
@Test
fun accessiblePlayPauseWorksWithoutAutomaticStartupAndHoldSurvivesContinuousChapterEntry() = runTest {
val db = fixtureDatabase(listOf(FIRST_CHAPTER_ID, SECOND_CHAPTER_ID), settings = {
it.copy(readerHoldToScroll = true, defaultReaderMode = DbReaderMode.HorizontalContinuousRtl)
})
val repository = DefaultYokanRepository(db)
repository.cachePageUrls(FIRST_CHAPTER_ID, "/1", pages("first-hold", 3))
repository.cachePageUrls(SECOND_CHAPTER_ID, "/2", pages("next-hold", 3))
val vm = viewModel(db, repository, backgroundScope, repository.chapter(FIRST_CHAPTER_ID))
vm.state.first { state -> state.holdScrollEnabled && state.streamItems.any { it is ReaderStreamItem.Page && it.chapter.id == SECOND_CHAPTER_ID } }
assertFalse(vm.state.value.autoScrollEnabled)
assertFalse(vm.state.value.autoScrolling)
val saved = db.settings()
vm.onEvent(ReaderEvent.ToggleAutoScroll)
assertTrue(vm.state.value.autoScrolling)
vm.onEvent(ReaderEvent.ToggleAutoScroll)
assertFalse(vm.state.value.autoScrolling)
assertEquals(saved, db.settings())
vm.onEvent(ReaderEvent.BeginHoldScroll(1))
vm.onEvent(ReaderEvent.CurrentPageChanged(streamIndexForChapterPage(vm.state.value.streamItems, SECOND_CHAPTER_ID, 1)))
assertEquals(SECOND_CHAPTER_ID, vm.state.value.chapter.id)
assertEquals(1L, vm.state.value.holdScroll.gestureId)
assertEquals(1, vm.state.value.currentPageIndex)
vm.onEvent(ReaderEvent.ToggleAutoScroll)
assertEquals(ReaderHoldPhase.Idle, vm.state.value.holdScroll.phase)
assertFalse(vm.state.value.autoScrolling)
}
@Test
fun automaticLayoutFallsBackAtDeadlineAndResolvesPreloadedChapterIndependently() = runTest {
val db = fixtureDatabase(listOf(FIRST_CHAPTER_ID, SECOND_CHAPTER_ID), settings = {
it.copy(automaticReaderLayout = true, defaultReaderMode = DbReaderMode.Rtl)
})
val repository = DefaultYokanRepository(db)
repository.cachePageUrls(FIRST_CHAPTER_ID, "/1", pages("slow", 3))
repository.cachePageUrls(SECOND_CHAPTER_ID, "/2", pages("tall-next", 3))
val vm = viewModel(db, repository, backgroundScope, repository.chapter(FIRST_CHAPTER_ID))
val ready = vm.state.first { state -> state.layoutSampleKey.isNotEmpty() &&
state.streamItems.any { it is ReaderStreamItem.Page && it.chapter.id == SECOND_CHAPTER_ID } }
val first = ready.streamItems.filterIsInstance<ReaderStreamItem.Page>().first()
vm.onEvent(ReaderEvent.PageShapeSampled(ready.layoutSampleKey, first.identity(), null))
advanceTimeBy(AUTOMATIC_LAYOUT_SAMPLE_TIMEOUT)
runCurrent()
assertTrue(vm.state.value.layoutSettled)
assertEquals(DbReaderMode.Rtl, vm.state.value.mode)
ready.streamItems.filterIsInstance<ReaderStreamItem.Page>().forEach {
vm.onEvent(ReaderEvent.PageShapeSampled(ready.layoutSampleKey, it.identity(), ReaderPageShape(800, 4000)))
}
assertEquals(DbReaderMode.Rtl, vm.state.value.mode)
val nextIndex = streamIndexForChapterPage(vm.state.value.streamItems, SECOND_CHAPTER_ID, 1)
vm.onEvent(ReaderEvent.CurrentPageChanged(nextIndex))
assertEquals(SECOND_CHAPTER_ID, vm.state.value.chapter.id)
assertEquals(1, vm.state.value.currentPageIndex)
assertEquals(DbReaderMode.Webtoon, vm.state.value.mode)
assertTrue(vm.state.value.layoutSettled)
}
@Test
fun automaticLayoutSamplesOnceAndKeepsLogicalPageAcrossRotationAndManualOverride() = runTest {
val db = fixtureDatabase(listOf(FIRST_CHAPTER_ID), settings = { it.copy(automaticReaderLayout = true, defaultReaderMode = DbReaderMode.Rtl) })
val repository = DefaultYokanRepository(db)
repository.cachePageUrls(FIRST_CHAPTER_ID, "/1", pages("layout", 5))
val vm = viewModel(db, repository, backgroundScope, repository.chapter(FIRST_CHAPTER_ID))
vm.state.first { it.automaticLayout && it.layoutSampleKey.isNotEmpty() }
vm.onEvent(ReaderEvent.CurrentPageChanged(2))
val key = vm.state.value.layoutSampleKey
val sample = vm.state.value.streamItems.filterIsInstance<ReaderStreamItem.Page>().take(3)
sample.forEach { vm.onEvent(ReaderEvent.PageShapeSampled(key, it.identity(), ReaderPageShape(800, 1200))) }
assertTrue(vm.state.value.layoutSettled)
assertEquals(DbReaderMode.Rtl, vm.state.value.mode)
vm.onEvent(ReaderEvent.ViewportChanged(ReaderViewport(1280, 800)))
assertTrue(vm.state.value.doublePage)
assertEquals(2, vm.state.value.currentPageIndex)
vm.onEvent(ReaderEvent.ViewportChanged(ReaderViewport(800, 1280)))
assertFalse(vm.state.value.doublePage)
sample.forEach { vm.onEvent(ReaderEvent.PageShapeSampled(key, it.identity(), ReaderPageShape(800, 4000))) }
assertEquals(DbReaderMode.Rtl, vm.state.value.mode)
vm.onEvent(ReaderEvent.ChangeMode(DbReaderMode.Ltr))
vm.state.first { !it.automaticLayout && it.mode == DbReaderMode.Ltr }
vm.onEvent(ReaderEvent.ViewportChanged(ReaderViewport(1280, 800)))
assertFalse(vm.state.value.doublePage)
assertEquals(2, vm.state.value.currentPageIndex)
vm.onEvent(ReaderEvent.AutomaticLayout)
assertTrue(vm.state.first { it.automaticLayout }.automaticLayout)
}
@Test
fun tallCachedSamplesResolveWebtoonAndStaleIdentityEventsAreIgnored() = runTest {
val db = fixtureDatabase(listOf(FIRST_CHAPTER_ID), settings = { it.copy(automaticReaderLayout = true) })
val repository = DefaultYokanRepository(db)
repository.cachePageUrls(FIRST_CHAPTER_ID, "/1", pages("webtoon", 3))
val vm = viewModel(db, repository, backgroundScope, repository.chapter(FIRST_CHAPTER_ID))
val ready = vm.state.first { it.layoutSampleKey.isNotEmpty() }
val sample = ready.streamItems.filterIsInstance<ReaderStreamItem.Page>().take(3)
vm.onEvent(ReaderEvent.PageShapeSampled("old key", sample[0].identity(), ReaderPageShape(800, 4000)))
assertTrue(vm.state.value.pageShapes.isEmpty())
sample.forEach { vm.onEvent(ReaderEvent.PageShapeSampled(ready.layoutSampleKey, it.identity(), ReaderPageShape(800, 4000))) }
assertEquals(DbReaderMode.Webtoon, vm.state.value.mode)
assertTrue(vm.state.value.layoutSettled)
assertFalse(vm.state.value.doublePage)
}
@Test
fun navigationRespondsToReleasePriorityChangesWithoutChangingTheOpenAlternate() = runTest {
val database = fixtureDatabase(chapterIds = listOf(FIRST_CHAPTER_ID, SECOND_CHAPTER_ID))
database.upsertChapter(checkNotNull(database.chapter(FIRST_CHAPTER_ID)).copy(name = "Chapter 1", scanlator = "A"))
database.upsertChapter(checkNotNull(database.chapter(SECOND_CHAPTER_ID)).copy(name = "Chapter 2", scanlator = "A"))
val alternateId = SECOND_CHAPTER_ID + 1
database.upsertChapter(checkNotNull(database.chapter(SECOND_CHAPTER_ID)).copy(id = alternateId, url = "/alternate", scanlator = "B"))
database.updateSettings(database.settings().copy(chapterReleasePreferences = listOf(
eu.friedcutlet.yokan.database.DbChapterReleasePreference(scanlatorPriority = listOf("A", "B"), skipDuplicateReleases = true))))
val repository = DefaultYokanRepository(database)
repository.cachePageUrls(FIRST_CHAPTER_ID, "/1", pages("first", 3))
repository.cachePageUrls(SECOND_CHAPTER_ID, "/2", pages("second", 2))
repository.cachePageUrls(alternateId, "/alternate", pages("alternate", 2))
val vm = viewModel(database, repository, backgroundScope, repository.chapter(FIRST_CHAPTER_ID))
vm.state.first { it.nextChapter?.id == SECOND_CHAPTER_ID && it.streamItems.any { item -> item is ReaderStreamItem.Page && item.chapter.id == SECOND_CHAPTER_ID } }
vm.onEvent(ReaderEvent.CurrentPageChanged(1))
database.updateSettings(database.settings().copy(chapterReleasePreferences = listOf(
eu.friedcutlet.yokan.database.DbChapterReleasePreference(scanlatorPriority = listOf("B", "A"), skipDuplicateReleases = true))))
val changed = vm.state.first { it.nextChapter?.id == alternateId && it.streamItems.any { item -> item is ReaderStreamItem.Page && item.chapter.id == alternateId } }
assertTrue(changed.streamItems.none { it is ReaderStreamItem.Page && it.chapter.id == SECOND_CHAPTER_ID })
assertEquals(FIRST_CHAPTER_ID, vm.state.value.chapter.id)
assertEquals(1, vm.state.value.currentPageIndex)
viewModelStore.clear()
val openedAlternate = viewModel(database, repository, backgroundScope, repository.chapter(SECOND_CHAPTER_ID))
val bridged = openedAlternate.state.first { it.chapterSequence.any { chapter -> chapter.id == SECOND_CHAPTER_ID } }
assertEquals(listOf(FIRST_CHAPTER_ID, SECOND_CHAPTER_ID), bridged.chapterSequence.map { it.id })
assertEquals(null, bridged.nextChapter)
}
private val viewModelStore = ViewModelStore()
private val readerJobs = mutableListOf<Job>()
private val dispatcher = UnconfinedTestDispatcher()
@BeforeTest
fun setUp() {
Dispatchers.setMain(dispatcher)
}
@AfterTest
fun tearDown() = runTest {
viewModelStore.clear()
// Flow producers may finish cancellation on the index dispatcher; keep Main installed until then.
readerJobs.forEach { it.join() }
Dispatchers.resetMain()
}
@Test
fun choosingAnotherChapterFlushesTheSessionAndReopeningResumesThere() = runTest {
val database = fixtureDatabase(chapterIds = listOf(FIRST_CHAPTER_ID, SECOND_CHAPTER_ID))
val repository = DefaultYokanRepository(database)
repository.cachePageUrls(FIRST_CHAPTER_ID, "/1", pages("first", 5))
repository.cachePageUrls(SECOND_CHAPTER_ID, "/2", pages("second", 2))
val second = repository.chapter(SECOND_CHAPTER_ID)
val viewModel = viewModel(database, repository, backgroundScope, repository.chapter(FIRST_CHAPTER_ID))
viewModel.onEvent(ReaderEvent.CurrentPageChanged(1))
viewModel.onEvent(ReaderEvent.SelectChapter(second))
assertEquals(ReaderEffect.OpenChapter(second), viewModel.effects.first())
assertEquals(FIRST_CHAPTER_ID, viewModel.state.value.chapter.id)
assertEquals("2", database.chapter(FIRST_CHAPTER_ID)?.lastPageRead)
viewModelStore.clear()
val reopened = viewModel(database, repository, backgroundScope, repository.chapter(FIRST_CHAPTER_ID))
assertEquals(FIRST_CHAPTER_ID, reopened.state.value.chapter.id)
assertEquals(1, reopened.state.value.currentPageIndex)
}
@Test
fun cachedNextChapterAppendsAndBecomesActiveInPlace() = runTest {
val database = fixtureDatabase(
chapterIds = listOf(FIRST_CHAPTER_ID, SECOND_CHAPTER_ID),
settings = { it.copy(defaultReaderMode = DbReaderMode.Ltr) },
)
val repository = DefaultYokanRepository(database)
repository.cachePageUrls(FIRST_CHAPTER_ID, "/1", pages("first", 3))
repository.cachePageUrls(SECOND_CHAPTER_ID, "/2", pages("second", 2))
val firstChapter = repository.chapter(FIRST_CHAPTER_ID)
val viewModel = viewModel(database, repository, backgroundScope, firstChapter)
val preloaded = viewModel.state.first { state ->
state.streamItems.any { it is ReaderStreamItem.Transition }
}
assertEquals(listOf(FIRST_CHAPTER_ID, SECOND_CHAPTER_ID), preloaded.chapterSequence.map { it.id })
assertEquals(SECOND_CHAPTER_ID, preloaded.nextChapter?.id)
val transitionIndex = preloaded.streamItems.indexOfFirst { it is ReaderStreamItem.Transition }
val transition = preloaded.streamItems[transitionIndex] as ReaderStreamItem.Transition
assertEquals(FIRST_CHAPTER_ID, transition.completedChapter.id)
assertEquals(SECOND_CHAPTER_ID, transition.nextChapter?.id)
viewModel.onEvent(ReaderEvent.CurrentPageChanged(transitionIndex))
assertEquals(FIRST_CHAPTER_ID, viewModel.state.value.chapter.id)
assertTrue(database.chapter(FIRST_CHAPTER_ID)?.isRead == true)
val nextPageIndex = streamIndexForChapterPage(
viewModel.state.value.streamItems,
SECOND_CHAPTER_ID,
pageIndex = 0,
)
viewModel.onEvent(ReaderEvent.CurrentPageChanged(nextPageIndex))
val switched = viewModel.state.value
assertEquals(SECOND_CHAPTER_ID, switched.chapter.id)
assertEquals(0, switched.currentPageIndex)
assertEquals(2, switched.pageCount)
val finished = viewModel.state.first { state ->
state.previousChapter?.id == FIRST_CHAPTER_ID &&
state.streamItems.any { item ->
item is ReaderStreamItem.Transition && item.completedChapter.id == SECOND_CHAPTER_ID
}
}
val end = finished.streamItems
.filterIsInstance<ReaderStreamItem.Transition>()
.first { it.completedChapter.id == SECOND_CHAPTER_ID }
assertNull(end.nextChapter)
assertNull(finished.nextChapter)
viewModel.onEvent(ReaderEvent.NextPage)
assertTrue(viewModel.state.value.animatePageChange)
viewModel.onEvent(ReaderEvent.JumpToPage(0))
assertFalse(viewModel.state.value.animatePageChange)
viewModel.onEvent(ReaderEvent.SelectChapter(firstChapter))
assertEquals(ReaderEffect.OpenChapter(firstChapter), viewModel.effects.first())
}
@Test
fun autoScrollPreferencePersistsAndSettingsSheetPausesOnlyTheRunningSession() = runTest {
val database = fixtureDatabase(
chapterIds = listOf(FIRST_CHAPTER_ID),
settings = {
it.copy(
defaultReaderMode = DbReaderMode.VerticalContinuous,
autoScrollPages = listOf(DbAutoScrollPages(mangaId = MANGA_ID, pageOffset = 12.0, autoScroll = true)),
)
},
)
val repository = DefaultYokanRepository(database)
repository.cachePageUrls(FIRST_CHAPTER_ID, "/1", pages("auto", 3))
val viewModel = viewModel(database, repository, backgroundScope, repository.chapter(FIRST_CHAPTER_ID))
assertTrue(viewModel.state.value.autoScrollEnabled)
assertTrue(viewModel.state.value.autoScrolling)
assertEquals(12.0, viewModel.state.value.autoScrollOffset)
viewModel.onEvent(ReaderEvent.OpenSettingsSheet)
assertFalse(viewModel.state.value.autoScrolling)
viewModel.onEvent(ReaderEvent.CloseSettingsSheet)
assertTrue(viewModel.state.value.autoScrolling)
viewModel.onEvent(ReaderEvent.ToggleAutoScroll)
assertFalse(viewModel.state.value.autoScrolling)
viewModel.onEvent(ReaderEvent.OpenSettingsSheet)
viewModel.onEvent(ReaderEvent.CloseSettingsSheet)
assertFalse(viewModel.state.value.autoScrolling)
viewModel.onEvent(ReaderEvent.SetAutoScrollOffset(40.0))
assertEquals(30.0, viewModel.state.value.autoScrollOffset)
assertEquals(30.0, database.settings().autoScrollPages?.single()?.pageOffset)
viewModel.onEvent(ReaderEvent.SetAutoScrollEnabled(false))
assertFalse(viewModel.state.value.autoScrollEnabled)
assertFalse(database.settings().autoScrollPages?.single()?.autoScroll ?: true)
}
@Test
fun aDeadImageLinkOnASavedListRefreshesItOnceInPlace() = runTest {
val database = fixtureDatabase(chapterIds = listOf(FIRST_CHAPTER_ID), sourceId = SOURCE_ID)
val repository = DefaultYokanRepository(database)
repository.cachePageUrls(FIRST_CHAPTER_ID, "/1", pages("saved", 3), database.source(SOURCE_ID))
val runtimes = PageListRuntimeFactory()
val viewModel = viewModel(database, repository, backgroundScope, repository.chapter(FIRST_CHAPTER_ID), runtimes)
viewModel.onEvent(ReaderEvent.CurrentPageChanged(2))
viewModel.onEvent(ReaderEvent.PageImageFailed(FIRST_CHAPTER_ID, IllegalStateException("socket timeout")))
assertEquals(0, runtimes.pageListCalls, "a transient failure keeps the saved list")
viewModel.onEvent(ReaderEvent.PageImageFailed(FIRST_CHAPTER_ID, HttpException(NetworkResponse(code = 403))))
val refreshed = viewModel.state.first { state -> state.pages.isNotEmpty() && state.pages.none { "saved" in it.url } }
assertEquals(1, runtimes.pageListCalls)
assertEquals(2, refreshed.currentPageIndex, "the reader stays on its page")
assertEquals(refreshed.pages, repository.pageUrls(FIRST_CHAPTER_ID), "the fresh list is saved")
viewModel.onEvent(ReaderEvent.PageImageFailed(FIRST_CHAPTER_ID, HttpException(NetworkResponse(code = 404))))
assertEquals(1, runtimes.pageListCalls, "after one refresh, failures fall back to per-page retry")
}
private fun fixtureDatabase(
chapterIds: List<Long>,
settings: (DbSettings) -> DbSettings = { it },
sourceId: Long? = null,
): InMemoryYokanDatabase {
val seed = seedDatabaseSnapshot()
return InMemoryYokanDatabase(
seed.copy(
settings = settings(seed.settings),
sources = seed.sources + listOfNotNull(sourceId?.let { DbSource(id = it, name = "Reader source", isAdded = true) }),
mangas = listOf(DbManga(id = MANGA_ID, name = "Reader fixture", itemType = DbItemType.Manga, sourceId = sourceId)),
chapters = chapterIds.mapIndexed { index, id ->
DbChapter(id = id, mangaId = MANGA_ID, name = "Chapter ${index + 1}", url = "/${index + 1}")
},
histories = emptyList(),
tracks = emptyList(),
downloads = emptyList(),
),
)
}
private fun viewModel(
database: InMemoryYokanDatabase,
repository: DefaultYokanRepository,
scope: CoroutineScope,
chapter: Chapter,
runtimes: PageListRuntimeFactory = PageListRuntimeFactory(),
): ReaderViewModel {
val manga = requireNotNull(repository.manga(MANGA_ID))
val settings = SettingsStore(repository, scope, onSchedulingChanged = {})
val index = LibraryIndexStore(repository, scope)
val chapterPages = ChapterPageResolver(repository, database, runtimes)
return ViewModelProvider.create(
viewModelStore,
viewModelFactory {
initializer {
ReaderViewModel(
manga,
chapter,
repository,
settings,
index,
chapterPages,
loadPages = { source, target, force -> chapterPages.pages(target, source?.id, force) },
files = NoFiles,
imageHttp = { error("Reader stream tests resolve no images") },
workDispatcher = dispatcher,
)
}
},
)[ReaderViewModel::class].also { readerJobs += checkNotNull(it.viewModelScope.coroutineContext[Job]) }
}
private fun DefaultYokanRepository.chapter(id: Long): Chapter = chapters(MANGA_ID).first { it.id == id }
private fun pages(prefix: String, count: Int): List<DbPageUrl> =
List(count) { index -> DbPageUrl("https://example.com/$prefix-$index.jpg") }
private companion object {
const val MANGA_ID = 920_000L
const val FIRST_CHAPTER_ID = 920_001L
const val SECOND_CHAPTER_ID = 920_002L
const val SOURCE_ID = 920_100L
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/colorization/ColorizerExifOrientationDesktopTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines ColorizerExifOrientationDesktopTest, withOrientation.
Read the setup, action and assertions in these cases before implementing their production paths:
rotatedAndMirroredJpegsAlignPreviewAndFullPageCrops
package eu.friedcutlet.yokan.services.colorization
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import javax.imageio.ImageIO
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
class ColorizerExifOrientationDesktopTest {
@Test fun rotatedAndMirroredJpegsAlignPreviewAndFullPageCrops() {
val image = BufferedImage(2, 3, BufferedImage.TYPE_INT_RGB)
val colors = intArrayOf(0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xff00ff, 0x00ffff)
colors.forEachIndexed { index, color -> image.setRGB(index % 2, index / 2, color) }
val jpeg = ByteArrayOutputStream().use { output -> ImageIO.write(image, "jpg", output); output.toByteArray() }
image.flush()
val platform = createColorizerPlatform()
val untagged = platform.decodeFullPage(jpeg)
for (orientation in listOf(2, 6)) {
val oriented = platform.decodeFullPage(withOrientation(jpeg, orientation))
val expected = orientPixels(untagged.width, untagged.height, untagged.argb, orientation)
assertEquals(expected.width, oriented.width)
assertEquals(expected.height, oriented.height)
assertContentEquals(expected.argb, oriented.argb)
val preview = platform.decode(withOrientation(jpeg, orientation))
assertEquals(oriented.width, preview.width)
assertEquals(oriented.height, preview.height)
val crop = PanelCrop(0f, 0f, .5f, 1f)
assertContentEquals(cropPanel(expected, crop).argb, cropPanel(oriented, crop).argb)
}
}
private fun withOrientation(jpeg: ByteArray, orientation: Int): ByteArray {
val payload = byteArrayOf(
'E'.code.toByte(), 'x'.code.toByte(), 'i'.code.toByte(), 'f'.code.toByte(), 0, 0,
'I'.code.toByte(), 'I'.code.toByte(), 42, 0, 8, 0, 0, 0,
1, 0, 0x12, 0x01, 3, 0, 1, 0, 0, 0, orientation.toByte(), 0, 0, 0,
0, 0, 0, 0,
)
val length = payload.size + 2
return jpeg.copyOfRange(0, 2) + byteArrayOf(0xff.toByte(), 0xe1.toByte(), (length shr 8).toByte(), length.toByte()) +
payload + jpeg.copyOfRange(2, jpeg.size)
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/colorization/LocalColorizationQueueDesktopTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines LocalColorizationQueueDesktopTest, completedJobSurvivesRestartWithoutRecoloringOrChangingSource, restartAndRetryReusesPageCheckpointAfterPackagingFailure, interruptedRunningMultiChapterJobAutoResumesAfterRestart, changedSourceAtSameLocatorBlocksResume, corruptPackagedArtifactWithSamePageCountBlocksSafely, publicationFailureCanRetryWithoutRecoloring, corruptPackageAfterCommittedPublicationFailureBlocksRetry, pausePersistsAcrossRestartAndOnlyExplicitResumePublishes, cancellationPersistsAcrossRestartAndRemovesOnlyIncompleteStage and 23 further declarations.
Read the setup, action and assertions in these cases before implementing their production paths:
completedJobSurvivesRestartWithoutRecoloringOrChangingSourcerestartAndRetryReusesPageCheckpointAfterPackagingFailureinterruptedRunningMultiChapterJobAutoResumesAfterRestartchangedSourceAtSameLocatorBlocksResumecorruptPackagedArtifactWithSamePageCountBlocksSafelypublicationFailureCanRetryWithoutRecoloringcorruptPackageAfterCommittedPublicationFailureBlocksRetrypausePersistsAcrossRestartAndOnlyExplicitResumePublishescancellationPersistsAcrossRestartAndRemovesOnlyIncompleteStage
Cross-chapter imports used by this file: DbChapter, DbManga, DbPageUrl, InMemoryYokanDatabase, seedDatabaseSnapshot, JvmLocalFileService. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.colorization
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.services.files.JvmLocalFileService
import eu.friedcutlet.yokan.services.files.LocalArchiveService
import eu.friedcutlet.yokan.services.library.LocalLibraryReconciliationResult
import eu.friedcutlet.yokan.services.library.LocalLibraryScanResult
import eu.friedcutlet.yokan.services.library.LocalLibraryService
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import java.io.File
import java.nio.file.Files
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import javax.imageio.ImageIO
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.async
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.flow.first
class LocalColorizationQueueDesktopTest {
@Test
fun completedJobSurvivesRestartWithoutRecoloringOrChangingSource() = runBlocking {
val root = Files.createTempDirectory("local-colorization-queue").toFile()
val files = JvmLocalFileService(File(root, "downloads").path, root.path, File(root, "cache").path)
val source = File(root, "source.png")
source.writeBytes(png())
val originalBytes = source.readBytes()
val platform = FakePlatform(png())
val colorizer = PanelColorizer(files, platform) { true }
colorizer.importModel("fixture")
val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
mangas = listOf(DbManga(id = 1, name = "A title", source = "local", isLocalArchive = true)),
chapters = listOf(DbChapter(id = 2, mangaId = 1, name = "Chapter 1", archivePath = "local/chapter.cbz")),
))
val archives = FakeArchives(source.absolutePath, files)
val library = FakeLibrary()
val firstScope = CoroutineScope(Dispatchers.Default)
try {
val first = LocalColorizationQueue(database, files, archives, colorizer, library, firstScope)
first.start()
val queued = first.enqueue(1)
awaitState(first, queued.id, ColorizationJobState.Completed)
assertEquals(1, platform.inferences)
assertContentEquals(originalBytes, source.readBytes())
assertEquals(1, library.scans)
first.close()
} finally {
firstScope.cancel()
}
val restartedScope = CoroutineScope(Dispatchers.Default)
try {
val malformedManifest = "${files.downloadRoot}/colorizer/jobs/malformed.json"
files.writeBytes(malformedManifest, "{broken".encodeToByteArray())
val restarted = LocalColorizationQueue(database, files, archives, colorizer, library, restartedScope)
restarted.start()
restarted.jobs.first { jobs -> jobs.any { it.state == ColorizationJobState.Completed } }
assertTrue(files.exists(malformedManifest), "Malformed manifests stay on disk for diagnosis")
assertEquals(1, platform.inferences)
assertContentEquals(originalBytes, source.readBytes())
} finally {
restartedScope.cancel()
root.deleteRecursively()
}
}
@Test
fun restartAndRetryReusesPageCheckpointAfterPackagingFailure() = runBlocking {
val root = Files.createTempDirectory("local-colorization-checkpoint").toFile()
val files = JvmLocalFileService(File(root, "downloads").path, root.path, File(root, "cache").path)
val source = File(root, "source.png").apply { writeBytes(png()) }
val platform = FakePlatform(png())
val colorizer = PanelColorizer(files, platform) { true }
colorizer.importModel("fixture")
val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
mangas = listOf(DbManga(id = 1, name = "A title", source = "local", isLocalArchive = true)),
chapters = listOf(DbChapter(id = 2, mangaId = 1, name = "Chapter 1", archivePath = "local/chapter.cbz")),
))
val archives = FakeArchives(source.absolutePath, files).apply { failPackaging = true }
val library = FakeLibrary()
val firstScope = CoroutineScope(Dispatchers.Default)
var jobId = ""
var checkpoint: File? = null
try {
val first = LocalColorizationQueue(database, files, archives, colorizer, library, firstScope)
first.start()
jobId = first.enqueue(1).id
checkpoint = File(root, "downloads/local/.colorizer-$jobId.partial/0001-Chapter 1/000001.png")
awaitState(first, jobId, ColorizationJobState.Blocked)
assertEquals(1, platform.inferences)
first.close()
} finally {
firstScope.cancel()
}
val restartedScope = CoroutineScope(Dispatchers.Default)
try {
val restarted = LocalColorizationQueue(database, files, archives, colorizer, library, restartedScope)
restarted.start()
restarted.jobs.first { jobs -> jobs.any { it.id == jobId } }
assertEquals(ColorizationJobState.Blocked, restarted.jobs.value.single { it.id == jobId }.state)
val missingCheckpoint = checkNotNull(checkpoint)
assertTrue(missingCheckpoint.delete())
archives.failPackaging = false
val repairBarrier = InferenceBarrier()
platform.inferenceBarrier = repairBarrier
restarted.retry(jobId)
assertTrue(repairBarrier.entered.await(5, TimeUnit.SECONDS))
assertEquals(0, restarted.jobs.value.single { it.id == jobId }.donePages)
repairBarrier.release.countDown()
awaitState(restarted, jobId, ColorizationJobState.Completed)
assertEquals(2, platform.inferences)
assertFalse(missingCheckpoint.exists(), "Temporary page directory is removed after packaging")
assertTrue(File(root, "downloads/local/A title-$jobId/0001-Chapter 1.cbz").isFile)
} finally {
platform.inferenceBarrier?.release?.countDown()
restartedScope.cancel()
root.deleteRecursively()
}
}
@Test
fun interruptedRunningMultiChapterJobAutoResumesAfterRestart() = runBlocking {
val root = Files.createTempDirectory("local-colorization-running-restart").toFile()
val files = JvmLocalFileService(File(root, "downloads").path, root.path, File(root, "cache").path)
val source = File(root, "source.png").apply { writeBytes(png()) }
val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
mangas = listOf(DbManga(id = 1, name = "A title", source = "local", isLocalArchive = true)),
chapters = listOf(
DbChapter(id = 2, mangaId = 1, name = "Chapter 1", archivePath = "local/chapter-1.cbz"),
DbChapter(id = 3, mangaId = 1, name = "Chapter 2", archivePath = "local/chapter-2.cbz"),
),
))
val barrier = PackagingBarrier()
val archives = FakeArchives(source.absolutePath, files, barrier)
val platform = FakePlatform(png())
val colorizer = PanelColorizer(files, platform) { true }
colorizer.importModel("fixture")
val firstScope = CoroutineScope(Dispatchers.Default)
var jobId = ""
try {
val first = LocalColorizationQueue(database, files, archives, colorizer, FakeLibrary(), firstScope)
first.start()
jobId = first.enqueue(1).id
assertTrue(barrier.entered.await(5, TimeUnit.SECONDS))
assertEquals(ColorizationJobState.Running, first.jobs.value.single { it.id == jobId }.state)
val children = firstScope.coroutineContext[Job]?.children?.toList().orEmpty()
firstScope.cancel()
barrier.release.countDown()
children.joinAll()
} finally {
barrier.release.countDown()
firstScope.cancel()
}
val restartedScope = CoroutineScope(Dispatchers.Default)
try {
val restarted = LocalColorizationQueue(database, files, archives, colorizer, FakeLibrary(), restartedScope)
restarted.start()
awaitState(restarted, jobId, ColorizationJobState.Completed)
val completed = restarted.jobs.value.single { it.id == jobId }
assertEquals(2, completed.totalPages)
assertEquals(2, completed.donePages)
assertEquals(2, platform.inferences, "The first checkpoint is reused; only the second chapter is inferred after restart")
} finally {
restartedScope.cancel()
root.deleteRecursively()
}
}
@Test
fun changedSourceAtSameLocatorBlocksResume() = runBlocking {
val root = Files.createTempDirectory("local-colorization-mutation").toFile()
val files = JvmLocalFileService(File(root, "downloads").path, root.path, File(root, "cache").path)
val source = File(root, "source.png").apply { writeBytes(png()) }
val original = source.readBytes()
val platform = FakePlatform(png())
val colorizer = PanelColorizer(files, platform) { true }
colorizer.importModel("fixture")
val database = localDatabase()
val archives = FakeArchives(source.absolutePath, files).apply { failPackaging = true }
val library = FakeLibrary()
val scope = CoroutineScope(Dispatchers.Default)
try {
val queue = LocalColorizationQueue(database, files, archives, colorizer, library, scope)
queue.start()
val id = queue.enqueue(1).id
awaitState(queue, id, ColorizationJobState.Blocked)
source.writeBytes(png(9))
archives.failPackaging = false
queue.retry(id)
awaitState(queue, id, ColorizationJobState.Blocked)
assertEquals(1, platform.inferences)
source.writeBytes(original)
} finally {
scope.cancel()
root.deleteRecursively()
}
}
@Test
fun corruptPackagedArtifactWithSamePageCountBlocksSafely() = runBlocking {
val root = Files.createTempDirectory("local-colorization-corrupt-cbz").toFile()
val files = JvmLocalFileService(File(root, "downloads").path, root.path, File(root, "cache").path)
val source = File(root, "source.png").apply { writeBytes(png()) }
val platform = FakePlatform(png())
val colorizer = PanelColorizer(files, platform) { true }
colorizer.importModel("fixture")
val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
mangas = listOf(DbManga(id = 1, name = "A title", source = "local", isLocalArchive = true)),
chapters = listOf(
DbChapter(id = 2, mangaId = 1, name = "Chapter 1", archivePath = "local/chapter-1.cbz"),
DbChapter(id = 3, mangaId = 1, name = "Chapter 2", archivePath = "local/chapter-2.cbz"),
),
))
val archives = FakeArchives(source.absolutePath, files).apply { failPackagingCall = 2 }
val firstScope = CoroutineScope(Dispatchers.Default)
var jobId = ""
try {
val queue = LocalColorizationQueue(database, files, archives, colorizer, FakeLibrary(), firstScope)
queue.start()
jobId = queue.enqueue(1).id
awaitState(queue, jobId, ColorizationJobState.Blocked)
} finally {
firstScope.cancel()
}
val artifact = File(root, "downloads/local/.colorizer-$jobId.partial/0001-Chapter 1.cbz")
val restartedScope = CoroutineScope(Dispatchers.Default)
try {
val queue = LocalColorizationQueue(database, files, archives, colorizer, FakeLibrary(), restartedScope)
queue.start()
queue.jobs.first { jobs -> jobs.any { it.id == jobId } }
assertEquals(ColorizationJobState.Blocked, queue.jobs.value.single { it.id == jobId }.state)
val packagedPage = File("${artifact.path}.pages/page-000001.png")
val bytes = packagedPage.readBytes()
bytes[0] = (bytes[0].toInt() xor 1).toByte()
packagedPage.writeBytes(bytes)
assertEquals(1, archives.listPagesStrict(artifact.path).size)
archives.failPackagingCall = null
queue.retry(jobId)
awaitState(queue, jobId, ColorizationJobState.Blocked)
assertEquals(2, platform.inferences)
} finally {
restartedScope.cancel()
root.deleteRecursively()
}
}
@Test
fun publicationFailureCanRetryWithoutRecoloring() = runBlocking {
val root = Files.createTempDirectory("local-colorization-publish-retry").toFile()
val files = JvmLocalFileService(File(root, "downloads").path, root.path, File(root, "cache").path)
val source = File(root, "source.png").apply { writeBytes(png()) }
val barrier = PackagingBarrier()
val archives = FakeArchives(source.absolutePath, files, barrier)
val platform = FakePlatform(png())
val colorizer = PanelColorizer(files, platform) { true }
colorizer.importModel("fixture")
val library = FakeLibrary()
val scope = CoroutineScope(Dispatchers.Default)
try {
val queue = LocalColorizationQueue(localDatabase(), files, archives, colorizer, library, scope)
queue.start()
val id = queue.enqueue(1).id
assertTrue(barrier.entered.await(5, TimeUnit.SECONDS))
val destination = File(root, "downloads/local/A title-$id").apply { mkdirs() }
File(destination, "foreign.txt").writeText("not this job")
barrier.release.countDown()
awaitState(queue, id, ColorizationJobState.Blocked)
assertEquals(1, platform.inferences)
destination.deleteRecursively()
val verificationBarrier = PackagingBarrier()
archives.strictBarrier = verificationBarrier
queue.retry(id)
assertTrue(verificationBarrier.entered.await(5, TimeUnit.SECONDS))
assertEquals(ColorizationJobState.Publishing, queue.jobs.value.single { it.id == id }.state)
assertEquals(null, queue.jobs.value.single { it.id == id }.error)
var pauseRejected = false
try { queue.pause(id) } catch (_: IllegalStateException) { pauseRejected = true }
var cancelRejected = false
try { queue.cancel(id) } catch (_: IllegalStateException) { cancelRejected = true }
assertTrue(pauseRejected)
assertTrue(cancelRejected)
verificationBarrier.release.countDown()
awaitState(queue, id, ColorizationJobState.Completed)
assertEquals(1, platform.inferences)
assertEquals(1, library.scans)
} finally {
barrier.release.countDown()
archives.strictBarrier?.release?.countDown()
scope.cancel()
root.deleteRecursively()
}
}
@Test
fun corruptPackageAfterCommittedPublicationFailureBlocksRetry() = runBlocking {
val root = Files.createTempDirectory("local-colorization-committed-corrupt").toFile()
val files = JvmLocalFileService(File(root, "downloads").path, root.path, File(root, "cache").path)
val source = File(root, "source.png").apply { writeBytes(png()) }
val barrier = PackagingBarrier()
val archives = FakeArchives(source.absolutePath, files, barrier)
val platform = FakePlatform(png())
val colorizer = PanelColorizer(files, platform) { true }
colorizer.importModel("fixture")
val scope = CoroutineScope(Dispatchers.Default)
try {
val queue = LocalColorizationQueue(localDatabase(), files, archives, colorizer, FakeLibrary(), scope)
queue.start()
val id = queue.enqueue(1).id
assertTrue(barrier.entered.await(5, TimeUnit.SECONDS))
val destination = File(root, "downloads/local/A title-$id").apply { mkdirs() }
File(destination, "foreign.txt").writeText("not this job")
barrier.release.countDown()
awaitState(queue, id, ColorizationJobState.Blocked)
val packageFile = File(root, "downloads/local/.colorizer-$id.partial/0001-Chapter 1.cbz")
val packagedPage = File("${packageFile.path}.pages/page-000001.png")
assertEquals(1, archives.listPagesStrict(packageFile.path).size)
packagedPage.writeBytes(png(9))
destination.deleteRecursively()
queue.retry(id)
awaitState(queue, id, ColorizationJobState.Blocked)
assertEquals(1, platform.inferences)
assertFalse(File(root, "downloads/local/A title-$id").exists())
} finally {
barrier.release.countDown()
scope.cancel()
root.deleteRecursively()
}
}
@Test
fun pausePersistsAcrossRestartAndOnlyExplicitResumePublishes() = runBlocking {
val root = Files.createTempDirectory("local-colorization-pause").toFile()
val files = JvmLocalFileService(File(root, "downloads").path, root.path, File(root, "cache").path)
val source = File(root, "source.png").apply { writeBytes(png()) }
val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
mangas = listOf(DbManga(id = 1, name = "A title", source = "local", isLocalArchive = true)),
chapters = listOf(DbChapter(id = 2, mangaId = 1, name = "Chapter 1", archivePath = "local/chapter.cbz")),
))
val barrier = PackagingBarrier()
val archives = FakeArchives(source.absolutePath, files, barrier)
val platform = FakePlatform(png())
val colorizer = PanelColorizer(files, platform) { true }
colorizer.importModel("fixture")
val library = FakeLibrary()
val firstScope = CoroutineScope(Dispatchers.Default)
var jobId = ""
try {
val first = LocalColorizationQueue(database, files, archives, colorizer, library, firstScope)
first.start()
jobId = first.enqueue(1).id
assertEquals(jobId, first.enqueue(1).id)
assertEquals(1, first.jobs.value.size)
assertTrue(barrier.entered.await(5, TimeUnit.SECONDS))
val pausing = async(Dispatchers.Default) { first.pause(jobId) }
first.jobs.first { jobs -> jobs.firstOrNull { it.id == jobId }?.state == ColorizationJobState.Paused }
barrier.release.countDown()
pausing.await()
assertEquals(1, platform.inferences)
first.close()
} finally {
barrier.release.countDown()
firstScope.cancel()
}
val finalPath = "${files.downloadRoot}/local/A title-$jobId"
val restartedScope = CoroutineScope(Dispatchers.Default)
try {
val restarted = LocalColorizationQueue(database, files, archives, colorizer, library, restartedScope)
restarted.start()
restarted.jobs.first { jobs -> jobs.firstOrNull { it.id == jobId }?.state == ColorizationJobState.Paused }
assertFalse(files.exists(finalPath))
assertEquals(0, library.scans)
restarted.resume(jobId)
awaitState(restarted, jobId, ColorizationJobState.Completed)
assertTrue(files.exists(finalPath))
assertEquals(1, library.scans)
} finally {
restartedScope.cancel()
root.deleteRecursively()
}
}
@Test
fun cancellationPersistsAcrossRestartAndRemovesOnlyIncompleteStage() = runBlocking {
val root = Files.createTempDirectory("local-colorization-cancel").toFile()
val files = JvmLocalFileService(File(root, "downloads").path, root.path, File(root, "cache").path)
val source = File(root, "source.png").apply { writeBytes(png()) }
val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
mangas = listOf(DbManga(id = 1, name = "A title", source = "local", isLocalArchive = true)),
chapters = listOf(DbChapter(id = 2, mangaId = 1, name = "Chapter 1", archivePath = "local/chapter.cbz")),
))
val barrier = PackagingBarrier()
val platform = FakePlatform(png())
val colorizer = PanelColorizer(files, platform) { true }
colorizer.importModel("fixture")
val archives = FakeArchives(source.absolutePath, files, barrier)
val library = FakeLibrary()
val firstScope = CoroutineScope(Dispatchers.Default)
var jobId = ""
try {
val first = LocalColorizationQueue(database, files, archives, colorizer, library, firstScope)
first.start()
jobId = first.enqueue(1).id
assertTrue(barrier.entered.await(5, TimeUnit.SECONDS))
val cancelling = async(Dispatchers.Default) { first.cancel(jobId) }
first.jobs.first { jobs -> jobs.firstOrNull { it.id == jobId }?.state == ColorizationJobState.Cancelled }
barrier.release.countDown()
cancelling.await()
first.close()
} finally {
barrier.release.countDown()
firstScope.cancel()
}
val stagePath = "${files.downloadRoot}/local/.colorizer-$jobId.partial"
val finalPath = "${files.downloadRoot}/local/A title-$jobId"
assertFalse(files.exists(stagePath))
val restartedScope = CoroutineScope(Dispatchers.Default)
try {
val restarted = LocalColorizationQueue(database, files, archives, colorizer, library, restartedScope)
restarted.start()
restarted.jobs.first { jobs -> jobs.firstOrNull { it.id == jobId }?.state == ColorizationJobState.Cancelled }
assertFalse(files.exists(stagePath))
assertFalse(files.exists(finalPath))
assertEquals(0, library.scans)
} finally {
restartedScope.cancel()
root.deleteRecursively()
}
}
private suspend fun awaitState(queue: LocalColorizationQueue, id: String, state: ColorizationJobState) {
withTimeout(10_000) {
queue.jobs.first { jobs ->
val job = jobs.firstOrNull { it.id == id }
if (job?.state == state) true else {
check(job?.state != ColorizationJobState.Blocked) { job?.error ?: "Colorization blocked." }
false
}
}
}
}
private fun png(): ByteArray = png(0)
private fun png(marker: Int): ByteArray = ByteArrayOutputStream().use { output ->
val image = BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB)
image.setRGB(0, 0, (marker * 0x010101) and 0xffffff)
ImageIO.write(image, "png", output)
image.flush()
output.toByteArray()
}
private fun localDatabase() = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
mangas = listOf(DbManga(id = 1, name = "A title", source = "local", isLocalArchive = true)),
chapters = listOf(DbChapter(id = 2, mangaId = 1, name = "Chapter 1", archivePath = "local/chapter.cbz")),
))
private class FakePlatform(private val png: ByteArray) : ColorizerPlatform {
var inferences = 0
@Volatile var inferenceBarrier: InferenceBarrier? = null
override fun readModel(path: String): ByteArray = byteArrayOf(1)
override fun decode(bytes: ByteArray) = PanelPixels(1, 1, intArrayOf(-1))
override fun decodeFullPage(bytes: ByteArray) = PanelPixels(1, 1, intArrayOf(-1))
override fun encode(image: PanelPixels): ByteArray = png
override fun infer(modelPath: String, input: PanelModelInput, verifiedModel: () -> ByteArray): FloatArray {
verifiedModel()
inferences += 1
inferenceBarrier?.blockOnce()
return FloatArray(3 * input.width * input.height)
}
}
private class FakeArchives(
private val sourcePath: String,
private val files: JvmLocalFileService,
private val packagingBarrier: PackagingBarrier? = null,
) : LocalArchiveService {
var failPackaging = false
var failPackagingCall: Int? = null
var strictBarrier: PackagingBarrier? = null
private var packagingCalls = 0
override fun listPages(archivePath: String): List<DbPageUrl> {
return listOf(DbPageUrl(File(sourcePath).toURI().toString(), "source.png"))
}
override fun listPagesStrict(archivePath: String): List<DbPageUrl> {
if (files.exists(archivePath)) {
strictBarrier?.blockOnce()
return files.listFiles("$archivePath.pages")
.filter { it.name.endsWith(".png", ignoreCase = true) }
.sortedBy { it.name }
.map { DbPageUrl(File(it.path).toURI().toString(), it.name) }
}
return listPages(archivePath)
}
override fun listEpubChapters(archivePath: String) = emptyList<eu.friedcutlet.yokan.services.files.LocalEpubChapter>()
override fun readEpubChapter(archivePath: String, index: Int): String = error("Not an EPUB")
override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? = null
override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String? {
packagingBarrier?.blockOnce()
packagingCalls += 1
if (failPackagingCall == packagingCalls) return null
if (failPackaging) return null
val cbzPath = "$directoryPath.cbz"
files.writeBytes(cbzPath, byteArrayOf(1))
files.listFiles(directoryPath)
.filter { it.name.endsWith(".png", ignoreCase = true) }
.sortedBy { it.name }
.forEachIndexed { index, entry ->
files.writeBytes(
"$cbzPath.pages/page-${(index + 1).toString().padStart(6, '0')}.png",
files.readBytesBounded(entry.path, 100_000_000L),
)
}
if (deleteSource) files.deleteRecursively(directoryPath)
return cbzPath
}
}
private class PackagingBarrier {
val entered = CountDownLatch(1)
val release = CountDownLatch(1)
private val pending = AtomicBoolean(true)
fun blockOnce() {
if (pending.compareAndSet(true, false)) {
entered.countDown()
check(release.await(10, TimeUnit.SECONDS)) { "Timed out waiting to release chapter packaging." }
}
}
}
private class InferenceBarrier {
val entered = CountDownLatch(1)
val release = CountDownLatch(1)
fun blockOnce() {
entered.countDown()
check(release.await(10, TimeUnit.SECONDS)) { "Timed out waiting to release inference." }
}
}
private class FakeLibrary : LocalLibraryService {
var scans = 0
override suspend fun scan() = LocalLibraryScanResult(0, 0, 0)
override suspend fun reconcile(): LocalLibraryReconciliationResult {
scans += 1
return LocalLibraryReconciliationResult()
}
override suspend fun importTorrent(pathOrMagnet: String, displayName: String?): Long? = null
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/colorization/LocalColorizationQueueFilesystemDesktopTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines LocalColorizationQueueFilesystemDesktopTest, realCbzAndLooseImagePublishScanAndRemainReadableAfterRestart, replacingSourceCbzAtSamePathBlocksCheckpointResume, awaitState, png, writeCbz, FilesystemFakePlatform, readModel, decode, decodeFullPage and 4 further declarations.
Read the setup, action and assertions in these cases before implementing their production paths:
realCbzAndLooseImagePublishScanAndRemainReadableAfterRestartreplacingSourceCbzAtSamePathBlocksCheckpointResume
Cross-chapter imports used by this file: InMemoryYokanDatabase, JvmLocalArchiveService, JvmLocalFileService, LocalArchiveService, DefaultLocalLibraryService, resolveConfiguredLocalArchivePath. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.colorization
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.services.files.JvmLocalArchiveService
import eu.friedcutlet.yokan.services.files.JvmLocalFileService
import eu.friedcutlet.yokan.services.files.LocalArchiveService
import eu.friedcutlet.yokan.services.library.DefaultLocalLibraryService
import eu.friedcutlet.yokan.services.files.resolveConfiguredLocalArchivePath
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import java.io.File
import java.nio.file.Files
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import javax.imageio.ImageIO
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
class LocalColorizationQueueFilesystemDesktopTest {
@Test
fun realCbzAndLooseImagePublishScanAndRemainReadableAfterRestart() = runBlocking {
val root = Files.createTempDirectory("local-colorization-filesystem").toFile()
val files = JvmLocalFileService(File(root, "downloads").path, root.path, File(root, "cache").path)
val archives = JvmLocalArchiveService(files.cacheRoot)
val database = InMemoryYokanDatabase()
val localLibrary = DefaultLocalLibraryService(database, files, archives)
val titleRoot = File(files.downloadRoot, "local/Source Book").apply { mkdirs() }
val sourceCbz = File(titleRoot, "Chapter One.cbz")
val firstPage = png(2)
val secondPage = png(3)
ZipOutputStream(sourceCbz.outputStream()).use { zip ->
listOf("page-1.png" to firstPage, "page-2.png" to secondPage).forEach { (name, bytes) ->
zip.putNextEntry(ZipEntry(name))
zip.write(bytes)
zip.closeEntry()
}
}
// Root-level images are intentionally reserved for title covers by the scanner; a
// loose-page chapter therefore lives in its own image directory.
val looseImage = File(titleRoot, "Loose Chapter/page.png").apply { parentFile.mkdirs() }
looseImage.writeBytes(png(4))
val originalArchive = sourceCbz.readBytes()
val originalLooseImage = looseImage.readBytes()
localLibrary.reconcile()
val source = database.mangas().single { it.name == "Source Book" }
val sourceChapters = database.chapters(source.id)
assertEquals(2, sourceChapters.size, "Scanner must index both the CBZ and loose image chapter")
val sourcePageCounts = sourceChapters.map { chapter ->
val path = resolveConfiguredLocalArchivePath(chapter.archivePath, files, database.settings())
if (path.substringBefore('#').substringAfterLast('.').equals("png", ignoreCase = true)) 1
else archives.listPagesStrict(path).size
}.sorted()
assertEquals(listOf(1, 2), sourcePageCounts, "Strict source inventory must retain both CBZ pages and the direct image")
val platform = FilesystemFakePlatform(png(2))
val colorizer = PanelColorizer(files, platform) { true }
colorizer.importModel("fixture")
val scope = CoroutineScope(Dispatchers.Default)
try {
val queue = LocalColorizationQueue(database, files, archives, colorizer, localLibrary, scope)
queue.start()
val job = queue.enqueue(source.id)
awaitState(queue, job.id, ColorizationJobState.Completed)
assertContentEquals(originalArchive, sourceCbz.readBytes())
assertContentEquals(originalLooseImage, looseImage.readBytes())
val completed = queue.jobs.value.single { it.id == job.id }
assertEquals(3, completed.totalPages, "Queue inventory must include every source page")
assertEquals(3, completed.donePages, "Every source page must be checkpointed")
val clone = database.mangas().single { it.name == "Source Book (Colorized)" }
val cloneChapters = database.chapters(clone.id)
assertEquals(2, cloneChapters.size)
val clonePages = cloneChapters.map { chapter ->
val path = resolveConfiguredLocalArchivePath(chapter.archivePath, files, database.settings())
archives.listPagesStrict(path).size
}.sorted()
assertEquals(listOf(1, 2), clonePages)
assertEquals(3, platform.inferences, "Every one of the three source pages must reach inference")
val restartedScope = CoroutineScope(Dispatchers.Default)
try {
val restarted = LocalColorizationQueue(database, files, archives, colorizer, localLibrary, restartedScope)
restarted.start()
restarted.jobs.first { jobs -> jobs.any { it.id == job.id && it.state == ColorizationJobState.Completed } }
assertEquals(3, platform.inferences)
assertEquals(2, database.chapters(clone.id).size)
} finally {
restartedScope.cancel()
}
} finally {
scope.cancel()
root.deleteRecursively()
}
}
@Test
fun replacingSourceCbzAtSamePathBlocksCheckpointResume() = runBlocking {
val root = Files.createTempDirectory("local-colorization-source-mutation").toFile()
val files = JvmLocalFileService(File(root, "downloads").path, root.path, File(root, "cache").path)
val actualArchives = JvmLocalArchiveService(files.cacheRoot)
val database = InMemoryYokanDatabase()
val localLibrary = DefaultLocalLibraryService(database, files, actualArchives)
val sourceCbz = File(files.downloadRoot, "local/Mutable Book/Chapter.cbz")
sourceCbz.parentFile.mkdirs()
writeCbz(sourceCbz, png(2))
localLibrary.reconcile()
val source = database.mangas().single { it.name == "Mutable Book" }
val archives = FailFirstPackageArchiveService(actualArchives)
val platform = FilesystemFakePlatform(png(2))
val colorizer = PanelColorizer(files, platform) { true }
colorizer.importModel("fixture")
val scope = CoroutineScope(Dispatchers.Default)
try {
val queue = LocalColorizationQueue(database, files, archives, colorizer, localLibrary, scope)
queue.start()
val job = queue.enqueue(source.id)
awaitState(queue, job.id, ColorizationJobState.Blocked)
writeCbz(sourceCbz, png(9))
queue.retry(job.id)
awaitState(queue, job.id, ColorizationJobState.Blocked)
assertEquals(1, platform.inferences)
assertTrue(queue.jobs.value.single { it.id == job.id }.error.orEmpty().contains("changed", ignoreCase = true))
} finally {
scope.cancel()
root.deleteRecursively()
}
}
private suspend fun awaitState(queue: LocalColorizationQueue, id: String, state: ColorizationJobState) {
withTimeout(15_000) {
queue.jobs.first { jobs -> jobs.firstOrNull { it.id == id }?.state == state }
}
}
private fun png(marker: Int): ByteArray = ByteArrayOutputStream().use { output ->
val image = BufferedImage(2, 2, BufferedImage.TYPE_INT_RGB)
image.setRGB(0, 0, marker shl 16)
ImageIO.write(image, "png", output)
image.flush()
output.toByteArray()
}
private fun writeCbz(file: File, image: ByteArray) {
ZipOutputStream(file.outputStream()).use { zip ->
zip.putNextEntry(ZipEntry("page.png"))
zip.write(image)
zip.closeEntry()
}
}
private class FilesystemFakePlatform(private val outputPng: ByteArray) : ColorizerPlatform {
var inferences = 0
override fun readModel(path: String) = byteArrayOf(1)
override fun decode(bytes: ByteArray) = PanelPixels(2, 2, IntArray(4) { -1 })
override fun decodeFullPage(bytes: ByteArray) = PanelPixels(2, 2, IntArray(4) { -1 })
override fun encode(image: PanelPixels) = outputPng
override fun infer(modelPath: String, input: PanelModelInput, verifiedModel: () -> ByteArray): FloatArray {
verifiedModel()
inferences += 1
return FloatArray(3 * input.width * input.height)
}
}
private class FailFirstPackageArchiveService(private val delegate: LocalArchiveService) : LocalArchiveService by delegate {
private var failNextPackage = true
override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String? {
if (failNextPackage) {
failNextPackage = false
return null
}
return delegate.zipDirectoryToCbz(directoryPath, deleteSource)
}
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/colorization/PanelColorizerDesktopTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines PanelColorizerDesktopTest, readModel, decode, decodeFullPage, encode, infer.
Read the setup, action and assertions in these cases before implementing their production paths:
downsamplesBeforeAllocatingFullImageAndWritesValidPngfullPageDecoderRejectsOversizedPagesWithoutDownsamplingboundedModelReaderRejectsTruncatedInputcancelledNativeJobFinishesBeforeAnotherSessionCanStartrealPinnedModelColorsAndReleasesRepeatedSessions
Cross-chapter imports used by this file: JvmLocalFileService. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.services.colorization
import eu.friedcutlet.yokan.services.files.JvmLocalFileService
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import java.io.File
import java.nio.file.Files
import javax.imageio.ImageIO
import kotlin.test.*
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.CancellationException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import org.junit.Assume.assumeTrue
class PanelColorizerDesktopTest {
@Test fun downsamplesBeforeAllocatingFullImageAndWritesValidPng() {
val image = BufferedImage(3201, 100, BufferedImage.TYPE_INT_RGB)
val bytes = ByteArrayOutputStream().use { ImageIO.write(image, "png", it); it.toByteArray() }
image.flush()
val platform = createColorizerPlatform()
val decoded = platform.decode(bytes)
assertTrue(decoded.width <= 1600 && decoded.height <= 1600)
assertEquals(decoded.width, ImageIO.read(platform.encode(decoded).inputStream()).width)
}
@Test fun fullPageDecoderRejectsOversizedPagesWithoutDownsampling() {
val image = BufferedImage(4097, 1, BufferedImage.TYPE_INT_RGB)
val bytes = ByteArrayOutputStream().use { ImageIO.write(image, "png", it); it.toByteArray() }
image.flush()
assertFailsWith<IllegalArgumentException> { createColorizerPlatform().decodeFullPage(bytes) }
}
@Test fun boundedModelReaderRejectsTruncatedInput() {
assertFailsWith<IllegalArgumentException> { readBoundedModel(byteArrayOf(1, 2).inputStream()) }
}
@Test fun cancelledNativeJobFinishesBeforeAnotherSessionCanStart() = runBlocking {
val root = Files.createTempDirectory("yokan-colorizer-cancel").toFile()
val started = CountDownLatch(1)
val release = CountDownLatch(1)
val active = AtomicInteger()
val peak = AtomicInteger()
val calls = AtomicInteger()
val platform = object : ColorizerPlatform {
override fun readModel(path: String) = byteArrayOf(1)
override fun decode(bytes: ByteArray) = PanelPixels(1, 1, intArrayOf(-1))
override fun decodeFullPage(bytes: ByteArray) = PanelPixels(1, 1, intArrayOf(-1))
override fun encode(image: PanelPixels) = byteArrayOf(1)
override fun infer(modelPath: String, input: PanelModelInput, verifiedModel: () -> ByteArray): FloatArray {
val concurrent = active.incrementAndGet()
peak.updateAndGet { maxOf(it, concurrent) }
try {
if (calls.incrementAndGet() == 1) {
started.countDown()
check(release.await(5, TimeUnit.SECONDS))
}
return FloatArray(3 * input.width * input.height)
} finally { active.decrementAndGet() }
}
}
try {
val colorizer = PanelColorizer(JvmLocalFileService(root.path, root.path, root.path), platform) { true }
colorizer.importModel("fixture")
val first = async { colorizer.colorize(byteArrayOf(1), PanelCrop()) }
// Give async a chance to dispatch the blocking native work.
withTimeout(5_000) { while (started.count > 0) delay(1) }
first.cancel()
val second = async { colorizer.colorize(byteArrayOf(1), PanelCrop()) }
delay(30)
assertEquals(1, calls.get())
release.countDown()
assertFailsWith<CancellationException> { first.await() }
assertContentEquals(byteArrayOf(1), second.await())
assertEquals(1, peak.get())
assertEquals(0, active.get())
} finally { release.countDown(); root.deleteRecursively() }
}
@Test fun realPinnedModelColorsAndReleasesRepeatedSessions() = runBlocking {
val modelPath = System.getenv("YOKAN_COLORIZER_TEST_MODEL")
val imagePath = System.getenv("YOKAN_COLORIZER_TEST_IMAGE")
assumeTrue("Set YOKAN_COLORIZER_TEST_MODEL and YOKAN_COLORIZER_TEST_IMAGE for real inference", modelPath != null && imagePath != null)
val root = Files.createTempDirectory("yokan-colorizer-test").toFile()
try {
val files = JvmLocalFileService(root.path, root.path, root.path)
val colorizer = PanelColorizer(files, createColorizerPlatform())
colorizer.importModel(checkNotNull(modelPath))
val source = File(checkNotNull(imagePath)).readBytes()
repeat(2) {
val png = colorizer.colorize(source, PanelCrop(0f, 0f, .5f, .5f))
val image = ImageIO.read(png.inputStream())
assertTrue(image.width > 0 && image.width <= 1600)
assertTrue(image.height > 0 && image.height <= 1600)
val colors = image.getRGB(0, 0, image.width, image.height, null, 0, image.width)
assertTrue(colors.any { (it ushr 16 and 255) != (it and 255) })
image.flush()
File("build/reports/colorizer/panel-$it.png").apply { parentFile.mkdirs(); writeBytes(png) }
}
colorizer.removeModel()
assertFalse(colorizer.installed())
} finally { root.deleteRecursively() }
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ImageSharingDesktopTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines ImageSharingDesktopTest, savesResolvedImageInUserVisiblePicturesDirectory.
Read the setup, action and assertions in these cases before implementing their production paths:
savesResolvedImageInUserVisiblePicturesDirectory
Cross-chapter imports used by this file: Chapter, Manga. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Manga
import java.nio.file.Files
import kotlin.io.path.createTempDirectory
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
class ImageSharingDesktopTest {
@Test
fun savesResolvedImageInUserVisiblePicturesDirectory() = runTest {
val previousHome = System.getProperty("user.home")
val temporaryHome = createTempDirectory("yokan-image-save")
try {
System.setProperty("user.home", temporaryHome.toString())
val bytes = byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47)
assertTrue(saveImageToGallery(bytes, "Manga Chapter - 1.png", "image/png", folder = null))
assertTrue(saveImageToGallery(bytes, "Manga Chapter - 2.png", "image/png", folder = readerImageFolderName("Manga: Part/2")))
val saved = temporaryHome.resolve("Pictures/Yokan/Manga_Chapter_-_1.png")
assertTrue(Files.exists(saved))
assertContentEquals(bytes, Files.readAllBytes(saved))
assertContentEquals(bytes, Files.readAllBytes(temporaryHome.resolve("Pictures/Yokan/Manga_ Part_2/Manga_Chapter_-_2.png")))
} finally {
System.setProperty("user.home", previousHome)
temporaryHome.toFile().deleteRecursively()
}
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/PanelColorizerRenderTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines PanelColorizerRenderTest, ui.
Read the setup, action and assertions in these cases before implementing their production paths:
rendersModelSetupSelectionResultAndBusyStatesAtPhoneAndDesktopWidths
Cross-chapter imports used by this file: DbPageUrl, Chapter, YokanTheme. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.use
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.compose.LocalLifecycleOwner
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.services.colorization.PanelCrop
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.ui.theme.YokanTheme
import java.awt.Color
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import java.io.File
import java.util.concurrent.FutureTask
import javax.imageio.ImageIO
import javax.swing.SwingUtilities
import kotlin.test.Test
class PanelColorizerRenderTest {
@Test fun rendersModelSetupSelectionResultAndBusyStatesAtPhoneAndDesktopWidths() {
val picture = BufferedImage(480, 640, BufferedImage.TYPE_INT_RGB)
picture.createGraphics().apply {
color = Color.WHITE; fillRect(0, 0, 480, 640)
color = Color.LIGHT_GRAY; fillRect(20, 20, 440, 285); fillRect(20, 330, 440, 285)
color = Color.BLACK; drawRect(20, 20, 440, 285); drawRect(20, 330, 440, 285)
dispose()
}
val bytes = ByteArrayOutputStream().use { ImageIO.write(picture, "png", it); it.toByteArray() }
picture.flush()
val item = ReaderStreamItem.Page(Chapter(1, 1, "Chapter", "/chapter"), DbPageUrl("fixture"), 0)
val target = ResolvedReaderImage(item, item.page, bytes, bytes, "page.png", "page.png", "image/png")
val states = listOf(
"setup" to ReaderColorizerState(open = true, supported = true),
"select" to ReaderColorizerState(open = true, supported = true, modelInstalled = true, crop = PanelCrop(.04f, .03f, .96f, .48f)),
"result" to ReaderColorizerState(open = true, supported = true, modelInstalled = true, preview = bytes, hasAppliedColorization = true),
"busy" to ReaderColorizerState(open = true, supported = true, modelInstalled = true, work = ColorizerWork.Colorizing, hasAppliedColorization = true),
)
for (width in listOf(360, 900)) for ((name, state) in states) {
val owner = object : LifecycleOwner { override val lifecycle = LifecycleRegistry.createUnsafe(this) }
ui { owner.lifecycle.currentState = Lifecycle.State.RESUMED }
val scene = ui { ImageComposeScene(width, 900) {
CompositionLocalProvider(LocalLifecycleOwner provides owner) {
YokanTheme(darkTheme = width == 360) { PanelColorizerSheet(target, state) {} }
}
} }
try {
repeat(16) { frame -> ui { scene.render(frame * 100_000_000L).close() } }
ui { scene.render(1_700_000_000L).use { image ->
checkNotNull(image.encodeToData()).use { data ->
File("build/reports/colorizer/ui-$name-$width.png").apply { parentFile.mkdirs(); writeBytes(data.bytes) }
}
} }
} finally {
ui { scene.close(); owner.lifecycle.currentState = Lifecycle.State.DESTROYED }
}
}
}
private fun <T> ui(block: () -> T): T {
val task = FutureTask<T> { block() }
SwingUtilities.invokeAndWait(task)
return task.get()
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderHoldScrollGestureTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines ReaderHoldScrollGestureTest, fixture, Fixture, press, move, release, secondPointer, pinch, event, advance and 2 further declarations.
Read the setup, action and assertions in these cases before implementing their production paths:
holdDragAndReleaseDoNotFireTapOrImageActionstapsDoubleTapsAndSwipesRemainSeparateFromHoldingsecondPointerCancelsBeforeAndAfterOwnershipdisablingCancelsTheHeldPointerAndDisabledLongPressStillOpensImageshorizontalHoldUsesTheReadingAxisInBothDirectionspinchZoomWinsBeforeHoldAndCancelsAnActiveHold
Cross-chapter imports used by this file: DbReaderMode. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.ui.unit.IntSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.ui.unit.dp
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.InternalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.PointerId
import androidx.compose.ui.input.pointer.PointerType
import androidx.compose.ui.scene.ComposeScenePointer
import eu.friedcutlet.yokan.database.DbReaderMode
import java.util.concurrent.FutureTask
import javax.swing.SwingUtilities
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestCoroutineScheduler
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
// Multi-pointer ComposeScenePointer events (pinch) are InternalComposeUiApi since Compose 1.12.
@OptIn(ExperimentalCoroutinesApi::class, ExperimentalComposeUiApi::class, InternalComposeUiApi::class)
class ReaderHoldScrollGestureTest {
@Test fun holdDragAndReleaseDoNotFireTapOrImageActions() = fixture { f ->
f.press()
f.advance(600)
assertEquals(1, f.starts.size)
f.move(Offset(100f, 40f))
assertEquals(60f, f.distances.last())
f.release(Offset(100f, 40f))
f.advance(350)
assertEquals(f.starts, f.stops)
assertEquals(0, f.taps)
assertEquals(0, f.doubleTaps)
assertEquals(0, f.images)
}
@Test fun tapsDoubleTapsAndSwipesRemainSeparateFromHolding() = fixture { f ->
f.press(); f.release(); f.advance(350)
assertEquals(1, f.taps)
f.press(); f.release(); f.advance(80); f.press(); f.release(); f.advance(350)
assertEquals(1, f.doubleTaps)
assertEquals(1, f.taps)
f.press(); f.move(Offset(100f, 20f)); f.advance(600); f.release(Offset(100f, 20f)); f.advance(350)
assertTrue(f.starts.isEmpty())
assertEquals(1, f.taps)
assertEquals(0, f.images)
}
@Test fun secondPointerCancelsBeforeAndAfterOwnership() = fixture { f ->
f.press(); f.secondPointer(true); f.advance(600)
assertTrue(f.starts.isEmpty())
f.secondPointer(false); f.release(); f.advance(350)
f.press(); f.advance(600)
assertEquals(1, f.starts.size)
f.secondPointer(true)
assertEquals(f.starts, f.stops)
f.secondPointer(false); f.release(); f.advance(350)
assertEquals(0, f.images)
}
@Test fun disablingCancelsTheHeldPointerAndDisabledLongPressStillOpensImages() = fixture { f ->
f.press(); f.advance(600)
ui { f.enabled.value = false }
f.advance(1)
assertEquals(f.starts, f.stops)
f.release(); f.advance(350)
f.press(); f.advance(600)
assertEquals(1, f.images)
f.release(); f.advance(350)
assertEquals(1, f.starts.size)
}
@Test fun horizontalHoldUsesTheReadingAxisInBothDirections() {
for (mode in listOf(DbReaderMode.HorizontalContinuous, DbReaderMode.HorizontalContinuousRtl)) fixture(mode) { f ->
f.press(); f.advance(600)
assertEquals(1, f.starts.size)
val x = if (mode.isRightToLeft()) 160f else 40f
f.move(Offset(x, 100f))
assertEquals(60f, f.distances.last())
f.release(); f.advance(350)
assertEquals(f.starts, f.stops)
assertEquals(0, f.taps)
}
}
@Test fun pinchZoomWinsBeforeHoldAndCancelsAnActiveHold() {
fixture { f ->
f.press(); f.secondPointer(true); f.pinch(); f.advance(600)
assertTrue(f.zoom.scale > 1f)
assertTrue(f.starts.isEmpty())
f.secondPointer(false); f.release(); f.advance(350)
assertEquals(0, f.taps)
assertEquals(0, f.images)
}
fixture { f ->
f.press(); f.advance(600); f.secondPointer(true); f.pinch(); f.advance(1)
assertTrue(f.zoom.scale > 1f)
assertEquals(f.starts, f.stops)
f.secondPointer(false); f.release(); f.advance(350)
assertEquals(0, f.taps)
assertEquals(0, f.images)
}
}
private fun fixture(mode: DbReaderMode = DbReaderMode.Webtoon, test: (Fixture) -> Unit) {
val f = Fixture(mode)
try { f.advance(1); test(f) } finally { ui { f.scene.close() } }
}
private class Fixture(val mode: DbReaderMode) {
val scheduler = TestCoroutineScheduler()
val enabled = mutableStateOf(true)
val starts = mutableListOf<Long>()
val stops = mutableListOf<Long>()
val distances = mutableListOf<Float>()
var taps = 0
var doubleTaps = 0
var images = 0
val zoom = ReaderZoomState().apply { updateViewport(IntSize(300, 400)) }
val scene = ui {
ImageComposeScene(300, 300, coroutineContext = UnconfinedTestDispatcher(scheduler)) {
Box(Modifier.fillMaxSize()
.readerTapZones(TapNavLayout.Disabled, false, false, false,
onToggleChrome = { taps++ }, onPreviousPage = {}, onNextPage = {},
onDoubleTap = { _, _ -> doubleTaps++ }, onLongPress = { _, _ -> images++ },
longPressImageActions = !enabled.value || zoom.scale > 1.01f)
.readerHoldScroll(enabled.value && zoom.scale <= 1.01f, mode, ReaderViewport(300, 300), 1f,
canStart = { true }, onStart = { starts += it }, onSpeed = { _, distance -> distances += distance }, onStop = { stops += it })) {
if (mode.isHorizontalContinuous()) LazyRow(Modifier.fillMaxSize(), reverseLayout = mode.isRightToLeft()) {
items(10, key = { it }) { Box(Modifier.width(400.dp).fillMaxSize().readerZoomGestures(zoom)) }
} else LazyColumn(Modifier.fillMaxSize()) {
items(10, key = { it }) { Box(Modifier.height(400.dp).fillMaxSize().readerZoomGestures(zoom)) }
}
}
}
}
private var position = Offset(100f, 100f)
fun press() { position = Offset(100f, 100f); event(PointerEventType.Press, true) }
fun move(at: Offset) { position = at; event(PointerEventType.Move, true) }
fun release(at: Offset = position) { position = at; event(PointerEventType.Release, false) }
fun secondPointer(pressed: Boolean) = ui {
scene.sendPointerEvent(if (pressed) PointerEventType.Press else PointerEventType.Release,
pointers = listOf(pointer(1, position, true), pointer(2, Offset(200f, 100f), pressed)),
timeMillis = scheduler.currentTime)
}
fun pinch() = ui {
scene.sendPointerEvent(PointerEventType.Move,
pointers = listOf(pointer(1, Offset(60f, 100f), true), pointer(2, Offset(240f, 100f), true)),
timeMillis = scheduler.currentTime)
}
private fun event(type: PointerEventType, pressed: Boolean) = ui {
scene.sendPointerEvent(type, pointers = listOf(pointer(1, position, pressed)), timeMillis = scheduler.currentTime)
}
fun advance(ms: Long) = ui {
scheduler.advanceTimeBy(ms)
scheduler.runCurrent()
scene.render(scheduler.currentTime * 1_000_000).close()
}
private fun pointer(id: Long, at: Offset, pressed: Boolean) =
ComposeScenePointer(PointerId(id), at, pressed, PointerType.Touch)
}
companion object {
private fun <T> ui(block: () -> T): T {
val task = FutureTask<T> { block() }
SwingUtilities.invokeAndWait(task)
return task.get()
}
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderScrollDriverTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines ReaderScrollDriverTest, fixture, Fixture, frames, position, ui.
Read the setup, action and assertions in these cases before implementing their production paths:
speedUpdatesUseOneControllerAndPauseStopsTheNextFrameloadingBoundaryWaitsForExtentAndConfirmedEndFinishesOncehorizontalRtlScrollsForwardInLogicalOrder
package eu.friedcutlet.yokan.ui.screens.reader
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import java.util.concurrent.FutureTask
import javax.swing.SwingUtilities
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestCoroutineScheduler
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
@OptIn(ExperimentalCoroutinesApi::class)
class ReaderScrollDriverTest {
@Test fun speedUpdatesUseOneControllerAndPauseStopsTheNextFrame() = fixture { f ->
ui { f.count.value = 20 }
f.frames(65)
val slow = f.position()
assertTrue(slow in 40..60, "Saved speed should retain approximately 50 pixels/second: $slow")
ui { f.speed.value = 60f }
f.frames(65)
assertTrue(f.position() - slow > 250, "Transient speed should update without resetting progress")
ui { f.playing.value = false }
f.frames(1)
val stopped = f.position()
f.frames(20)
assertEquals(stopped, f.position())
assertEquals(0, f.finished)
}
@Test fun loadingBoundaryWaitsForExtentAndConfirmedEndFinishesOnce() = fixture { f ->
f.frames(8)
assertEquals(0, f.position())
assertEquals(0, f.finished)
ui { f.count.value = 5 }
f.frames(65)
assertTrue(f.position() > 30)
ui { f.terminal.value = true; f.list.requestScrollToItem(4) }
f.frames(8)
assertEquals(1, f.finished)
assertEquals(false, f.playing.value)
f.frames(20)
assertEquals(1, f.finished)
}
@Test fun horizontalRtlScrollsForwardInLogicalOrder() = fixture(horizontalRtl = true) { f ->
ui { f.count.value = 20 }
f.frames(65)
assertTrue(f.position() in 40..60)
ui { f.speed.value = 60f }
f.frames(65)
assertTrue(f.position() > 300)
assertEquals(0, f.finished)
}
private fun fixture(horizontalRtl: Boolean = false, test: (Fixture) -> Unit) {
val f = Fixture(horizontalRtl)
try { f.frames(2); test(f) } finally { ui { f.scene.close() } }
}
private class Fixture(val horizontalRtl: Boolean) {
val scheduler = TestCoroutineScheduler()
val count = mutableStateOf(1)
val playing = mutableStateOf(true)
val speed = mutableStateOf(10f)
val terminal = mutableStateOf(false)
var finished = 0
lateinit var list: LazyListState
val scene = ui {
ImageComposeScene(300, 300, coroutineContext = UnconfinedTestDispatcher(scheduler)) {
list = rememberLazyListState()
if (horizontalRtl) LazyRow(Modifier.fillMaxSize(), state = list, reverseLayout = true) {
items(count.value, key = { it }) { Box(Modifier.width(200.dp)) }
} else LazyColumn(Modifier.fillMaxSize(), state = list) {
items(count.value, key = { it }) { Box(Modifier.height(200.dp)) }
}
DriveAutoScroll(list, playing.value, speed.value, terminal.value) { finished++; playing.value = false }
}
}
fun frames(count: Int) = ui {
repeat(count) {
scheduler.advanceTimeBy(16)
scheduler.runCurrent()
scene.render(scheduler.currentTime * 1_000_000).close()
}
}
fun position() = ui { list.firstVisibleItemIndex * 200 + list.firstVisibleItemScrollOffset }
}
companion object {
private fun <T> ui(block: () -> T): T {
val task = FutureTask<T> { block() }
SwingUtilities.invokeAndWait(task)
return task.get()
}
}
}
Write composeApp/src/iosTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/IosReaderSystemUiTest.kt
Create this path in your reconstruction project. Source set: iosTest. Exact file download.
The implementation below defines IosReaderSystemUiTest, fullscreenPreferenceReachesHostAndResetRestoresChrome.
Read the setup, action and assertions in these cases before implementing their production paths:
fullscreenPreferenceReachesHostAndResetRestoresChrome
package eu.friedcutlet.yokan.ui.screens.reader
import kotlin.test.Test
import kotlin.test.assertEquals
class IosReaderSystemUiTest {
@Test
fun fullscreenPreferenceReachesHostAndResetRestoresChrome() {
val observed = mutableListOf<Boolean>()
IosReaderSystemUiBridge.register(observed::add)
try {
val controller = createReaderSystemUiController()
controller.apply(ReaderSystemUiPreferences(fullscreen = true, keepScreenOn = false))
controller.reset()
assertEquals(listOf(false, true, false), observed)
} finally {
IosReaderSystemUiBridge.unregister()
}
}
}
Write composeApp/src/jvmCommonTest/kotlin/eu/friedcutlet/yokan/services/colorization/ModelSessionCacheTest.kt
Create this path in your reconstruction project. Source set: jvmCommonTest. Exact file download.
The implementation below defines ModelSessionCacheTest, Session, close, keepsOneVerifiedSessionUntilIdleOrReleased.
Read the setup, action and assertions in these cases before implementing their production paths:
keepsOneVerifiedSessionUntilIdleOrReleased
package eu.friedcutlet.yokan.services.colorization
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runTest
class ModelSessionCacheTest {
private class Session : AutoCloseable {
var closed = false
override fun close() { closed = true }
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun keepsOneVerifiedSessionUntilIdleOrReleased() = runTest {
val sessions = mutableListOf<Session>()
var loads = 0
val loadModel = { loads++; byteArrayOf(1) }
val cache = ModelSessionCache(backgroundScope, idleTimeout = 1.minutes) { Session().also(sessions::add) }
repeat(2) { cache.use("model", loadModel) {} }
assertEquals(1, loads)
assertEquals(1, sessions.size)
// Each use restarts the idle clock.
advanceTimeBy(59.seconds)
cache.use("model", loadModel) {}
advanceTimeBy(59.seconds)
assertFalse(sessions[0].closed)
advanceTimeBy(2.seconds)
assertTrue(sessions[0].closed)
// Closed sessions reload, so the model is read and verified again.
cache.use("model", loadModel) {}
assertEquals(2, loads)
cache.release()
assertTrue(sessions[1].closed)
}
}
Write composeApp/src/skikoTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/BorderCropTransformationTest.kt
Create this path in your reconstruction project. Source set: skikoTest. Exact file download.
The implementation below defines BorderCropTransformationTest, transformationReturnsDetectedContentSubset.
Read the setup, action and assertions in these cases before implementing their production paths:
transformationReturnsDetectedContentSubset
package eu.friedcutlet.yokan.ui.screens.reader
import coil3.size.Size
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlinx.coroutines.test.runTest
import org.jetbrains.skia.Bitmap
import org.jetbrains.skia.IRect
class BorderCropTransformationTest {
@Test
fun transformationReturnsDetectedContentSubset() = runTest {
val input = Bitmap().apply {
check(allocN32Pixels(5, 4))
erase(0xFFFFFFFF.toInt())
erase(0xFF808080.toInt(), IRect.makeXYWH(1, 1, 3, 2))
}
val result = createBorderCropTransformation().transform(input, Size.ORIGINAL)
assertEquals(3, result.width)
assertEquals(2, result.height)
assertEquals(0xFF808080.toInt(), result.getColor(0, 0))
}
}
Write composeApp/src/skikoTest/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderPageProcessingSkiaTest.kt
Create this path in your reconstruction project. Source set: skikoTest. Exact file download.
The implementation below defines ReaderPageProcessingSkiaTest, halvesKeepTheRequestedSideOfASpread, rotationTurnsOnlyLandscapePagesInTheChosenDirection, spreadMergeScalesToTheTallerPageAndKeepsSides, bitmap, png, Int.isMostly.
Read the setup, action and assertions in these cases before implementing their production paths:
halvesKeepTheRequestedSideOfASpreadrotationTurnsOnlyLandscapePagesInTheChosenDirectionspreadMergeScalesToTheTallerPageAndKeepsSides
package eu.friedcutlet.yokan.ui.screens.reader
import coil3.size.Size
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import org.jetbrains.skia.Bitmap
import org.jetbrains.skia.EncodedImageFormat
import org.jetbrains.skia.IRect
import org.jetbrains.skia.Image
import org.jetbrains.skia.Surface
class ReaderPageProcessingSkiaTest {
private val red = 0xFFFF0000.toInt()
private val blue = 0xFF0000FF.toInt()
private val white = 0xFFFFFFFF.toInt()
@Test
fun halvesKeepTheRequestedSideOfASpread() = runTest {
val spread = bitmap(4, 2, white).apply {
erase(red, IRect.makeXYWH(0, 0, 2, 2))
erase(blue, IRect.makeXYWH(2, 0, 2, 2))
}
val left = createPageHalfTransformation(left = true).transform(spread, Size.ORIGINAL)
val right = createPageHalfTransformation(left = false).transform(spread, Size.ORIGINAL)
assertEquals(2 to 2, left.width to left.height)
assertEquals(red, left.getColor(1, 1))
assertEquals(blue, right.getColor(0, 0))
}
@Test
fun rotationTurnsOnlyLandscapePagesInTheChosenDirection() = runTest {
val landscape = bitmap(4, 2, white).apply { erase(red, IRect.makeXYWH(0, 0, 1, 1)) }
val clockwise = createWidePageRotation(90).transform(landscape, Size.ORIGINAL)
val counter = createWidePageRotation(-90).transform(landscape, Size.ORIGINAL)
assertEquals(2 to 4, clockwise.width to clockwise.height)
assertEquals(red, clockwise.getColor(1, 0))
assertEquals(red, counter.getColor(0, 3))
val portrait = bitmap(2, 4, white)
assertSame(portrait, createWidePageRotation(90).transform(portrait, Size.ORIGINAL))
}
@Test
fun spreadMergeScalesToTheTallerPageAndKeepsSides() = runTest {
val merged = assertNotNull(mergeSpreadImages(png(10, 20, red), png(20, 40, blue)))
val image = Image.makeFromEncoded(merged)
assertEquals(40 to 40, image.width to image.height)
val pixels = Bitmap().apply { check(allocN32Pixels(40, 40)) }
assertTrue(image.readPixels(pixels, 0, 0))
assertTrue(pixels.getColor(5, 20).isMostly(red))
assertTrue(pixels.getColor(35, 20).isMostly(blue))
assertNull(mergeSpreadImages(byteArrayOf(1, 2, 3), png(2, 2, red)))
}
private fun bitmap(width: Int, height: Int, color: Int) = Bitmap().apply {
check(allocN32Pixels(width, height))
erase(color)
}
private fun png(width: Int, height: Int, color: Int): ByteArray {
val surface = Surface.makeRasterN32Premul(width, height)
surface.canvas.clear(color)
return surface.makeImageSnapshot().encodeToData(EncodedImageFormat.PNG)!!.bytes
}
private fun Int.isMostly(color: Int): Boolean =
listOf(16, 8, 0).all { shift -> kotlin.math.abs((this shr shift and 0xFF) - (color shr shift and 0xFF)) < 24 }
}
Completion record
- [ ] Every implementation/configuration and required asset shown above is present at its displayed path.
- [ ] Cross-chapter imports resolve against the intended contracts and platform source sets.
- [ ] The tests for this chapter pass in the rebuilt app; record the command, platform and result.
- [ ] Native, device, browser and live-service checks have evidence or an explicit “not run” entry. [chapter-content-end]: #
Gate: page/resume positions survive chapter changes, process restart and profile retirement; continuous streams keep visible leases; headers reach both online and cached reads; gesture and processing tests pass. Run rendering/gesture tests and actual large/rotated/AVIF/tall page samples on each platform.