Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c9c119689d | |||
| 38a327cdf6 | |||
| b25679c8de | |||
| dfd57544a9 | |||
| 3a5a4c0fb2 | |||
| 8e113fcbff | |||
| 74cb92278f | |||
| 5de6a8f110 | |||
| d4789c2373 | |||
| 8dc5a0fc0b | |||
| 105551f658 | |||
| 6a57bc601f | |||
| fe73aff860 | |||
| a347cd10b8 | |||
| 849148691a | |||
| c0e0ef1575 | |||
| 6391c9376c | |||
| dcec339477 | |||
| 1b01c894ad |
@@ -22,3 +22,6 @@
|
||||
*.woff binary
|
||||
*.pyc binary
|
||||
*.swp binary
|
||||
|
||||
# Android packages
|
||||
*.apk binary
|
||||
|
||||
@@ -33,8 +33,8 @@ android {
|
||||
defaultConfig {
|
||||
applicationId = "app.mihon"
|
||||
|
||||
versionCode = 30
|
||||
versionName = "0.20.4"
|
||||
versionCode = 31
|
||||
versionName = "0.20.5"
|
||||
|
||||
buildConfigField("String", "COMMIT_COUNT", "\"${getLatestCommitCount()}\"")
|
||||
buildConfigField("String", "COMMIT_SHA", "\"${getLatestCommitSha()}\"")
|
||||
@@ -216,6 +216,7 @@ dependencies {
|
||||
implementation(projects.coreMetadata)
|
||||
implementation(projects.sourceApi)
|
||||
implementation(projects.sourceLocal)
|
||||
implementation(libs.jsoup)
|
||||
implementation(projects.data)
|
||||
implementation(projects.domain)
|
||||
implementation(projects.presentationCore)
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
tools:ignore="ProtectedPermissions" />
|
||||
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
|
||||
|
||||
<application
|
||||
android:name=".App"
|
||||
@@ -209,6 +210,11 @@
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="shortService" />
|
||||
|
||||
<service
|
||||
android:name=".ui.reader.tts.ReaderTtsService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="mediaPlayback" />
|
||||
|
||||
<service
|
||||
android:name="androidx.appcompat.app.AppLocalesMetadataHolderService"
|
||||
android:enabled="false"
|
||||
|
||||
@@ -73,6 +73,9 @@ fun ReaderAppBars(
|
||||
onClickOrientation: () -> Unit,
|
||||
cropEnabled: Boolean,
|
||||
onClickCropBorder: () -> Unit,
|
||||
ttsAvailable: Boolean,
|
||||
ttsPlaying: Boolean,
|
||||
onClickTts: () -> Unit,
|
||||
onClickSettings: () -> Unit,
|
||||
) {
|
||||
val backgroundColor = MaterialTheme.colorScheme
|
||||
@@ -172,6 +175,9 @@ fun ReaderAppBars(
|
||||
onClickOrientation = onClickOrientation,
|
||||
cropEnabled = cropEnabled,
|
||||
onClickCropBorder = onClickCropBorder,
|
||||
ttsAvailable = ttsAvailable,
|
||||
ttsPlaying = ttsPlaying,
|
||||
onClickTts = onClickTts,
|
||||
onClickSettings = onClickSettings,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -25,6 +25,9 @@ fun ReaderBottomBar(
|
||||
onClickOrientation: () -> Unit,
|
||||
cropEnabled: Boolean,
|
||||
onClickCropBorder: () -> Unit,
|
||||
ttsAvailable: Boolean,
|
||||
ttsPlaying: Boolean,
|
||||
onClickTts: () -> Unit,
|
||||
onClickSettings: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
@@ -55,6 +58,17 @@ fun ReaderBottomBar(
|
||||
)
|
||||
}
|
||||
|
||||
if (ttsAvailable) {
|
||||
IconButton(onClick = onClickTts) {
|
||||
Icon(
|
||||
painter = painterResource(if (ttsPlaying) R.drawable.ic_pause_24dp else R.drawable.ic_play_arrow_24dp),
|
||||
contentDescription = stringResource(
|
||||
if (ttsPlaying) MR.strings.reader_tts_pause else MR.strings.reader_tts_start,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
IconButton(onClick = onClickSettings) {
|
||||
Icon(
|
||||
imageVector = MaterialSymbols.Rounded.Settings,
|
||||
|
||||
@@ -51,7 +51,10 @@ internal fun ColumnScope.GeneralPage(viewModel: ReaderSettingsViewModel) {
|
||||
themes.map { (labelRes, value) ->
|
||||
FilterChip(
|
||||
selected = readerTheme == value,
|
||||
onClick = { viewModel.preferences.readerTheme.set(value) },
|
||||
onClick = {
|
||||
viewModel.preferences.readerTheme.set(value)
|
||||
viewModel.requestTextAppearanceReload()
|
||||
},
|
||||
label = { Text(stringResource(labelRes)) },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.window.DialogWindowProvider
|
||||
@@ -33,15 +32,11 @@ fun ReaderSettingsDialog(
|
||||
stringResource(MR.strings.pref_category_text_reader),
|
||||
)
|
||||
val pagerState = rememberPagerState { tabTitles.size }
|
||||
val initialTextStyle = remember { viewModel.preferences.textReaderStyle() }
|
||||
|
||||
BoxWithConstraints {
|
||||
TabbedDialog(
|
||||
modifier = Modifier.heightIn(max = maxHeight * 0.75f),
|
||||
onDismissRequest = {
|
||||
if (viewModel.preferences.textReaderStyle() != initialTextStyle) {
|
||||
viewModel.onTextSettingsChanged()
|
||||
}
|
||||
viewModel.flushTextSettingsReload()
|
||||
onDismissRequest()
|
||||
onShowMenus()
|
||||
},
|
||||
@@ -51,7 +46,7 @@ fun ReaderSettingsDialog(
|
||||
val window = (LocalView.current.parent as? DialogWindowProvider)?.window
|
||||
|
||||
LaunchedEffect(pagerState.currentPage) {
|
||||
if (pagerState.currentPage == 2) {
|
||||
if (pagerState.currentPage == 2 || pagerState.currentPage == 3) {
|
||||
window?.setDimAmount(0f)
|
||||
onHideMenus()
|
||||
} else {
|
||||
|
||||
@@ -1,16 +1,25 @@
|
||||
package eu.kanade.presentation.reader.settings
|
||||
|
||||
import android.content.Intent
|
||||
import android.speech.tts.TextToSpeech
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences
|
||||
import eu.kanade.tachiyomi.ui.reader.setting.ReaderSettingsViewModel
|
||||
import eu.kanade.tachiyomi.ui.reader.tts.ReaderTtsController
|
||||
import eu.kanade.tachiyomi.ui.reader.tts.ReaderTtsService
|
||||
import tachiyomi.i18n.MR
|
||||
import tachiyomi.presentation.core.components.SettingsChipRow
|
||||
import tachiyomi.presentation.core.components.SliderItem
|
||||
@@ -26,15 +35,28 @@ private val fontFamilies = listOf(
|
||||
|
||||
@Composable
|
||||
internal fun ColumnScope.TextSettingsPage(viewModel: ReaderSettingsViewModel) {
|
||||
val context = LocalContext.current
|
||||
val ttsSettingsLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult(),
|
||||
) {
|
||||
ReaderTtsController.refreshVoiceSettings(
|
||||
context,
|
||||
viewModel.preferences.textTtsEnginePackage.get(),
|
||||
)
|
||||
}
|
||||
|
||||
val fontSizePref = viewModel.preferences.textFontSize
|
||||
val fontSize by fontSizePref.collectAsState()
|
||||
SliderItem(
|
||||
label = stringResource(MR.strings.pref_text_reader_font_size),
|
||||
value = fontSize,
|
||||
valueRange = 32..72,
|
||||
valueRange = 10..30,
|
||||
steps = 19,
|
||||
valueString = fontSize.toString(),
|
||||
onChange = fontSizePref::set,
|
||||
valueString = "$fontSize sp",
|
||||
onChange = { value ->
|
||||
fontSizePref.set(value)
|
||||
viewModel.requestTextSettingsReload()
|
||||
},
|
||||
pillColor = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||
)
|
||||
|
||||
@@ -45,8 +67,11 @@ internal fun ColumnScope.TextSettingsPage(viewModel: ReaderSettingsViewModel) {
|
||||
value = lineSpacing,
|
||||
valueRange = 90..180,
|
||||
steps = 17,
|
||||
valueString = "$lineSpacing%",
|
||||
onChange = lineSpacingPref::set,
|
||||
valueString = String.format("%.2fx", lineSpacing / 100f),
|
||||
onChange = { value ->
|
||||
lineSpacingPref.set(value)
|
||||
viewModel.requestTextSettingsReload()
|
||||
},
|
||||
pillColor = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||
)
|
||||
|
||||
@@ -55,10 +80,13 @@ internal fun ColumnScope.TextSettingsPage(viewModel: ReaderSettingsViewModel) {
|
||||
SliderItem(
|
||||
label = stringResource(MR.strings.pref_text_reader_paragraph_spacing),
|
||||
value = paragraphSpacing,
|
||||
valueRange = 0..48,
|
||||
steps = 11,
|
||||
valueString = paragraphSpacing.toString(),
|
||||
onChange = paragraphSpacingPref::set,
|
||||
valueRange = 0..16,
|
||||
steps = 15,
|
||||
valueString = "$paragraphSpacing dp",
|
||||
onChange = { value ->
|
||||
paragraphSpacingPref.set(value)
|
||||
viewModel.requestTextSettingsReload()
|
||||
},
|
||||
pillColor = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||
)
|
||||
|
||||
@@ -68,12 +96,87 @@ internal fun ColumnScope.TextSettingsPage(viewModel: ReaderSettingsViewModel) {
|
||||
fontFamilies.forEach { (label, value) ->
|
||||
FilterChip(
|
||||
selected = fontFamily == value,
|
||||
onClick = { fontFamilyPref.set(value) },
|
||||
onClick = {
|
||||
fontFamilyPref.set(value)
|
||||
viewModel.requestTextSettingsReload()
|
||||
},
|
||||
label = { Text(stringResource(label)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val ttsSpeedPref = viewModel.preferences.textTtsSpeedStep
|
||||
val ttsSpeedStep by ttsSpeedPref.collectAsState()
|
||||
SliderItem(
|
||||
label = stringResource(MR.strings.pref_text_reader_tts_speed),
|
||||
value = ttsSpeedStep,
|
||||
valueRange = 6..15,
|
||||
steps = 8,
|
||||
valueString = String.format("%.1fx", ttsSpeedStep / 5f),
|
||||
onChange = { value ->
|
||||
ttsSpeedPref.set(value)
|
||||
ReaderTtsController.setSpeed(context, value / 5f)
|
||||
},
|
||||
pillColor = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||
)
|
||||
|
||||
val enginePref = viewModel.preferences.textTtsEnginePackage
|
||||
val selectedEngine by enginePref.collectAsState()
|
||||
val installedEngines = remember {
|
||||
@Suppress("DEPRECATION")
|
||||
context.packageManager.queryIntentServices(
|
||||
Intent(TextToSpeech.Engine.INTENT_ACTION_TTS_SERVICE),
|
||||
0,
|
||||
)
|
||||
.mapNotNull { info ->
|
||||
val serviceInfo = info.serviceInfo ?: return@mapNotNull null
|
||||
val packageName = serviceInfo.packageName ?: return@mapNotNull null
|
||||
packageName to info.loadLabel(context.packageManager).toString()
|
||||
}
|
||||
.distinctBy { it.first }
|
||||
.sortedBy { it.second.lowercase() }
|
||||
}
|
||||
|
||||
SettingsChipRow(MR.strings.pref_text_reader_tts_engine) {
|
||||
FilterChip(
|
||||
selected = selectedEngine == ReaderTtsService.AUTO_ENGINE,
|
||||
onClick = {
|
||||
enginePref.set(ReaderTtsService.AUTO_ENGINE)
|
||||
ReaderTtsController.setEngine(context, ReaderTtsService.AUTO_ENGINE)
|
||||
},
|
||||
label = { Text(stringResource(MR.strings.pref_text_reader_tts_engine_auto)) },
|
||||
)
|
||||
FilterChip(
|
||||
selected = selectedEngine == ReaderTtsService.SYSTEM_DEFAULT_ENGINE,
|
||||
onClick = {
|
||||
enginePref.set(ReaderTtsService.SYSTEM_DEFAULT_ENGINE)
|
||||
ReaderTtsController.setEngine(context, ReaderTtsService.SYSTEM_DEFAULT_ENGINE)
|
||||
},
|
||||
label = { Text(stringResource(MR.strings.pref_text_reader_tts_engine_system)) },
|
||||
)
|
||||
installedEngines.forEach { (packageName, label) ->
|
||||
FilterChip(
|
||||
selected = selectedEngine == packageName,
|
||||
onClick = {
|
||||
enginePref.set(packageName)
|
||||
ReaderTtsController.setEngine(context, packageName)
|
||||
},
|
||||
label = { Text(label) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
TextButton(
|
||||
onClick = {
|
||||
runCatching {
|
||||
ttsSettingsLauncher.launch(Intent("com.android.settings.TTS_SETTINGS"))
|
||||
}
|
||||
},
|
||||
modifier = Modifier.padding(horizontal = 16.dp),
|
||||
) {
|
||||
Text(stringResource(MR.strings.pref_text_reader_tts_voice_settings))
|
||||
}
|
||||
|
||||
Text(
|
||||
text = stringResource(MR.strings.pref_text_reader_pdf_note),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
|
||||
@@ -95,7 +95,7 @@ class DownloadCache(
|
||||
.stateIn(scope, SharingStarted.WhileSubscribed(), false)
|
||||
|
||||
private val diskCacheFile: File
|
||||
get() = File(context.cacheDir, "dl_index_cache_v3")
|
||||
get() = File(context.cacheDir, "dl_index_cache_v4")
|
||||
|
||||
private val rootDownloadsDirMutex = Mutex()
|
||||
private var rootDownloadsDir = RootDirectory(storageManager.getDownloadsDirectory())
|
||||
@@ -374,10 +374,13 @@ class DownloadCache(
|
||||
when {
|
||||
// Ignore incomplete downloads
|
||||
it.name?.endsWith(Downloader.TMP_DIR_SUFFIX) == true -> null
|
||||
it.name?.contains(".download.", ignoreCase = true) == true -> null
|
||||
// Folder of images
|
||||
it.isDirectory -> it.name
|
||||
// CBZ files
|
||||
it.isFile && it.extension == "cbz" -> it.nameWithoutExtension
|
||||
// Archived or original document files
|
||||
it.isFile && it.extension?.lowercase()?.let { extension ->
|
||||
extension == "cbz" || extension in DOCUMENT_DOWNLOAD_EXTENSIONS
|
||||
} == true -> it.nameWithoutExtension
|
||||
// Anything else is irrelevant
|
||||
else -> null
|
||||
}
|
||||
|
||||
@@ -214,7 +214,8 @@ class DownloadManager(
|
||||
mangaTitle: String,
|
||||
source: Source,
|
||||
): Boolean {
|
||||
return provider.findChapterDir(chapterName, chapterScanlator, chapterUrl, mangaTitle, source) != null
|
||||
return provider.findChapterDir(chapterName, chapterScanlator, chapterUrl, mangaTitle, source) != null ||
|
||||
provider.findChapterDocument(chapterName, chapterScanlator, chapterUrl, mangaTitle, source) != null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -253,8 +254,8 @@ class DownloadManager(
|
||||
|
||||
removeFromDownloadQueue(filteredChapters)
|
||||
|
||||
val (mangaDir, chapterDirs) = provider.findChapterDirs(filteredChapters, manga, source)
|
||||
chapterDirs.forEach { it.delete() }
|
||||
val (mangaDir, chapterDownloads) = provider.findChapterDirs(filteredChapters, manga, source)
|
||||
chapterDownloads.forEach { it.delete() }
|
||||
cache.removeChapters(filteredChapters, manga)
|
||||
|
||||
// Delete manga directory if empty
|
||||
@@ -405,8 +406,12 @@ class DownloadManager(
|
||||
.firstOrNull() ?: return
|
||||
|
||||
var newName = provider.getChapterDirName(newChapter.name, newChapter.scanlator, newChapter.url)
|
||||
if (oldDownload.isFile && oldDownload.extension == "cbz") {
|
||||
newName += ".cbz"
|
||||
if (oldDownload.isFile) {
|
||||
oldDownload.extension?.lowercase()?.let { extension ->
|
||||
if (extension == "cbz" || extension in DOCUMENT_DOWNLOAD_EXTENSIONS) {
|
||||
newName += ".$extension"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (oldDownload.name == newName) return
|
||||
|
||||
@@ -19,6 +19,8 @@ import tachiyomi.domain.storage.service.StorageManager
|
||||
import tachiyomi.i18n.MR
|
||||
import java.io.IOException
|
||||
|
||||
internal val DOCUMENT_DOWNLOAD_EXTENSIONS = setOf("epub", "txt")
|
||||
|
||||
/**
|
||||
* This class is used to provide the directories where the downloads should be saved.
|
||||
* It uses the following path scheme: /<root downloads dir>/<source name>/<manga>/<chapter>
|
||||
@@ -116,11 +118,39 @@ class DownloadProvider(
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of downloaded directories for the chapters that exist.
|
||||
* Returns a downloaded EPUB/TXT document for a chapter if it exists.
|
||||
*
|
||||
* @param chapters the chapters to query.
|
||||
* @param manga the manga of the chapter.
|
||||
* @param source the source of the chapter.
|
||||
* Document files are checked explicitly before the generic chapter path so
|
||||
* a stale image directory with the same chapter name cannot shadow them.
|
||||
*/
|
||||
fun findChapterDocument(
|
||||
chapterName: String,
|
||||
chapterScanlator: String?,
|
||||
chapterUrl: String,
|
||||
mangaTitle: String,
|
||||
source: Source,
|
||||
): UniFile? {
|
||||
val mangaDir = findMangaDir(mangaTitle, source) ?: return null
|
||||
val chapterDirName = getChapterDirName(chapterName, chapterScanlator, chapterUrl)
|
||||
val legacyChapterDirNames = getLegacyChapterDirNames(chapterName, chapterScanlator, chapterUrl)
|
||||
|
||||
return buildList {
|
||||
DOCUMENT_DOWNLOAD_EXTENSIONS.forEach { extension ->
|
||||
add("$chapterDirName.$extension")
|
||||
}
|
||||
legacyChapterDirNames.forEach { legacyName ->
|
||||
DOCUMENT_DOWNLOAD_EXTENSIONS.forEach { extension ->
|
||||
add("$legacyName.$extension")
|
||||
}
|
||||
}
|
||||
}.asSequence()
|
||||
.mapNotNull { mangaDir.findFile(it) }
|
||||
.firstOrNull { it.isFile }
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns downloaded chapter entries that exist, including image directories,
|
||||
* CBZ files and standalone EPUB/TXT document files.
|
||||
*/
|
||||
fun findChapterDirs(chapters: List<Chapter>, manga: Manga, source: Source): Pair<UniFile?, List<UniFile>> {
|
||||
val mangaDir = findMangaDir(manga.title, source) ?: return null to emptyList()
|
||||
@@ -128,6 +158,13 @@ class DownloadProvider(
|
||||
getValidChapterDirNames(chapter.name, chapter.scanlator, chapter.url).asSequence()
|
||||
.mapNotNull { mangaDir.findFile(it) }
|
||||
.firstOrNull()
|
||||
?: findChapterDocument(
|
||||
chapter.name,
|
||||
chapter.scanlator,
|
||||
chapter.url,
|
||||
manga.title,
|
||||
source,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -250,11 +287,17 @@ class DownloadProvider(
|
||||
add(chapterDirName)
|
||||
// Archived chapters
|
||||
add("$chapterDirName.cbz")
|
||||
DOCUMENT_DOWNLOAD_EXTENSIONS.forEach { extension ->
|
||||
add("$chapterDirName.$extension")
|
||||
}
|
||||
|
||||
// any legacy names
|
||||
legacyChapterDirNames.forEach {
|
||||
add(it)
|
||||
add("$it.cbz")
|
||||
DOCUMENT_DOWNLOAD_EXTENSIONS.forEach { extension ->
|
||||
add("$it.$extension")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,8 +12,16 @@ import eu.kanade.tachiyomi.data.download.model.Download
|
||||
import eu.kanade.tachiyomi.data.library.LibraryUpdateNotifier
|
||||
import eu.kanade.tachiyomi.data.notification.NotificationHandler
|
||||
import eu.kanade.tachiyomi.network.HttpException
|
||||
import eu.kanade.tachiyomi.network.await
|
||||
import eu.kanade.tachiyomi.source.UnmeteredSource
|
||||
import eu.kanade.tachiyomi.source.bookoasis.bookOasisDocumentDownloadRequest
|
||||
import eu.kanade.tachiyomi.source.bookoasis.isBookOasisSource
|
||||
import eu.kanade.tachiyomi.source.bookoasis.toBookOasisChapterRef
|
||||
import eu.kanade.tachiyomi.source.model.Page
|
||||
import eu.kanade.tachiyomi.source.kavita.detectKavitaDocumentFormat
|
||||
import eu.kanade.tachiyomi.source.kavita.isKavitaSource
|
||||
import eu.kanade.tachiyomi.source.kavita.kavitaDocumentDownloadRequest
|
||||
import eu.kanade.tachiyomi.source.kavita.toKavitaChapterId
|
||||
import eu.kanade.tachiyomi.source.online.HttpSource
|
||||
import eu.kanade.tachiyomi.util.storage.DiskUtil
|
||||
import eu.kanade.tachiyomi.util.storage.DiskUtil.NOMEDIA_FILE
|
||||
@@ -44,6 +52,7 @@ import kotlinx.coroutines.supervisorScope
|
||||
import logcat.LogPriority
|
||||
import mihon.core.archive.ZipWriter
|
||||
import nl.adaptivity.xmlutil.serialization.XML
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import tachiyomi.core.common.i18n.stringResource
|
||||
import tachiyomi.core.common.util.lang.launchIO
|
||||
@@ -339,9 +348,15 @@ class Downloader(
|
||||
download.chapter.scanlator,
|
||||
download.chapter.url,
|
||||
)
|
||||
val tmpDir = mangaDir.createDirectory(chapterDirname + TMP_DIR_SUFFIX)!!
|
||||
|
||||
try {
|
||||
val remoteDocument = findRemoteDocument(download)
|
||||
if (remoteDocument != null) {
|
||||
downloadDocument(download, mangaDir, chapterDirname, remoteDocument)
|
||||
return
|
||||
}
|
||||
|
||||
val tmpDir = mangaDir.createDirectory(chapterDirname + TMP_DIR_SUFFIX)!!
|
||||
|
||||
// If the page list already exists, start from the file
|
||||
val pageList = download.pages ?: run {
|
||||
// Otherwise, pull page list from network and add them to download object
|
||||
@@ -415,6 +430,85 @@ class Downloader(
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun findRemoteDocument(download: Download): RemoteDocument? {
|
||||
val source = download.source
|
||||
return when {
|
||||
source.isBookOasisSource() -> download.chapter.url
|
||||
.toBookOasisChapterRef()
|
||||
?.takeIf { it.format in DOCUMENT_DOWNLOAD_EXTENSIONS }
|
||||
?.let { ref -> RemoteDocument(ref.format, source.bookOasisDocumentDownloadRequest(ref)) }
|
||||
source.isKavitaSource() -> download.chapter.url
|
||||
.toKavitaChapterId()
|
||||
?.let { chapterId ->
|
||||
source.detectKavitaDocumentFormat(chapterId)?.let { format ->
|
||||
RemoteDocument(format, source.kavitaDocumentDownloadRequest(chapterId))
|
||||
}
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun downloadDocument(
|
||||
download: Download,
|
||||
mangaDir: UniFile,
|
||||
chapterDirname: String,
|
||||
document: RemoteDocument,
|
||||
) {
|
||||
val targetName = "$chapterDirname.${document.extension}"
|
||||
val tempName = "$chapterDirname.download.${document.extension}"
|
||||
mangaDir.findFile(tempName)?.delete()
|
||||
val temp = mangaDir.createFile(tempName)
|
||||
?: error("Failed to create temporary document file")
|
||||
val page = Page(0).apply {
|
||||
status = Page.State.DownloadImage
|
||||
}
|
||||
download.pages = listOf(page)
|
||||
download.status = Download.State.DOWNLOADING
|
||||
notifier.onProgressChange(download)
|
||||
|
||||
try {
|
||||
download.source.client.newCall(document.request).await().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
throw IllegalStateException(
|
||||
"Document download failed: HTTP ${response.code}",
|
||||
)
|
||||
}
|
||||
temp.openOutputStream().use { output ->
|
||||
response.body.byteStream().use { input -> input.copyTo(output) }
|
||||
}
|
||||
}
|
||||
|
||||
if (temp.length() <= 0L) {
|
||||
throw IllegalStateException("Document download returned an empty file")
|
||||
}
|
||||
|
||||
mangaDir.findFile(targetName)?.delete()
|
||||
if (!temp.renameTo(targetName)) {
|
||||
val target = mangaDir.createFile(targetName)
|
||||
?: error("Failed to create downloaded document file")
|
||||
temp.openInputStream().use { input ->
|
||||
target.openOutputStream().use { output ->
|
||||
input.copyTo(output)
|
||||
}
|
||||
}
|
||||
temp.delete()
|
||||
}
|
||||
} catch (error: Throwable) {
|
||||
temp.delete()
|
||||
throw error
|
||||
}
|
||||
|
||||
val target = mangaDir.findFile(targetName)
|
||||
?: error("Downloaded document file is missing")
|
||||
page.uri = target.uri
|
||||
page.status = Page.State.Ready
|
||||
page.progress = 100
|
||||
notifier.onProgressChange(download)
|
||||
cache.addChapter(chapterDirname, mangaDir, download.manga)
|
||||
DiskUtil.createNoMediaFile(mangaDir, context)
|
||||
download.status = Download.State.DOWNLOADED
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the image from the filesystem if it exists or downloads it otherwise.
|
||||
*
|
||||
@@ -740,5 +834,10 @@ class Downloader(
|
||||
}
|
||||
}
|
||||
|
||||
private data class RemoteDocument(
|
||||
val extension: String,
|
||||
val request: Request,
|
||||
)
|
||||
|
||||
// Arbitrary minimum required space to start a download: 200 MB
|
||||
private const val MIN_DISK_SPACE = 200L * 1024 * 1024
|
||||
|
||||
@@ -21,6 +21,10 @@ object Notifications {
|
||||
const val CHANNEL_COMMON = "common_channel"
|
||||
const val ID_DOWNLOAD_IMAGE = 2
|
||||
|
||||
/** Foreground notification used by EPUB/TXT text-to-speech playback. */
|
||||
const val CHANNEL_READER_TTS = "reader_tts_channel"
|
||||
const val ID_READER_TTS = -801
|
||||
|
||||
/**
|
||||
* Notification channel and ids used by the library updater.
|
||||
*/
|
||||
@@ -119,6 +123,10 @@ object Notifications {
|
||||
buildNotificationChannel(CHANNEL_COMMON, IMPORTANCE_LOW) {
|
||||
setName(context.stringResource(MR.strings.channel_common))
|
||||
},
|
||||
buildNotificationChannel(CHANNEL_READER_TTS, IMPORTANCE_LOW) {
|
||||
setName("Text-to-speech")
|
||||
setShowBadge(false)
|
||||
},
|
||||
buildNotificationChannel(CHANNEL_LIBRARY_PROGRESS, IMPORTANCE_LOW) {
|
||||
setName(context.stringResource(MR.strings.channel_progress))
|
||||
setGroup(GROUP_LIBRARY)
|
||||
|
||||
@@ -21,13 +21,40 @@ internal data class BookOasisChapterRef(
|
||||
val format: String,
|
||||
)
|
||||
|
||||
private fun HttpSource.bookOasisServerBase(): String {
|
||||
val normalized = baseUrl.trimEnd('/')
|
||||
return when {
|
||||
normalized.endsWith("/app-opds-adult", ignoreCase = true) ->
|
||||
normalized.dropLast("/app-opds-adult".length)
|
||||
normalized.endsWith("/app-opds", ignoreCase = true) ->
|
||||
normalized.dropLast("/app-opds".length)
|
||||
else -> normalized
|
||||
}
|
||||
}
|
||||
|
||||
internal fun HttpSource.bookOasisDocumentDownloadRequest(ref: BookOasisChapterRef): Request {
|
||||
val downloadUrl = buildString {
|
||||
append(bookOasisServerBase())
|
||||
append("/app-opds/download/")
|
||||
append(ref.dbType)
|
||||
append('/')
|
||||
append(ref.bookId)
|
||||
}
|
||||
|
||||
return Request.Builder()
|
||||
.url(downloadUrl)
|
||||
.headers(headers)
|
||||
.get()
|
||||
.build()
|
||||
}
|
||||
|
||||
internal fun Source.isBookOasisSource(): Boolean {
|
||||
return this::class.java.name.startsWith(BOOKOASIS_PACKAGE_PREFIX)
|
||||
}
|
||||
|
||||
internal fun String.toBookOasisChapterRef(): BookOasisChapterRef? {
|
||||
val path = substringBefore('?')
|
||||
val match = Regex("""^/api/media/books/(\d+)/info$""").matchEntire(path) ?: return null
|
||||
val match = Regex("""^/(?:app-opds(?:-adult)?/)?api/media/books/(\d+)/info$""").matchEntire(path) ?: return null
|
||||
val params = parseQueryParameters(this)
|
||||
val format = params["bo_format"]?.lowercase() ?: return null
|
||||
if (format !in DOCUMENT_FORMATS) return null
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package eu.kanade.tachiyomi.source.kavita
|
||||
|
||||
import eu.kanade.tachiyomi.network.await
|
||||
import eu.kanade.tachiyomi.source.Source
|
||||
import eu.kanade.tachiyomi.source.online.HttpSource
|
||||
import okhttp3.Request
|
||||
import org.json.JSONObject
|
||||
import java.util.Locale
|
||||
|
||||
private const val KAVITA_PACKAGE_PREFIX = "eu.kanade.tachiyomi.extension.all.kavita."
|
||||
|
||||
internal fun Source.isKavitaSource(): Boolean =
|
||||
this::class.java.name.startsWith(KAVITA_PACKAGE_PREFIX)
|
||||
|
||||
private fun HttpSource.kavitaApiBase(): String {
|
||||
val normalized = baseUrl.trimEnd('/')
|
||||
return if (normalized.endsWith("/api", ignoreCase = true)) normalized else "$normalized/api"
|
||||
}
|
||||
|
||||
internal suspend fun HttpSource.detectKavitaDocumentFormat(chapterId: Int): String? {
|
||||
val apiBase = kavitaApiBase()
|
||||
val request = Request.Builder()
|
||||
.url("$apiBase/Chapter?chapterId=$chapterId")
|
||||
.headers(headers)
|
||||
.get()
|
||||
.build()
|
||||
|
||||
client.newCall(request).await().use { response ->
|
||||
if (!response.isSuccessful) return null
|
||||
|
||||
val body = response.body.string()
|
||||
if (body.isBlank()) return null
|
||||
|
||||
val files = JSONObject(body).optJSONArray("files") ?: return null
|
||||
for (i in 0 until files.length()) {
|
||||
val file = files.optJSONObject(i) ?: continue
|
||||
val extension = file.optString("extension")
|
||||
.ifBlank { file.optString("filePath") }
|
||||
.substringAfterLast('.')
|
||||
.trim()
|
||||
.trimStart('.')
|
||||
.lowercase(Locale.ROOT)
|
||||
if (extension == "epub" || extension == "txt") return extension
|
||||
if (file.optInt("format", -1) == 3) return "epub"
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
internal fun HttpSource.kavitaDocumentDownloadRequest(chapterId: Int): Request {
|
||||
val apiBase = kavitaApiBase()
|
||||
return Request.Builder()
|
||||
.url("$apiBase/Download/chapter?chapterId=$chapterId")
|
||||
.headers(headers)
|
||||
.get()
|
||||
.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* Kavita extension chapter URLs are normally /Chapter/{id}. Keep compatibility
|
||||
* with older/alternate forms used by reading lists and previous releases.
|
||||
*/
|
||||
internal fun String.toKavitaChapterId(): Int? {
|
||||
Regex("""(?:^|/)Chapter/(\d+)""", RegexOption.IGNORE_CASE)
|
||||
.find(this)
|
||||
?.groupValues
|
||||
?.getOrNull(1)
|
||||
?.toIntOrNull()
|
||||
?.let { return it }
|
||||
|
||||
Regex("""(?:^|/)chapter_(\d+)""", RegexOption.IGNORE_CASE)
|
||||
.find(this)
|
||||
?.groupValues
|
||||
?.getOrNull(1)
|
||||
?.toIntOrNull()
|
||||
?.let { return it }
|
||||
|
||||
Regex("""[?&]chapterId=(\d+)""", RegexOption.IGNORE_CASE)
|
||||
.find(this)
|
||||
?.groupValues
|
||||
?.getOrNull(1)
|
||||
?.toIntOrNull()
|
||||
?.let { return it }
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -20,13 +20,20 @@ import android.view.WindowManager
|
||||
import android.widget.Toast
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.activity.viewModels
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
@@ -34,6 +41,7 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.getSystemService
|
||||
import androidx.core.graphics.Insets
|
||||
@@ -42,6 +50,8 @@ import androidx.core.transition.doOnEnd
|
||||
import androidx.core.view.ViewCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
import androidx.core.view.WindowInsetsControllerCompat
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.flowWithLifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.google.android.material.transition.platform.MaterialContainerTransform
|
||||
import dev.zacsweers.metro.Inject
|
||||
@@ -65,6 +75,7 @@ import eu.kanade.tachiyomi.ui.main.MainActivity
|
||||
import eu.kanade.tachiyomi.ui.reader.ReaderViewModel.SetAsCoverResult.AddToLibraryFirst
|
||||
import eu.kanade.tachiyomi.ui.reader.ReaderViewModel.SetAsCoverResult.Error
|
||||
import eu.kanade.tachiyomi.ui.reader.ReaderViewModel.SetAsCoverResult.Success
|
||||
import eu.kanade.tachiyomi.ui.reader.loader.TextReaderPage
|
||||
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
|
||||
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
|
||||
import eu.kanade.tachiyomi.ui.reader.model.ViewerChapters
|
||||
@@ -72,6 +83,8 @@ import eu.kanade.tachiyomi.ui.reader.setting.ReaderOrientation
|
||||
import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences
|
||||
import eu.kanade.tachiyomi.ui.reader.setting.ReaderSettingsViewModel
|
||||
import eu.kanade.tachiyomi.ui.reader.setting.ReadingMode
|
||||
import eu.kanade.tachiyomi.ui.reader.tts.ReaderTtsController
|
||||
import eu.kanade.tachiyomi.ui.reader.tts.ReaderTtsSessionStore
|
||||
import eu.kanade.tachiyomi.ui.reader.viewer.ReaderProgressIndicator
|
||||
import eu.kanade.tachiyomi.ui.reader.viewer.pager.R2LPagerViewer
|
||||
import eu.kanade.tachiyomi.ui.reader.viewer.webgpu.WebGpuViewer
|
||||
@@ -137,6 +150,7 @@ class ReaderActivity : BaseActivity() {
|
||||
private val windowInsetsController by lazy { WindowInsetsControllerCompat(window, window.decorView) }
|
||||
|
||||
private var loadingIndicator: ReaderProgressIndicator? = null
|
||||
private var ttsHighlightedPage: TextReaderPage? = null
|
||||
|
||||
var isScrollingThroughPages = false
|
||||
private set
|
||||
@@ -217,12 +231,28 @@ class ReaderActivity : BaseActivity() {
|
||||
.onEach(::setChapters)
|
||||
.launchIn(lifecycleScope)
|
||||
|
||||
ReaderTtsController.state
|
||||
.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
|
||||
.sample(0.2.seconds)
|
||||
.onEach(::applyTtsState)
|
||||
.launchIn(lifecycleScope)
|
||||
|
||||
viewModel.eventFlow
|
||||
.onEach { event ->
|
||||
when (event) {
|
||||
ReaderViewModel.Event.ReloadViewerChapters -> {
|
||||
viewModel.state.value.viewerChapters?.let(::setChapters)
|
||||
}
|
||||
ReaderViewModel.Event.RefreshCurrentTextPage -> {
|
||||
viewModel.state.value.viewer?.refreshCurrentPage()
|
||||
}
|
||||
ReaderViewModel.Event.ReloadTextViewerChapters -> {
|
||||
val state = viewModel.state.value
|
||||
val chapters = state.viewerChapters
|
||||
if (chapters != null) {
|
||||
state.viewer?.refreshTextChapters(chapters)
|
||||
}
|
||||
}
|
||||
ReaderViewModel.Event.PageChanged -> {
|
||||
displayRefreshHost.flash()
|
||||
}
|
||||
@@ -249,12 +279,14 @@ class ReaderActivity : BaseActivity() {
|
||||
private fun ReaderActivityBinding.setComposeOverlay(): Unit = composeOverlay.setComposeContent {
|
||||
val state by viewModel.state.collectAsState()
|
||||
val showPageNumber by readerPreferences.showPageNumber.collectAsState()
|
||||
val ttsState by ReaderTtsController.state.collectAsState()
|
||||
val settingsviewModel = remember {
|
||||
ReaderSettingsViewModel(
|
||||
readerState = viewModel.state,
|
||||
onChangeReadingMode = viewModel::setMangaReadingMode,
|
||||
onChangeOrientation = viewModel::setMangaOrientationType,
|
||||
onTextSettingsChanged = viewModel::reloadTextReaderStyle,
|
||||
onTextSettingsPreview = viewModel::previewTextReaderStyle,
|
||||
onTextSettingsCommit = viewModel::commitTextReaderStyle,
|
||||
preferences = readerPreferences,
|
||||
)
|
||||
}
|
||||
@@ -273,6 +305,34 @@ class ReaderActivity : BaseActivity() {
|
||||
ContentOverlay(state = state)
|
||||
|
||||
AppBars(state = state)
|
||||
|
||||
val showFloatingTts = ttsState.active &&
|
||||
ttsState.readerChapterId == state.currentChapter?.chapter?.id &&
|
||||
state.currentChapter?.pages?.any { it is TextReaderPage } == true
|
||||
if (showFloatingTts) {
|
||||
IconButton(
|
||||
onClick = ::toggleTts,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomEnd)
|
||||
.navigationBarsPadding()
|
||||
.padding(end = 18.dp, bottom = 72.dp)
|
||||
.size(52.dp)
|
||||
.background(
|
||||
color = MaterialTheme.colorScheme.surface.copy(alpha = 0.55f),
|
||||
shape = CircleShape,
|
||||
),
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(
|
||||
if (ttsState.playing) R.drawable.ic_pause_24dp else R.drawable.ic_play_arrow_24dp,
|
||||
),
|
||||
contentDescription = stringResource(
|
||||
if (ttsState.playing) MR.strings.reader_tts_pause else MR.strings.reader_tts_start,
|
||||
),
|
||||
tint = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.92f),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val onDismissRequest = viewModel::closeDialog
|
||||
@@ -462,6 +522,10 @@ class ReaderActivity : BaseActivity() {
|
||||
)
|
||||
val verticalNavigatorOnLeft by readerPreferences.verticalNavigatorOnLeft.collectAsState()
|
||||
val verticalNavigatorHeight by readerPreferences.verticalNavigatorHeight.collectAsState()
|
||||
val ttsState by ReaderTtsController.state.collectAsState()
|
||||
val ttsAvailable = state.currentChapter?.pages?.any { it is TextReaderPage } == true
|
||||
val ttsForCurrentChapter = ttsState.active &&
|
||||
ttsState.readerChapterId == state.currentChapter?.chapter?.id
|
||||
|
||||
ReaderAppBars(
|
||||
visible = state.menuVisible,
|
||||
@@ -518,6 +582,9 @@ class ReaderActivity : BaseActivity() {
|
||||
menuToggleToast?.cancel()
|
||||
menuToggleToast = toast(if (enabled) MR.strings.on else MR.strings.off)
|
||||
},
|
||||
ttsAvailable = ttsAvailable,
|
||||
ttsPlaying = ttsForCurrentChapter && ttsState.playing,
|
||||
onClickTts = ::toggleTts,
|
||||
onClickSettings = viewModel::openSettingsDialog,
|
||||
)
|
||||
}
|
||||
@@ -664,6 +731,126 @@ class ReaderActivity : BaseActivity() {
|
||||
viewer.moveToPage(page)
|
||||
}
|
||||
|
||||
private fun toggleTts() {
|
||||
val state = viewModel.state.value
|
||||
val chapter = state.currentChapter ?: return
|
||||
val chapterId = chapter.chapter.id ?: return
|
||||
val ttsState = ReaderTtsController.state.value
|
||||
|
||||
if (ttsState.active && ttsState.readerChapterId == chapterId) {
|
||||
if (ttsState.playing) {
|
||||
ReaderTtsController.toggle(this)
|
||||
} else {
|
||||
val currentPageIndex = (state.currentPage - 1).coerceAtLeast(0)
|
||||
if (currentPageIndex != ttsState.readerPageIndex) {
|
||||
ReaderTtsController.resumeFromPage(this, currentPageIndex)
|
||||
} else {
|
||||
ReaderTtsController.toggle(this)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
val textPages = chapter.pages?.filterIsInstance<TextReaderPage>().orEmpty()
|
||||
if (textPages.isEmpty()) return
|
||||
|
||||
val startPageIndex = (state.currentPage - 1).coerceAtLeast(0)
|
||||
val title = state.manga?.title ?: chapter.chapter.name
|
||||
val subtitle = chapter.chapter.name
|
||||
val speed = readerPreferences.textTtsSpeedStep.get().coerceIn(6, 15) / 5f
|
||||
val enginePackage = readerPreferences.textTtsEnginePackage.get()
|
||||
|
||||
lifecycleScope.launchIO {
|
||||
val session = runCatching {
|
||||
ReaderTtsSessionStore.create(this@ReaderActivity, textPages)
|
||||
}.getOrElse { error ->
|
||||
logcat(LogPriority.ERROR, error) { "Failed to create TTS text session" }
|
||||
return@launchIO
|
||||
}
|
||||
ReaderTtsController.start(
|
||||
context = this@ReaderActivity,
|
||||
sessionId = session.id,
|
||||
startReaderPageIndex = startPageIndex,
|
||||
readerChapterId = chapterId,
|
||||
title = title,
|
||||
subtitle = subtitle,
|
||||
speed = speed,
|
||||
enginePackage = enginePackage,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyTtsState(ttsState: ReaderTtsController.State) {
|
||||
val state = viewModel.state.value
|
||||
val chapter = state.currentChapter
|
||||
val chapterId = chapter?.chapter?.id
|
||||
|
||||
if (!ttsState.active || chapter == null || chapterId != ttsState.readerChapterId) {
|
||||
if (ttsHighlightedPage != null) {
|
||||
ttsHighlightedPage?.clearTtsHighlight()
|
||||
ttsHighlightedPage = null
|
||||
state.viewer?.refreshCurrentPage()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
val textPages = chapter.pages?.filterIsInstance<TextReaderPage>().orEmpty()
|
||||
if (textPages.isEmpty()) return
|
||||
|
||||
val targetSourceOffset = when {
|
||||
ttsState.sourceHighlightStart >= 0L -> ttsState.sourceHighlightStart
|
||||
ttsState.sourceSentenceStart >= 0L -> ttsState.sourceSentenceStart
|
||||
else -> -1L
|
||||
}
|
||||
val targetPage = if (targetSourceOffset >= 0L) {
|
||||
textPages.firstOrNull { page ->
|
||||
page.anchor.documentIndex == ttsState.documentIndex &&
|
||||
targetSourceOffset >= page.anchor.startOffset &&
|
||||
targetSourceOffset < page.anchor.endOffsetExclusive
|
||||
}
|
||||
} else {
|
||||
chapter.pages?.getOrNull(ttsState.readerPageIndex) as? TextReaderPage
|
||||
} ?: return
|
||||
|
||||
if (ttsHighlightedPage !== targetPage) {
|
||||
ttsHighlightedPage?.clearTtsHighlight()
|
||||
}
|
||||
|
||||
val sentenceStart = maxOf(ttsState.sourceSentenceStart, targetPage.anchor.startOffset)
|
||||
val sentenceEnd = minOf(ttsState.sourceSentenceEndExclusive, targetPage.anchor.endOffsetExclusive)
|
||||
val activeStart = maxOf(ttsState.sourceHighlightStart, targetPage.anchor.startOffset)
|
||||
val activeEnd = minOf(ttsState.sourceHighlightEndExclusive, targetPage.anchor.endOffsetExclusive)
|
||||
|
||||
if (
|
||||
ttsState.sourceSentenceStart >= 0L &&
|
||||
ttsState.sourceSentenceEndExclusive > ttsState.sourceSentenceStart &&
|
||||
sentenceEnd > sentenceStart
|
||||
) {
|
||||
targetPage.updateTtsHighlight(
|
||||
sentenceStart = (sentenceStart - targetPage.anchor.startOffset).toInt(),
|
||||
sentenceEndExclusive = (sentenceEnd - targetPage.anchor.startOffset).toInt(),
|
||||
activeStart = if (activeEnd > activeStart) {
|
||||
(activeStart - targetPage.anchor.startOffset).toInt()
|
||||
} else {
|
||||
-1
|
||||
},
|
||||
activeEndExclusive = if (activeEnd > activeStart) {
|
||||
(activeEnd - targetPage.anchor.startOffset).toInt()
|
||||
} else {
|
||||
-1
|
||||
},
|
||||
)
|
||||
} else {
|
||||
targetPage.clearTtsHighlight()
|
||||
}
|
||||
|
||||
ttsHighlightedPage = targetPage
|
||||
if (state.currentPage != targetPage.index + 1) {
|
||||
moveToPageIndex(targetPage.index)
|
||||
}
|
||||
state.viewer?.refreshCurrentPage()
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells the presenter to load the next chapter and mark it as active. The progress dialog
|
||||
* should be automatically shown.
|
||||
|
||||
@@ -40,6 +40,8 @@ import eu.kanade.tachiyomi.source.model.Page
|
||||
import eu.kanade.tachiyomi.source.online.HttpSource
|
||||
import eu.kanade.tachiyomi.ui.reader.loader.ChapterLoader
|
||||
import eu.kanade.tachiyomi.ui.reader.loader.DownloadPageLoader
|
||||
import eu.kanade.tachiyomi.ui.reader.loader.TextReaderAnchor
|
||||
import eu.kanade.tachiyomi.ui.reader.loader.TextReaderPage
|
||||
import eu.kanade.tachiyomi.ui.reader.model.InsertPage
|
||||
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
|
||||
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
|
||||
@@ -56,6 +58,8 @@ import eu.kanade.tachiyomi.util.storage.DiskUtil
|
||||
import eu.kanade.tachiyomi.util.storage.cacheImageDir
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
@@ -184,6 +188,12 @@ class ReaderViewModel(
|
||||
*/
|
||||
private var loader: ChapterLoader? = null
|
||||
|
||||
/**
|
||||
* Only the newest text repagination request is allowed to finish. Slider
|
||||
* changes can arrive faster than a large TXT/EPUB chapter can be rebuilt.
|
||||
*/
|
||||
private var textRepaginationJob: Job? = null
|
||||
|
||||
/**
|
||||
* The time the chapter was started reading
|
||||
*/
|
||||
@@ -823,27 +833,59 @@ class ReaderViewModel(
|
||||
mutableState.update { it.copy(dialog = null) }
|
||||
}
|
||||
|
||||
fun reloadTextReaderStyle() {
|
||||
fun previewTextReaderStyle() {
|
||||
val chapter = state.value.currentChapter ?: return
|
||||
if (chapter.pageLoader?.usesTextReaderStyle != true) return
|
||||
val chapterLoader = loader ?: return
|
||||
val requestedPage = (state.value.currentPage - 1).coerceAtLeast(0)
|
||||
val oldLastIndex = (chapter.pages?.lastIndex ?: 0).coerceAtLeast(0)
|
||||
val readingProgress = if (oldLastIndex == 0) 0f else requestedPage.toFloat() / oldLastIndex
|
||||
val style = readerPreferences.textReaderStyle(context)
|
||||
val textPages = chapter.pages?.filterIsInstance<TextReaderPage>().orEmpty()
|
||||
if (textPages.isEmpty()) return
|
||||
|
||||
viewModelScope.launchIO {
|
||||
textPages.forEach { it.updateStyle(style) }
|
||||
eventChannel.trySend(Event.RefreshCurrentTextPage)
|
||||
}
|
||||
|
||||
fun commitTextReaderStyle() {
|
||||
val chapter = state.value.currentChapter ?: return
|
||||
if (chapter.pageLoader?.usesTextReaderStyle != true) return
|
||||
if (chapter.pages?.any { it is TextReaderPage } != true) return
|
||||
val chapterLoader = loader ?: return
|
||||
|
||||
val oldPageCount = chapter.pages?.size?.coerceAtLeast(1) ?: 1
|
||||
val requestedPage = chapter.requestedPage.coerceIn(0, oldPageCount - 1)
|
||||
val currentTextPage = chapter.pages?.getOrNull(requestedPage) as? TextReaderPage
|
||||
val readingAnchor = currentTextPage?.anchor?.let { anchor ->
|
||||
val midpoint = anchor.startOffset +
|
||||
((anchor.endOffsetExclusive - anchor.startOffset).coerceAtLeast(1L) / 2L)
|
||||
TextReaderAnchor(
|
||||
documentIndex = anchor.documentIndex,
|
||||
startOffset = midpoint,
|
||||
endOffsetExclusive = midpoint + 1L,
|
||||
)
|
||||
}
|
||||
// Keep the page-ratio fallback for non-text/malformed cases, but prefer
|
||||
// the source-text anchor so font/spacing changes return to the same text.
|
||||
val readingProgress = ((requestedPage + 0.5f) / oldPageCount)
|
||||
.coerceIn(0f, 0.999999f)
|
||||
|
||||
textRepaginationJob?.cancel()
|
||||
textRepaginationJob = viewModelScope.launchIO {
|
||||
try {
|
||||
chapter.pageLoader?.recycle()
|
||||
chapter.pageLoader = null
|
||||
chapter.state = ReaderChapter.State.Wait
|
||||
chapter.requestedPage = requestedPage
|
||||
chapterLoader.loadChapter(chapter)
|
||||
val newLastIndex = (chapter.pages?.lastIndex ?: 0).coerceAtLeast(0)
|
||||
chapter.requestedPage = (readingProgress * newLastIndex).roundToInt().coerceIn(0, newLastIndex)
|
||||
eventChannel.send(Event.ReloadViewerChapters)
|
||||
val oldLoader = chapterLoader.reloadTextChapter(
|
||||
chapter = chapter,
|
||||
readingAnchor = readingAnchor,
|
||||
readingProgress = readingProgress,
|
||||
) ?: return@launchIO
|
||||
|
||||
// Resource cleanup must survive cancellation by the next slider value.
|
||||
viewModelScope.launchNonCancellable {
|
||||
delay(750)
|
||||
oldLoader.recycle()
|
||||
}
|
||||
|
||||
eventChannel.trySend(Event.ReloadTextViewerChapters)
|
||||
} catch (e: Throwable) {
|
||||
if (e is CancellationException) throw e
|
||||
logcat(LogPriority.ERROR, e) { "Failed to reload text reader style" }
|
||||
logcat(LogPriority.ERROR, e) { "Failed to repaginate text reader style" }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1037,6 +1079,8 @@ class ReaderViewModel(
|
||||
|
||||
sealed interface Event {
|
||||
data object ReloadViewerChapters : Event
|
||||
data object RefreshCurrentTextPage : Event
|
||||
data object ReloadTextViewerChapters : Event
|
||||
data object PageChanged : Event
|
||||
data class SetOrientation(val orientation: Int) : Event
|
||||
data class SetCoverResult(val result: SetAsCoverResult) : Event
|
||||
|
||||
@@ -4,11 +4,11 @@ import android.content.Context
|
||||
import com.hippo.unifile.UniFile
|
||||
import eu.kanade.tachiyomi.network.await
|
||||
import eu.kanade.tachiyomi.source.bookoasis.BookOasisChapterRef
|
||||
import eu.kanade.tachiyomi.source.bookoasis.bookOasisDocumentDownloadRequest
|
||||
import eu.kanade.tachiyomi.source.online.HttpSource
|
||||
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
|
||||
import eu.kanade.tachiyomi.ui.reader.setting.TextReaderStyle
|
||||
import mihon.core.archive.epubReader
|
||||
import okhttp3.Request
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
|
||||
@@ -34,9 +34,9 @@ internal class BookOasisFilePageLoader(
|
||||
val uniFile = UniFile.fromFile(file)
|
||||
?: error("Unable to open cached BookOasis file: ${file.absolutePath}")
|
||||
val loader = when (ref.format) {
|
||||
"epub" -> EpubPageLoader(uniFile.epubReader(context), textStyle)
|
||||
"epub" -> EpubPageLoader(uniFile.epubReader(context), textStyle, context.cacheDir)
|
||||
"pdf" -> PdfPageLoader(context, uniFile)
|
||||
"txt" -> TextPageLoader(uniFile, textStyle)
|
||||
"txt" -> TextPageLoader(uniFile, textStyle, context.cacheDir)
|
||||
else -> error("Unsupported BookOasis document format: ${ref.format}")
|
||||
}
|
||||
|
||||
@@ -68,19 +68,7 @@ internal class BookOasisFilePageLoader(
|
||||
val temp = File(cacheDir, "${target.name}.part")
|
||||
if (temp.exists()) temp.delete()
|
||||
|
||||
val downloadUrl = buildString {
|
||||
append(source.baseUrl.trimEnd('/'))
|
||||
append("/api/media/books/")
|
||||
append(ref.bookId)
|
||||
append("/download?type=")
|
||||
append(ref.dbType)
|
||||
}
|
||||
|
||||
val request = Request.Builder()
|
||||
.url(downloadUrl)
|
||||
.headers(source.headers)
|
||||
.get()
|
||||
.build()
|
||||
val request = source.bookOasisDocumentDownloadRequest(ref)
|
||||
|
||||
source.client.newCall(request).await().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
|
||||
@@ -7,6 +7,8 @@ import eu.kanade.tachiyomi.data.download.DownloadProvider
|
||||
import eu.kanade.tachiyomi.source.Source
|
||||
import eu.kanade.tachiyomi.source.bookoasis.isBookOasisSource
|
||||
import eu.kanade.tachiyomi.source.bookoasis.toBookOasisChapterRef
|
||||
import eu.kanade.tachiyomi.source.kavita.isKavitaSource
|
||||
import eu.kanade.tachiyomi.source.kavita.toKavitaChapterId
|
||||
import eu.kanade.tachiyomi.source.online.HttpSource
|
||||
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
|
||||
import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences
|
||||
@@ -20,6 +22,8 @@ import tachiyomi.domain.source.model.StubSource
|
||||
import tachiyomi.i18n.MR
|
||||
import tachiyomi.source.local.LocalSource
|
||||
import tachiyomi.source.local.io.Format
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
|
||||
/**
|
||||
* Loader used to retrieve the [PageLoader] for a given chapter.
|
||||
@@ -71,6 +75,55 @@ class ChapterLoader(
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
internal suspend fun reloadTextChapter(
|
||||
chapter: ReaderChapter,
|
||||
readingAnchor: TextReaderAnchor?,
|
||||
readingProgress: Float,
|
||||
): PageLoader? {
|
||||
return withIOContext {
|
||||
val newLoader = getPageLoader(chapter)
|
||||
if (!newLoader.usesTextReaderStyle) {
|
||||
newLoader.recycle()
|
||||
return@withIOContext null
|
||||
}
|
||||
|
||||
try {
|
||||
val pages = newLoader.getPages()
|
||||
.onEach { it.chapter = chapter }
|
||||
if (pages.isEmpty()) {
|
||||
throw Exception(context.stringResource(MR.strings.page_list_empty_error))
|
||||
}
|
||||
|
||||
// If a newer slider value cancelled this rebuild while getPages()
|
||||
// was working, do not publish stale pages into the active chapter.
|
||||
currentCoroutineContext().ensureActive()
|
||||
|
||||
val oldLoader = chapter.pageLoader
|
||||
chapter.pageLoader = newLoader
|
||||
val anchoredPageIndex = readingAnchor?.let { anchor ->
|
||||
val textPages = pages.filterIsInstance<TextReaderPage>()
|
||||
textPages.firstOrNull { it.anchor.contains(anchor) }?.index
|
||||
?: textPages
|
||||
.filter { it.anchor.documentIndex == anchor.documentIndex }
|
||||
.minByOrNull { page ->
|
||||
kotlin.math.abs(page.anchor.startOffset - anchor.startOffset)
|
||||
}
|
||||
?.index
|
||||
}
|
||||
chapter.requestedPage = anchoredPageIndex
|
||||
?: (readingProgress.coerceIn(0f, 0.999999f) * pages.size)
|
||||
.toInt()
|
||||
.coerceIn(0, pages.lastIndex)
|
||||
chapter.state = ReaderChapter.State.Loaded(pages)
|
||||
oldLoader
|
||||
} catch (e: Throwable) {
|
||||
newLoader.recycle()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks [chapter] to be loaded based on present pages and loader in addition to state.
|
||||
*/
|
||||
@@ -91,6 +144,34 @@ class ChapterLoader(
|
||||
source,
|
||||
)
|
||||
val bookOasisRef = dbChapter.url.toBookOasisChapterRef()
|
||||
val kavitaChapterId = dbChapter.url.toKavitaChapterId()
|
||||
val httpSource = source as? HttpSource
|
||||
val documentFallback: (() -> PageLoader)? = when {
|
||||
httpSource != null && httpSource.isBookOasisSource() && bookOasisRef != null &&
|
||||
(bookOasisRef.format == "epub" || bookOasisRef.format == "txt") -> {
|
||||
{
|
||||
BookOasisFilePageLoader(
|
||||
context,
|
||||
httpSource,
|
||||
bookOasisRef,
|
||||
readerPreferences.textReaderStyle(context),
|
||||
)
|
||||
}
|
||||
}
|
||||
httpSource != null && httpSource.isKavitaSource() && kavitaChapterId != null -> {
|
||||
{
|
||||
KavitaCompatPageLoader(
|
||||
context = context,
|
||||
chapter = chapter,
|
||||
source = httpSource,
|
||||
chapterCache = chapterCache,
|
||||
chapterId = kavitaChapterId,
|
||||
textStyle = readerPreferences.textReaderStyle(context),
|
||||
)
|
||||
}
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
|
||||
return when {
|
||||
isDownloaded -> DownloadPageLoader(
|
||||
@@ -99,18 +180,29 @@ class ChapterLoader(
|
||||
source,
|
||||
downloadManager,
|
||||
downloadProvider,
|
||||
documentFallback,
|
||||
)
|
||||
source is LocalSource -> source.getFormat(chapter.chapter).let { format ->
|
||||
when (format) {
|
||||
is Format.Directory -> DirectoryPageLoader(format.file)
|
||||
is Format.Archive -> ArchivePageLoader(format.file.archiveReader(context))
|
||||
is Format.Epub -> EpubPageLoader(format.file.epubReader(context), readerPreferences.textReaderStyle())
|
||||
is Format.Epub -> EpubPageLoader(format.file.epubReader(context), readerPreferences.textReaderStyle(context), context.cacheDir)
|
||||
is Format.Pdf -> PdfPageLoader(context, format.file)
|
||||
is Format.Text -> TextPageLoader(format.file, readerPreferences.textReaderStyle())
|
||||
is Format.Text -> TextPageLoader(format.file, readerPreferences.textReaderStyle(context), context.cacheDir)
|
||||
}
|
||||
}
|
||||
source is HttpSource && source.isBookOasisSource() && bookOasisRef != null -> {
|
||||
BookOasisFilePageLoader(context, source, bookOasisRef, readerPreferences.textReaderStyle())
|
||||
BookOasisFilePageLoader(context, source, bookOasisRef, readerPreferences.textReaderStyle(context))
|
||||
}
|
||||
source is HttpSource && source.isKavitaSource() && kavitaChapterId != null -> {
|
||||
KavitaCompatPageLoader(
|
||||
context = context,
|
||||
chapter = chapter,
|
||||
source = source,
|
||||
chapterCache = chapterCache,
|
||||
chapterId = kavitaChapterId,
|
||||
textStyle = readerPreferences.textReaderStyle(context),
|
||||
)
|
||||
}
|
||||
source is HttpSource -> HttpPageLoader(chapter, source, chapterCache)
|
||||
source is StubSource -> error(context.stringResource(MR.strings.source_not_installed, source.toString()))
|
||||
|
||||
@@ -10,9 +10,14 @@ import eu.kanade.tachiyomi.source.Source
|
||||
import eu.kanade.tachiyomi.source.model.Page
|
||||
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
|
||||
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import mihon.core.archive.archiveReader
|
||||
import mihon.core.archive.epubReader
|
||||
import tachiyomi.core.common.storage.extension
|
||||
import tachiyomi.domain.manga.model.Manga
|
||||
import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences
|
||||
import uy.kohesive.injekt.injectLazy
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Loader used to load a chapter from the downloaded chapters.
|
||||
@@ -23,15 +28,45 @@ internal class DownloadPageLoader(
|
||||
private val source: Source,
|
||||
private val downloadManager: DownloadManager,
|
||||
private val downloadProvider: DownloadProvider,
|
||||
private val documentFallback: (() -> PageLoader)? = null,
|
||||
) : PageLoader() {
|
||||
|
||||
private val context: Context by injectLazy()
|
||||
|
||||
private var archivePageLoader: ArchivePageLoader? = null
|
||||
private var pageLoader: PageLoader? = null
|
||||
private val readerPreferences: ReaderPreferences by injectLazy()
|
||||
|
||||
override var isLocal: Boolean = true
|
||||
override val usesTextReaderStyle: Boolean
|
||||
get() = pageLoader?.usesTextReaderStyle == true || findDownloadedDocument() != null
|
||||
|
||||
override suspend fun getPages(): List<ReaderPage> {
|
||||
check(!isRecycled)
|
||||
|
||||
return try {
|
||||
val pages = getDownloadedPages()
|
||||
if (pages.isNotEmpty() || documentFallback == null) {
|
||||
pages
|
||||
} else {
|
||||
getFallbackPages()
|
||||
}
|
||||
} catch (error: Throwable) {
|
||||
if (error is CancellationException || documentFallback == null) throw error
|
||||
getFallbackPages()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun getDownloadedPages(): List<ReaderPage> {
|
||||
val downloadedDocument = findDownloadedDocument()
|
||||
if (downloadedDocument != null) {
|
||||
val readableDocument = prepareDownloadedDocument(downloadedDocument)
|
||||
return when (readableDocument.extension?.lowercase()) {
|
||||
"epub" -> getPagesFromEpub(readableDocument)
|
||||
"txt" -> getPagesFromText(readableDocument)
|
||||
else -> error("Unsupported downloaded document: ${downloadedDocument.name}")
|
||||
}
|
||||
}
|
||||
|
||||
val dbChapter = chapter.chapter
|
||||
val chapterPath = downloadProvider.findChapterDir(
|
||||
dbChapter.name,
|
||||
@@ -40,6 +75,7 @@ internal class DownloadPageLoader(
|
||||
manga.title,
|
||||
source,
|
||||
)
|
||||
|
||||
return if (chapterPath?.isFile == true) {
|
||||
getPagesFromArchive(chapterPath)
|
||||
} else {
|
||||
@@ -47,13 +83,97 @@ internal class DownloadPageLoader(
|
||||
}
|
||||
}
|
||||
|
||||
private fun findDownloadedDocument(): UniFile? {
|
||||
val dbChapter = chapter.chapter
|
||||
return downloadProvider.findChapterDocument(
|
||||
dbChapter.name,
|
||||
dbChapter.scanlator,
|
||||
dbChapter.url,
|
||||
manga.title,
|
||||
source,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirror SAF-backed documents into the app cache before opening them.
|
||||
* EPUB uses mmap internally, which is not guaranteed to work with every
|
||||
* document provider even though regular stream reads/writes succeed.
|
||||
*/
|
||||
private fun prepareDownloadedDocument(file: UniFile): UniFile {
|
||||
val extension = file.extension?.lowercase()
|
||||
?: error("Downloaded document has no extension: ${file.name}")
|
||||
val sourceLength = file.length()
|
||||
if (sourceLength <= 0L) {
|
||||
error("Downloaded document is empty: ${file.name}")
|
||||
}
|
||||
|
||||
val cacheDir = File(context.cacheDir, "downloaded_reader").apply { mkdirs() }
|
||||
val prefix = "${source.id}-${chapter.chapter.id}-"
|
||||
val target = File(
|
||||
cacheDir,
|
||||
"$prefix$sourceLength-${file.lastModified()}.$extension",
|
||||
)
|
||||
|
||||
if (!target.isFile || target.length() != sourceLength) {
|
||||
cacheDir.listFiles()
|
||||
?.filter { it.name.startsWith(prefix) }
|
||||
?.forEach { it.delete() }
|
||||
|
||||
val temp = File(cacheDir, "${target.name}.part")
|
||||
if (temp.exists()) temp.delete()
|
||||
file.openInputStream().use { input ->
|
||||
temp.outputStream().use { output -> input.copyTo(output) }
|
||||
}
|
||||
if (temp.length() != sourceLength) {
|
||||
temp.delete()
|
||||
error("Downloaded document cache copy is incomplete: ${file.name}")
|
||||
}
|
||||
if (!temp.renameTo(target)) {
|
||||
temp.copyTo(target, overwrite = true)
|
||||
temp.delete()
|
||||
}
|
||||
}
|
||||
|
||||
return UniFile.fromFile(target)
|
||||
?: error("Unable to open cached downloaded document: ${target.absolutePath}")
|
||||
}
|
||||
|
||||
private suspend fun getFallbackPages(): List<ReaderPage> {
|
||||
pageLoader?.recycle()
|
||||
val fallback = documentFallback?.invoke()
|
||||
?: error("Downloaded document fallback is unavailable")
|
||||
pageLoader = fallback
|
||||
val pages = fallback.getPages()
|
||||
isLocal = fallback.isLocal
|
||||
return pages
|
||||
}
|
||||
|
||||
override fun recycle() {
|
||||
super.recycle()
|
||||
archivePageLoader?.recycle()
|
||||
pageLoader?.recycle()
|
||||
pageLoader = null
|
||||
}
|
||||
|
||||
private suspend fun getPagesFromArchive(file: UniFile): List<ReaderPage> {
|
||||
val loader = ArchivePageLoader(file.archiveReader(context)).also { archivePageLoader = it }
|
||||
val loader = ArchivePageLoader(file.archiveReader(context)).also { pageLoader = it }
|
||||
return loader.getPages()
|
||||
}
|
||||
|
||||
private suspend fun getPagesFromEpub(file: UniFile): List<ReaderPage> {
|
||||
val loader = EpubPageLoader(
|
||||
file.epubReader(context),
|
||||
readerPreferences.textReaderStyle(context),
|
||||
context.cacheDir,
|
||||
).also { pageLoader = it }
|
||||
return loader.getPages()
|
||||
}
|
||||
|
||||
private suspend fun getPagesFromText(file: UniFile): List<ReaderPage> {
|
||||
val loader = TextPageLoader(
|
||||
file,
|
||||
readerPreferences.textReaderStyle(context),
|
||||
context.cacheDir,
|
||||
).also { pageLoader = it }
|
||||
return loader.getPages()
|
||||
}
|
||||
|
||||
@@ -69,6 +189,6 @@ internal class DownloadPageLoader(
|
||||
}
|
||||
|
||||
override suspend fun loadPage(page: ReaderPage) {
|
||||
archivePageLoader?.loadPage(page)
|
||||
pageLoader?.loadPage(page)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,41 +4,140 @@ import eu.kanade.tachiyomi.source.model.Page
|
||||
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
|
||||
import eu.kanade.tachiyomi.ui.reader.setting.TextReaderStyle
|
||||
import mihon.core.archive.EpubReader
|
||||
import org.jsoup.Jsoup
|
||||
import java.io.File
|
||||
import java.io.InputStream
|
||||
import java.io.StringReader
|
||||
|
||||
/**
|
||||
* Loader used to load a chapter from a .epub file.
|
||||
*
|
||||
* Text-based EPUBs are rendered as regular Mihon pages. Image-only EPUBs
|
||||
* keep the original image extraction behavior.
|
||||
* Text-based EPUBs are rendered as regular Mihon pages. EPUB spine documents
|
||||
* are processed one at a time so the full book text is never retained in heap.
|
||||
* Image-only EPUBs keep the original image extraction behavior.
|
||||
*/
|
||||
internal class EpubPageLoader(
|
||||
private val reader: EpubReader,
|
||||
private val style: TextReaderStyle,
|
||||
private val cacheDir: File,
|
||||
) : PageLoader() {
|
||||
|
||||
override var isLocal: Boolean = true
|
||||
override val usesTextReaderStyle: Boolean = true
|
||||
|
||||
override suspend fun getPages(): List<ReaderPage> {
|
||||
val textPages = reader.getTextFromPages()
|
||||
.filter { it.isNotBlank() }
|
||||
.flatMap { TextPageRenderer.paginate(it, style) }
|
||||
private var pageStore: TextPageStore? = null
|
||||
|
||||
if (textPages.isNotEmpty()) {
|
||||
return textPages.mapIndexed { index, text ->
|
||||
ReaderPage(index).apply {
|
||||
stream = { TextPageRenderer.render(text, style) }
|
||||
status = Page.State.Ready
|
||||
override suspend fun getPages(): List<ReaderPage> {
|
||||
check(!isRecycled)
|
||||
|
||||
pageStore?.close()
|
||||
pageStore = null
|
||||
|
||||
val store = TextPageStore(cacheDir)
|
||||
return try {
|
||||
val textPages = buildTextPages(store)
|
||||
if (textPages.isNotEmpty()) {
|
||||
store.finishWriting()
|
||||
pageStore = store
|
||||
textPages
|
||||
} else {
|
||||
store.close()
|
||||
reader.getImagesFromPages().mapIndexed { index, path ->
|
||||
ReaderPage(index).apply {
|
||||
stream = { reader.getInputStream(path)!! }
|
||||
status = Page.State.Ready
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Throwable) {
|
||||
store.close()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildTextPages(store: TextPageStore): MutableList<ReaderPage> {
|
||||
val packageHref = reader.getPackageHref()
|
||||
val packageDocument = reader.getPackageDocument(packageHref)
|
||||
val manifest = packageDocument.select("manifest > item")
|
||||
.filter { item ->
|
||||
val mediaType = item.attr("media-type")
|
||||
mediaType == "application/xhtml+xml" || mediaType == "text/html"
|
||||
}
|
||||
.associateBy { it.attr("id") }
|
||||
val spine = packageDocument.select("spine > itemref")
|
||||
.map { it.attr("idref") }
|
||||
|
||||
val result = mutableListOf<ReaderPage>()
|
||||
spine.forEachIndexed { documentIndex, id ->
|
||||
val href = manifest[id]?.attr("href").orEmpty()
|
||||
if (href.isBlank()) return@forEachIndexed
|
||||
|
||||
openEntry(packageHref, href)?.use { input ->
|
||||
val text = extractText(input)
|
||||
if (text.isBlank()) return@use
|
||||
|
||||
StringReader(text).use { textReader ->
|
||||
TextPageRenderer.paginate(textReader, style) { page ->
|
||||
val ref = store.append(page.text)
|
||||
result += TextReaderPage(
|
||||
index = result.size,
|
||||
pageTextProvider = { store.read(ref) },
|
||||
initialStyle = style,
|
||||
anchor = TextReaderAnchor(
|
||||
documentIndex = documentIndex,
|
||||
startOffset = page.startOffset,
|
||||
endOffsetExclusive = page.endOffsetExclusive,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
return reader.getImagesFromPages().mapIndexed { index, path ->
|
||||
ReaderPage(index).apply {
|
||||
stream = { reader.getInputStream(path)!! }
|
||||
status = Page.State.Ready
|
||||
private fun extractText(input: InputStream): String {
|
||||
val pageDoc = Jsoup.parse(input, null, "")
|
||||
pageDoc.select("br").append("\n")
|
||||
pageDoc.select("p,div,li,h1,h2,h3,h4,h5,h6,blockquote").append("\n")
|
||||
return pageDoc.body().wholeText()
|
||||
?.replace(Regex("[ \\t]+\\n"), "\n")
|
||||
?.replace(Regex("\\n{3,}"), "\n\n")
|
||||
?.trim()
|
||||
.orEmpty()
|
||||
}
|
||||
|
||||
private fun openEntry(packageHref: String, href: String): InputStream? {
|
||||
val resolved = resolveEntryPath(packageHref, href)
|
||||
val candidates = linkedSetOf(
|
||||
resolved,
|
||||
resolved.replace('\\', '/'),
|
||||
resolved.replace('/', '\\'),
|
||||
)
|
||||
return candidates.firstNotNullOfOrNull { path ->
|
||||
reader.getInputStream(path)
|
||||
}
|
||||
}
|
||||
|
||||
private fun resolveEntryPath(packageHref: String, href: String): String {
|
||||
val relative = href
|
||||
.substringBefore('#')
|
||||
.substringBefore('?')
|
||||
.trimStart('/', '\\')
|
||||
val separator = if ('\\' in packageHref) '\\' else '/'
|
||||
val base = packageHref.substringBeforeLast(separator, "")
|
||||
val combined = if (base.isBlank()) relative else "$base$separator$relative"
|
||||
val parts = combined.split('/', '\\')
|
||||
val normalized = ArrayDeque<String>()
|
||||
|
||||
parts.forEach { part ->
|
||||
when (part) {
|
||||
"", "." -> Unit
|
||||
".." -> if (normalized.isNotEmpty()) normalized.removeLast()
|
||||
else -> normalized.addLast(part)
|
||||
}
|
||||
}
|
||||
return normalized.joinToString(separator.toString())
|
||||
}
|
||||
|
||||
override suspend fun loadPage(page: ReaderPage) {
|
||||
@@ -46,6 +145,8 @@ internal class EpubPageLoader(
|
||||
}
|
||||
|
||||
override fun recycle() {
|
||||
pageStore?.close()
|
||||
pageStore = null
|
||||
super.recycle()
|
||||
reader.close()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package eu.kanade.tachiyomi.ui.reader.loader
|
||||
|
||||
import android.content.Context
|
||||
import com.hippo.unifile.UniFile
|
||||
import eu.kanade.tachiyomi.data.cache.ChapterCache
|
||||
import eu.kanade.tachiyomi.network.await
|
||||
import eu.kanade.tachiyomi.source.kavita.detectKavitaDocumentFormat
|
||||
import eu.kanade.tachiyomi.source.kavita.kavitaDocumentDownloadRequest
|
||||
import eu.kanade.tachiyomi.source.online.HttpSource
|
||||
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
|
||||
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
|
||||
import eu.kanade.tachiyomi.ui.reader.setting.TextReaderStyle
|
||||
import mihon.core.archive.epubReader
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
* Compatibility loader for Kavita document chapters.
|
||||
*
|
||||
* The Kavita extension renders every chapter through /Reader/image. That works
|
||||
* for image/archive content, but EPUB/TXT can fail while Kavita is preparing an
|
||||
* image cache. For document files, download the original chapter and use
|
||||
* Mihon's native document reader instead. Other formats keep the extension's
|
||||
* normal HttpPageLoader behavior.
|
||||
*/
|
||||
internal class KavitaCompatPageLoader(
|
||||
private val context: Context,
|
||||
private val chapter: ReaderChapter,
|
||||
private val source: HttpSource,
|
||||
private val chapterCache: ChapterCache,
|
||||
private val chapterId: Int,
|
||||
private val textStyle: TextReaderStyle,
|
||||
) : PageLoader() {
|
||||
|
||||
override var isLocal: Boolean = false
|
||||
override val usesTextReaderStyle: Boolean
|
||||
get() = delegate?.usesTextReaderStyle == true
|
||||
|
||||
private var delegate: PageLoader? = null
|
||||
|
||||
override suspend fun getPages(): List<ReaderPage> {
|
||||
check(!isRecycled)
|
||||
|
||||
val format = source.detectKavitaDocumentFormat(chapterId)
|
||||
val loader = when (format) {
|
||||
"epub", "txt" -> createDocumentLoader(format)
|
||||
else -> HttpPageLoader(chapter, source, chapterCache)
|
||||
}
|
||||
|
||||
delegate = loader
|
||||
isLocal = loader.isLocal
|
||||
return loader.getPages()
|
||||
}
|
||||
|
||||
override suspend fun loadPage(page: ReaderPage) {
|
||||
delegate?.loadPage(page)
|
||||
}
|
||||
|
||||
override fun retryPage(page: ReaderPage) {
|
||||
delegate?.retryPage(page)
|
||||
}
|
||||
|
||||
override fun recycle() {
|
||||
delegate?.recycle()
|
||||
delegate = null
|
||||
super.recycle()
|
||||
}
|
||||
|
||||
private suspend fun createDocumentLoader(format: String): PageLoader {
|
||||
val file = getOrDownloadDocument(format)
|
||||
val uniFile = UniFile.fromFile(file)
|
||||
?: throw IOException("Unable to open cached Kavita ${format.uppercase()} file")
|
||||
|
||||
return when (format) {
|
||||
"epub" -> EpubPageLoader(uniFile.epubReader(context), textStyle, context.cacheDir)
|
||||
"txt" -> TextPageLoader(uniFile, textStyle, context.cacheDir)
|
||||
else -> error("Unsupported Kavita document format: $format")
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun getOrDownloadDocument(format: String): File {
|
||||
val cacheDir = File(context.cacheDir, "kavita_reader").apply { mkdirs() }
|
||||
val target = File(cacheDir, "${source.id}-$chapterId.$format")
|
||||
if (target.isFile && target.length() > 0L) return target
|
||||
|
||||
val temp = File(cacheDir, "${target.name}.part")
|
||||
if (temp.exists()) temp.delete()
|
||||
|
||||
val request = source.kavitaDocumentDownloadRequest(chapterId)
|
||||
|
||||
source.client.newCall(request).await().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
val message = when (response.code) {
|
||||
403 -> "Kavita account does not have Download permission"
|
||||
404 -> "Kavita original file is missing or no longer available"
|
||||
500 -> "Kavita could not access the original $format file"
|
||||
else -> "Kavita document download failed: HTTP ${response.code}"
|
||||
}
|
||||
throw IOException(message)
|
||||
}
|
||||
|
||||
temp.outputStream().use { output ->
|
||||
response.body.byteStream().use { input -> input.copyTo(output) }
|
||||
}
|
||||
}
|
||||
|
||||
if (temp.length() <= 0L) {
|
||||
temp.delete()
|
||||
throw IOException("Kavita returned an empty ${format.uppercase()} file")
|
||||
}
|
||||
|
||||
if (!temp.renameTo(target)) {
|
||||
temp.copyTo(target, overwrite = true)
|
||||
temp.delete()
|
||||
}
|
||||
return target
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
package eu.kanade.tachiyomi.ui.reader.loader
|
||||
|
||||
import com.hippo.unifile.UniFile
|
||||
import eu.kanade.tachiyomi.source.model.Page
|
||||
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
|
||||
import eu.kanade.tachiyomi.ui.reader.setting.TextReaderStyle
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.charset.CharacterCodingException
|
||||
import java.io.File
|
||||
import java.io.InputStreamReader
|
||||
import java.io.Reader
|
||||
import java.nio.charset.Charset
|
||||
import java.nio.charset.CodingErrorAction
|
||||
import java.nio.charset.StandardCharsets
|
||||
@@ -13,39 +13,99 @@ import java.nio.charset.StandardCharsets
|
||||
internal class TextPageLoader(
|
||||
private val file: UniFile,
|
||||
private val style: TextReaderStyle,
|
||||
private val cacheDir: File,
|
||||
) : PageLoader() {
|
||||
|
||||
override var isLocal: Boolean = true
|
||||
override val usesTextReaderStyle: Boolean = true
|
||||
|
||||
private var pageStore: TextPageStore? = null
|
||||
|
||||
override suspend fun getPages(): List<ReaderPage> {
|
||||
val bytes = file.openInputStream().use { it.readBytes() }
|
||||
val text = decodeText(bytes)
|
||||
return TextPageRenderer.paginate(text, style).mapIndexed { index, pageText ->
|
||||
ReaderPage(index).apply {
|
||||
stream = { TextPageRenderer.render(pageText, style) }
|
||||
status = Page.State.Ready
|
||||
pageStore?.close()
|
||||
pageStore = null
|
||||
|
||||
val store = TextPageStore(cacheDir)
|
||||
return try {
|
||||
val pages = mutableListOf<ReaderPage>()
|
||||
openDecodedReader().use { reader ->
|
||||
TextPageRenderer.paginate(reader, style) { page ->
|
||||
val ref = store.append(page.text)
|
||||
pages += TextReaderPage(
|
||||
index = pages.size,
|
||||
pageTextProvider = { store.read(ref) },
|
||||
initialStyle = style,
|
||||
anchor = TextReaderAnchor(
|
||||
documentIndex = 0,
|
||||
startOffset = page.startOffset,
|
||||
endOffsetExclusive = page.endOffsetExclusive,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
store.finishWriting()
|
||||
pageStore = store
|
||||
pages
|
||||
} catch (e: Throwable) {
|
||||
store.close()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
private fun decodeText(bytes: ByteArray): String {
|
||||
if (bytes.size >= 3 &&
|
||||
bytes[0] == 0xEF.toByte() &&
|
||||
bytes[1] == 0xBB.toByte() &&
|
||||
bytes[2] == 0xBF.toByte()
|
||||
) {
|
||||
return String(bytes, 3, bytes.size - 3, StandardCharsets.UTF_8)
|
||||
override fun recycle() {
|
||||
pageStore?.close()
|
||||
pageStore = null
|
||||
super.recycle()
|
||||
}
|
||||
|
||||
private fun openDecodedReader(): Reader {
|
||||
val charset = detectCharset()
|
||||
return InputStreamReader(file.openInputStream().buffered(), charset)
|
||||
}
|
||||
|
||||
private fun detectCharset(): Charset {
|
||||
val prefix = ByteArray(3)
|
||||
val prefixSize = file.openInputStream().buffered().use { input ->
|
||||
input.read(prefix)
|
||||
}
|
||||
|
||||
if (
|
||||
prefixSize >= 3 &&
|
||||
prefix[0] == 0xEF.toByte() &&
|
||||
prefix[1] == 0xBB.toByte() &&
|
||||
prefix[2] == 0xBF.toByte()
|
||||
) {
|
||||
return StandardCharsets.UTF_8
|
||||
}
|
||||
if (prefixSize >= 2 && prefix[0] == 0xFF.toByte() && prefix[1] == 0xFE.toByte()) {
|
||||
return StandardCharsets.UTF_16LE
|
||||
}
|
||||
if (prefixSize >= 2 && prefix[0] == 0xFE.toByte() && prefix[1] == 0xFF.toByte()) {
|
||||
return StandardCharsets.UTF_16BE
|
||||
}
|
||||
|
||||
return if (isValidUtf8()) {
|
||||
StandardCharsets.UTF_8
|
||||
} else {
|
||||
Charset.forName("MS949")
|
||||
}
|
||||
}
|
||||
|
||||
private fun isValidUtf8(): Boolean {
|
||||
val decoder = StandardCharsets.UTF_8.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT)
|
||||
|
||||
return try {
|
||||
StandardCharsets.UTF_8.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT)
|
||||
.decode(ByteBuffer.wrap(bytes))
|
||||
.toString()
|
||||
} catch (_: CharacterCodingException) {
|
||||
String(bytes, Charset.forName("MS949"))
|
||||
InputStreamReader(file.openInputStream().buffered(), decoder).use { reader ->
|
||||
val buffer = CharArray(8 * 1024)
|
||||
while (reader.read(buffer) >= 0) {
|
||||
// Validation only. Decoded characters are intentionally discarded.
|
||||
}
|
||||
}
|
||||
true
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,52 +10,172 @@ import android.text.Spannable
|
||||
import android.text.SpannableString
|
||||
import android.text.StaticLayout
|
||||
import android.text.TextPaint
|
||||
import android.text.style.BackgroundColorSpan
|
||||
import android.text.style.ForegroundColorSpan
|
||||
import android.text.style.LineHeightSpan
|
||||
import eu.kanade.tachiyomi.ui.reader.setting.TextReaderStyle
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.InputStream
|
||||
import java.io.Reader
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
internal data class PaginatedTextPage(
|
||||
val text: String,
|
||||
val startOffset: Long,
|
||||
val endOffsetExclusive: Long,
|
||||
)
|
||||
|
||||
internal object TextPageRenderer {
|
||||
private const val PAGE_WIDTH = 1440
|
||||
private const val PAGE_HEIGHT = 2160
|
||||
private const val MARGIN = 96
|
||||
private const val CONTENT_WIDTH = PAGE_WIDTH - (MARGIN * 2)
|
||||
private const val CONTENT_HEIGHT = PAGE_HEIGHT - (MARGIN * 2)
|
||||
private const val MARGIN_DP = 32f
|
||||
private const val STREAM_BUFFER_CHARS = 64 * 1024
|
||||
private const val STREAM_READ_CHARS = 8 * 1024
|
||||
|
||||
fun paginate(text: String, style: TextReaderStyle): List<String> {
|
||||
fun paginate(text: String, style: TextReaderStyle): List<PaginatedTextPage> {
|
||||
if (text.isBlank()) return emptyList()
|
||||
|
||||
val layout = createLayout(text, style)
|
||||
if (layout.lineCount == 0) return listOf(text)
|
||||
return calculatePageSlices(text, style)
|
||||
.mapNotNull { slice -> createPage(text, slice, 0L) }
|
||||
.ifEmpty {
|
||||
listOf(
|
||||
PaginatedTextPage(
|
||||
text = text,
|
||||
startOffset = 0L,
|
||||
endOffsetExclusive = text.length.toLong(),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val pages = mutableListOf<String>()
|
||||
/**
|
||||
* Incrementally paginates a text stream while keeping only a bounded text
|
||||
* window in memory. The final incomplete page is retained between windows
|
||||
* so normal page filling is preserved across chunk boundaries.
|
||||
*/
|
||||
fun paginate(
|
||||
reader: Reader,
|
||||
style: TextReaderStyle,
|
||||
onPage: (PaginatedTextPage) -> Unit,
|
||||
) {
|
||||
val working = StringBuilder(STREAM_BUFFER_CHARS + STREAM_READ_CHARS)
|
||||
val chars = CharArray(STREAM_READ_CHARS)
|
||||
var firstChunk = true
|
||||
var workingStartOffset = 0L
|
||||
|
||||
while (true) {
|
||||
val read = reader.read(chars)
|
||||
if (read < 0) break
|
||||
if (read == 0) continue
|
||||
|
||||
var offset = 0
|
||||
if (firstChunk) {
|
||||
firstChunk = false
|
||||
if (chars[0] == '\uFEFF') {
|
||||
offset = 1
|
||||
workingStartOffset = 1L
|
||||
}
|
||||
}
|
||||
if (offset < read) {
|
||||
working.append(chars, offset, read - offset)
|
||||
}
|
||||
|
||||
if (working.length >= STREAM_BUFFER_CHARS) {
|
||||
val consumed = emitCompletePages(working, style, workingStartOffset, onPage)
|
||||
workingStartOffset += consumed
|
||||
}
|
||||
}
|
||||
|
||||
if (working.isNotEmpty()) {
|
||||
val text = working.toString()
|
||||
calculatePageSlices(text, style)
|
||||
.mapNotNull { slice -> createPage(text, slice, workingStartOffset) }
|
||||
.forEach(onPage)
|
||||
}
|
||||
}
|
||||
|
||||
private fun emitCompletePages(
|
||||
working: StringBuilder,
|
||||
style: TextReaderStyle,
|
||||
baseOffset: Long,
|
||||
onPage: (PaginatedTextPage) -> Unit,
|
||||
): Long {
|
||||
val text = working.toString()
|
||||
val slices = calculatePageSlices(text, style)
|
||||
if (slices.size <= 1) return 0L
|
||||
|
||||
for (index in 0 until slices.lastIndex) {
|
||||
createPage(text, slices[index], baseOffset)?.let(onPage)
|
||||
}
|
||||
|
||||
val consumed = slices.last().start
|
||||
working.delete(0, consumed)
|
||||
return consumed.toLong()
|
||||
}
|
||||
|
||||
private fun createPage(
|
||||
text: String,
|
||||
slice: PageSlice,
|
||||
baseOffset: Long,
|
||||
): PaginatedTextPage? {
|
||||
val rawPageText = text.substring(slice.start, slice.endExclusive)
|
||||
val leading = rawPageText.indexOfFirst { !it.isWhitespace() }
|
||||
if (leading < 0) return null
|
||||
val trailing = rawPageText.indexOfLast { !it.isWhitespace() }
|
||||
val pageText = rawPageText.substring(leading, trailing + 1)
|
||||
return PaginatedTextPage(
|
||||
text = pageText,
|
||||
startOffset = baseOffset + slice.start + leading,
|
||||
endOffsetExclusive = baseOffset + slice.start + trailing + 1,
|
||||
)
|
||||
}
|
||||
|
||||
private fun calculatePageSlices(text: String, style: TextReaderStyle): List<PageSlice> {
|
||||
if (text.isEmpty()) return emptyList()
|
||||
|
||||
val metrics = resolveLayoutMetrics(style)
|
||||
val layout = createLayout(text, style, metrics.contentWidth)
|
||||
if (layout.lineCount == 0) return listOf(PageSlice(0, text.length))
|
||||
|
||||
val pages = mutableListOf<PageSlice>()
|
||||
var startLine = 0
|
||||
while (startLine < layout.lineCount) {
|
||||
val startTop = layout.getLineTop(startLine)
|
||||
var endLine = startLine
|
||||
while (
|
||||
endLine + 1 < layout.lineCount &&
|
||||
layout.getLineBottom(endLine + 1) - startTop <= CONTENT_HEIGHT
|
||||
layout.getLineBottom(endLine + 1) - startTop <= metrics.contentHeight
|
||||
) {
|
||||
endLine++
|
||||
}
|
||||
|
||||
val start = layout.getLineStart(startLine)
|
||||
val end = layout.getLineEnd(endLine).coerceAtLeast(start + 1).coerceAtMost(text.length)
|
||||
text.substring(start, end).trim().takeIf { it.isNotEmpty() }?.let(pages::add)
|
||||
pages += PageSlice(start, end)
|
||||
startLine = endLine + 1
|
||||
}
|
||||
return pages.ifEmpty { listOf(text) }
|
||||
return pages.ifEmpty { listOf(PageSlice(0, text.length)) }
|
||||
}
|
||||
|
||||
fun render(text: String, style: TextReaderStyle): InputStream {
|
||||
val bitmap = Bitmap.createBitmap(PAGE_WIDTH, PAGE_HEIGHT, Bitmap.Config.ARGB_8888)
|
||||
fun render(
|
||||
text: String,
|
||||
style: TextReaderStyle,
|
||||
sentenceHighlightRange: IntRange? = null,
|
||||
activeHighlightRange: IntRange? = null,
|
||||
): InputStream {
|
||||
val metrics = resolveLayoutMetrics(style)
|
||||
val bitmap = Bitmap.createBitmap(metrics.pageWidth, metrics.pageHeight, Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
canvas.drawColor(Color.WHITE)
|
||||
val (backgroundColor, _) = resolveColors(style)
|
||||
canvas.drawColor(backgroundColor)
|
||||
canvas.save()
|
||||
canvas.translate(MARGIN.toFloat(), MARGIN.toFloat())
|
||||
createLayout(text, style).draw(canvas)
|
||||
canvas.translate(metrics.horizontalMargin.toFloat(), metrics.verticalMargin.toFloat())
|
||||
createLayout(
|
||||
text = text,
|
||||
style = style,
|
||||
contentWidth = metrics.contentWidth,
|
||||
sentenceHighlightRange = sentenceHighlightRange,
|
||||
activeHighlightRange = activeHighlightRange,
|
||||
).draw(canvas)
|
||||
canvas.restore()
|
||||
|
||||
val output = ByteArrayOutputStream()
|
||||
@@ -64,40 +184,145 @@ internal object TextPageRenderer {
|
||||
return ByteArrayInputStream(output.toByteArray())
|
||||
}
|
||||
|
||||
private fun createLayout(text: String, style: TextReaderStyle): StaticLayout {
|
||||
private fun createLayout(
|
||||
text: String,
|
||||
style: TextReaderStyle,
|
||||
contentWidth: Int,
|
||||
sentenceHighlightRange: IntRange? = null,
|
||||
activeHighlightRange: IntRange? = null,
|
||||
): StaticLayout {
|
||||
val (_, textColor) = resolveColors(style)
|
||||
val paint = TextPaint().apply {
|
||||
isAntiAlias = true
|
||||
color = Color.BLACK
|
||||
textSize = style.fontSize.toFloat()
|
||||
color = textColor
|
||||
textSize = style.fontSizePx.coerceAtLeast(1f)
|
||||
typeface = style.fontFamily.androidFamilyName
|
||||
?.let { Typeface.create(it, Typeface.NORMAL) }
|
||||
?: Typeface.DEFAULT
|
||||
}
|
||||
val styledText = addParagraphSpacing(text, style.paragraphSpacing)
|
||||
val styledText = addTextSpans(
|
||||
text = text,
|
||||
style = style,
|
||||
sentenceHighlightRange = sentenceHighlightRange,
|
||||
activeHighlightRange = activeHighlightRange,
|
||||
)
|
||||
return StaticLayout.Builder
|
||||
.obtain(styledText, 0, styledText.length, paint, CONTENT_WIDTH)
|
||||
.obtain(styledText, 0, styledText.length, paint, contentWidth)
|
||||
.setAlignment(Layout.Alignment.ALIGN_NORMAL)
|
||||
.setIncludePad(true)
|
||||
// Page slices are laid out again when rendered. Keeping font padding
|
||||
// here can make the sliced layout taller than the same lines measured
|
||||
// during pagination, which clips the last line at larger font sizes.
|
||||
.setIncludePad(false)
|
||||
.setLineSpacing(0f, style.lineSpacingPercent / 100f)
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun addParagraphSpacing(text: String, spacing: Int): CharSequence {
|
||||
if (spacing <= 0 || '\n' !in text) return text
|
||||
private fun resolveLayoutMetrics(style: TextReaderStyle): LayoutMetrics {
|
||||
val pageWidth = style.pageWidthPx.coerceAtLeast(1)
|
||||
val pageHeight = style.pageHeightPx.coerceAtLeast(1)
|
||||
val requestedMargin = (MARGIN_DP * style.density).roundToInt().coerceAtLeast(1)
|
||||
val horizontalMargin = requestedMargin.coerceAtMost(((pageWidth - 1) / 2).coerceAtLeast(0))
|
||||
val verticalMargin = requestedMargin.coerceAtMost(((pageHeight - 1) / 2).coerceAtLeast(0))
|
||||
|
||||
return LayoutMetrics(
|
||||
pageWidth = pageWidth,
|
||||
pageHeight = pageHeight,
|
||||
horizontalMargin = horizontalMargin,
|
||||
verticalMargin = verticalMargin,
|
||||
contentWidth = (pageWidth - horizontalMargin * 2).coerceAtLeast(1),
|
||||
contentHeight = (pageHeight - verticalMargin * 2).coerceAtLeast(1),
|
||||
)
|
||||
}
|
||||
|
||||
private fun resolveColors(style: TextReaderStyle): Pair<Int, Int> {
|
||||
val useDark = when (style.readerTheme) {
|
||||
0 -> false
|
||||
1 -> true
|
||||
2 -> true
|
||||
3 -> style.automaticDark
|
||||
else -> style.automaticDark
|
||||
}
|
||||
val background = when (style.readerTheme) {
|
||||
2 -> Color.rgb(48, 48, 48)
|
||||
else -> if (useDark) Color.BLACK else Color.WHITE
|
||||
}
|
||||
val foreground = if (useDark) Color.WHITE else Color.BLACK
|
||||
return background to foreground
|
||||
}
|
||||
|
||||
private fun addTextSpans(
|
||||
text: String,
|
||||
style: TextReaderStyle,
|
||||
sentenceHighlightRange: IntRange?,
|
||||
activeHighlightRange: IntRange?,
|
||||
): CharSequence {
|
||||
val needsParagraphSpacing = style.paragraphSpacingPx > 0 && '\n' in text
|
||||
val needsSentenceHighlight = sentenceHighlightRange != null && !sentenceHighlightRange.isEmpty()
|
||||
val needsActiveHighlight = activeHighlightRange != null && !activeHighlightRange.isEmpty()
|
||||
if (!needsParagraphSpacing && !needsSentenceHighlight && !needsActiveHighlight) return text
|
||||
|
||||
val spannable = SpannableString(text)
|
||||
text.forEachIndexed { index, char ->
|
||||
if (char == '\n') {
|
||||
spannable.setSpan(
|
||||
ParagraphSpacingSpan(spacing),
|
||||
index,
|
||||
(index + 1).coerceAtMost(text.length),
|
||||
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,
|
||||
)
|
||||
if (needsParagraphSpacing) {
|
||||
text.forEachIndexed { index, char ->
|
||||
if (char == '\n') {
|
||||
spannable.setSpan(
|
||||
ParagraphSpacingSpan(style.paragraphSpacingPx),
|
||||
index,
|
||||
(index + 1).coerceAtMost(text.length),
|
||||
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val (_, baseTextColor) = resolveColors(style)
|
||||
val darkTheme = baseTextColor == Color.WHITE
|
||||
sentenceHighlightRange?.let { range ->
|
||||
applyHighlightSpan(
|
||||
spannable = spannable,
|
||||
textLength = text.length,
|
||||
range = range,
|
||||
backgroundColor = if (darkTheme) Color.rgb(77, 66, 25) else Color.rgb(255, 243, 176),
|
||||
foregroundColor = if (darkTheme) Color.WHITE else Color.BLACK,
|
||||
)
|
||||
}
|
||||
activeHighlightRange?.let { range ->
|
||||
applyHighlightSpan(
|
||||
spannable = spannable,
|
||||
textLength = text.length,
|
||||
range = range,
|
||||
backgroundColor = if (darkTheme) Color.rgb(255, 193, 7) else Color.rgb(255, 179, 0),
|
||||
foregroundColor = Color.BLACK,
|
||||
)
|
||||
}
|
||||
return spannable
|
||||
}
|
||||
|
||||
private fun applyHighlightSpan(
|
||||
spannable: SpannableString,
|
||||
textLength: Int,
|
||||
range: IntRange,
|
||||
backgroundColor: Int,
|
||||
foregroundColor: Int,
|
||||
) {
|
||||
if (range.isEmpty()) return
|
||||
val start = range.first.coerceIn(0, textLength)
|
||||
val endExclusive = (range.last + 1).coerceIn(start, textLength)
|
||||
if (start >= endExclusive) return
|
||||
spannable.setSpan(
|
||||
BackgroundColorSpan(backgroundColor),
|
||||
start,
|
||||
endExclusive,
|
||||
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,
|
||||
)
|
||||
spannable.setSpan(
|
||||
ForegroundColorSpan(foregroundColor),
|
||||
start,
|
||||
endExclusive,
|
||||
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,
|
||||
)
|
||||
}
|
||||
|
||||
private class ParagraphSpacingSpan(private val spacing: Int) : LineHeightSpan {
|
||||
override fun chooseHeight(
|
||||
text: CharSequence?,
|
||||
@@ -111,4 +336,18 @@ internal object TextPageRenderer {
|
||||
fm.bottom += spacing
|
||||
}
|
||||
}
|
||||
|
||||
private data class LayoutMetrics(
|
||||
val pageWidth: Int,
|
||||
val pageHeight: Int,
|
||||
val horizontalMargin: Int,
|
||||
val verticalMargin: Int,
|
||||
val contentWidth: Int,
|
||||
val contentHeight: Int,
|
||||
)
|
||||
|
||||
private data class PageSlice(
|
||||
val start: Int,
|
||||
val endExclusive: Int,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package eu.kanade.tachiyomi.ui.reader.loader
|
||||
|
||||
import java.io.Closeable
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.nio.charset.StandardCharsets
|
||||
|
||||
/**
|
||||
* Disk-backed storage for text reader pages.
|
||||
*
|
||||
* Keeping page strings here avoids retaining an entire large TXT/EPUB in the
|
||||
* Java heap. Individual pages are loaded only when the viewer renders them.
|
||||
*/
|
||||
internal class TextPageStore(cacheRoot: File) : Closeable {
|
||||
|
||||
private val cacheDir = File(cacheRoot, "text_reader_pages").apply {
|
||||
mkdirs()
|
||||
pruneStaleFiles()
|
||||
}
|
||||
private val file = File.createTempFile("pages-", ".utf8", cacheDir)
|
||||
private var writer: RandomAccessFile? = RandomAccessFile(file, "rw")
|
||||
|
||||
@Synchronized
|
||||
fun append(text: String): PageRef {
|
||||
val output = checkNotNull(writer) { "Text page store is already finalized" }
|
||||
val bytes = text.toByteArray(StandardCharsets.UTF_8)
|
||||
val offset = output.filePointer
|
||||
output.write(bytes)
|
||||
return PageRef(offset, bytes.size)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun finishWriting() {
|
||||
writer?.fd?.sync()
|
||||
writer?.close()
|
||||
writer = null
|
||||
}
|
||||
|
||||
fun read(ref: PageRef): String {
|
||||
val bytes = ByteArray(ref.byteLength)
|
||||
RandomAccessFile(file, "r").use { input ->
|
||||
input.seek(ref.offset)
|
||||
input.readFully(bytes)
|
||||
}
|
||||
return String(bytes, StandardCharsets.UTF_8)
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
writer?.close()
|
||||
writer = null
|
||||
file.delete()
|
||||
}
|
||||
|
||||
internal data class PageRef(
|
||||
val offset: Long,
|
||||
val byteLength: Int,
|
||||
)
|
||||
|
||||
private fun File.pruneStaleFiles() {
|
||||
val cutoff = System.currentTimeMillis() - STALE_FILE_AGE_MS
|
||||
listFiles()
|
||||
?.filter { it.isFile && it.lastModified() < cutoff }
|
||||
?.forEach { it.delete() }
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val STALE_FILE_AGE_MS = 24L * 60L * 60L * 1000L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package eu.kanade.tachiyomi.ui.reader.loader
|
||||
|
||||
import eu.kanade.tachiyomi.source.model.Page
|
||||
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
|
||||
import eu.kanade.tachiyomi.ui.reader.setting.TextReaderStyle
|
||||
|
||||
/**
|
||||
* A rendered text page whose visual style can be refreshed cheaply while layout-affecting
|
||||
* changes trigger a debounced chapter repagination to rebuild page boundaries.
|
||||
*/
|
||||
internal data class TextReaderAnchor(
|
||||
val documentIndex: Int,
|
||||
val startOffset: Long,
|
||||
val endOffsetExclusive: Long,
|
||||
) {
|
||||
fun contains(other: TextReaderAnchor): Boolean {
|
||||
if (documentIndex != other.documentIndex) return false
|
||||
val point = other.startOffset
|
||||
return point in startOffset until endOffsetExclusive
|
||||
}
|
||||
}
|
||||
|
||||
internal class TextReaderPage(
|
||||
index: Int,
|
||||
private val pageTextProvider: () -> String,
|
||||
initialStyle: TextReaderStyle,
|
||||
val anchor: TextReaderAnchor,
|
||||
) : ReaderPage(index) {
|
||||
|
||||
@Volatile
|
||||
private var style: TextReaderStyle = initialStyle
|
||||
|
||||
@Volatile
|
||||
private var sentenceHighlightRange: IntRange? = null
|
||||
|
||||
@Volatile
|
||||
private var activeHighlightRange: IntRange? = null
|
||||
|
||||
init {
|
||||
stream = {
|
||||
TextPageRenderer.render(
|
||||
text = pageTextProvider(),
|
||||
style = style,
|
||||
sentenceHighlightRange = sentenceHighlightRange,
|
||||
activeHighlightRange = activeHighlightRange,
|
||||
)
|
||||
}
|
||||
status = Page.State.Ready
|
||||
}
|
||||
|
||||
constructor(
|
||||
index: Int,
|
||||
pageText: String,
|
||||
initialStyle: TextReaderStyle,
|
||||
anchor: TextReaderAnchor,
|
||||
) : this(index, { pageText }, initialStyle, anchor)
|
||||
|
||||
fun updateStyle(newStyle: TextReaderStyle) {
|
||||
style = newStyle
|
||||
}
|
||||
|
||||
fun readText(): String = pageTextProvider()
|
||||
|
||||
fun updateTtsHighlight(
|
||||
sentenceStart: Int,
|
||||
sentenceEndExclusive: Int,
|
||||
activeStart: Int,
|
||||
activeEndExclusive: Int,
|
||||
) {
|
||||
sentenceHighlightRange = if (sentenceStart >= 0 && sentenceEndExclusive > sentenceStart) {
|
||||
sentenceStart until sentenceEndExclusive
|
||||
} else {
|
||||
null
|
||||
}
|
||||
activeHighlightRange = if (activeStart >= 0 && activeEndExclusive > activeStart) {
|
||||
activeStart until activeEndExclusive
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun clearTtsHighlight() {
|
||||
sentenceHighlightRange = null
|
||||
activeHighlightRange = null
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
package eu.kanade.tachiyomi.ui.reader.setting
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.os.Build
|
||||
import android.util.TypedValue
|
||||
import androidx.compose.ui.graphics.BlendMode
|
||||
import dev.icerock.moko.resources.StringResource
|
||||
import dev.zacsweers.metro.AppScope
|
||||
@@ -11,6 +14,7 @@ import tachiyomi.core.common.preference.PreferenceStore
|
||||
import tachiyomi.core.common.preference.getEnum
|
||||
import tachiyomi.core.common.preference.getEnumSet
|
||||
import tachiyomi.i18n.MR
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@Inject
|
||||
@SingleIn(AppScope::class)
|
||||
@@ -110,23 +114,74 @@ class ReaderPreferences(
|
||||
|
||||
// region Text reader
|
||||
|
||||
val textFontSize: Preference<Int> = preferenceStore.getInt("reader_text_font_size", 44)
|
||||
val textFontSize: Preference<Int> = preferenceStore.getInt("reader_text_font_size", 16)
|
||||
|
||||
val textLineSpacing: Preference<Int> = preferenceStore.getInt("reader_text_line_spacing", 115)
|
||||
|
||||
val textParagraphSpacing: Preference<Int> = preferenceStore.getInt("reader_text_paragraph_spacing", 12)
|
||||
val textParagraphSpacing: Preference<Int> = preferenceStore.getInt("reader_text_paragraph_spacing", 4)
|
||||
|
||||
val textFontFamily: Preference<TextFontFamily> = preferenceStore.getEnum(
|
||||
"reader_text_font_family",
|
||||
TextFontFamily.SYSTEM,
|
||||
)
|
||||
|
||||
fun textReaderStyle() = TextReaderStyle(
|
||||
fontSize = textFontSize.get(),
|
||||
lineSpacingPercent = textLineSpacing.get(),
|
||||
paragraphSpacing = textParagraphSpacing.get(),
|
||||
fontFamily = textFontFamily.get(),
|
||||
)
|
||||
// TTS speed is stored as fifths: 6 = 1.2x, 15 = 3.0x.
|
||||
val textTtsSpeedStep: Preference<Int> = preferenceStore.getInt("reader_text_tts_speed_step", 6)
|
||||
|
||||
// auto: prefer Google TTS when installed, then fall back to the Android system default.
|
||||
val textTtsEnginePackage: Preference<String> = preferenceStore.getString("reader_text_tts_engine", "auto")
|
||||
|
||||
private val textUnitsMigrated = preferenceStore.getBoolean("reader_text_units_v2_migrated", false)
|
||||
|
||||
init {
|
||||
if (!textUnitsMigrated.get()) {
|
||||
val legacyFontSize = textFontSize.get()
|
||||
if (legacyFontSize > 30) {
|
||||
textFontSize.set((legacyFontSize / 3f).roundToInt().coerceIn(10, 30))
|
||||
textParagraphSpacing.set((textParagraphSpacing.get() / 3f).roundToInt().coerceIn(0, 16))
|
||||
}
|
||||
textUnitsMigrated.set(true)
|
||||
}
|
||||
}
|
||||
|
||||
fun textReaderStyle(context: Context): TextReaderStyle {
|
||||
val displayMetrics = context.resources.displayMetrics
|
||||
val rawWidth = displayMetrics.widthPixels.coerceAtLeast(1)
|
||||
val rawHeight = displayMetrics.heightPixels.coerceAtLeast(1)
|
||||
|
||||
// Keep the same physical page proportions as the device while capping the
|
||||
// raster size so high-resolution phones do not create oversized bitmaps.
|
||||
val renderScale = minOf(
|
||||
1f,
|
||||
TEXT_READER_MAX_RENDER_WIDTH / rawWidth.toFloat(),
|
||||
TEXT_READER_MAX_RENDER_HEIGHT / rawHeight.toFloat(),
|
||||
)
|
||||
|
||||
return TextReaderStyle(
|
||||
fontSize = textFontSize.get(),
|
||||
lineSpacingPercent = textLineSpacing.get(),
|
||||
paragraphSpacing = textParagraphSpacing.get(),
|
||||
fontFamily = textFontFamily.get(),
|
||||
readerTheme = readerTheme.get(),
|
||||
automaticDark = (context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) ==
|
||||
Configuration.UI_MODE_NIGHT_YES,
|
||||
pageWidthPx = (rawWidth * renderScale).roundToInt().coerceAtLeast(1),
|
||||
pageHeightPx = (rawHeight * renderScale).roundToInt().coerceAtLeast(1),
|
||||
density = displayMetrics.density * renderScale,
|
||||
fontSizePx = TypedValue.applyDimension(
|
||||
TypedValue.COMPLEX_UNIT_SP,
|
||||
textFontSize.get().toFloat(),
|
||||
displayMetrics,
|
||||
) * renderScale,
|
||||
paragraphSpacingPx = (
|
||||
TypedValue.applyDimension(
|
||||
TypedValue.COMPLEX_UNIT_DIP,
|
||||
textParagraphSpacing.get().toFloat(),
|
||||
displayMetrics,
|
||||
) * renderScale
|
||||
).roundToInt(),
|
||||
)
|
||||
}
|
||||
|
||||
// endregion
|
||||
|
||||
@@ -317,6 +372,9 @@ class ReaderPreferences(
|
||||
const val WEBTOON_PADDING_MIN = 0
|
||||
const val WEBTOON_PADDING_MAX = 25
|
||||
|
||||
private const val TEXT_READER_MAX_RENDER_WIDTH = 1440
|
||||
private const val TEXT_READER_MAX_RENDER_HEIGHT = 2400
|
||||
|
||||
const val MILLI_CONVERSION = 100
|
||||
|
||||
val TapZones = listOf(
|
||||
@@ -378,4 +436,11 @@ data class TextReaderStyle(
|
||||
val lineSpacingPercent: Int,
|
||||
val paragraphSpacing: Int,
|
||||
val fontFamily: ReaderPreferences.TextFontFamily,
|
||||
val readerTheme: Int,
|
||||
val automaticDark: Boolean,
|
||||
val pageWidthPx: Int,
|
||||
val pageHeightPx: Int,
|
||||
val density: Float,
|
||||
val fontSizePx: Float,
|
||||
val paragraphSpacingPx: Int,
|
||||
)
|
||||
|
||||
@@ -6,14 +6,18 @@ import eu.kanade.tachiyomi.ui.reader.ReaderViewModel
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class ReaderSettingsViewModel(
|
||||
readerState: StateFlow<ReaderViewModel.State>,
|
||||
val onChangeReadingMode: (ReadingMode) -> Unit,
|
||||
val onChangeOrientation: (ReaderOrientation) -> Unit,
|
||||
val onTextSettingsChanged: () -> Unit,
|
||||
private val onTextSettingsPreview: () -> Unit,
|
||||
private val onTextSettingsCommit: () -> Unit,
|
||||
val preferences: ReaderPreferences,
|
||||
) : ViewModel() {
|
||||
|
||||
@@ -26,4 +30,53 @@ class ReaderSettingsViewModel(
|
||||
.map { it.manga }
|
||||
.distinctUntilChanged()
|
||||
.stateIn(viewModelScope, SharingStarted.Lazily, null)
|
||||
|
||||
private var textSettingsReloadJob: Job? = null
|
||||
private var textAppearanceReloadJob: Job? = null
|
||||
private var textSettingsDirty = false
|
||||
|
||||
/**
|
||||
* Layout-affecting text settings are applied only after the chapter has been
|
||||
* repaginated. Applying a new style to pages that still use old boundaries
|
||||
* can push text below the rendered page and clip the last lines.
|
||||
*/
|
||||
fun requestTextSettingsReload() {
|
||||
textSettingsDirty = true
|
||||
textSettingsReloadJob?.cancel()
|
||||
textSettingsReloadJob = viewModelScope.launch {
|
||||
delay(250)
|
||||
textSettingsDirty = false
|
||||
onTextSettingsCommit()
|
||||
textSettingsReloadJob = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Theme-only changes do not affect page boundaries, so avoid an unnecessary
|
||||
* full repagination.
|
||||
*/
|
||||
fun requestTextAppearanceReload() {
|
||||
textAppearanceReloadJob?.cancel()
|
||||
textAppearanceReloadJob = viewModelScope.launch {
|
||||
delay(50)
|
||||
onTextSettingsPreview()
|
||||
textAppearanceReloadJob = null
|
||||
}
|
||||
}
|
||||
|
||||
fun flushTextSettingsReload() {
|
||||
val hadPendingAppearanceReload = textAppearanceReloadJob != null
|
||||
textAppearanceReloadJob?.cancel()
|
||||
textAppearanceReloadJob = null
|
||||
if (!textSettingsDirty) {
|
||||
if (hadPendingAppearanceReload) {
|
||||
onTextSettingsPreview()
|
||||
}
|
||||
return
|
||||
}
|
||||
textSettingsReloadJob?.cancel()
|
||||
textSettingsReloadJob = null
|
||||
textSettingsDirty = false
|
||||
onTextSettingsCommit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package eu.kanade.tachiyomi.ui.reader.tts
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.core.content.ContextCompat
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
|
||||
object ReaderTtsController {
|
||||
|
||||
data class State(
|
||||
val active: Boolean = false,
|
||||
val playing: Boolean = false,
|
||||
val readerChapterId: Long = -1L,
|
||||
val readerPageIndex: Int = -1,
|
||||
val documentIndex: Int = -1,
|
||||
val sourceSentenceStart: Long = -1L,
|
||||
val sourceSentenceEndExclusive: Long = -1L,
|
||||
val sourceHighlightStart: Long = -1L,
|
||||
val sourceHighlightEndExclusive: Long = -1L,
|
||||
)
|
||||
|
||||
private val mutableState = MutableStateFlow(State())
|
||||
val state = mutableState.asStateFlow()
|
||||
|
||||
internal fun updateState(state: State) {
|
||||
mutableState.value = state
|
||||
}
|
||||
|
||||
fun start(
|
||||
context: Context,
|
||||
sessionId: String,
|
||||
startReaderPageIndex: Int,
|
||||
readerChapterId: Long,
|
||||
title: String,
|
||||
subtitle: String?,
|
||||
speed: Float,
|
||||
enginePackage: String,
|
||||
) {
|
||||
val intent = Intent(context, ReaderTtsService::class.java).apply {
|
||||
action = ReaderTtsService.ACTION_START
|
||||
putExtra(ReaderTtsService.EXTRA_SESSION_ID, sessionId)
|
||||
putExtra(ReaderTtsService.EXTRA_START_PAGE_INDEX, startReaderPageIndex)
|
||||
putExtra(ReaderTtsService.EXTRA_CHAPTER_ID, readerChapterId)
|
||||
putExtra(ReaderTtsService.EXTRA_TITLE, title)
|
||||
putExtra(ReaderTtsService.EXTRA_SUBTITLE, subtitle)
|
||||
putExtra(ReaderTtsService.EXTRA_SPEED, speed)
|
||||
putExtra(ReaderTtsService.EXTRA_ENGINE_PACKAGE, enginePackage)
|
||||
}
|
||||
ContextCompat.startForegroundService(context, intent)
|
||||
}
|
||||
|
||||
fun toggle(context: Context) {
|
||||
if (!state.value.active) return
|
||||
context.startService(
|
||||
Intent(context, ReaderTtsService::class.java).setAction(ReaderTtsService.ACTION_TOGGLE),
|
||||
)
|
||||
}
|
||||
|
||||
fun resumeFromPage(context: Context, readerPageIndex: Int) {
|
||||
if (!state.value.active) return
|
||||
context.startService(
|
||||
Intent(context, ReaderTtsService::class.java)
|
||||
.setAction(ReaderTtsService.ACTION_RESUME_FROM_PAGE)
|
||||
.putExtra(ReaderTtsService.EXTRA_START_PAGE_INDEX, readerPageIndex),
|
||||
)
|
||||
}
|
||||
|
||||
fun stop(context: Context) {
|
||||
if (!state.value.active) return
|
||||
context.startService(
|
||||
Intent(context, ReaderTtsService::class.java).setAction(ReaderTtsService.ACTION_STOP),
|
||||
)
|
||||
}
|
||||
|
||||
fun setSpeed(context: Context, speed: Float) {
|
||||
if (!state.value.active) return
|
||||
context.startService(
|
||||
Intent(context, ReaderTtsService::class.java)
|
||||
.setAction(ReaderTtsService.ACTION_SET_SPEED)
|
||||
.putExtra(ReaderTtsService.EXTRA_SPEED, speed),
|
||||
)
|
||||
}
|
||||
|
||||
fun setEngine(context: Context, enginePackage: String) {
|
||||
if (!state.value.active) return
|
||||
context.startService(
|
||||
Intent(context, ReaderTtsService::class.java)
|
||||
.setAction(ReaderTtsService.ACTION_SET_ENGINE)
|
||||
.putExtra(ReaderTtsService.EXTRA_ENGINE_PACKAGE, enginePackage),
|
||||
)
|
||||
}
|
||||
|
||||
fun refreshVoiceSettings(context: Context, enginePackage: String) {
|
||||
if (!state.value.active) return
|
||||
context.startService(
|
||||
Intent(context, ReaderTtsService::class.java)
|
||||
.setAction(ReaderTtsService.ACTION_REFRESH_VOICE)
|
||||
.putExtra(ReaderTtsService.EXTRA_ENGINE_PACKAGE, enginePackage),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,753 @@
|
||||
package eu.kanade.tachiyomi.ui.reader.tts
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Intent
|
||||
import android.media.AudioAttributes
|
||||
import android.os.Handler
|
||||
import android.os.IBinder
|
||||
import android.os.Looper
|
||||
import android.speech.tts.TextToSpeech
|
||||
import android.speech.tts.UtteranceProgressListener
|
||||
import androidx.core.app.NotificationCompat
|
||||
import eu.kanade.tachiyomi.R
|
||||
import eu.kanade.tachiyomi.data.notification.Notifications
|
||||
import eu.kanade.tachiyomi.util.system.notificationBuilder
|
||||
import java.text.BreakIterator
|
||||
import java.util.Locale
|
||||
import kotlin.math.min
|
||||
|
||||
class ReaderTtsService : Service() {
|
||||
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
private var tts: TextToSpeech? = null
|
||||
private var sessionId: String? = null
|
||||
private var session: ReaderTtsSessionStore.SessionReader? = null
|
||||
private var pagePosition = 0
|
||||
private var pageSpeechStartOffset = 0
|
||||
private var currentWindow: SpeechWindow? = null
|
||||
private var currentSegments: List<Segment> = emptyList()
|
||||
private var lookaheadConsumedChars: Map<Int, Int> = emptyMap()
|
||||
private var segmentPosition = 0
|
||||
private var segmentSpeechOffset = 0
|
||||
private var currentUtteranceBaseOffset = 0
|
||||
private var currentUtteranceId: String? = null
|
||||
private var ttsGeneration = 0
|
||||
private var playbackSpeed = DEFAULT_SPEED
|
||||
private var enginePreference = AUTO_ENGINE
|
||||
private var readerChapterId = -1L
|
||||
private var title = "Text reader"
|
||||
private var subtitle: String? = null
|
||||
private var playing = false
|
||||
private var initialized = false
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
when (intent?.action) {
|
||||
ACTION_START -> startSession(intent)
|
||||
ACTION_TOGGLE -> if (playing) pausePlayback() else resumePlayback()
|
||||
ACTION_RESUME_FROM_PAGE -> resumeFromPage(
|
||||
intent.getIntExtra(EXTRA_START_PAGE_INDEX, -1),
|
||||
)
|
||||
ACTION_STOP -> stopPlayback()
|
||||
ACTION_SET_SPEED -> {
|
||||
playbackSpeed = intent.getFloatExtra(EXTRA_SPEED, playbackSpeed).coerceIn(MIN_SPEED, MAX_SPEED)
|
||||
tts?.setSpeechRate(playbackSpeed)
|
||||
if (playing && initialized) restartCurrentUtterance()
|
||||
refreshNotification()
|
||||
}
|
||||
ACTION_SET_ENGINE, ACTION_REFRESH_VOICE -> {
|
||||
val requestedEngine = intent.getStringExtra(EXTRA_ENGINE_PACKAGE).orEmpty()
|
||||
reinitializeTts(requestedEngine)
|
||||
}
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
private fun startSession(intent: Intent) {
|
||||
val newSessionId = intent.getStringExtra(EXTRA_SESSION_ID) ?: run {
|
||||
stopSelf()
|
||||
return
|
||||
}
|
||||
val newSession = ReaderTtsSessionStore.open(this, newSessionId) ?: run {
|
||||
ReaderTtsSessionStore.delete(this, newSessionId)
|
||||
stopSelf()
|
||||
return
|
||||
}
|
||||
|
||||
cleanupTts()
|
||||
session?.close()
|
||||
ReaderTtsSessionStore.delete(this, sessionId)
|
||||
|
||||
sessionId = newSessionId
|
||||
session = newSession
|
||||
readerChapterId = intent.getLongExtra(EXTRA_CHAPTER_ID, -1L)
|
||||
title = intent.getStringExtra(EXTRA_TITLE).orEmpty().ifBlank { "Text reader" }
|
||||
subtitle = intent.getStringExtra(EXTRA_SUBTITLE)
|
||||
playbackSpeed = intent.getFloatExtra(EXTRA_SPEED, DEFAULT_SPEED).coerceIn(MIN_SPEED, MAX_SPEED)
|
||||
enginePreference = intent.getStringExtra(EXTRA_ENGINE_PACKAGE).orEmpty().ifBlank { AUTO_ENGINE }
|
||||
|
||||
val requestedPageIndex = intent.getIntExtra(EXTRA_START_PAGE_INDEX, 0)
|
||||
pagePosition = newSession.pages.indexOfFirst { it.readerPageIndex >= requestedPageIndex }
|
||||
.takeIf { it >= 0 }
|
||||
?: 0
|
||||
pageSpeechStartOffset = 0
|
||||
currentWindow = null
|
||||
currentSegments = emptyList()
|
||||
lookaheadConsumedChars = emptyMap()
|
||||
segmentPosition = 0
|
||||
segmentSpeechOffset = 0
|
||||
currentUtteranceBaseOffset = 0
|
||||
currentUtteranceId = null
|
||||
playing = false
|
||||
initialized = false
|
||||
|
||||
startForeground(Notifications.ID_READER_TTS, buildNotification(preparing = true))
|
||||
ReaderTtsController.updateState(
|
||||
ReaderTtsController.State(
|
||||
active = true,
|
||||
playing = false,
|
||||
readerChapterId = readerChapterId,
|
||||
readerPageIndex = newSession.pages[pagePosition].readerPageIndex,
|
||||
documentIndex = newSession.pages[pagePosition].documentIndex,
|
||||
),
|
||||
)
|
||||
|
||||
initializeTts(enginePreference, resumeAfterInit = true)
|
||||
}
|
||||
|
||||
private fun initializeTts(
|
||||
requestedEnginePreference: String,
|
||||
resumeAfterInit: Boolean,
|
||||
) {
|
||||
enginePreference = requestedEnginePreference.ifBlank { AUTO_ENGINE }
|
||||
val engine = resolveEngine(enginePreference)
|
||||
val generation = ++ttsGeneration
|
||||
val listener = TextToSpeech.OnInitListener { status ->
|
||||
mainHandler.post {
|
||||
if (generation != ttsGeneration) return@post
|
||||
if (status != TextToSpeech.SUCCESS) {
|
||||
if (engine != null) {
|
||||
cleanupTts()
|
||||
initializeTts(SYSTEM_DEFAULT_ENGINE, resumeAfterInit)
|
||||
} else {
|
||||
stopPlayback()
|
||||
}
|
||||
return@post
|
||||
}
|
||||
|
||||
initialized = true
|
||||
tts?.apply {
|
||||
setSpeechRate(playbackSpeed)
|
||||
setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
|
||||
.build(),
|
||||
)
|
||||
setOnUtteranceProgressListener(progressListener)
|
||||
}
|
||||
playing = resumeAfterInit
|
||||
updatePlaybackState(clearHighlight = false)
|
||||
if (playing) speakCurrentSegment()
|
||||
}
|
||||
}
|
||||
|
||||
tts = if (engine == null) {
|
||||
TextToSpeech(this, listener)
|
||||
} else {
|
||||
TextToSpeech(this, listener, engine)
|
||||
}
|
||||
}
|
||||
|
||||
private fun reinitializeTts(requestedEnginePreference: String) {
|
||||
if (session == null) return
|
||||
val resumeAfterInit = playing
|
||||
currentUtteranceId = null
|
||||
cleanupTts()
|
||||
initializeTts(
|
||||
requestedEnginePreference.ifBlank { enginePreference },
|
||||
resumeAfterInit = resumeAfterInit,
|
||||
)
|
||||
}
|
||||
|
||||
private fun restartCurrentUtterance() {
|
||||
if (!playing || !initialized) return
|
||||
currentUtteranceId = null
|
||||
tts?.stop()
|
||||
speakCurrentSegment()
|
||||
}
|
||||
|
||||
private fun resolveEngine(preference: String): String? {
|
||||
if (preference == SYSTEM_DEFAULT_ENGINE) return null
|
||||
if (preference.isNotBlank() && preference != AUTO_ENGINE) return preference
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
val installed = packageManager.queryIntentServices(
|
||||
Intent(TextToSpeech.Engine.INTENT_ACTION_TTS_SERVICE),
|
||||
0,
|
||||
)
|
||||
return installed
|
||||
.asSequence()
|
||||
.mapNotNull { it.serviceInfo?.packageName }
|
||||
.firstOrNull { it == GOOGLE_TTS_PACKAGE }
|
||||
}
|
||||
|
||||
private fun pausePlayback() {
|
||||
if (!initialized || !playing) return
|
||||
tts?.stop()
|
||||
playing = false
|
||||
updatePlaybackState(clearHighlight = false)
|
||||
}
|
||||
|
||||
private fun resumePlayback() {
|
||||
if (!initialized || session == null) return
|
||||
playing = true
|
||||
updatePlaybackState(clearHighlight = false)
|
||||
speakCurrentSegment()
|
||||
}
|
||||
|
||||
private fun resumeFromPage(readerPageIndex: Int) {
|
||||
if (!initialized || readerPageIndex < 0) return
|
||||
val session = session ?: return
|
||||
val newPagePosition = session.pages.indexOfFirst { it.readerPageIndex >= readerPageIndex }
|
||||
.takeIf { it >= 0 }
|
||||
?: return
|
||||
|
||||
tts?.stop()
|
||||
pagePosition = newPagePosition
|
||||
pageSpeechStartOffset = 0
|
||||
currentWindow = null
|
||||
currentSegments = emptyList()
|
||||
lookaheadConsumedChars = emptyMap()
|
||||
segmentPosition = 0
|
||||
segmentSpeechOffset = 0
|
||||
currentUtteranceBaseOffset = 0
|
||||
currentUtteranceId = null
|
||||
playing = true
|
||||
updatePlaybackState(clearHighlight = true)
|
||||
speakCurrentSegment()
|
||||
}
|
||||
|
||||
private fun speakCurrentSegment() {
|
||||
if (!playing || !initialized) return
|
||||
|
||||
if (currentSegments.isEmpty()) {
|
||||
if (!prepareCurrentSegments()) return
|
||||
}
|
||||
|
||||
if (segmentPosition !in currentSegments.indices) {
|
||||
advancePage()
|
||||
return
|
||||
}
|
||||
|
||||
val segment = currentSegments[segmentPosition]
|
||||
val speechOffset = segmentSpeechOffset.coerceIn(0, segment.text.length)
|
||||
if (speechOffset >= segment.text.length) {
|
||||
segmentSpeechOffset = 0
|
||||
advanceSegment()
|
||||
return
|
||||
}
|
||||
|
||||
currentUtteranceBaseOffset = speechOffset
|
||||
val utteranceId = "$ttsGeneration:$pagePosition:$segmentPosition:$speechOffset"
|
||||
currentUtteranceId = utteranceId
|
||||
val result = tts?.speak(
|
||||
segment.text.substring(speechOffset),
|
||||
TextToSpeech.QUEUE_FLUSH,
|
||||
null,
|
||||
utteranceId,
|
||||
)
|
||||
if (result == TextToSpeech.ERROR) {
|
||||
currentUtteranceId = null
|
||||
segmentSpeechOffset = 0
|
||||
advanceSegment()
|
||||
}
|
||||
}
|
||||
|
||||
private fun prepareCurrentSegments(): Boolean {
|
||||
val session = session ?: run {
|
||||
stopPlayback()
|
||||
return false
|
||||
}
|
||||
val currentEntry = session.pages.getOrNull(pagePosition) ?: run {
|
||||
stopPlayback()
|
||||
return false
|
||||
}
|
||||
val currentText = session.readPage(pagePosition)
|
||||
val safeStart = pageSpeechStartOffset.coerceIn(0, currentText.length)
|
||||
|
||||
if (safeStart >= currentText.length) {
|
||||
advancePage()
|
||||
return false
|
||||
}
|
||||
|
||||
val window = buildSpeechWindow(session, currentEntry.documentIndex, safeStart)
|
||||
val currentPart = window.parts.firstOrNull { it.pagePosition == pagePosition } ?: run {
|
||||
advancePage()
|
||||
return false
|
||||
}
|
||||
val segments = segmentText(window.text)
|
||||
.filter { it.start < currentPart.windowEndExclusive }
|
||||
|
||||
if (segments.isEmpty()) {
|
||||
advancePage()
|
||||
return false
|
||||
}
|
||||
|
||||
currentWindow = window
|
||||
currentSegments = segments
|
||||
segmentPosition = 0
|
||||
lookaheadConsumedChars = buildMap {
|
||||
val last = segments.last()
|
||||
window.parts
|
||||
.asSequence()
|
||||
.filter { it.pagePosition > pagePosition }
|
||||
.forEach { part ->
|
||||
val consumedEnd = min(last.endExclusive, part.windowEndExclusive)
|
||||
if (consumedEnd > part.windowStart) {
|
||||
put(part.pagePosition, consumedEnd - part.windowStart)
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun buildSpeechWindow(
|
||||
session: ReaderTtsSessionStore.SessionReader,
|
||||
documentIndex: Int,
|
||||
currentPageStart: Int,
|
||||
): SpeechWindow {
|
||||
val text = StringBuilder()
|
||||
val parts = mutableListOf<WindowPart>()
|
||||
var candidatePage = pagePosition
|
||||
var pagesAdded = 0
|
||||
var firstPageEnd = -1
|
||||
|
||||
while (
|
||||
candidatePage < session.pages.size &&
|
||||
pagesAdded < MAX_LOOKAHEAD_PAGES &&
|
||||
text.length < MAX_SPEECH_WINDOW_CHARS
|
||||
) {
|
||||
val entry = session.pages[candidatePage]
|
||||
if (entry.documentIndex != documentIndex) break
|
||||
|
||||
val pageText = session.readPage(candidatePage)
|
||||
val pageStart = if (candidatePage == pagePosition) currentPageStart else 0
|
||||
if (pageStart >= pageText.length) {
|
||||
candidatePage++
|
||||
continue
|
||||
}
|
||||
|
||||
if (text.isNotEmpty()) text.append(' ')
|
||||
val windowStart = text.length
|
||||
val available = (MAX_SPEECH_WINDOW_CHARS - text.length).coerceAtLeast(0)
|
||||
if (available == 0) break
|
||||
|
||||
val takeCount = min(pageText.length - pageStart, available)
|
||||
text.append(pageText, pageStart, pageStart + takeCount)
|
||||
val windowEnd = text.length
|
||||
parts += WindowPart(
|
||||
windowStart = windowStart,
|
||||
windowEndExclusive = windowEnd,
|
||||
pagePosition = candidatePage,
|
||||
documentIndex = entry.documentIndex,
|
||||
sourceStartOffset = entry.sourceStartOffset + pageStart,
|
||||
)
|
||||
|
||||
if (candidatePage == pagePosition) {
|
||||
firstPageEnd = windowEnd
|
||||
}
|
||||
|
||||
pagesAdded++
|
||||
if (
|
||||
candidatePage > pagePosition &&
|
||||
firstPageEnd >= 0 &&
|
||||
hasSentenceTerminatorAfter(text, firstPageEnd)
|
||||
) {
|
||||
break
|
||||
}
|
||||
if (takeCount < pageText.length - pageStart) break
|
||||
candidatePage++
|
||||
}
|
||||
|
||||
return SpeechWindow(
|
||||
text = text.toString(),
|
||||
parts = parts,
|
||||
)
|
||||
}
|
||||
|
||||
private fun hasSentenceTerminatorAfter(text: CharSequence, start: Int): Boolean {
|
||||
for (index in start.coerceAtLeast(0) until text.length) {
|
||||
if (text[index] in SENTENCE_TERMINATORS) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun advanceSegment() {
|
||||
currentUtteranceId = null
|
||||
segmentSpeechOffset = 0
|
||||
currentUtteranceBaseOffset = 0
|
||||
segmentPosition++
|
||||
if (segmentPosition >= currentSegments.size) advancePage() else speakCurrentSegment()
|
||||
}
|
||||
|
||||
private fun advancePage() {
|
||||
val session = session ?: return stopPlayback()
|
||||
if (pagePosition + 1 >= session.pages.size) {
|
||||
stopPlayback()
|
||||
return
|
||||
}
|
||||
|
||||
pagePosition++
|
||||
pageSpeechStartOffset = lookaheadConsumedChars[pagePosition] ?: 0
|
||||
currentWindow = null
|
||||
currentSegments = emptyList()
|
||||
segmentPosition = 0
|
||||
segmentSpeechOffset = 0
|
||||
currentUtteranceBaseOffset = 0
|
||||
currentUtteranceId = null
|
||||
speakCurrentSegment()
|
||||
}
|
||||
|
||||
private fun stopPlayback() {
|
||||
playing = false
|
||||
cleanupTts()
|
||||
session?.close()
|
||||
session = null
|
||||
currentWindow = null
|
||||
currentSegments = emptyList()
|
||||
lookaheadConsumedChars = emptyMap()
|
||||
val oldSessionId = sessionId
|
||||
sessionId = null
|
||||
ReaderTtsSessionStore.delete(this, oldSessionId)
|
||||
ReaderTtsController.updateState(ReaderTtsController.State())
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
private fun cleanupTts() {
|
||||
ttsGeneration++
|
||||
currentUtteranceId = null
|
||||
initialized = false
|
||||
tts?.stop()
|
||||
tts?.shutdown()
|
||||
tts = null
|
||||
}
|
||||
|
||||
private fun updatePlaybackState(clearHighlight: Boolean = true) {
|
||||
val session = session ?: return
|
||||
val page = session.pages.getOrNull(pagePosition) ?: return
|
||||
val previous = ReaderTtsController.state.value
|
||||
ReaderTtsController.updateState(
|
||||
ReaderTtsController.State(
|
||||
active = true,
|
||||
playing = playing,
|
||||
readerChapterId = readerChapterId,
|
||||
readerPageIndex = if (!clearHighlight && previous.readerPageIndex >= 0) {
|
||||
previous.readerPageIndex
|
||||
} else {
|
||||
page.readerPageIndex
|
||||
},
|
||||
documentIndex = if (!clearHighlight && previous.documentIndex >= 0) {
|
||||
previous.documentIndex
|
||||
} else {
|
||||
page.documentIndex
|
||||
},
|
||||
sourceSentenceStart = if (clearHighlight) -1L else previous.sourceSentenceStart,
|
||||
sourceSentenceEndExclusive = if (clearHighlight) -1L else previous.sourceSentenceEndExclusive,
|
||||
sourceHighlightStart = if (clearHighlight) -1L else previous.sourceHighlightStart,
|
||||
sourceHighlightEndExclusive = if (clearHighlight) -1L else previous.sourceHighlightEndExclusive,
|
||||
),
|
||||
)
|
||||
refreshNotification()
|
||||
}
|
||||
|
||||
private fun publishHighlight(
|
||||
segment: Segment,
|
||||
relativeStart: Int = 0,
|
||||
relativeEndExclusive: Int = segment.text.length,
|
||||
) {
|
||||
val session = session ?: return
|
||||
val window = currentWindow ?: return
|
||||
val sentenceStart = window.mapStart(segment.start) ?: return
|
||||
val sentenceEnd = window.mapEnd(segment.endExclusive) ?: return
|
||||
|
||||
val safeStart = relativeStart.coerceIn(0, segment.text.length)
|
||||
val safeEnd = relativeEndExclusive.coerceIn(safeStart, segment.text.length)
|
||||
val activeStart = if (safeEnd > safeStart) {
|
||||
window.mapStart(segment.start + safeStart)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val activeEnd = if (safeEnd > safeStart) {
|
||||
window.mapEnd(segment.start + safeEnd)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val activePosition = activeStart ?: sentenceStart
|
||||
val page = session.pages.getOrNull(activePosition.pagePosition) ?: return
|
||||
|
||||
ReaderTtsController.updateState(
|
||||
ReaderTtsController.State(
|
||||
active = true,
|
||||
playing = playing,
|
||||
readerChapterId = readerChapterId,
|
||||
readerPageIndex = page.readerPageIndex,
|
||||
documentIndex = activePosition.documentIndex,
|
||||
sourceSentenceStart = sentenceStart.sourceOffset,
|
||||
sourceSentenceEndExclusive = sentenceEnd.sourceOffset,
|
||||
sourceHighlightStart = activeStart?.sourceOffset ?: -1L,
|
||||
sourceHighlightEndExclusive = activeEnd?.sourceOffset ?: -1L,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun SpeechWindow.mapStart(windowOffset: Int): MappedPosition? {
|
||||
if (text.isEmpty() || parts.isEmpty()) return null
|
||||
val clamped = windowOffset.coerceIn(0, text.lastIndex)
|
||||
val part = parts.firstOrNull { clamped in it.windowStart until it.windowEndExclusive }
|
||||
?: parts.firstOrNull { it.windowStart > clamped }
|
||||
?: parts.lastOrNull()
|
||||
?: return null
|
||||
val charIndex = clamped.coerceIn(part.windowStart, part.windowEndExclusive - 1)
|
||||
return MappedPosition(
|
||||
pagePosition = part.pagePosition,
|
||||
documentIndex = part.documentIndex,
|
||||
sourceOffset = part.sourceStartOffset + (charIndex - part.windowStart),
|
||||
)
|
||||
}
|
||||
|
||||
private fun SpeechWindow.mapEnd(windowEndExclusive: Int): MappedPosition? {
|
||||
if (text.isEmpty() || parts.isEmpty()) return null
|
||||
val clamped = (windowEndExclusive - 1).coerceIn(0, text.lastIndex)
|
||||
val part = parts.firstOrNull { clamped in it.windowStart until it.windowEndExclusive }
|
||||
?: parts.lastOrNull { it.windowEndExclusive <= clamped + 1 }
|
||||
?: parts.firstOrNull()
|
||||
?: return null
|
||||
val charIndex = clamped.coerceIn(part.windowStart, part.windowEndExclusive - 1)
|
||||
return MappedPosition(
|
||||
pagePosition = part.pagePosition,
|
||||
documentIndex = part.documentIndex,
|
||||
sourceOffset = part.sourceStartOffset + (charIndex - part.windowStart) + 1L,
|
||||
)
|
||||
}
|
||||
|
||||
private fun refreshNotification() {
|
||||
if (session == null) return
|
||||
startForeground(Notifications.ID_READER_TTS, buildNotification(preparing = false))
|
||||
}
|
||||
|
||||
private fun buildNotification(preparing: Boolean): android.app.Notification {
|
||||
val toggleIntent = PendingIntent.getService(
|
||||
this,
|
||||
REQUEST_TOGGLE,
|
||||
Intent(this, ReaderTtsService::class.java).setAction(ACTION_TOGGLE),
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
val stopIntent = PendingIntent.getService(
|
||||
this,
|
||||
REQUEST_STOP,
|
||||
Intent(this, ReaderTtsService::class.java).setAction(ACTION_STOP),
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
|
||||
return notificationBuilder(Notifications.CHANNEL_READER_TTS) {
|
||||
setSmallIcon(R.drawable.ic_mihon)
|
||||
setOngoing(true)
|
||||
setOnlyAlertOnce(true)
|
||||
setShowWhen(false)
|
||||
setCategory(NotificationCompat.CATEGORY_TRANSPORT)
|
||||
setContentTitle(title)
|
||||
setContentText(
|
||||
when {
|
||||
preparing -> "TTS preparing"
|
||||
subtitle.isNullOrBlank() -> String.format(Locale.US, "TTS %.1fx", playbackSpeed)
|
||||
else -> subtitle + " · " + String.format(Locale.US, "%.1fx", playbackSpeed)
|
||||
},
|
||||
)
|
||||
addAction(
|
||||
if (playing) R.drawable.ic_pause_24dp else R.drawable.ic_play_arrow_24dp,
|
||||
if (playing) "Pause" else "Play",
|
||||
toggleIntent,
|
||||
)
|
||||
addAction(R.drawable.ic_close_24dp, "Stop", stopIntent)
|
||||
}.build()
|
||||
}
|
||||
|
||||
private val progressListener = object : UtteranceProgressListener() {
|
||||
override fun onStart(utteranceId: String?) {
|
||||
mainHandler.post {
|
||||
if (!playing || utteranceId != currentUtteranceId) return@post
|
||||
currentSegments.getOrNull(segmentPosition)?.let { segment ->
|
||||
publishHighlight(
|
||||
segment = segment,
|
||||
relativeStart = currentUtteranceBaseOffset,
|
||||
relativeEndExclusive = (currentUtteranceBaseOffset + 1).coerceAtMost(segment.text.length),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onRangeStart(utteranceId: String?, start: Int, end: Int, frame: Int) {
|
||||
mainHandler.post {
|
||||
if (!playing || utteranceId != currentUtteranceId) return@post
|
||||
currentSegments.getOrNull(segmentPosition)?.let { segment ->
|
||||
val absoluteStart = (currentUtteranceBaseOffset + start).coerceIn(0, segment.text.length)
|
||||
val absoluteEnd = (currentUtteranceBaseOffset + end).coerceIn(absoluteStart, segment.text.length)
|
||||
segmentSpeechOffset = absoluteStart
|
||||
publishHighlight(segment, absoluteStart, absoluteEnd)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDone(utteranceId: String?) {
|
||||
mainHandler.post {
|
||||
if (!playing || utteranceId != currentUtteranceId) return@post
|
||||
currentUtteranceId = null
|
||||
segmentSpeechOffset = 0
|
||||
advanceSegment()
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated("Deprecated in Java")
|
||||
override fun onError(utteranceId: String?) {
|
||||
mainHandler.post {
|
||||
if (!playing || utteranceId != currentUtteranceId) return@post
|
||||
currentUtteranceId = null
|
||||
segmentSpeechOffset = 0
|
||||
advanceSegment()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(utteranceId: String?, errorCode: Int) {
|
||||
onError(utteranceId)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
cleanupTts()
|
||||
session?.close()
|
||||
session = null
|
||||
ReaderTtsSessionStore.delete(this, sessionId)
|
||||
sessionId = null
|
||||
ReaderTtsController.updateState(ReaderTtsController.State())
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
private fun segmentText(text: String): List<Segment> {
|
||||
if (text.isBlank()) return emptyList()
|
||||
|
||||
val segments = ArrayList<Segment>()
|
||||
val iterator = BreakIterator.getSentenceInstance(Locale.getDefault())
|
||||
iterator.setText(text)
|
||||
var start = iterator.first()
|
||||
var end = iterator.next()
|
||||
|
||||
while (end != BreakIterator.DONE) {
|
||||
addBoundedSegments(text, start, end, segments)
|
||||
start = end
|
||||
end = iterator.next()
|
||||
}
|
||||
|
||||
if (segments.isEmpty()) addBoundedSegments(text, 0, text.length, segments)
|
||||
return segments
|
||||
}
|
||||
|
||||
private fun addBoundedSegments(
|
||||
text: String,
|
||||
rawStart: Int,
|
||||
rawEnd: Int,
|
||||
out: MutableList<Segment>,
|
||||
) {
|
||||
var start = rawStart
|
||||
var end = rawEnd
|
||||
while (start < end && text[start].isWhitespace()) start++
|
||||
while (end > start && text[end - 1].isWhitespace()) end--
|
||||
if (start >= end) return
|
||||
|
||||
val maxLength = min(TextToSpeech.getMaxSpeechInputLength() - 64, MAX_SEGMENT_CHARS)
|
||||
var cursor = start
|
||||
while (cursor < end) {
|
||||
var chunkEnd = min(cursor + maxLength, end)
|
||||
if (chunkEnd < end) {
|
||||
val preferredBreak = text.lastIndexOfAny(
|
||||
charArrayOf(' ', '\n', ',', '.', '!', '?', '。', '!', '?'),
|
||||
startIndex = chunkEnd,
|
||||
)
|
||||
if (preferredBreak > cursor + maxLength / 2) chunkEnd = preferredBreak + 1
|
||||
}
|
||||
val chunk = text.substring(cursor, chunkEnd)
|
||||
val leading = chunk.indexOfFirst { !it.isWhitespace() }.coerceAtLeast(0)
|
||||
val last = chunk.indexOfLast { !it.isWhitespace() }
|
||||
if (last >= 0) {
|
||||
out += Segment(
|
||||
start = cursor + leading,
|
||||
endExclusive = cursor + last + 1,
|
||||
text = chunk.substring(leading, last + 1),
|
||||
)
|
||||
}
|
||||
cursor = chunkEnd
|
||||
}
|
||||
}
|
||||
|
||||
private data class Segment(
|
||||
val start: Int,
|
||||
val endExclusive: Int,
|
||||
val text: String,
|
||||
)
|
||||
|
||||
private data class SpeechWindow(
|
||||
val text: String,
|
||||
val parts: List<WindowPart>,
|
||||
)
|
||||
|
||||
private data class WindowPart(
|
||||
val windowStart: Int,
|
||||
val windowEndExclusive: Int,
|
||||
val pagePosition: Int,
|
||||
val documentIndex: Int,
|
||||
val sourceStartOffset: Long,
|
||||
)
|
||||
|
||||
private data class MappedPosition(
|
||||
val pagePosition: Int,
|
||||
val documentIndex: Int,
|
||||
val sourceOffset: Long,
|
||||
)
|
||||
|
||||
companion object {
|
||||
const val ACTION_START = "eu.kanade.tachiyomi.reader.tts.START"
|
||||
const val ACTION_TOGGLE = "eu.kanade.tachiyomi.reader.tts.TOGGLE"
|
||||
const val ACTION_RESUME_FROM_PAGE = "eu.kanade.tachiyomi.reader.tts.RESUME_FROM_PAGE"
|
||||
const val ACTION_STOP = "eu.kanade.tachiyomi.reader.tts.STOP"
|
||||
const val ACTION_SET_SPEED = "eu.kanade.tachiyomi.reader.tts.SET_SPEED"
|
||||
const val ACTION_SET_ENGINE = "eu.kanade.tachiyomi.reader.tts.SET_ENGINE"
|
||||
const val ACTION_REFRESH_VOICE = "eu.kanade.tachiyomi.reader.tts.REFRESH_VOICE"
|
||||
|
||||
const val EXTRA_SESSION_ID = "session_id"
|
||||
const val EXTRA_START_PAGE_INDEX = "start_page_index"
|
||||
const val EXTRA_CHAPTER_ID = "chapter_id"
|
||||
const val EXTRA_TITLE = "title"
|
||||
const val EXTRA_SUBTITLE = "subtitle"
|
||||
const val EXTRA_SPEED = "speed"
|
||||
const val EXTRA_ENGINE_PACKAGE = "engine_package"
|
||||
|
||||
const val AUTO_ENGINE = "auto"
|
||||
const val SYSTEM_DEFAULT_ENGINE = "system"
|
||||
private const val GOOGLE_TTS_PACKAGE = "com.google.android.tts"
|
||||
|
||||
private const val DEFAULT_SPEED = 1.2f
|
||||
private const val MIN_SPEED = 1.2f
|
||||
private const val MAX_SPEED = 3.0f
|
||||
private const val MAX_SEGMENT_CHARS = 1200
|
||||
private const val MAX_LOOKAHEAD_PAGES = 3
|
||||
private const val MAX_SPEECH_WINDOW_CHARS = 6000
|
||||
private val SENTENCE_TERMINATORS = setOf('.', '!', '?', '。', '!', '?')
|
||||
|
||||
private const val REQUEST_TOGGLE = 9101
|
||||
private const val REQUEST_STOP = 9102
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package eu.kanade.tachiyomi.ui.reader.tts
|
||||
|
||||
import android.content.Context
|
||||
import eu.kanade.tachiyomi.ui.reader.loader.TextReaderPage
|
||||
import java.io.Closeable
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.util.UUID
|
||||
|
||||
internal object ReaderTtsSessionStore {
|
||||
|
||||
data class PageEntry(
|
||||
val readerPageIndex: Int,
|
||||
val documentIndex: Int,
|
||||
val sourceStartOffset: Long,
|
||||
val sourceEndOffsetExclusive: Long,
|
||||
val fileOffset: Long,
|
||||
val byteLength: Int,
|
||||
)
|
||||
|
||||
data class SessionInfo(
|
||||
val id: String,
|
||||
val pages: List<PageEntry>,
|
||||
)
|
||||
|
||||
class SessionReader(
|
||||
private val contentFile: File,
|
||||
val pages: List<PageEntry>,
|
||||
) : Closeable {
|
||||
fun readPage(position: Int): String {
|
||||
val entry = pages[position]
|
||||
val bytes = ByteArray(entry.byteLength)
|
||||
RandomAccessFile(contentFile, "r").use { input ->
|
||||
input.seek(entry.fileOffset)
|
||||
input.readFully(bytes)
|
||||
}
|
||||
return String(bytes, StandardCharsets.UTF_8)
|
||||
}
|
||||
|
||||
override fun close() = Unit
|
||||
}
|
||||
|
||||
fun create(
|
||||
context: Context,
|
||||
pages: List<TextReaderPage>,
|
||||
): SessionInfo {
|
||||
val dir = sessionDir(context)
|
||||
pruneStale(dir)
|
||||
|
||||
val id = UUID.randomUUID().toString()
|
||||
val contentFile = File(dir, "$id.utf8")
|
||||
val indexFile = File(dir, "$id.idx")
|
||||
val entries = ArrayList<PageEntry>(pages.size)
|
||||
|
||||
RandomAccessFile(contentFile, "rw").use { output ->
|
||||
pages.forEach { page ->
|
||||
val text = page.readText()
|
||||
val bytes = text.toByteArray(StandardCharsets.UTF_8)
|
||||
val fileOffset = output.filePointer
|
||||
output.write(bytes)
|
||||
entries += PageEntry(
|
||||
readerPageIndex = page.index,
|
||||
documentIndex = page.anchor.documentIndex,
|
||||
sourceStartOffset = page.anchor.startOffset,
|
||||
sourceEndOffsetExclusive = page.anchor.endOffsetExclusive,
|
||||
fileOffset = fileOffset,
|
||||
byteLength = bytes.size,
|
||||
)
|
||||
}
|
||||
output.fd.sync()
|
||||
}
|
||||
|
||||
indexFile.bufferedWriter(StandardCharsets.UTF_8).use { writer ->
|
||||
entries.forEach { entry ->
|
||||
writer.append(entry.readerPageIndex.toString())
|
||||
.append('\t')
|
||||
.append(entry.documentIndex.toString())
|
||||
.append('\t')
|
||||
.append(entry.sourceStartOffset.toString())
|
||||
.append('\t')
|
||||
.append(entry.sourceEndOffsetExclusive.toString())
|
||||
.append('\t')
|
||||
.append(entry.fileOffset.toString())
|
||||
.append('\t')
|
||||
.append(entry.byteLength.toString())
|
||||
.append('\n')
|
||||
}
|
||||
}
|
||||
return SessionInfo(id, entries)
|
||||
}
|
||||
|
||||
fun open(context: Context, id: String): SessionReader? {
|
||||
val dir = sessionDir(context)
|
||||
val contentFile = File(dir, "$id.utf8")
|
||||
val indexFile = File(dir, "$id.idx")
|
||||
if (!contentFile.isFile || !indexFile.isFile) return null
|
||||
|
||||
val pages = indexFile.useLines { lines ->
|
||||
lines.mapNotNull { line ->
|
||||
val parts = line.split('\t')
|
||||
if (parts.size != 6) return@mapNotNull null
|
||||
PageEntry(
|
||||
readerPageIndex = parts[0].toIntOrNull() ?: return@mapNotNull null,
|
||||
documentIndex = parts[1].toIntOrNull() ?: return@mapNotNull null,
|
||||
sourceStartOffset = parts[2].toLongOrNull() ?: return@mapNotNull null,
|
||||
sourceEndOffsetExclusive = parts[3].toLongOrNull() ?: return@mapNotNull null,
|
||||
fileOffset = parts[4].toLongOrNull() ?: return@mapNotNull null,
|
||||
byteLength = parts[5].toIntOrNull() ?: return@mapNotNull null,
|
||||
)
|
||||
}.toList()
|
||||
}
|
||||
if (pages.isEmpty()) return null
|
||||
return SessionReader(contentFile, pages)
|
||||
}
|
||||
|
||||
fun delete(context: Context, id: String?) {
|
||||
if (id.isNullOrBlank()) return
|
||||
val dir = sessionDir(context)
|
||||
File(dir, "$id.utf8").delete()
|
||||
File(dir, "$id.idx").delete()
|
||||
}
|
||||
|
||||
private fun sessionDir(context: Context): File {
|
||||
return File(context.cacheDir, "reader_tts_sessions").apply { mkdirs() }
|
||||
}
|
||||
|
||||
private fun pruneStale(dir: File) {
|
||||
val cutoff = System.currentTimeMillis() - STALE_FILE_AGE_MS
|
||||
dir.listFiles()
|
||||
?.filter { it.isFile && it.lastModified() < cutoff }
|
||||
?.forEach { it.delete() }
|
||||
}
|
||||
|
||||
private const val STALE_FILE_AGE_MS = 24L * 60L * 60L * 1000L
|
||||
}
|
||||
@@ -26,6 +26,14 @@ interface Viewer {
|
||||
*/
|
||||
fun setChapters(chapters: ViewerChapters)
|
||||
|
||||
/** Rebinds only the currently visible page(s), used for lightweight text-style preview. */
|
||||
fun refreshCurrentPage() {}
|
||||
|
||||
/** Replaces repaginated text pages without expensive per-item diffing where possible. */
|
||||
fun refreshTextChapters(chapters: ViewerChapters) {
|
||||
setChapters(chapters)
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells this viewer to move to the given [page].
|
||||
*/
|
||||
|
||||
@@ -380,6 +380,17 @@ abstract class PagerViewer(val activity: ReaderActivity) : Viewer {
|
||||
pager.setCurrentItem(currentItem, false)
|
||||
}
|
||||
|
||||
override fun refreshCurrentPage() {
|
||||
refreshAdapter()
|
||||
}
|
||||
|
||||
override fun refreshTextChapters(chapters: ViewerChapters) {
|
||||
setChaptersInternal(chapters)
|
||||
val pages = chapters.currChapter.pages ?: return
|
||||
val page = pages[min(chapters.currChapter.requestedPage, pages.lastIndex)]
|
||||
moveToPage(page)
|
||||
}
|
||||
|
||||
/**
|
||||
* Called from the containing activity when a key [event] is received. It should return true
|
||||
* if the event was handled, false otherwise.
|
||||
|
||||
@@ -35,7 +35,7 @@ class WebtoonAdapter(val viewer: WebtoonViewer) : RecyclerView.Adapter<RecyclerV
|
||||
* Updates this adapter with the given [chapters]. It handles setting a few pages of the
|
||||
* next/previous chapter to allow seamless transitions.
|
||||
*/
|
||||
fun setChapters(chapters: ViewerChapters, forceTransition: Boolean) {
|
||||
fun setChapters(chapters: ViewerChapters, forceTransition: Boolean, useDiff: Boolean = true) {
|
||||
val newItems = mutableListOf<Any>()
|
||||
|
||||
// Forces chapter transition if there is missing chapters
|
||||
@@ -65,13 +65,18 @@ class WebtoonAdapter(val viewer: WebtoonViewer) : RecyclerView.Adapter<RecyclerV
|
||||
|
||||
chapters.nextChapter?.pages?.let(newItems::addAll)
|
||||
|
||||
updateItems(newItems)
|
||||
updateItems(newItems, useDiff)
|
||||
}
|
||||
|
||||
private fun updateItems(newItems: List<Any>) {
|
||||
val result = DiffUtil.calculateDiff(Callback(items, newItems))
|
||||
items = newItems
|
||||
result.dispatchUpdatesTo(this)
|
||||
private fun updateItems(newItems: List<Any>, useDiff: Boolean) {
|
||||
if (useDiff) {
|
||||
val result = DiffUtil.calculateDiff(Callback(items, newItems))
|
||||
items = newItems
|
||||
result.dispatchUpdatesTo(this)
|
||||
} else {
|
||||
items = newItems
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
}
|
||||
|
||||
fun refresh() {
|
||||
|
||||
@@ -353,6 +353,19 @@ class WebtoonViewer(val activity: ReaderActivity, val isContinuous: Boolean = tr
|
||||
min(position + 3, adapter.itemCount - 1),
|
||||
)
|
||||
}
|
||||
|
||||
override fun refreshCurrentPage() {
|
||||
refreshAdapter()
|
||||
}
|
||||
|
||||
override fun refreshTextChapters(chapters: ViewerChapters) {
|
||||
val forceTransition = config.alwaysShowChapterTransition || currentPage is ChapterTransition
|
||||
adapter.setChapters(chapters, forceTransition, useDiff = false)
|
||||
val pages = chapters.currChapter.pages ?: return
|
||||
val page = pages[min(chapters.currChapter.requestedPage, pages.lastIndex)]
|
||||
moveToPage(page)
|
||||
currentPage = page
|
||||
}
|
||||
}
|
||||
|
||||
// Double the cache size to reduce rebinds/recycles incurred by the extra layout space on scroll direction changes
|
||||
|
||||
@@ -1103,6 +1103,13 @@
|
||||
<!-- Text reader -->
|
||||
<string name="pref_category_text_reader">Text</string>
|
||||
<string name="pref_text_reader_font_size">Font size</string>
|
||||
<string name="pref_text_reader_tts_speed">TTS speed</string>
|
||||
<string name="pref_text_reader_tts_engine">TTS engine</string>
|
||||
<string name="pref_text_reader_tts_engine_auto">Google TTS preferred</string>
|
||||
<string name="pref_text_reader_tts_engine_system">System default</string>
|
||||
<string name="pref_text_reader_tts_voice_settings">Voice data settings</string>
|
||||
<string name="reader_tts_start">Start TTS</string>
|
||||
<string name="reader_tts_pause">Pause TTS</string>
|
||||
<string name="pref_text_reader_line_spacing">Line spacing</string>
|
||||
<string name="pref_text_reader_paragraph_spacing">Paragraph spacing</string>
|
||||
<string name="pref_text_reader_font_family">Font</string>
|
||||
|
||||
@@ -911,6 +911,13 @@
|
||||
<!-- Text reader -->
|
||||
<string name="pref_category_text_reader">텍스트</string>
|
||||
<string name="pref_text_reader_font_size">글자 크기</string>
|
||||
<string name="pref_text_reader_tts_speed">TTS 배속</string>
|
||||
<string name="pref_text_reader_tts_engine">TTS 엔진</string>
|
||||
<string name="pref_text_reader_tts_engine_auto">Google TTS 우선</string>
|
||||
<string name="pref_text_reader_tts_engine_system">시스템 기본</string>
|
||||
<string name="pref_text_reader_tts_voice_settings">음성 데이터 설정</string>
|
||||
<string name="reader_tts_start">TTS 시작</string>
|
||||
<string name="reader_tts_pause">TTS 일시정지</string>
|
||||
<string name="pref_text_reader_line_spacing">행간</string>
|
||||
<string name="pref_text_reader_paragraph_spacing">문단 간격</string>
|
||||
<string name="pref_text_reader_font_family">글꼴</string>
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user