Compare commits

...

25 Commits

Author SHA1 Message Date
BookOasis Reader c622f74c62 Preview text reader margins while dragging
Build & Test / Build & Test App (push) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Update website / update_website (release) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
2026-09-29 10:06:10 +09:00
BookOasis Reader 95b1199f1d Add adjustable text reader side margins
Build & Test / Build & Test App (push) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Update website / update_website (release) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
2026-09-29 08:16:09 +09:00
BookOasis Reader eca7a3b886 Move floating TTS controls above reader menu
Build & Test / Build & Test App (push) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Update website / update_website (release) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
2026-09-27 17:03:29 +09:00
BookOasis Reader ba1b4d2362 Add floating TTS stop control
Build & Test / Build & Test App (push) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Update website / update_website (release) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
2026-09-27 14:23:06 +09:00
BookOasis Reader 023c3bb2f1 Resume paused TTS by source position
Build & Test / Build & Test App (push) Has been cancelled
2026-09-27 14:14:59 +09:00
BookOasis Reader aec03c6c71 Keep manual reader position while TTS is paused
Build & Test / Build & Test App (push) Has been cancelled
Update website / update_website (release) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
2026-09-27 09:00:49 +09:00
BookOasis Reader c9c119689d Show floating TTS control only in text reader
Build & Test / Build & Test App (push) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
2026-09-27 01:11:17 +09:00
BookOasis Reader 38a327cdf6 Improve TTS highlight contrast
Build & Test / Build & Test App (push) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Update website / update_website (release) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
2026-09-27 00:55:01 +09:00
BookOasis Reader b25679c8de Resume TTS from current reader position
Build & Test / Build & Test App (push) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Update website / update_website (release) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
2026-09-27 00:36:30 +09:00
BookOasis Reader dfd57544a9 Improve TTS highlighting and download detection
Build & Test / Build & Test App (push) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Update website / update_website (release) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
2026-09-26 21:56:54 +09:00
BookOasis Reader 3a5a4c0fb2 Apply TTS setting changes during playback
Build & Test / Build & Test App (push) Has been cancelled
Update website / update_website (release) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
2026-09-26 21:31:28 +09:00
BookOasis Reader 8e113fcbff Add background TTS for EPUB and TXT reader
Build & Test / Build & Test App (push) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Update website / update_website (release) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
2026-09-26 21:13:45 +09:00
BookOasis Reader 74cb92278f Fix EPUB/TXT pagination and reading position restore
Build & Test / Build & Test App (push) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Update website / update_website (release) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
2026-09-26 20:23:45 +09:00
BookOasis Reader 5de6a8f110 Reconcile release artifact history
Build & Test / Build & Test App (push) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Update website / update_website (release) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
2026-09-21 16:41:28 +09:00
BookOasis Reader d4789c2373 Update release APKs for 0.20.5 2026-09-21 16:41:02 +09:00
BookOasis Reader 8dc5a0fc0b Update release APKs for 0.20.5
Build & Test / Build & Test App (push) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
2026-09-21 16:38:01 +09:00
BookOasis Reader 105551f658 Bump version to 0.20.5
Release / Extract tag name (push) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
2026-09-21 16:29:22 +09:00
BookOasis Reader 6a57bc601f Fix reading downloaded EPUB and TXT books
Build & Test / Build & Test App (push) Has been cancelled
2026-09-21 16:23:42 +09:00
javara999 fe73aff860 Fix EPUB and TXT document downloads
Build & Test / Build & Test App (push) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Update website / update_website (release) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
2026-09-21 13:29:23 +09:00
javara999 a347cd10b8 Add release APK artifacts
Build & Test / Build & Test App (push) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
Update website / update_website (release) Has been cancelled
2026-09-21 11:11:15 +09:00
javara999 849148691a Support EPUB and TXT downloads from Kavita and BookOasis
Build & Test / Build & Test App (push) Has been cancelled
2026-09-21 11:02:48 +09:00
javara999 c0e0ef1575 Improve live text reader repagination
Build & Test / Build & Test App (push) Has been cancelled
2026-09-19 20:12:09 +09:00
javara999 6391c9376c Improve text reader streaming and theming
Build & Test / Build & Test App (push) Has been cancelled
Update website / update_website (release) Has been cancelled
2026-09-19 19:39:48 +09:00
javara999 dcec339477 fix: avoid ANR during live text style updates
Build & Test / Build & Test App (push) Has been cancelled
2026-09-19 13:42:50 +09:00
javara999 1b01c894ad feat: add Kavita document fallback and live text settings
Build & Test / Build & Test App (push) Has been cancelled
2026-09-19 12:58:13 +09:00
43 changed files with 2951 additions and 160 deletions
+3
View File
@@ -22,3 +22,6 @@
*.woff binary *.woff binary
*.pyc binary *.pyc binary
*.swp binary *.swp binary
# Android packages
*.apk binary
+3 -2
View File
@@ -33,8 +33,8 @@ android {
defaultConfig { defaultConfig {
applicationId = "app.mihon" applicationId = "app.mihon"
versionCode = 30 versionCode = 31
versionName = "0.20.4" versionName = "0.20.5"
buildConfigField("String", "COMMIT_COUNT", "\"${getLatestCommitCount()}\"") buildConfigField("String", "COMMIT_COUNT", "\"${getLatestCommitCount()}\"")
buildConfigField("String", "COMMIT_SHA", "\"${getLatestCommitSha()}\"") buildConfigField("String", "COMMIT_SHA", "\"${getLatestCommitSha()}\"")
@@ -216,6 +216,7 @@ dependencies {
implementation(projects.coreMetadata) implementation(projects.coreMetadata)
implementation(projects.sourceApi) implementation(projects.sourceApi)
implementation(projects.sourceLocal) implementation(projects.sourceLocal)
implementation(libs.jsoup)
implementation(projects.data) implementation(projects.data)
implementation(projects.domain) implementation(projects.domain)
implementation(projects.presentationCore) implementation(projects.presentationCore)
+6
View File
@@ -32,6 +32,7 @@
tools:ignore="ProtectedPermissions" /> tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<application <application
android:name=".App" android:name=".App"
@@ -209,6 +210,11 @@
android:exported="false" android:exported="false"
android:foregroundServiceType="shortService" /> android:foregroundServiceType="shortService" />
<service
android:name=".ui.reader.tts.ReaderTtsService"
android:exported="false"
android:foregroundServiceType="mediaPlayback" />
<service <service
android:name="androidx.appcompat.app.AppLocalesMetadataHolderService" android:name="androidx.appcompat.app.AppLocalesMetadataHolderService"
android:enabled="false" android:enabled="false"
@@ -73,6 +73,9 @@ fun ReaderAppBars(
onClickOrientation: () -> Unit, onClickOrientation: () -> Unit,
cropEnabled: Boolean, cropEnabled: Boolean,
onClickCropBorder: () -> Unit, onClickCropBorder: () -> Unit,
ttsAvailable: Boolean,
ttsPlaying: Boolean,
onClickTts: () -> Unit,
onClickSettings: () -> Unit, onClickSettings: () -> Unit,
) { ) {
val backgroundColor = MaterialTheme.colorScheme val backgroundColor = MaterialTheme.colorScheme
@@ -172,6 +175,9 @@ fun ReaderAppBars(
onClickOrientation = onClickOrientation, onClickOrientation = onClickOrientation,
cropEnabled = cropEnabled, cropEnabled = cropEnabled,
onClickCropBorder = onClickCropBorder, onClickCropBorder = onClickCropBorder,
ttsAvailable = ttsAvailable,
ttsPlaying = ttsPlaying,
onClickTts = onClickTts,
onClickSettings = onClickSettings, onClickSettings = onClickSettings,
) )
} }
@@ -25,6 +25,9 @@ fun ReaderBottomBar(
onClickOrientation: () -> Unit, onClickOrientation: () -> Unit,
cropEnabled: Boolean, cropEnabled: Boolean,
onClickCropBorder: () -> Unit, onClickCropBorder: () -> Unit,
ttsAvailable: Boolean,
ttsPlaying: Boolean,
onClickTts: () -> Unit,
onClickSettings: () -> Unit, onClickSettings: () -> Unit,
modifier: Modifier = Modifier, 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) { IconButton(onClick = onClickSettings) {
Icon( Icon(
imageVector = MaterialSymbols.Rounded.Settings, imageVector = MaterialSymbols.Rounded.Settings,
@@ -51,7 +51,10 @@ internal fun ColumnScope.GeneralPage(viewModel: ReaderSettingsViewModel) {
themes.map { (labelRes, value) -> themes.map { (labelRes, value) ->
FilterChip( FilterChip(
selected = readerTheme == value, selected = readerTheme == value,
onClick = { viewModel.preferences.readerTheme.set(value) }, onClick = {
viewModel.preferences.readerTheme.set(value)
viewModel.requestTextAppearanceReload()
},
label = { Text(stringResource(labelRes)) }, label = { Text(stringResource(labelRes)) },
) )
} }
@@ -9,7 +9,6 @@ import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalView import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.window.DialogWindowProvider import androidx.compose.ui.window.DialogWindowProvider
@@ -33,15 +32,11 @@ fun ReaderSettingsDialog(
stringResource(MR.strings.pref_category_text_reader), stringResource(MR.strings.pref_category_text_reader),
) )
val pagerState = rememberPagerState { tabTitles.size } val pagerState = rememberPagerState { tabTitles.size }
val initialTextStyle = remember { viewModel.preferences.textReaderStyle() }
BoxWithConstraints { BoxWithConstraints {
TabbedDialog( TabbedDialog(
modifier = Modifier.heightIn(max = maxHeight * 0.75f), modifier = Modifier.heightIn(max = maxHeight * 0.75f),
onDismissRequest = { onDismissRequest = {
if (viewModel.preferences.textReaderStyle() != initialTextStyle) { viewModel.flushTextSettingsReload()
viewModel.onTextSettingsChanged()
}
onDismissRequest() onDismissRequest()
onShowMenus() onShowMenus()
}, },
@@ -51,7 +46,7 @@ fun ReaderSettingsDialog(
val window = (LocalView.current.parent as? DialogWindowProvider)?.window val window = (LocalView.current.parent as? DialogWindowProvider)?.window
LaunchedEffect(pagerState.currentPage) { LaunchedEffect(pagerState.currentPage) {
if (pagerState.currentPage == 2) { if (pagerState.currentPage == 2 || pagerState.currentPage == 3) {
window?.setDimAmount(0f) window?.setDimAmount(0f)
onHideMenus() onHideMenus()
} else { } else {
@@ -1,16 +1,25 @@
package eu.kanade.presentation.reader.settings 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.ColumnScope
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.material3.FilterChip import androidx.compose.material3.FilterChip
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences
import eu.kanade.tachiyomi.ui.reader.setting.ReaderSettingsViewModel 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.i18n.MR
import tachiyomi.presentation.core.components.SettingsChipRow import tachiyomi.presentation.core.components.SettingsChipRow
import tachiyomi.presentation.core.components.SliderItem import tachiyomi.presentation.core.components.SliderItem
@@ -26,15 +35,28 @@ private val fontFamilies = listOf(
@Composable @Composable
internal fun ColumnScope.TextSettingsPage(viewModel: ReaderSettingsViewModel) { 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 fontSizePref = viewModel.preferences.textFontSize
val fontSize by fontSizePref.collectAsState() val fontSize by fontSizePref.collectAsState()
SliderItem( SliderItem(
label = stringResource(MR.strings.pref_text_reader_font_size), label = stringResource(MR.strings.pref_text_reader_font_size),
value = fontSize, value = fontSize,
valueRange = 32..72, valueRange = 10..30,
steps = 19, steps = 19,
valueString = fontSize.toString(), valueString = "$fontSize sp",
onChange = fontSizePref::set, onChange = { value ->
fontSizePref.set(value)
viewModel.requestTextSettingsReload()
},
pillColor = MaterialTheme.colorScheme.surfaceContainerHighest, pillColor = MaterialTheme.colorScheme.surfaceContainerHighest,
) )
@@ -45,8 +67,11 @@ internal fun ColumnScope.TextSettingsPage(viewModel: ReaderSettingsViewModel) {
value = lineSpacing, value = lineSpacing,
valueRange = 90..180, valueRange = 90..180,
steps = 17, steps = 17,
valueString = "$lineSpacing%", valueString = String.format("%.2fx", lineSpacing / 100f),
onChange = lineSpacingPref::set, onChange = { value ->
lineSpacingPref.set(value)
viewModel.requestTextSettingsReload()
},
pillColor = MaterialTheme.colorScheme.surfaceContainerHighest, pillColor = MaterialTheme.colorScheme.surfaceContainerHighest,
) )
@@ -55,10 +80,28 @@ internal fun ColumnScope.TextSettingsPage(viewModel: ReaderSettingsViewModel) {
SliderItem( SliderItem(
label = stringResource(MR.strings.pref_text_reader_paragraph_spacing), label = stringResource(MR.strings.pref_text_reader_paragraph_spacing),
value = paragraphSpacing, value = paragraphSpacing,
valueRange = 0..48, valueRange = 0..16,
steps = 11, steps = 15,
valueString = paragraphSpacing.toString(), valueString = "$paragraphSpacing dp",
onChange = paragraphSpacingPref::set, onChange = { value ->
paragraphSpacingPref.set(value)
viewModel.requestTextSettingsReload()
},
pillColor = MaterialTheme.colorScheme.surfaceContainerHighest,
)
val horizontalMarginPref = viewModel.preferences.textHorizontalMargin
val horizontalMargin by horizontalMarginPref.collectAsState()
SliderItem(
label = stringResource(MR.strings.pref_text_reader_horizontal_margin),
value = horizontalMargin,
valueRange = 0..64,
steps = 15,
valueString = "$horizontalMargin dp",
onChange = { value ->
horizontalMarginPref.set(value)
viewModel.previewAndRequestTextSettingsReload()
},
pillColor = MaterialTheme.colorScheme.surfaceContainerHighest, pillColor = MaterialTheme.colorScheme.surfaceContainerHighest,
) )
@@ -68,12 +111,87 @@ internal fun ColumnScope.TextSettingsPage(viewModel: ReaderSettingsViewModel) {
fontFamilies.forEach { (label, value) -> fontFamilies.forEach { (label, value) ->
FilterChip( FilterChip(
selected = fontFamily == value, selected = fontFamily == value,
onClick = { fontFamilyPref.set(value) }, onClick = {
fontFamilyPref.set(value)
viewModel.requestTextSettingsReload()
},
label = { Text(stringResource(label)) }, 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(
text = stringResource(MR.strings.pref_text_reader_pdf_note), text = stringResource(MR.strings.pref_text_reader_pdf_note),
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
@@ -95,7 +95,7 @@ class DownloadCache(
.stateIn(scope, SharingStarted.WhileSubscribed(), false) .stateIn(scope, SharingStarted.WhileSubscribed(), false)
private val diskCacheFile: File 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 val rootDownloadsDirMutex = Mutex()
private var rootDownloadsDir = RootDirectory(storageManager.getDownloadsDirectory()) private var rootDownloadsDir = RootDirectory(storageManager.getDownloadsDirectory())
@@ -374,10 +374,13 @@ class DownloadCache(
when { when {
// Ignore incomplete downloads // Ignore incomplete downloads
it.name?.endsWith(Downloader.TMP_DIR_SUFFIX) == true -> null it.name?.endsWith(Downloader.TMP_DIR_SUFFIX) == true -> null
it.name?.contains(".download.", ignoreCase = true) == true -> null
// Folder of images // Folder of images
it.isDirectory -> it.name it.isDirectory -> it.name
// CBZ files // Archived or original document files
it.isFile && it.extension == "cbz" -> it.nameWithoutExtension it.isFile && it.extension?.lowercase()?.let { extension ->
extension == "cbz" || extension in DOCUMENT_DOWNLOAD_EXTENSIONS
} == true -> it.nameWithoutExtension
// Anything else is irrelevant // Anything else is irrelevant
else -> null else -> null
} }
@@ -214,7 +214,8 @@ class DownloadManager(
mangaTitle: String, mangaTitle: String,
source: Source, source: Source,
): Boolean { ): 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) removeFromDownloadQueue(filteredChapters)
val (mangaDir, chapterDirs) = provider.findChapterDirs(filteredChapters, manga, source) val (mangaDir, chapterDownloads) = provider.findChapterDirs(filteredChapters, manga, source)
chapterDirs.forEach { it.delete() } chapterDownloads.forEach { it.delete() }
cache.removeChapters(filteredChapters, manga) cache.removeChapters(filteredChapters, manga)
// Delete manga directory if empty // Delete manga directory if empty
@@ -405,8 +406,12 @@ class DownloadManager(
.firstOrNull() ?: return .firstOrNull() ?: return
var newName = provider.getChapterDirName(newChapter.name, newChapter.scanlator, newChapter.url) var newName = provider.getChapterDirName(newChapter.name, newChapter.scanlator, newChapter.url)
if (oldDownload.isFile && oldDownload.extension == "cbz") { if (oldDownload.isFile) {
newName += ".cbz" oldDownload.extension?.lowercase()?.let { extension ->
if (extension == "cbz" || extension in DOCUMENT_DOWNLOAD_EXTENSIONS) {
newName += ".$extension"
}
}
} }
if (oldDownload.name == newName) return if (oldDownload.name == newName) return
@@ -19,6 +19,8 @@ import tachiyomi.domain.storage.service.StorageManager
import tachiyomi.i18n.MR import tachiyomi.i18n.MR
import java.io.IOException 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. * 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> * 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. * Document files are checked explicitly before the generic chapter path so
* @param manga the manga of the chapter. * a stale image directory with the same chapter name cannot shadow them.
* @param source the source of the chapter. */
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>> { fun findChapterDirs(chapters: List<Chapter>, manga: Manga, source: Source): Pair<UniFile?, List<UniFile>> {
val mangaDir = findMangaDir(manga.title, source) ?: return null to emptyList() val mangaDir = findMangaDir(manga.title, source) ?: return null to emptyList()
@@ -128,6 +158,13 @@ class DownloadProvider(
getValidChapterDirNames(chapter.name, chapter.scanlator, chapter.url).asSequence() getValidChapterDirNames(chapter.name, chapter.scanlator, chapter.url).asSequence()
.mapNotNull { mangaDir.findFile(it) } .mapNotNull { mangaDir.findFile(it) }
.firstOrNull() .firstOrNull()
?: findChapterDocument(
chapter.name,
chapter.scanlator,
chapter.url,
manga.title,
source,
)
} }
} }
@@ -250,11 +287,17 @@ class DownloadProvider(
add(chapterDirName) add(chapterDirName)
// Archived chapters // Archived chapters
add("$chapterDirName.cbz") add("$chapterDirName.cbz")
DOCUMENT_DOWNLOAD_EXTENSIONS.forEach { extension ->
add("$chapterDirName.$extension")
}
// any legacy names // any legacy names
legacyChapterDirNames.forEach { legacyChapterDirNames.forEach {
add(it) add(it)
add("$it.cbz") 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.library.LibraryUpdateNotifier
import eu.kanade.tachiyomi.data.notification.NotificationHandler import eu.kanade.tachiyomi.data.notification.NotificationHandler
import eu.kanade.tachiyomi.network.HttpException import eu.kanade.tachiyomi.network.HttpException
import eu.kanade.tachiyomi.network.await
import eu.kanade.tachiyomi.source.UnmeteredSource 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.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.source.online.HttpSource
import eu.kanade.tachiyomi.util.storage.DiskUtil import eu.kanade.tachiyomi.util.storage.DiskUtil
import eu.kanade.tachiyomi.util.storage.DiskUtil.NOMEDIA_FILE import eu.kanade.tachiyomi.util.storage.DiskUtil.NOMEDIA_FILE
@@ -44,6 +52,7 @@ import kotlinx.coroutines.supervisorScope
import logcat.LogPriority import logcat.LogPriority
import mihon.core.archive.ZipWriter import mihon.core.archive.ZipWriter
import nl.adaptivity.xmlutil.serialization.XML import nl.adaptivity.xmlutil.serialization.XML
import okhttp3.Request
import okhttp3.Response import okhttp3.Response
import tachiyomi.core.common.i18n.stringResource import tachiyomi.core.common.i18n.stringResource
import tachiyomi.core.common.util.lang.launchIO import tachiyomi.core.common.util.lang.launchIO
@@ -339,9 +348,15 @@ class Downloader(
download.chapter.scanlator, download.chapter.scanlator,
download.chapter.url, download.chapter.url,
) )
val tmpDir = mangaDir.createDirectory(chapterDirname + TMP_DIR_SUFFIX)!!
try { 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 // If the page list already exists, start from the file
val pageList = download.pages ?: run { val pageList = download.pages ?: run {
// Otherwise, pull page list from network and add them to download object // 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. * 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 // Arbitrary minimum required space to start a download: 200 MB
private const val MIN_DISK_SPACE = 200L * 1024 * 1024 private const val MIN_DISK_SPACE = 200L * 1024 * 1024
@@ -21,6 +21,10 @@ object Notifications {
const val CHANNEL_COMMON = "common_channel" const val CHANNEL_COMMON = "common_channel"
const val ID_DOWNLOAD_IMAGE = 2 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. * Notification channel and ids used by the library updater.
*/ */
@@ -119,6 +123,10 @@ object Notifications {
buildNotificationChannel(CHANNEL_COMMON, IMPORTANCE_LOW) { buildNotificationChannel(CHANNEL_COMMON, IMPORTANCE_LOW) {
setName(context.stringResource(MR.strings.channel_common)) 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) { buildNotificationChannel(CHANNEL_LIBRARY_PROGRESS, IMPORTANCE_LOW) {
setName(context.stringResource(MR.strings.channel_progress)) setName(context.stringResource(MR.strings.channel_progress))
setGroup(GROUP_LIBRARY) setGroup(GROUP_LIBRARY)
@@ -21,13 +21,40 @@ internal data class BookOasisChapterRef(
val format: String, 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 { internal fun Source.isBookOasisSource(): Boolean {
return this::class.java.name.startsWith(BOOKOASIS_PACKAGE_PREFIX) return this::class.java.name.startsWith(BOOKOASIS_PACKAGE_PREFIX)
} }
internal fun String.toBookOasisChapterRef(): BookOasisChapterRef? { internal fun String.toBookOasisChapterRef(): BookOasisChapterRef? {
val path = substringBefore('?') 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 params = parseQueryParameters(this)
val format = params["bo_format"]?.lowercase() ?: return null val format = params["bo_format"]?.lowercase() ?: return null
if (format !in DOCUMENT_FORMATS) 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,22 @@ import android.view.WindowManager
import android.widget.Toast import android.widget.Toast
import androidx.activity.enableEdgeToEdge import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels import androidx.activity.viewModels
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.navigationBarsPadding 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.AlertDialog
import androidx.compose.material3.CircularProgressIndicator 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.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState import androidx.compose.runtime.collectAsState
@@ -34,6 +43,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.core.content.getSystemService import androidx.core.content.getSystemService
import androidx.core.graphics.Insets import androidx.core.graphics.Insets
@@ -42,6 +52,8 @@ import androidx.core.transition.doOnEnd
import androidx.core.view.ViewCompat import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat import androidx.core.view.WindowInsetsControllerCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import com.google.android.material.transition.platform.MaterialContainerTransform import com.google.android.material.transition.platform.MaterialContainerTransform
import dev.zacsweers.metro.Inject import dev.zacsweers.metro.Inject
@@ -65,6 +77,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.AddToLibraryFirst
import eu.kanade.tachiyomi.ui.reader.ReaderViewModel.SetAsCoverResult.Error import eu.kanade.tachiyomi.ui.reader.ReaderViewModel.SetAsCoverResult.Error
import eu.kanade.tachiyomi.ui.reader.ReaderViewModel.SetAsCoverResult.Success 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.ReaderChapter
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
import eu.kanade.tachiyomi.ui.reader.model.ViewerChapters import eu.kanade.tachiyomi.ui.reader.model.ViewerChapters
@@ -72,6 +85,8 @@ import eu.kanade.tachiyomi.ui.reader.setting.ReaderOrientation
import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences
import eu.kanade.tachiyomi.ui.reader.setting.ReaderSettingsViewModel import eu.kanade.tachiyomi.ui.reader.setting.ReaderSettingsViewModel
import eu.kanade.tachiyomi.ui.reader.setting.ReadingMode 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.ReaderProgressIndicator
import eu.kanade.tachiyomi.ui.reader.viewer.pager.R2LPagerViewer import eu.kanade.tachiyomi.ui.reader.viewer.pager.R2LPagerViewer
import eu.kanade.tachiyomi.ui.reader.viewer.webgpu.WebGpuViewer import eu.kanade.tachiyomi.ui.reader.viewer.webgpu.WebGpuViewer
@@ -137,6 +152,7 @@ class ReaderActivity : BaseActivity() {
private val windowInsetsController by lazy { WindowInsetsControllerCompat(window, window.decorView) } private val windowInsetsController by lazy { WindowInsetsControllerCompat(window, window.decorView) }
private var loadingIndicator: ReaderProgressIndicator? = null private var loadingIndicator: ReaderProgressIndicator? = null
private var ttsHighlightedPage: TextReaderPage? = null
var isScrollingThroughPages = false var isScrollingThroughPages = false
private set private set
@@ -217,12 +233,28 @@ class ReaderActivity : BaseActivity() {
.onEach(::setChapters) .onEach(::setChapters)
.launchIn(lifecycleScope) .launchIn(lifecycleScope)
ReaderTtsController.state
.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
.sample(0.2.seconds)
.onEach(::applyTtsState)
.launchIn(lifecycleScope)
viewModel.eventFlow viewModel.eventFlow
.onEach { event -> .onEach { event ->
when (event) { when (event) {
ReaderViewModel.Event.ReloadViewerChapters -> { ReaderViewModel.Event.ReloadViewerChapters -> {
viewModel.state.value.viewerChapters?.let(::setChapters) 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 -> { ReaderViewModel.Event.PageChanged -> {
displayRefreshHost.flash() displayRefreshHost.flash()
} }
@@ -249,12 +281,14 @@ class ReaderActivity : BaseActivity() {
private fun ReaderActivityBinding.setComposeOverlay(): Unit = composeOverlay.setComposeContent { private fun ReaderActivityBinding.setComposeOverlay(): Unit = composeOverlay.setComposeContent {
val state by viewModel.state.collectAsState() val state by viewModel.state.collectAsState()
val showPageNumber by readerPreferences.showPageNumber.collectAsState() val showPageNumber by readerPreferences.showPageNumber.collectAsState()
val ttsState by ReaderTtsController.state.collectAsState()
val settingsviewModel = remember { val settingsviewModel = remember {
ReaderSettingsViewModel( ReaderSettingsViewModel(
readerState = viewModel.state, readerState = viewModel.state,
onChangeReadingMode = viewModel::setMangaReadingMode, onChangeReadingMode = viewModel::setMangaReadingMode,
onChangeOrientation = viewModel::setMangaOrientationType, onChangeOrientation = viewModel::setMangaOrientationType,
onTextSettingsChanged = viewModel::reloadTextReaderStyle, onTextSettingsPreview = viewModel::previewTextReaderStyle,
onTextSettingsCommit = viewModel::commitTextReaderStyle,
preferences = readerPreferences, preferences = readerPreferences,
) )
} }
@@ -273,6 +307,59 @@ class ReaderActivity : BaseActivity() {
ContentOverlay(state = state) ContentOverlay(state = state)
AppBars(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) {
val floatingTtsBottomPadding by animateDpAsState(
targetValue = if (state.menuVisible) 144.dp else 72.dp,
animationSpec = tween(durationMillis = 200),
label = "floatingTtsBottomPadding",
)
Row(
modifier = Modifier
.align(Alignment.BottomEnd)
.navigationBarsPadding()
.padding(end = 18.dp, bottom = floatingTtsBottomPadding),
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
IconButton(
onClick = ::toggleTts,
modifier = Modifier
.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),
)
}
IconButton(
onClick = { ReaderTtsController.stop(this@ReaderActivity) },
modifier = Modifier
.size(52.dp)
.background(
color = MaterialTheme.colorScheme.surface.copy(alpha = 0.55f),
shape = CircleShape,
),
) {
Icon(
painter = painterResource(R.drawable.ic_stop_24dp),
contentDescription = stringResource(MR.strings.reader_tts_stop),
tint = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.92f),
)
}
}
}
} }
val onDismissRequest = viewModel::closeDialog val onDismissRequest = viewModel::closeDialog
@@ -462,6 +549,10 @@ class ReaderActivity : BaseActivity() {
) )
val verticalNavigatorOnLeft by readerPreferences.verticalNavigatorOnLeft.collectAsState() val verticalNavigatorOnLeft by readerPreferences.verticalNavigatorOnLeft.collectAsState()
val verticalNavigatorHeight by readerPreferences.verticalNavigatorHeight.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( ReaderAppBars(
visible = state.menuVisible, visible = state.menuVisible,
@@ -518,6 +609,9 @@ class ReaderActivity : BaseActivity() {
menuToggleToast?.cancel() menuToggleToast?.cancel()
menuToggleToast = toast(if (enabled) MR.strings.on else MR.strings.off) menuToggleToast = toast(if (enabled) MR.strings.on else MR.strings.off)
}, },
ttsAvailable = ttsAvailable,
ttsPlaying = ttsForCurrentChapter && ttsState.playing,
onClickTts = ::toggleTts,
onClickSettings = viewModel::openSettingsDialog, onClickSettings = viewModel::openSettingsDialog,
) )
} }
@@ -664,6 +758,134 @@ class ReaderActivity : BaseActivity() {
viewer.moveToPage(page) 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 currentPage = chapter.pages
?.getOrNull((state.currentPage - 1).coerceAtLeast(0)) as? TextReaderPage
if (currentPage != null) {
ReaderTtsController.resumeFromSource(
context = this,
documentIndex = currentPage.anchor.documentIndex,
sourceOffset = currentPage.anchor.startOffset,
)
} 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
val targetPageIsVisible = state.currentPage == targetPage.index + 1
if (ttsState.playing && !targetPageIsVisible) {
moveToPageIndex(targetPage.index)
}
if (ttsState.playing || targetPageIsVisible) {
state.viewer?.refreshCurrentPage()
}
}
/** /**
* Tells the presenter to load the next chapter and mark it as active. The progress dialog * Tells the presenter to load the next chapter and mark it as active. The progress dialog
* should be automatically shown. * 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.source.online.HttpSource
import eu.kanade.tachiyomi.ui.reader.loader.ChapterLoader import eu.kanade.tachiyomi.ui.reader.loader.ChapterLoader
import eu.kanade.tachiyomi.ui.reader.loader.DownloadPageLoader 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.InsertPage
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage 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 eu.kanade.tachiyomi.util.storage.cacheImageDir
import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
@@ -184,6 +188,12 @@ class ReaderViewModel(
*/ */
private var loader: ChapterLoader? = null 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 * The time the chapter was started reading
*/ */
@@ -823,27 +833,59 @@ class ReaderViewModel(
mutableState.update { it.copy(dialog = null) } mutableState.update { it.copy(dialog = null) }
} }
fun reloadTextReaderStyle() { fun previewTextReaderStyle() {
val chapter = state.value.currentChapter ?: return val chapter = state.value.currentChapter ?: return
if (chapter.pageLoader?.usesTextReaderStyle != true) return if (chapter.pageLoader?.usesTextReaderStyle != true) return
val chapterLoader = loader ?: return val style = readerPreferences.textReaderStyle(context)
val requestedPage = (state.value.currentPage - 1).coerceAtLeast(0) val textPages = chapter.pages?.filterIsInstance<TextReaderPage>().orEmpty()
val oldLastIndex = (chapter.pages?.lastIndex ?: 0).coerceAtLeast(0) if (textPages.isEmpty()) return
val readingProgress = if (oldLastIndex == 0) 0f else requestedPage.toFloat() / oldLastIndex
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 { try {
chapter.pageLoader?.recycle() val oldLoader = chapterLoader.reloadTextChapter(
chapter.pageLoader = null chapter = chapter,
chapter.state = ReaderChapter.State.Wait readingAnchor = readingAnchor,
chapter.requestedPage = requestedPage readingProgress = readingProgress,
chapterLoader.loadChapter(chapter) ) ?: return@launchIO
val newLastIndex = (chapter.pages?.lastIndex ?: 0).coerceAtLeast(0)
chapter.requestedPage = (readingProgress * newLastIndex).roundToInt().coerceIn(0, newLastIndex) // Resource cleanup must survive cancellation by the next slider value.
eventChannel.send(Event.ReloadViewerChapters) viewModelScope.launchNonCancellable {
delay(750)
oldLoader.recycle()
}
eventChannel.trySend(Event.ReloadTextViewerChapters)
} catch (e: Throwable) { } catch (e: Throwable) {
if (e is CancellationException) throw e 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 { sealed interface Event {
data object ReloadViewerChapters : Event data object ReloadViewerChapters : Event
data object RefreshCurrentTextPage : Event
data object ReloadTextViewerChapters : Event
data object PageChanged : Event data object PageChanged : Event
data class SetOrientation(val orientation: Int) : Event data class SetOrientation(val orientation: Int) : Event
data class SetCoverResult(val result: SetAsCoverResult) : Event data class SetCoverResult(val result: SetAsCoverResult) : Event
@@ -4,11 +4,11 @@ import android.content.Context
import com.hippo.unifile.UniFile import com.hippo.unifile.UniFile
import eu.kanade.tachiyomi.network.await import eu.kanade.tachiyomi.network.await
import eu.kanade.tachiyomi.source.bookoasis.BookOasisChapterRef 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.source.online.HttpSource
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
import eu.kanade.tachiyomi.ui.reader.setting.TextReaderStyle import eu.kanade.tachiyomi.ui.reader.setting.TextReaderStyle
import mihon.core.archive.epubReader import mihon.core.archive.epubReader
import okhttp3.Request
import java.io.File import java.io.File
import java.io.IOException import java.io.IOException
@@ -34,9 +34,9 @@ internal class BookOasisFilePageLoader(
val uniFile = UniFile.fromFile(file) val uniFile = UniFile.fromFile(file)
?: error("Unable to open cached BookOasis file: ${file.absolutePath}") ?: error("Unable to open cached BookOasis file: ${file.absolutePath}")
val loader = when (ref.format) { val loader = when (ref.format) {
"epub" -> EpubPageLoader(uniFile.epubReader(context), textStyle) "epub" -> EpubPageLoader(uniFile.epubReader(context), textStyle, context.cacheDir)
"pdf" -> PdfPageLoader(context, uniFile) "pdf" -> PdfPageLoader(context, uniFile)
"txt" -> TextPageLoader(uniFile, textStyle) "txt" -> TextPageLoader(uniFile, textStyle, context.cacheDir)
else -> error("Unsupported BookOasis document format: ${ref.format}") else -> error("Unsupported BookOasis document format: ${ref.format}")
} }
@@ -68,19 +68,7 @@ internal class BookOasisFilePageLoader(
val temp = File(cacheDir, "${target.name}.part") val temp = File(cacheDir, "${target.name}.part")
if (temp.exists()) temp.delete() if (temp.exists()) temp.delete()
val downloadUrl = buildString { val request = source.bookOasisDocumentDownloadRequest(ref)
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()
source.client.newCall(request).await().use { response -> source.client.newCall(request).await().use { response ->
if (!response.isSuccessful) { 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.Source
import eu.kanade.tachiyomi.source.bookoasis.isBookOasisSource import eu.kanade.tachiyomi.source.bookoasis.isBookOasisSource
import eu.kanade.tachiyomi.source.bookoasis.toBookOasisChapterRef 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.source.online.HttpSource
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences
@@ -20,6 +22,8 @@ import tachiyomi.domain.source.model.StubSource
import tachiyomi.i18n.MR import tachiyomi.i18n.MR
import tachiyomi.source.local.LocalSource import tachiyomi.source.local.LocalSource
import tachiyomi.source.local.io.Format import tachiyomi.source.local.io.Format
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
/** /**
* Loader used to retrieve the [PageLoader] for a given chapter. * 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. * Checks [chapter] to be loaded based on present pages and loader in addition to state.
*/ */
@@ -91,6 +144,34 @@ class ChapterLoader(
source, source,
) )
val bookOasisRef = dbChapter.url.toBookOasisChapterRef() 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 { return when {
isDownloaded -> DownloadPageLoader( isDownloaded -> DownloadPageLoader(
@@ -99,18 +180,29 @@ class ChapterLoader(
source, source,
downloadManager, downloadManager,
downloadProvider, downloadProvider,
documentFallback,
) )
source is LocalSource -> source.getFormat(chapter.chapter).let { format -> source is LocalSource -> source.getFormat(chapter.chapter).let { format ->
when (format) { when (format) {
is Format.Directory -> DirectoryPageLoader(format.file) is Format.Directory -> DirectoryPageLoader(format.file)
is Format.Archive -> ArchivePageLoader(format.file.archiveReader(context)) 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.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 -> { 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 HttpSource -> HttpPageLoader(chapter, source, chapterCache)
source is StubSource -> error(context.stringResource(MR.strings.source_not_installed, source.toString())) 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.source.model.Page
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
import kotlinx.coroutines.CancellationException
import mihon.core.archive.archiveReader import mihon.core.archive.archiveReader
import mihon.core.archive.epubReader
import tachiyomi.core.common.storage.extension
import tachiyomi.domain.manga.model.Manga import tachiyomi.domain.manga.model.Manga
import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences
import uy.kohesive.injekt.injectLazy import uy.kohesive.injekt.injectLazy
import java.io.File
/** /**
* Loader used to load a chapter from the downloaded chapters. * Loader used to load a chapter from the downloaded chapters.
@@ -23,15 +28,45 @@ internal class DownloadPageLoader(
private val source: Source, private val source: Source,
private val downloadManager: DownloadManager, private val downloadManager: DownloadManager,
private val downloadProvider: DownloadProvider, private val downloadProvider: DownloadProvider,
private val documentFallback: (() -> PageLoader)? = null,
) : PageLoader() { ) : PageLoader() {
private val context: Context by injectLazy() 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 var isLocal: Boolean = true
override val usesTextReaderStyle: Boolean
get() = pageLoader?.usesTextReaderStyle == true || findDownloadedDocument() != null
override suspend fun getPages(): List<ReaderPage> { 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 dbChapter = chapter.chapter
val chapterPath = downloadProvider.findChapterDir( val chapterPath = downloadProvider.findChapterDir(
dbChapter.name, dbChapter.name,
@@ -40,6 +75,7 @@ internal class DownloadPageLoader(
manga.title, manga.title,
source, source,
) )
return if (chapterPath?.isFile == true) { return if (chapterPath?.isFile == true) {
getPagesFromArchive(chapterPath) getPagesFromArchive(chapterPath)
} else { } 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() { override fun recycle() {
super.recycle() super.recycle()
archivePageLoader?.recycle() pageLoader?.recycle()
pageLoader = null
} }
private suspend fun getPagesFromArchive(file: UniFile): List<ReaderPage> { 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() return loader.getPages()
} }
@@ -69,6 +189,6 @@ internal class DownloadPageLoader(
} }
override suspend fun loadPage(page: ReaderPage) { 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.model.ReaderPage
import eu.kanade.tachiyomi.ui.reader.setting.TextReaderStyle import eu.kanade.tachiyomi.ui.reader.setting.TextReaderStyle
import mihon.core.archive.EpubReader 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. * Loader used to load a chapter from a .epub file.
* *
* Text-based EPUBs are rendered as regular Mihon pages. Image-only EPUBs * Text-based EPUBs are rendered as regular Mihon pages. EPUB spine documents
* keep the original image extraction behavior. * 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( internal class EpubPageLoader(
private val reader: EpubReader, private val reader: EpubReader,
private val style: TextReaderStyle, private val style: TextReaderStyle,
private val cacheDir: File,
) : PageLoader() { ) : PageLoader() {
override var isLocal: Boolean = true override var isLocal: Boolean = true
override val usesTextReaderStyle: Boolean = true override val usesTextReaderStyle: Boolean = true
override suspend fun getPages(): List<ReaderPage> { private var pageStore: TextPageStore? = null
val textPages = reader.getTextFromPages()
.filter { it.isNotBlank() }
.flatMap { TextPageRenderer.paginate(it, style) }
if (textPages.isNotEmpty()) { override suspend fun getPages(): List<ReaderPage> {
return textPages.mapIndexed { index, text -> check(!isRecycled)
ReaderPage(index).apply {
stream = { TextPageRenderer.render(text, style) } pageStore?.close()
status = Page.State.Ready 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 -> private fun extractText(input: InputStream): String {
ReaderPage(index).apply { val pageDoc = Jsoup.parse(input, null, "")
stream = { reader.getInputStream(path)!! } pageDoc.select("br").append("\n")
status = Page.State.Ready 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) { override suspend fun loadPage(page: ReaderPage) {
@@ -46,6 +145,8 @@ internal class EpubPageLoader(
} }
override fun recycle() { override fun recycle() {
pageStore?.close()
pageStore = null
super.recycle() super.recycle()
reader.close() 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 package eu.kanade.tachiyomi.ui.reader.loader
import com.hippo.unifile.UniFile 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.model.ReaderPage
import eu.kanade.tachiyomi.ui.reader.setting.TextReaderStyle import eu.kanade.tachiyomi.ui.reader.setting.TextReaderStyle
import java.nio.ByteBuffer import java.io.File
import java.nio.charset.CharacterCodingException import java.io.InputStreamReader
import java.io.Reader
import java.nio.charset.Charset import java.nio.charset.Charset
import java.nio.charset.CodingErrorAction import java.nio.charset.CodingErrorAction
import java.nio.charset.StandardCharsets import java.nio.charset.StandardCharsets
@@ -13,39 +13,99 @@ import java.nio.charset.StandardCharsets
internal class TextPageLoader( internal class TextPageLoader(
private val file: UniFile, private val file: UniFile,
private val style: TextReaderStyle, private val style: TextReaderStyle,
private val cacheDir: File,
) : PageLoader() { ) : PageLoader() {
override var isLocal: Boolean = true override var isLocal: Boolean = true
override val usesTextReaderStyle: Boolean = true override val usesTextReaderStyle: Boolean = true
private var pageStore: TextPageStore? = null
override suspend fun getPages(): List<ReaderPage> { override suspend fun getPages(): List<ReaderPage> {
val bytes = file.openInputStream().use { it.readBytes() } pageStore?.close()
val text = decodeText(bytes) pageStore = null
return TextPageRenderer.paginate(text, style).mapIndexed { index, pageText ->
ReaderPage(index).apply { val store = TextPageStore(cacheDir)
stream = { TextPageRenderer.render(pageText, style) } return try {
status = Page.State.Ready 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 { override fun recycle() {
if (bytes.size >= 3 && pageStore?.close()
bytes[0] == 0xEF.toByte() && pageStore = null
bytes[1] == 0xBB.toByte() && super.recycle()
bytes[2] == 0xBF.toByte() }
) {
return String(bytes, 3, bytes.size - 3, StandardCharsets.UTF_8) 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 { return try {
StandardCharsets.UTF_8.newDecoder() InputStreamReader(file.openInputStream().buffered(), decoder).use { reader ->
.onMalformedInput(CodingErrorAction.REPORT) val buffer = CharArray(8 * 1024)
.onUnmappableCharacter(CodingErrorAction.REPORT) while (reader.read(buffer) >= 0) {
.decode(ByteBuffer.wrap(bytes)) // Validation only. Decoded characters are intentionally discarded.
.toString() }
} catch (_: CharacterCodingException) { }
String(bytes, Charset.forName("MS949")) true
} catch (_: Exception) {
false
} }
} }
} }
@@ -10,52 +10,172 @@ import android.text.Spannable
import android.text.SpannableString import android.text.SpannableString
import android.text.StaticLayout import android.text.StaticLayout
import android.text.TextPaint import android.text.TextPaint
import android.text.style.BackgroundColorSpan
import android.text.style.ForegroundColorSpan
import android.text.style.LineHeightSpan import android.text.style.LineHeightSpan
import eu.kanade.tachiyomi.ui.reader.setting.TextReaderStyle import eu.kanade.tachiyomi.ui.reader.setting.TextReaderStyle
import java.io.ByteArrayInputStream import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream import java.io.ByteArrayOutputStream
import java.io.InputStream 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 { internal object TextPageRenderer {
private const val PAGE_WIDTH = 1440 private const val VERTICAL_MARGIN_DP = 32f
private const val PAGE_HEIGHT = 2160 private const val STREAM_BUFFER_CHARS = 64 * 1024
private const val MARGIN = 96 private const val STREAM_READ_CHARS = 8 * 1024
private const val CONTENT_WIDTH = PAGE_WIDTH - (MARGIN * 2)
private const val CONTENT_HEIGHT = PAGE_HEIGHT - (MARGIN * 2)
fun paginate(text: String, style: TextReaderStyle): List<String> { fun paginate(text: String, style: TextReaderStyle): List<PaginatedTextPage> {
if (text.isBlank()) return emptyList() if (text.isBlank()) return emptyList()
val layout = createLayout(text, style) return calculatePageSlices(text, style)
if (layout.lineCount == 0) return listOf(text) .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 var startLine = 0
while (startLine < layout.lineCount) { while (startLine < layout.lineCount) {
val startTop = layout.getLineTop(startLine) val startTop = layout.getLineTop(startLine)
var endLine = startLine var endLine = startLine
while ( while (
endLine + 1 < layout.lineCount && endLine + 1 < layout.lineCount &&
layout.getLineBottom(endLine + 1) - startTop <= CONTENT_HEIGHT layout.getLineBottom(endLine + 1) - startTop <= metrics.contentHeight
) { ) {
endLine++ endLine++
} }
val start = layout.getLineStart(startLine) val start = layout.getLineStart(startLine)
val end = layout.getLineEnd(endLine).coerceAtLeast(start + 1).coerceAtMost(text.length) 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 startLine = endLine + 1
} }
return pages.ifEmpty { listOf(text) } return pages.ifEmpty { listOf(PageSlice(0, text.length)) }
} }
fun render(text: String, style: TextReaderStyle): InputStream { fun render(
val bitmap = Bitmap.createBitmap(PAGE_WIDTH, PAGE_HEIGHT, Bitmap.Config.ARGB_8888) 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) val canvas = Canvas(bitmap)
canvas.drawColor(Color.WHITE) val (backgroundColor, _) = resolveColors(style)
canvas.drawColor(backgroundColor)
canvas.save() canvas.save()
canvas.translate(MARGIN.toFloat(), MARGIN.toFloat()) canvas.translate(metrics.horizontalMargin.toFloat(), metrics.verticalMargin.toFloat())
createLayout(text, style).draw(canvas) createLayout(
text = text,
style = style,
contentWidth = metrics.contentWidth,
sentenceHighlightRange = sentenceHighlightRange,
activeHighlightRange = activeHighlightRange,
).draw(canvas)
canvas.restore() canvas.restore()
val output = ByteArrayOutputStream() val output = ByteArrayOutputStream()
@@ -64,40 +184,148 @@ internal object TextPageRenderer {
return ByteArrayInputStream(output.toByteArray()) 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 { val paint = TextPaint().apply {
isAntiAlias = true isAntiAlias = true
color = Color.BLACK color = textColor
textSize = style.fontSize.toFloat() textSize = style.fontSizePx.coerceAtLeast(1f)
typeface = style.fontFamily.androidFamilyName typeface = style.fontFamily.androidFamilyName
?.let { Typeface.create(it, Typeface.NORMAL) } ?.let { Typeface.create(it, Typeface.NORMAL) }
?: Typeface.DEFAULT ?: Typeface.DEFAULT
} }
val styledText = addParagraphSpacing(text, style.paragraphSpacing) val styledText = addTextSpans(
text = text,
style = style,
sentenceHighlightRange = sentenceHighlightRange,
activeHighlightRange = activeHighlightRange,
)
return StaticLayout.Builder return StaticLayout.Builder
.obtain(styledText, 0, styledText.length, paint, CONTENT_WIDTH) .obtain(styledText, 0, styledText.length, paint, contentWidth)
.setAlignment(Layout.Alignment.ALIGN_NORMAL) .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) .setLineSpacing(0f, style.lineSpacingPercent / 100f)
.build() .build()
} }
private fun addParagraphSpacing(text: String, spacing: Int): CharSequence { private fun resolveLayoutMetrics(style: TextReaderStyle): LayoutMetrics {
if (spacing <= 0 || '\n' !in text) return text val pageWidth = style.pageWidthPx.coerceAtLeast(1)
val pageHeight = style.pageHeightPx.coerceAtLeast(1)
val requestedHorizontalMargin = (style.horizontalMarginDp * style.density)
.roundToInt()
.coerceAtLeast(0)
val requestedVerticalMargin = (VERTICAL_MARGIN_DP * style.density).roundToInt().coerceAtLeast(1)
val horizontalMargin = requestedHorizontalMargin.coerceAtMost(((pageWidth - 1) / 2).coerceAtLeast(0))
val verticalMargin = requestedVerticalMargin.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) val spannable = SpannableString(text)
text.forEachIndexed { index, char -> if (needsParagraphSpacing) {
if (char == '\n') { text.forEachIndexed { index, char ->
spannable.setSpan( if (char == '\n') {
ParagraphSpacingSpan(spacing), spannable.setSpan(
index, ParagraphSpacingSpan(style.paragraphSpacingPx),
(index + 1).coerceAtMost(text.length), index,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE, (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 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 { private class ParagraphSpacingSpan(private val spacing: Int) : LineHeightSpan {
override fun chooseHeight( override fun chooseHeight(
text: CharSequence?, text: CharSequence?,
@@ -111,4 +339,18 @@ internal object TextPageRenderer {
fm.bottom += spacing 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 package eu.kanade.tachiyomi.ui.reader.setting
import android.content.Context
import android.content.res.Configuration
import android.os.Build import android.os.Build
import android.util.TypedValue
import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.BlendMode
import dev.icerock.moko.resources.StringResource import dev.icerock.moko.resources.StringResource
import dev.zacsweers.metro.AppScope 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.getEnum
import tachiyomi.core.common.preference.getEnumSet import tachiyomi.core.common.preference.getEnumSet
import tachiyomi.i18n.MR import tachiyomi.i18n.MR
import kotlin.math.roundToInt
@Inject @Inject
@SingleIn(AppScope::class) @SingleIn(AppScope::class)
@@ -110,23 +114,77 @@ class ReaderPreferences(
// region Text reader // 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 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 textHorizontalMargin: Preference<Int> = preferenceStore.getInt("reader_text_horizontal_margin", 32)
val textFontFamily: Preference<TextFontFamily> = preferenceStore.getEnum( val textFontFamily: Preference<TextFontFamily> = preferenceStore.getEnum(
"reader_text_font_family", "reader_text_font_family",
TextFontFamily.SYSTEM, TextFontFamily.SYSTEM,
) )
fun textReaderStyle() = TextReaderStyle( // TTS speed is stored as fifths: 6 = 1.2x, 15 = 3.0x.
fontSize = textFontSize.get(), val textTtsSpeedStep: Preference<Int> = preferenceStore.getInt("reader_text_tts_speed_step", 6)
lineSpacingPercent = textLineSpacing.get(),
paragraphSpacing = textParagraphSpacing.get(), // auto: prefer Google TTS when installed, then fall back to the Android system default.
fontFamily = textFontFamily.get(), 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(),
horizontalMarginDp = textHorizontalMargin.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 // endregion
@@ -317,6 +375,9 @@ class ReaderPreferences(
const val WEBTOON_PADDING_MIN = 0 const val WEBTOON_PADDING_MIN = 0
const val WEBTOON_PADDING_MAX = 25 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 const val MILLI_CONVERSION = 100
val TapZones = listOf( val TapZones = listOf(
@@ -377,5 +438,13 @@ data class TextReaderStyle(
val fontSize: Int, val fontSize: Int,
val lineSpacingPercent: Int, val lineSpacingPercent: Int,
val paragraphSpacing: Int, val paragraphSpacing: Int,
val horizontalMarginDp: Int,
val fontFamily: ReaderPreferences.TextFontFamily, 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.SharingStarted
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
class ReaderSettingsViewModel( class ReaderSettingsViewModel(
readerState: StateFlow<ReaderViewModel.State>, readerState: StateFlow<ReaderViewModel.State>,
val onChangeReadingMode: (ReadingMode) -> Unit, val onChangeReadingMode: (ReadingMode) -> Unit,
val onChangeOrientation: (ReaderOrientation) -> Unit, val onChangeOrientation: (ReaderOrientation) -> Unit,
val onTextSettingsChanged: () -> Unit, private val onTextSettingsPreview: () -> Unit,
private val onTextSettingsCommit: () -> Unit,
val preferences: ReaderPreferences, val preferences: ReaderPreferences,
) : ViewModel() { ) : ViewModel() {
@@ -26,4 +30,58 @@ class ReaderSettingsViewModel(
.map { it.manga } .map { it.manga }
.distinctUntilChanged() .distinctUntilChanged()
.stateIn(viewModelScope, SharingStarted.Lazily, null) .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
}
}
fun previewAndRequestTextSettingsReload() {
onTextSettingsPreview()
requestTextSettingsReload()
}
/**
* 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,107 @@
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 resumeFromSource(
context: Context,
documentIndex: Int,
sourceOffset: Long,
) {
if (!state.value.active) return
context.startService(
Intent(context, ReaderTtsService::class.java)
.setAction(ReaderTtsService.ACTION_RESUME_FROM_SOURCE)
.putExtra(ReaderTtsService.EXTRA_DOCUMENT_INDEX, documentIndex)
.putExtra(ReaderTtsService.EXTRA_SOURCE_OFFSET, sourceOffset),
)
}
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,798 @@
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_SOURCE -> resumeFromSource(
documentIndex = intent.getIntExtra(EXTRA_DOCUMENT_INDEX, -1),
sourceOffset = intent.getLongExtra(EXTRA_SOURCE_OFFSET, -1L),
)
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 resumeFromSource(
documentIndex: Int,
sourceOffset: Long,
) {
if (!initialized || documentIndex < 0 || sourceOffset < 0L) return
val session = session ?: return
val exactPosition = session.pages.indexOfFirst { entry ->
entry.documentIndex == documentIndex &&
sourceOffset >= entry.sourceStartOffset &&
sourceOffset < entry.sourceEndOffsetExclusive
}
val nextPosition = if (exactPosition < 0) {
session.pages.indexOfFirst { entry ->
entry.documentIndex == documentIndex && entry.sourceStartOffset >= sourceOffset
}
} else {
-1
}
val previousPosition = if (exactPosition < 0 && nextPosition < 0) {
session.pages.indexOfLast { entry ->
entry.documentIndex == documentIndex && entry.sourceStartOffset <= sourceOffset
}
} else {
-1
}
val newPagePosition = when {
exactPosition >= 0 -> exactPosition
nextPosition >= 0 -> nextPosition
previousPosition >= 0 -> previousPosition
else -> return
}
val entry = session.pages[newPagePosition]
val relativeOffset = (sourceOffset - entry.sourceStartOffset)
.coerceAtLeast(0L)
.coerceAtMost(Int.MAX_VALUE.toLong())
.toInt()
tts?.stop()
pagePosition = newPagePosition
pageSpeechStartOffset = relativeOffset
currentWindow = null
currentSegments = emptyList()
lookaheadConsumedChars = emptyMap()
segmentPosition = 0
segmentSpeechOffset = 0
currentUtteranceBaseOffset = 0
currentUtteranceId = null
playing = true
ReaderTtsController.updateState(
ReaderTtsController.State(
active = true,
playing = true,
readerChapterId = readerChapterId,
readerPageIndex = entry.readerPageIndex,
documentIndex = documentIndex,
sourceSentenceStart = sourceOffset,
sourceSentenceEndExclusive = sourceOffset,
),
)
refreshNotification()
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_SOURCE = "eu.kanade.tachiyomi.reader.tts.RESUME_FROM_SOURCE"
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_DOCUMENT_INDEX = "document_index"
const val EXTRA_SOURCE_OFFSET = "source_offset"
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) 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]. * Tells this viewer to move to the given [page].
*/ */
@@ -380,6 +380,17 @@ abstract class PagerViewer(val activity: ReaderActivity) : Viewer {
pager.setCurrentItem(currentItem, false) 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 * Called from the containing activity when a key [event] is received. It should return true
* if the event was handled, false otherwise. * 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 * Updates this adapter with the given [chapters]. It handles setting a few pages of the
* next/previous chapter to allow seamless transitions. * 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>() val newItems = mutableListOf<Any>()
// Forces chapter transition if there is missing chapters // 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) chapters.nextChapter?.pages?.let(newItems::addAll)
updateItems(newItems) updateItems(newItems, useDiff)
} }
private fun updateItems(newItems: List<Any>) { private fun updateItems(newItems: List<Any>, useDiff: Boolean) {
val result = DiffUtil.calculateDiff(Callback(items, newItems)) if (useDiff) {
items = newItems val result = DiffUtil.calculateDiff(Callback(items, newItems))
result.dispatchUpdatesTo(this) items = newItems
result.dispatchUpdatesTo(this)
} else {
items = newItems
notifyDataSetChanged()
}
} }
fun refresh() { fun refresh() {
@@ -353,6 +353,19 @@ class WebtoonViewer(val activity: ReaderActivity, val isContinuous: Boolean = tr
min(position + 3, adapter.itemCount - 1), 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 // Double the cache size to reduce rebinds/recycles incurred by the extra layout space on scroll direction changes
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FF000000"
android:pathData="M6,6h12v12H6z" />
</vector>
@@ -1103,8 +1103,17 @@
<!-- Text reader --> <!-- Text reader -->
<string name="pref_category_text_reader">Text</string> <string name="pref_category_text_reader">Text</string>
<string name="pref_text_reader_font_size">Font size</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="reader_tts_stop">Stop TTS</string>
<string name="pref_text_reader_line_spacing">Line spacing</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_paragraph_spacing">Paragraph spacing</string>
<string name="pref_text_reader_horizontal_margin">Side margins</string>
<string name="pref_text_reader_font_family">Font</string> <string name="pref_text_reader_font_family">Font</string>
<string name="pref_text_reader_font_system">System</string> <string name="pref_text_reader_font_system">System</string>
<string name="pref_text_reader_font_sans">Sans-serif</string> <string name="pref_text_reader_font_sans">Sans-serif</string>
@@ -911,8 +911,17 @@
<!-- Text reader --> <!-- Text reader -->
<string name="pref_category_text_reader">텍스트</string> <string name="pref_category_text_reader">텍스트</string>
<string name="pref_text_reader_font_size">글자 크기</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="reader_tts_stop">TTS 정지</string>
<string name="pref_text_reader_line_spacing">행간</string> <string name="pref_text_reader_line_spacing">행간</string>
<string name="pref_text_reader_paragraph_spacing">문단 간격</string> <string name="pref_text_reader_paragraph_spacing">문단 간격</string>
<string name="pref_text_reader_horizontal_margin">좌우 여백</string>
<string name="pref_text_reader_font_family">글꼴</string> <string name="pref_text_reader_font_family">글꼴</string>
<string name="pref_text_reader_font_system">시스템</string> <string name="pref_text_reader_font_system">시스템</string>
<string name="pref_text_reader_font_sans">고딕</string> <string name="pref_text_reader_font_sans">고딕</string>
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.