Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions app/src/main/java/com/kmworks/kmreader/core/epub/EpubBookPages.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package com.kmworks.kmreader.core.epub

import kotlin.math.roundToInt

/**
* Where the reader sits in the whole book, counted in pages (mirrors the iOS
* `EpubBookPageProgress`: a value type carrying `currentPage` / `totalPages`).
*
* The pages are the reader's own layout pages, not the server's positions: a chapter that this
* device has laid out contributes its measured page count, and one it has not contributes an
* estimate (see [resolveEpubBookPages]). The total therefore firms up as the reader walks the
* book — the same bargain the iOS reader makes, where the label is an estimate until every
* chapter has been measured.
*/
data class EpubBookPageProgress(val currentPage: Int, val totalPages: Int)

/**
* Per-chapter page counts in reading order, plus the running offsets that turn "chapter 7, page 3"
* into "page 421 of 8,431".
*
* [pagesByChapter] is index-aligned with the manifest's reading order and always at least 1 page
* per chapter: the whole-book total must never shrink to zero when a measure pass is missing.
*/
data class EpubBookPages(val pagesByChapter: List<Int>) {

/** Prefix sums: `prefixBefore[i]` is the number of pages in the chapters before `i`. */
private val prefixBefore: IntArray = IntArray(pagesByChapter.size + 1).also { sums ->
pagesByChapter.forEachIndexed { index, pages -> sums[index + 1] = sums[index] + pages }
}

val totalPages: Int
get() = prefixBefore.lastOrNull() ?: 0

/** Pages that precede [chapterIndex] (0 for the first chapter). */
fun pagesBefore(chapterIndex: Int): Int =
prefixBefore[chapterIndex.coerceIn(0, pagesByChapter.size)]

/**
* Book page of a 0-based [pageInChapter] (1-based result), clamped into the chapter: a
* repagination that reports a page index from the port/starboard side of a page turn must not
* push the number past the chapter's own count.
*/
fun pageAt(chapterIndex: Int, pageInChapter: Int): Int? {
val pages = pagesByChapter.getOrNull(chapterIndex) ?: return null
val withinChapter = pageInChapter.coerceIn(0, pages - 1) + 1
return pagesBefore(chapterIndex) + withinChapter
}

/**
* Book page for a scrolling chapter, where the only position available is the in-chapter
* fraction (scrolled mode reports no pages). Fraction 1 is the chapter's last page.
*/
fun pageAt(chapterIndex: Int, chapterFraction: Float): Int? {
val pages = pagesByChapter.getOrNull(chapterIndex) ?: return null
val withinChapter = ((chapterFraction.coerceIn(0f, 1f) * (pages - 1)).roundToInt() + 1)
.coerceIn(1, pages)
return pagesBefore(chapterIndex) + withinChapter
}
}

/**
* Resolves the book-wide page counts: measured chapters keep their exact count, the rest are
* estimated from the server's positions for that chapter.
*
* The estimate is scaled by the ratio this session has already learned (measured pages ÷ the
* positions those same chapters carried): positions are page-like but not pages, and the ratio
* absorbs the reader's font size, margins and viewport. Without a single measured chapter the
* positions are taken at face value, and without positions a chapter gets the average of the
* measured ones — anything is better than pretending a 400-page novel has 12 pages.
*/
fun resolveEpubBookPages(
chapters: List<EpubChapter>,
measured: Map<String, Int>,
positionIndex: EpubPositionIndex?,
): EpubBookPages {
if (chapters.isEmpty()) return EpubBookPages(emptyList())

var measuredPages = 0
var measuredPositions = 0
var measuredChapters = 0
chapters.forEach { chapter ->
val pages = measured[chapter.href] ?: return@forEach
if (pages <= 0) return@forEach
measuredPages += pages
measuredChapters += 1
measuredPositions += positionIndex?.countByHref?.get(chapter.href) ?: 0
}
// How many of this reader's pages one server position is worth. Only meaningful once both
// sides exist; without positions the estimate is whatever the positions themselves say.
val pagesPerPosition = if (measuredPositions > 0) measuredPages.toFloat() / measuredPositions else 1f
val averageMeasured = if (measuredChapters > 0) measuredPages.toFloat() / measuredChapters else null

return EpubBookPages(
chapters.map { chapter ->
measured[chapter.href]?.takeIf { it > 0 } ?: estimatePages(
href = chapter.href,
positionIndex = positionIndex,
pagesPerPosition = pagesPerPosition,
averageMeasured = averageMeasured,
)
},
)
}

private fun estimatePages(
href: String,
positionIndex: EpubPositionIndex?,
pagesPerPosition: Float,
averageMeasured: Float?,
): Int {
val positions = positionIndex?.countByHref?.get(href) ?: 0
if (positions > 0) return (positions * pagesPerPosition).roundToInt().coerceAtLeast(1)
return averageMeasured?.roundToInt()?.coerceAtLeast(1) ?: 1
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.kmworks.kmreader.core.epub

/**
* Titles for the manifest's reading order, resolved so that split chapters keep their name.
*
* A spine item is not a chapter: books routinely split one chapter across several files (a 4 MB
* "chapter" becomes `ch12a.xhtml`, `ch12b.xhtml`), and only the first file carries the toc entry —
* Komga's `readingOrder` links then have a title for the head and none for the rest. Numbering
* those tails by position produced a table of contents reading "Chapter 12, Chapter 13, Chapter
* 14" for what is one chapter, and a progress label naming the wrong chapter.
*
* Resolution order per spine item: the manifest's own link title, then the title the toc gives that
* file, then the title of the nearest preceding spine item that HAD one, and only then the
* positional fallback. Inheritance deliberately stops at chapters with an explicit title, so an
* untitled front-matter file before the first chapter still falls back to its position instead of
* borrowing the chapter that follows it.
*
* [fallback] supplies the positional label (already localized) for spine items nothing named.
*/
fun resolveEpubChapterTitles(
order: List<EpubLinkDto>,
toc: List<EpubLinkDto>,
fallback: (Int) -> String,
): List<String> {
val tocTitles = tocTitlesByHref(toc)
var inherited: String? = null
return order.mapIndexed { index, link ->
val href = EpubHref.normalize(link.href)
val explicit = link.title?.trim()?.takeIf { it.isNotEmpty() }
?: tocTitles[href]?.takeIf { it.isNotEmpty() }
if (explicit != null) inherited = explicit
explicit ?: inherited ?: fallback(index)
}
}

/**
* First title the toc gives each file, deeper entries winning over their containers: a file that is
* both a part's landing page and a chapter start should be named after the chapter.
*/
private fun tocTitlesByHref(toc: List<EpubLinkDto>): Map<String, String> {
val titles = HashMap<String, String>()
fun walk(links: List<EpubLinkDto>) {
links.forEach { link ->
val href = EpubHref.normalize(link.href)
val title = link.title?.trim()
if (href.isNotEmpty() && !title.isNullOrEmpty()) titles[href] = title
link.children?.let(::walk)
}
}
walk(toc)
return titles
}
135 changes: 135 additions & 0 deletions app/src/main/java/com/kmworks/kmreader/core/epub/EpubPageCountStore.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package com.kmworks.kmreader.core.epub

import android.content.Context
import dagger.hilt.android.qualifiers.ApplicationContext
import java.io.File
import java.security.MessageDigest
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject

/**
* Cache identity of the measured page counts: the spine the counts were measured against plus the
* layout that produced them.
*
* Page counts are a property of the LAYOUT, not of the book: a chapter measured at 18sp with wide
* margins becomes a different number of pages at 26sp, so reusing those counts after a theme change
* would print a wrong "page 421 of 8,431". The caller passes a [layout] signature of the settings
* that decide pagination (font size, line height, margins, columns, viewport, insets), and a
* mismatch is a cache miss — the estimates take over until the chapters are measured again.
*/
fun epubPageCountKey(chapters: List<EpubChapter>, layout: String): String {
val digest = MessageDigest.getInstance("SHA-256")
chapters.forEach {
digest.update(it.href.toByteArray())
digest.update(0)
}
digest.update(layout.toByteArray())
return digest.digest().take(12).joinToString("") { "%02x".format(it.toInt() and 0xFF) }
}

/** Serialisation of `href → pages` (org.json: the reader module already depends on it). */
internal object EpubPageCountCodec {

/** Bump when the encoding changes; older files are then ignored and re-measured. */
const val FORMAT_VERSION = 1

data class Stored(val key: String, val counts: Map<String, Int>)

fun encode(key: String, counts: Map<String, Int>): String {
val root = JSONObject()
root.put("format", FORMAT_VERSION)
root.put("key", key)
val json = JSONObject()
counts.forEach { (href, pages) -> json.put(href, pages) }
root.put("counts", json)
return root.toString()
}

fun decode(raw: String): Stored? {
val root = runCatching { JSONObject(raw) }.getOrNull() ?: return null
if (root.optInt("format", -1) != FORMAT_VERSION) return null
val countsJson = root.optJSONObject("counts") ?: return null
val counts = HashMap<String, Int>(countsJson.length())
countsJson.keys().forEach { href ->
val pages = countsJson.optInt(href, 0)
if (pages > 0) counts[href] = pages
}
return Stored(root.optString("key", ""), counts)
}
}

/**
* Keeps the measured page counts of recently opened books: in memory for the current session and on
* disk (cacheDir, so the OS may evict it) across launches.
*
* The point of the disk copy is the reopening read: the whole-book page total is the sum over every
* chapter, and without it the reader has to lay the book out chapter by chapter before the total
* means anything. The caller passes the identity it expects [key]; a mismatch (a re-imported book,
* a different layout) is a miss.
*/
@Singleton
class EpubPageCountStore @Inject constructor(
@ApplicationContext private val context: Context,
) {

private val memory = object : LinkedHashMap<String, Pair<String, Map<String, Int>>>(
MEMORY_ENTRIES, 0.75f, true,
) {
override fun removeEldestEntry(
eldest: MutableMap.MutableEntry<String, Pair<String, Map<String, Int>>>,
): Boolean = size > MEMORY_ENTRIES
}

/** Cached counts for [bookDtoId] when they were written for [key]; null otherwise. Never throws. */
suspend fun cached(bookDtoId: String, key: String): Map<String, Int>? =
withContext(Dispatchers.IO) {
synchronized(memory) {
val hit = memory[bookDtoId]
if (hit != null && hit.first == key) return@withContext hit.second
}
val file = fileFor(bookDtoId)
if (!file.isFile) return@withContext null
val stored = runCatching { EpubPageCountCodec.decode(file.readText()) }
.getOrNull() ?: run {
runCatching { file.delete() }
return@withContext null
}
if (stored.key != key) return@withContext null
synchronized(memory) { memory[bookDtoId] = key to stored.counts }
stored.counts
}

/** Remembers [counts] for [bookDtoId] in memory and on disk. Never throws. */
suspend fun remember(bookDtoId: String, key: String, counts: Map<String, Int>) {
if (counts.isEmpty()) return
synchronized(memory) { memory[bookDtoId] = key to counts }
withContext(Dispatchers.IO) {
runCatching {
val file = fileFor(bookDtoId)
file.parentFile?.mkdirs()
val temp = File(file.parentFile, file.name + ".tmp")
temp.writeText(EpubPageCountCodec.encode(key, counts))
if (!temp.renameTo(file)) {
// Windows/older Android: rename over an existing file is not atomic, so replace.
file.delete()
if (!temp.renameTo(file)) temp.delete()
}
}
}
}

private fun fileFor(bookDtoId: String): File {
val digest = MessageDigest.getInstance("SHA-256").digest(bookDtoId.toByteArray())
val name = digest.take(16).joinToString("") { "%02x".format(it.toInt() and 0xFF) } + ".json"
return File(File(context.cacheDir, DIRECTORY), name)
}

private companion object {
/** Enough for the books a reader actually moves between; each entry is one int per chapter. */
const val MEMORY_ENTRIES = 8
const val DIRECTORY = "epub-page-counts"
}
}
Loading