Compare commits

...

9 Commits

Author SHA1 Message Date
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
30 changed files with 1640 additions and 68 deletions
+3
View File
@@ -22,3 +22,6 @@
*.woff binary
*.pyc binary
*.swp binary
# Android packages
*.apk binary
+2 -2
View File
@@ -33,8 +33,8 @@ android {
defaultConfig {
applicationId = "app.mihon"
versionCode = 30
versionName = "0.20.4"
versionCode = 31
versionName = "0.20.5"
buildConfigField("String", "COMMIT_COUNT", "\"${getLatestCommitCount()}\"")
buildConfigField("String", "COMMIT_SHA", "\"${getLatestCommitSha()}\"")
+6
View File
@@ -32,6 +32,7 @@
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<application
android:name=".App"
@@ -209,6 +210,11 @@
android:exported="false"
android:foregroundServiceType="shortService" />
<service
android:name=".ui.reader.tts.ReaderTtsService"
android:exported="false"
android:foregroundServiceType="mediaPlayback" />
<service
android:name="androidx.appcompat.app.AppLocalesMetadataHolderService"
android:enabled="false"
@@ -73,6 +73,9 @@ fun ReaderAppBars(
onClickOrientation: () -> Unit,
cropEnabled: Boolean,
onClickCropBorder: () -> Unit,
ttsAvailable: Boolean,
ttsPlaying: Boolean,
onClickTts: () -> Unit,
onClickSettings: () -> Unit,
) {
val backgroundColor = MaterialTheme.colorScheme
@@ -172,6 +175,9 @@ fun ReaderAppBars(
onClickOrientation = onClickOrientation,
cropEnabled = cropEnabled,
onClickCropBorder = onClickCropBorder,
ttsAvailable = ttsAvailable,
ttsPlaying = ttsPlaying,
onClickTts = onClickTts,
onClickSettings = onClickSettings,
)
}
@@ -25,6 +25,9 @@ fun ReaderBottomBar(
onClickOrientation: () -> Unit,
cropEnabled: Boolean,
onClickCropBorder: () -> Unit,
ttsAvailable: Boolean,
ttsPlaying: Boolean,
onClickTts: () -> Unit,
onClickSettings: () -> Unit,
modifier: Modifier = Modifier,
) {
@@ -55,6 +58,17 @@ fun ReaderBottomBar(
)
}
if (ttsAvailable) {
IconButton(onClick = onClickTts) {
Icon(
painter = painterResource(if (ttsPlaying) R.drawable.ic_pause_24dp else R.drawable.ic_play_arrow_24dp),
contentDescription = stringResource(
if (ttsPlaying) MR.strings.reader_tts_pause else MR.strings.reader_tts_start,
),
)
}
}
IconButton(onClick = onClickSettings) {
Icon(
imageVector = MaterialSymbols.Rounded.Settings,
@@ -1,16 +1,25 @@
package eu.kanade.presentation.reader.settings
import android.content.Intent
import android.speech.tts.TextToSpeech
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.FilterChip
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences
import eu.kanade.tachiyomi.ui.reader.setting.ReaderSettingsViewModel
import eu.kanade.tachiyomi.ui.reader.tts.ReaderTtsController
import eu.kanade.tachiyomi.ui.reader.tts.ReaderTtsService
import tachiyomi.i18n.MR
import tachiyomi.presentation.core.components.SettingsChipRow
import tachiyomi.presentation.core.components.SliderItem
@@ -26,6 +35,16 @@ private val fontFamilies = listOf(
@Composable
internal fun ColumnScope.TextSettingsPage(viewModel: ReaderSettingsViewModel) {
val context = LocalContext.current
val ttsSettingsLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult(),
) {
ReaderTtsController.refreshVoiceSettings(
context,
viewModel.preferences.textTtsEnginePackage.get(),
)
}
val fontSizePref = viewModel.preferences.textFontSize
val fontSize by fontSizePref.collectAsState()
SliderItem(
@@ -86,6 +105,78 @@ internal fun ColumnScope.TextSettingsPage(viewModel: ReaderSettingsViewModel) {
}
}
val ttsSpeedPref = viewModel.preferences.textTtsSpeedStep
val ttsSpeedStep by ttsSpeedPref.collectAsState()
SliderItem(
label = stringResource(MR.strings.pref_text_reader_tts_speed),
value = ttsSpeedStep,
valueRange = 6..15,
steps = 8,
valueString = String.format("%.1fx", ttsSpeedStep / 5f),
onChange = { value ->
ttsSpeedPref.set(value)
ReaderTtsController.setSpeed(context, value / 5f)
},
pillColor = MaterialTheme.colorScheme.surfaceContainerHighest,
)
val enginePref = viewModel.preferences.textTtsEnginePackage
val selectedEngine by enginePref.collectAsState()
val installedEngines = remember {
@Suppress("DEPRECATION")
context.packageManager.queryIntentServices(
Intent(TextToSpeech.Engine.INTENT_ACTION_TTS_SERVICE),
0,
)
.mapNotNull { info ->
val serviceInfo = info.serviceInfo ?: return@mapNotNull null
val packageName = serviceInfo.packageName ?: return@mapNotNull null
packageName to info.loadLabel(context.packageManager).toString()
}
.distinctBy { it.first }
.sortedBy { it.second.lowercase() }
}
SettingsChipRow(MR.strings.pref_text_reader_tts_engine) {
FilterChip(
selected = selectedEngine == ReaderTtsService.AUTO_ENGINE,
onClick = {
enginePref.set(ReaderTtsService.AUTO_ENGINE)
ReaderTtsController.setEngine(context, ReaderTtsService.AUTO_ENGINE)
},
label = { Text(stringResource(MR.strings.pref_text_reader_tts_engine_auto)) },
)
FilterChip(
selected = selectedEngine == ReaderTtsService.SYSTEM_DEFAULT_ENGINE,
onClick = {
enginePref.set(ReaderTtsService.SYSTEM_DEFAULT_ENGINE)
ReaderTtsController.setEngine(context, ReaderTtsService.SYSTEM_DEFAULT_ENGINE)
},
label = { Text(stringResource(MR.strings.pref_text_reader_tts_engine_system)) },
)
installedEngines.forEach { (packageName, label) ->
FilterChip(
selected = selectedEngine == packageName,
onClick = {
enginePref.set(packageName)
ReaderTtsController.setEngine(context, packageName)
},
label = { Text(label) },
)
}
}
TextButton(
onClick = {
runCatching {
ttsSettingsLauncher.launch(Intent("com.android.settings.TTS_SETTINGS"))
}
},
modifier = Modifier.padding(horizontal = 16.dp),
) {
Text(stringResource(MR.strings.pref_text_reader_tts_voice_settings))
}
Text(
text = stringResource(MR.strings.pref_text_reader_pdf_note),
style = MaterialTheme.typography.bodySmall,
@@ -95,7 +95,7 @@ class DownloadCache(
.stateIn(scope, SharingStarted.WhileSubscribed(), false)
private val diskCacheFile: File
get() = File(context.cacheDir, "dl_index_cache_v3")
get() = File(context.cacheDir, "dl_index_cache_v4")
private val rootDownloadsDirMutex = Mutex()
private var rootDownloadsDir = RootDirectory(storageManager.getDownloadsDirectory())
@@ -214,7 +214,8 @@ class DownloadManager(
mangaTitle: String,
source: Source,
): Boolean {
return provider.findChapterDir(chapterName, chapterScanlator, chapterUrl, mangaTitle, source) != null
return provider.findChapterDir(chapterName, chapterScanlator, chapterUrl, mangaTitle, source) != null ||
provider.findChapterDocument(chapterName, chapterScanlator, chapterUrl, mangaTitle, source) != null
}
/**
@@ -253,8 +254,8 @@ class DownloadManager(
removeFromDownloadQueue(filteredChapters)
val (mangaDir, chapterDirs) = provider.findChapterDirs(filteredChapters, manga, source)
chapterDirs.forEach { it.delete() }
val (mangaDir, chapterDownloads) = provider.findChapterDirs(filteredChapters, manga, source)
chapterDownloads.forEach { it.delete() }
cache.removeChapters(filteredChapters, manga)
// Delete manga directory if empty
@@ -118,11 +118,39 @@ class DownloadProvider(
}
/**
* Returns a list of downloaded directories for the chapters that exist.
* Returns a downloaded EPUB/TXT document for a chapter if it exists.
*
* @param chapters the chapters to query.
* @param manga the manga of the chapter.
* @param source the source of the chapter.
* Document files are checked explicitly before the generic chapter path so
* a stale image directory with the same chapter name cannot shadow them.
*/
fun findChapterDocument(
chapterName: String,
chapterScanlator: String?,
chapterUrl: String,
mangaTitle: String,
source: Source,
): UniFile? {
val mangaDir = findMangaDir(mangaTitle, source) ?: return null
val chapterDirName = getChapterDirName(chapterName, chapterScanlator, chapterUrl)
val legacyChapterDirNames = getLegacyChapterDirNames(chapterName, chapterScanlator, chapterUrl)
return buildList {
DOCUMENT_DOWNLOAD_EXTENSIONS.forEach { extension ->
add("$chapterDirName.$extension")
}
legacyChapterDirNames.forEach { legacyName ->
DOCUMENT_DOWNLOAD_EXTENSIONS.forEach { extension ->
add("$legacyName.$extension")
}
}
}.asSequence()
.mapNotNull { mangaDir.findFile(it) }
.firstOrNull { it.isFile }
}
/**
* Returns downloaded chapter entries that exist, including image directories,
* CBZ files and standalone EPUB/TXT document files.
*/
fun findChapterDirs(chapters: List<Chapter>, manga: Manga, source: Source): Pair<UniFile?, List<UniFile>> {
val mangaDir = findMangaDir(manga.title, source) ?: return null to emptyList()
@@ -130,6 +158,13 @@ class DownloadProvider(
getValidChapterDirNames(chapter.name, chapter.scanlator, chapter.url).asSequence()
.mapNotNull { mangaDir.findFile(it) }
.firstOrNull()
?: findChapterDocument(
chapter.name,
chapter.scanlator,
chapter.url,
manga.title,
source,
)
}
}
@@ -21,6 +21,10 @@ object Notifications {
const val CHANNEL_COMMON = "common_channel"
const val ID_DOWNLOAD_IMAGE = 2
/** Foreground notification used by EPUB/TXT text-to-speech playback. */
const val CHANNEL_READER_TTS = "reader_tts_channel"
const val ID_READER_TTS = -801
/**
* Notification channel and ids used by the library updater.
*/
@@ -119,6 +123,10 @@ object Notifications {
buildNotificationChannel(CHANNEL_COMMON, IMPORTANCE_LOW) {
setName(context.stringResource(MR.strings.channel_common))
},
buildNotificationChannel(CHANNEL_READER_TTS, IMPORTANCE_LOW) {
setName("Text-to-speech")
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_LIBRARY_PROGRESS, IMPORTANCE_LOW) {
setName(context.stringResource(MR.strings.channel_progress))
setGroup(GROUP_LIBRARY)
@@ -42,6 +42,8 @@ import androidx.core.transition.doOnEnd
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import com.google.android.material.transition.platform.MaterialContainerTransform
import dev.zacsweers.metro.Inject
@@ -65,6 +67,7 @@ import eu.kanade.tachiyomi.ui.main.MainActivity
import eu.kanade.tachiyomi.ui.reader.ReaderViewModel.SetAsCoverResult.AddToLibraryFirst
import eu.kanade.tachiyomi.ui.reader.ReaderViewModel.SetAsCoverResult.Error
import eu.kanade.tachiyomi.ui.reader.ReaderViewModel.SetAsCoverResult.Success
import eu.kanade.tachiyomi.ui.reader.loader.TextReaderPage
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
import eu.kanade.tachiyomi.ui.reader.model.ViewerChapters
@@ -72,6 +75,8 @@ import eu.kanade.tachiyomi.ui.reader.setting.ReaderOrientation
import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences
import eu.kanade.tachiyomi.ui.reader.setting.ReaderSettingsViewModel
import eu.kanade.tachiyomi.ui.reader.setting.ReadingMode
import eu.kanade.tachiyomi.ui.reader.tts.ReaderTtsController
import eu.kanade.tachiyomi.ui.reader.tts.ReaderTtsSessionStore
import eu.kanade.tachiyomi.ui.reader.viewer.ReaderProgressIndicator
import eu.kanade.tachiyomi.ui.reader.viewer.pager.R2LPagerViewer
import eu.kanade.tachiyomi.ui.reader.viewer.webgpu.WebGpuViewer
@@ -137,6 +142,7 @@ class ReaderActivity : BaseActivity() {
private val windowInsetsController by lazy { WindowInsetsControllerCompat(window, window.decorView) }
private var loadingIndicator: ReaderProgressIndicator? = null
private var ttsHighlightedPage: TextReaderPage? = null
var isScrollingThroughPages = false
private set
@@ -217,6 +223,12 @@ class ReaderActivity : BaseActivity() {
.onEach(::setChapters)
.launchIn(lifecycleScope)
ReaderTtsController.state
.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
.sample(0.2.seconds)
.onEach(::applyTtsState)
.launchIn(lifecycleScope)
viewModel.eventFlow
.onEach { event ->
when (event) {
@@ -473,6 +485,10 @@ class ReaderActivity : BaseActivity() {
)
val verticalNavigatorOnLeft by readerPreferences.verticalNavigatorOnLeft.collectAsState()
val verticalNavigatorHeight by readerPreferences.verticalNavigatorHeight.collectAsState()
val ttsState by ReaderTtsController.state.collectAsState()
val ttsAvailable = state.currentChapter?.pages?.any { it is TextReaderPage } == true
val ttsForCurrentChapter = ttsState.active &&
ttsState.readerChapterId == state.currentChapter?.chapter?.id
ReaderAppBars(
visible = state.menuVisible,
@@ -529,6 +545,9 @@ class ReaderActivity : BaseActivity() {
menuToggleToast?.cancel()
menuToggleToast = toast(if (enabled) MR.strings.on else MR.strings.off)
},
ttsAvailable = ttsAvailable,
ttsPlaying = ttsForCurrentChapter && ttsState.playing,
onClickTts = ::toggleTts,
onClickSettings = viewModel::openSettingsDialog,
)
}
@@ -675,6 +694,117 @@ class ReaderActivity : BaseActivity() {
viewer.moveToPage(page)
}
private fun toggleTts() {
val state = viewModel.state.value
val chapter = state.currentChapter ?: return
val chapterId = chapter.chapter.id ?: return
val ttsState = ReaderTtsController.state.value
if (ttsState.active && ttsState.readerChapterId == chapterId) {
ReaderTtsController.toggle(this)
return
}
val textPages = chapter.pages?.filterIsInstance<TextReaderPage>().orEmpty()
if (textPages.isEmpty()) return
val startPageIndex = (state.currentPage - 1).coerceAtLeast(0)
val title = state.manga?.title ?: chapter.chapter.name
val subtitle = chapter.chapter.name
val speed = readerPreferences.textTtsSpeedStep.get().coerceIn(6, 15) / 5f
val enginePackage = readerPreferences.textTtsEnginePackage.get()
lifecycleScope.launchIO {
val session = runCatching {
ReaderTtsSessionStore.create(this@ReaderActivity, textPages)
}.getOrElse { error ->
logcat(LogPriority.ERROR, error) { "Failed to create TTS text session" }
return@launchIO
}
ReaderTtsController.start(
context = this@ReaderActivity,
sessionId = session.id,
startReaderPageIndex = startPageIndex,
readerChapterId = chapterId,
title = title,
subtitle = subtitle,
speed = speed,
enginePackage = enginePackage,
)
}
}
private fun applyTtsState(ttsState: ReaderTtsController.State) {
val state = viewModel.state.value
val chapter = state.currentChapter
val chapterId = chapter?.chapter?.id
if (!ttsState.active || chapter == null || chapterId != ttsState.readerChapterId) {
if (ttsHighlightedPage != null) {
ttsHighlightedPage?.clearTtsHighlight()
ttsHighlightedPage = null
state.viewer?.refreshCurrentPage()
}
return
}
val textPages = chapter.pages?.filterIsInstance<TextReaderPage>().orEmpty()
if (textPages.isEmpty()) return
val targetSourceOffset = when {
ttsState.sourceHighlightStart >= 0L -> ttsState.sourceHighlightStart
ttsState.sourceSentenceStart >= 0L -> ttsState.sourceSentenceStart
else -> -1L
}
val targetPage = if (targetSourceOffset >= 0L) {
textPages.firstOrNull { page ->
page.anchor.documentIndex == ttsState.documentIndex &&
targetSourceOffset >= page.anchor.startOffset &&
targetSourceOffset < page.anchor.endOffsetExclusive
}
} else {
chapter.pages?.getOrNull(ttsState.readerPageIndex) as? TextReaderPage
} ?: return
if (ttsHighlightedPage !== targetPage) {
ttsHighlightedPage?.clearTtsHighlight()
}
val sentenceStart = maxOf(ttsState.sourceSentenceStart, targetPage.anchor.startOffset)
val sentenceEnd = minOf(ttsState.sourceSentenceEndExclusive, targetPage.anchor.endOffsetExclusive)
val activeStart = maxOf(ttsState.sourceHighlightStart, targetPage.anchor.startOffset)
val activeEnd = minOf(ttsState.sourceHighlightEndExclusive, targetPage.anchor.endOffsetExclusive)
if (
ttsState.sourceSentenceStart >= 0L &&
ttsState.sourceSentenceEndExclusive > ttsState.sourceSentenceStart &&
sentenceEnd > sentenceStart
) {
targetPage.updateTtsHighlight(
sentenceStart = (sentenceStart - targetPage.anchor.startOffset).toInt(),
sentenceEndExclusive = (sentenceEnd - targetPage.anchor.startOffset).toInt(),
activeStart = if (activeEnd > activeStart) {
(activeStart - targetPage.anchor.startOffset).toInt()
} else {
-1
},
activeEndExclusive = if (activeEnd > activeStart) {
(activeEnd - targetPage.anchor.startOffset).toInt()
} else {
-1
},
)
} else {
targetPage.clearTtsHighlight()
}
ttsHighlightedPage = targetPage
if (state.currentPage != targetPage.index + 1) {
moveToPageIndex(targetPage.index)
}
state.viewer?.refreshCurrentPage()
}
/**
* Tells the presenter to load the next chapter and mark it as active. The progress dialog
* should be automatically shown.
@@ -40,6 +40,7 @@ import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.ui.reader.loader.ChapterLoader
import eu.kanade.tachiyomi.ui.reader.loader.DownloadPageLoader
import eu.kanade.tachiyomi.ui.reader.loader.TextReaderAnchor
import eu.kanade.tachiyomi.ui.reader.loader.TextReaderPage
import eu.kanade.tachiyomi.ui.reader.model.InsertPage
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
@@ -851,15 +852,29 @@ class ReaderViewModel(
val oldPageCount = chapter.pages?.size?.coerceAtLeast(1) ?: 1
val requestedPage = chapter.requestedPage.coerceIn(0, oldPageCount - 1)
// Anchor at the middle of the visible page so position remains stable
// when font size/spacing changes the total page count.
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 {
val oldLoader = chapterLoader.reloadTextChapter(chapter, readingProgress) ?: return@launchIO
val oldLoader = chapterLoader.reloadTextChapter(
chapter = chapter,
readingAnchor = readingAnchor,
readingProgress = readingProgress,
) ?: return@launchIO
// Resource cleanup must survive cancellation by the next slider value.
viewModelScope.launchNonCancellable {
@@ -76,7 +76,11 @@ class ChapterLoader(
}
suspend fun reloadTextChapter(chapter: ReaderChapter, readingProgress: Float): PageLoader? {
internal suspend fun reloadTextChapter(
chapter: ReaderChapter,
readingAnchor: TextReaderAnchor?,
readingProgress: Float,
): PageLoader? {
return withIOContext {
val newLoader = getPageLoader(chapter)
if (!newLoader.usesTextReaderStyle) {
@@ -97,9 +101,20 @@ class ChapterLoader(
val oldLoader = chapter.pageLoader
chapter.pageLoader = newLoader
chapter.requestedPage = (readingProgress.coerceIn(0f, 0.999999f) * pages.size)
.toInt()
.coerceIn(0, pages.lastIndex)
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) {
@@ -130,6 +145,33 @@ class ChapterLoader(
)
val bookOasisRef = dbChapter.url.toBookOasisChapterRef()
val kavitaChapterId = dbChapter.url.toKavitaChapterId()
val httpSource = source as? HttpSource
val documentFallback: (() -> PageLoader)? = when {
httpSource != null && httpSource.isBookOasisSource() && bookOasisRef != null &&
(bookOasisRef.format == "epub" || bookOasisRef.format == "txt") -> {
{
BookOasisFilePageLoader(
context,
httpSource,
bookOasisRef,
readerPreferences.textReaderStyle(context),
)
}
}
httpSource != null && httpSource.isKavitaSource() && kavitaChapterId != null -> {
{
KavitaCompatPageLoader(
context = context,
chapter = chapter,
source = httpSource,
chapterCache = chapterCache,
chapterId = kavitaChapterId,
textStyle = readerPreferences.textReaderStyle(context),
)
}
}
else -> null
}
return when {
isDownloaded -> DownloadPageLoader(
@@ -138,6 +180,7 @@ class ChapterLoader(
source,
downloadManager,
downloadProvider,
documentFallback,
)
source is LocalSource -> source.getFormat(chapter.chapter).let { format ->
when (format) {
@@ -10,12 +10,14 @@ import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
import kotlinx.coroutines.CancellationException
import mihon.core.archive.archiveReader
import mihon.core.archive.epubReader
import tachiyomi.core.common.storage.extension
import tachiyomi.domain.manga.model.Manga
import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences
import uy.kohesive.injekt.injectLazy
import java.io.File
/**
* Loader used to load a chapter from the downloaded chapters.
@@ -26,6 +28,7 @@ internal class DownloadPageLoader(
private val source: Source,
private val downloadManager: DownloadManager,
private val downloadProvider: DownloadProvider,
private val documentFallback: (() -> PageLoader)? = null,
) : PageLoader() {
private val context: Context by injectLazy()
@@ -35,9 +38,35 @@ internal class DownloadPageLoader(
override var isLocal: Boolean = true
override val usesTextReaderStyle: Boolean
get() = pageLoader?.usesTextReaderStyle == true
get() = pageLoader?.usesTextReaderStyle == true || findDownloadedDocument() != null
override suspend fun getPages(): List<ReaderPage> {
check(!isRecycled)
return try {
val pages = getDownloadedPages()
if (pages.isNotEmpty() || documentFallback == null) {
pages
} else {
getFallbackPages()
}
} catch (error: Throwable) {
if (error is CancellationException || documentFallback == null) throw error
getFallbackPages()
}
}
private suspend fun getDownloadedPages(): List<ReaderPage> {
val downloadedDocument = findDownloadedDocument()
if (downloadedDocument != null) {
val readableDocument = prepareDownloadedDocument(downloadedDocument)
return when (readableDocument.extension?.lowercase()) {
"epub" -> getPagesFromEpub(readableDocument)
"txt" -> getPagesFromText(readableDocument)
else -> error("Unsupported downloaded document: ${downloadedDocument.name}")
}
}
val dbChapter = chapter.chapter
val chapterPath = downloadProvider.findChapterDir(
dbChapter.name,
@@ -46,17 +75,79 @@ internal class DownloadPageLoader(
manga.title,
source,
)
return if (chapterPath?.isFile == true) {
when (chapterPath.extension?.lowercase()) {
"epub" -> getPagesFromEpub(chapterPath)
"txt" -> getPagesFromText(chapterPath)
else -> getPagesFromArchive(chapterPath)
}
getPagesFromArchive(chapterPath)
} else {
getPagesFromDirectory()
}
}
private fun findDownloadedDocument(): UniFile? {
val dbChapter = chapter.chapter
return downloadProvider.findChapterDocument(
dbChapter.name,
dbChapter.scanlator,
dbChapter.url,
manga.title,
source,
)
}
/**
* Mirror SAF-backed documents into the app cache before opening them.
* EPUB uses mmap internally, which is not guaranteed to work with every
* document provider even though regular stream reads/writes succeed.
*/
private fun prepareDownloadedDocument(file: UniFile): UniFile {
val extension = file.extension?.lowercase()
?: error("Downloaded document has no extension: ${file.name}")
val sourceLength = file.length()
if (sourceLength <= 0L) {
error("Downloaded document is empty: ${file.name}")
}
val cacheDir = File(context.cacheDir, "downloaded_reader").apply { mkdirs() }
val prefix = "${source.id}-${chapter.chapter.id}-"
val target = File(
cacheDir,
"$prefix$sourceLength-${file.lastModified()}.$extension",
)
if (!target.isFile || target.length() != sourceLength) {
cacheDir.listFiles()
?.filter { it.name.startsWith(prefix) }
?.forEach { it.delete() }
val temp = File(cacheDir, "${target.name}.part")
if (temp.exists()) temp.delete()
file.openInputStream().use { input ->
temp.outputStream().use { output -> input.copyTo(output) }
}
if (temp.length() != sourceLength) {
temp.delete()
error("Downloaded document cache copy is incomplete: ${file.name}")
}
if (!temp.renameTo(target)) {
temp.copyTo(target, overwrite = true)
temp.delete()
}
}
return UniFile.fromFile(target)
?: error("Unable to open cached downloaded document: ${target.absolutePath}")
}
private suspend fun getFallbackPages(): List<ReaderPage> {
pageLoader?.recycle()
val fallback = documentFallback?.invoke()
?: error("Downloaded document fallback is unavailable")
pageLoader = fallback
val pages = fallback.getPages()
isLocal = fallback.isLocal
return pages
}
override fun recycle() {
super.recycle()
pageLoader?.recycle()
@@ -68,21 +68,26 @@ internal class EpubPageLoader(
.map { it.attr("idref") }
val result = mutableListOf<ReaderPage>()
spine.forEach { id ->
spine.forEachIndexed { documentIndex, id ->
val href = manifest[id]?.attr("href").orEmpty()
if (href.isBlank()) return@forEach
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) { pageText ->
val ref = store.append(pageText)
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,
),
)
}
}
@@ -29,12 +29,17 @@ internal class TextPageLoader(
return try {
val pages = mutableListOf<ReaderPage>()
openDecodedReader().use { reader ->
TextPageRenderer.paginate(reader, style) { pageText ->
val ref = store.append(pageText)
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,
),
)
}
}
@@ -10,6 +10,7 @@ import android.text.Spannable
import android.text.SpannableString
import android.text.StaticLayout
import android.text.TextPaint
import android.text.style.BackgroundColorSpan
import android.text.style.LineHeightSpan
import eu.kanade.tachiyomi.ui.reader.setting.TextReaderStyle
import java.io.ByteArrayInputStream
@@ -18,21 +19,31 @@ import java.io.InputStream
import java.io.Reader
import kotlin.math.roundToInt
internal data class PaginatedTextPage(
val text: String,
val startOffset: Long,
val endOffsetExclusive: Long,
)
internal object TextPageRenderer {
private const val MARGIN_DP = 32f
private const val STREAM_BUFFER_CHARS = 64 * 1024
private const val STREAM_READ_CHARS = 8 * 1024
fun paginate(text: String, style: TextReaderStyle): List<String> {
fun paginate(text: String, style: TextReaderStyle): List<PaginatedTextPage> {
if (text.isBlank()) return emptyList()
return calculatePageSlices(text, style)
.mapNotNull { slice ->
text.substring(slice.start, slice.endExclusive)
.trim()
.takeIf { it.isNotEmpty() }
.mapNotNull { slice -> createPage(text, slice, 0L) }
.ifEmpty {
listOf(
PaginatedTextPage(
text = text,
startOffset = 0L,
endOffsetExclusive = text.length.toLong(),
),
)
}
.ifEmpty { listOf(text) }
}
/**
@@ -43,11 +54,12 @@ internal object TextPageRenderer {
fun paginate(
reader: Reader,
style: TextReaderStyle,
onPage: (String) -> Unit,
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)
@@ -59,6 +71,7 @@ internal object TextPageRenderer {
firstChunk = false
if (chars[0] == '\uFEFF') {
offset = 1
workingStartOffset = 1L
}
}
if (offset < read) {
@@ -66,33 +79,53 @@ internal object TextPageRenderer {
}
if (working.length >= STREAM_BUFFER_CHARS) {
emitCompletePages(working, style, onPage)
val consumed = emitCompletePages(working, style, workingStartOffset, onPage)
workingStartOffset += consumed
}
}
if (working.isNotEmpty()) {
paginate(working.toString(), style).forEach(onPage)
val text = working.toString()
calculatePageSlices(text, style)
.mapNotNull { slice -> createPage(text, slice, workingStartOffset) }
.forEach(onPage)
}
}
private fun emitCompletePages(
working: StringBuilder,
style: TextReaderStyle,
onPage: (String) -> Unit,
) {
baseOffset: Long,
onPage: (PaginatedTextPage) -> Unit,
): Long {
val text = working.toString()
val slices = calculatePageSlices(text, style)
if (slices.size <= 1) return
if (slices.size <= 1) return 0L
for (index in 0 until slices.lastIndex) {
val slice = slices[index]
text.substring(slice.start, slice.endExclusive)
.trim()
.takeIf { it.isNotEmpty() }
?.let(onPage)
createPage(text, slices[index], baseOffset)?.let(onPage)
}
working.delete(0, slices.last().start)
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> {
@@ -122,7 +155,12 @@ internal object TextPageRenderer {
return pages.ifEmpty { listOf(PageSlice(0, text.length)) }
}
fun render(text: String, style: TextReaderStyle): InputStream {
fun render(
text: String,
style: TextReaderStyle,
sentenceHighlightRange: IntRange? = null,
activeHighlightRange: IntRange? = null,
): InputStream {
val metrics = resolveLayoutMetrics(style)
val bitmap = Bitmap.createBitmap(metrics.pageWidth, metrics.pageHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
@@ -130,7 +168,13 @@ internal object TextPageRenderer {
canvas.drawColor(backgroundColor)
canvas.save()
canvas.translate(metrics.horizontalMargin.toFloat(), metrics.verticalMargin.toFloat())
createLayout(text, style, metrics.contentWidth).draw(canvas)
createLayout(
text = text,
style = style,
contentWidth = metrics.contentWidth,
sentenceHighlightRange = sentenceHighlightRange,
activeHighlightRange = activeHighlightRange,
).draw(canvas)
canvas.restore()
val output = ByteArrayOutputStream()
@@ -143,6 +187,8 @@ internal object TextPageRenderer {
text: String,
style: TextReaderStyle,
contentWidth: Int,
sentenceHighlightRange: IntRange? = null,
activeHighlightRange: IntRange? = null,
): StaticLayout {
val (_, textColor) = resolveColors(style)
val paint = TextPaint().apply {
@@ -153,11 +199,19 @@ internal object TextPageRenderer {
?.let { Typeface.create(it, Typeface.NORMAL) }
?: Typeface.DEFAULT
}
val styledText = addParagraphSpacing(text, style.paragraphSpacingPx)
val styledText = addTextSpans(
text = text,
style = style,
sentenceHighlightRange = sentenceHighlightRange,
activeHighlightRange = activeHighlightRange,
)
return StaticLayout.Builder
.obtain(styledText, 0, styledText.length, paint, contentWidth)
.setAlignment(Layout.Alignment.ALIGN_NORMAL)
.setIncludePad(true)
// Page slices are laid out again when rendered. Keeping font padding
// here can make the sliced layout taller than the same lines measured
// during pagination, which clips the last line at larger font sizes.
.setIncludePad(false)
.setLineSpacing(0f, style.lineSpacingPercent / 100f)
.build()
}
@@ -195,22 +249,69 @@ internal object TextPageRenderer {
return background to foreground
}
private fun addParagraphSpacing(text: String, spacing: Int): CharSequence {
if (spacing <= 0 || '\n' !in text) return text
private fun addTextSpans(
text: String,
style: TextReaderStyle,
sentenceHighlightRange: IntRange?,
activeHighlightRange: IntRange?,
): CharSequence {
val needsParagraphSpacing = style.paragraphSpacingPx > 0 && '\n' in text
val needsSentenceHighlight = sentenceHighlightRange != null && !sentenceHighlightRange.isEmpty()
val needsActiveHighlight = activeHighlightRange != null && !activeHighlightRange.isEmpty()
if (!needsParagraphSpacing && !needsSentenceHighlight && !needsActiveHighlight) return text
val spannable = SpannableString(text)
text.forEachIndexed { index, char ->
if (char == '\n') {
spannable.setSpan(
ParagraphSpacingSpan(spacing),
index,
(index + 1).coerceAtMost(text.length),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,
)
if (needsParagraphSpacing) {
text.forEachIndexed { index, char ->
if (char == '\n') {
spannable.setSpan(
ParagraphSpacingSpan(style.paragraphSpacingPx),
index,
(index + 1).coerceAtMost(text.length),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,
)
}
}
}
val darkBackground = resolveColors(style).first == Color.BLACK
sentenceHighlightRange?.let { range ->
applyHighlightSpan(
spannable = spannable,
textLength = text.length,
range = range,
color = if (darkBackground) Color.rgb(72, 68, 40) else Color.rgb(255, 249, 196),
)
}
activeHighlightRange?.let { range ->
applyHighlightSpan(
spannable = spannable,
textLength = text.length,
range = range,
color = if (darkBackground) Color.rgb(150, 117, 0) else Color.rgb(255, 193, 7),
)
}
return spannable
}
private fun applyHighlightSpan(
spannable: SpannableString,
textLength: Int,
range: IntRange,
color: 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(color),
start,
endExclusive,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,
)
}
private class ParagraphSpacingSpan(private val spacing: Int) : LineHeightSpan {
override fun chooseHeight(
text: CharSequence?,
@@ -8,17 +8,43 @@ 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(pageTextProvider(), style) }
stream = {
TextPageRenderer.render(
text = pageTextProvider(),
style = style,
sentenceHighlightRange = sentenceHighlightRange,
activeHighlightRange = activeHighlightRange,
)
}
status = Page.State.Ready
}
@@ -26,9 +52,35 @@ internal class TextReaderPage(
index: Int,
pageText: String,
initialStyle: TextReaderStyle,
) : this(index, { pageText }, initialStyle)
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
}
}
@@ -125,6 +125,12 @@ class ReaderPreferences(
TextFontFamily.SYSTEM,
)
// TTS speed is stored as fifths: 6 = 1.2x, 15 = 3.0x.
val textTtsSpeedStep: Preference<Int> = preferenceStore.getInt("reader_text_tts_speed_step", 6)
// auto: prefer Google TTS when installed, then fall back to the Android system default.
val textTtsEnginePackage: Preference<String> = preferenceStore.getString("reader_text_tts_engine", "auto")
private val textUnitsMigrated = preferenceStore.getBoolean("reader_text_units_v2_migrated", false)
init {
@@ -36,16 +36,15 @@ class ReaderSettingsViewModel(
private var textSettingsDirty = false
/**
* Layout-affecting text settings are previewed quickly, then the chapter is
* repaginated after a short debounce. This keeps the slider responsive while
* ensuring the number of characters/lines on a page follows the new style.
* 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)
onTextSettingsPreview()
textSettingsDirty = false
onTextSettingsCommit()
textSettingsReloadJob = null
@@ -77,7 +76,6 @@ class ReaderSettingsViewModel(
}
textSettingsReloadJob?.cancel()
textSettingsReloadJob = null
onTextSettingsPreview()
textSettingsDirty = false
onTextSettingsCommit()
}
@@ -0,0 +1,93 @@
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 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,719 @@
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_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 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 = page.readerPageIndex,
documentIndex = 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_STOP = "eu.kanade.tachiyomi.reader.tts.STOP"
const val ACTION_SET_SPEED = "eu.kanade.tachiyomi.reader.tts.SET_SPEED"
const val ACTION_SET_ENGINE = "eu.kanade.tachiyomi.reader.tts.SET_ENGINE"
const val ACTION_REFRESH_VOICE = "eu.kanade.tachiyomi.reader.tts.REFRESH_VOICE"
const val EXTRA_SESSION_ID = "session_id"
const val EXTRA_START_PAGE_INDEX = "start_page_index"
const val EXTRA_CHAPTER_ID = "chapter_id"
const val EXTRA_TITLE = "title"
const val EXTRA_SUBTITLE = "subtitle"
const val EXTRA_SPEED = "speed"
const val EXTRA_ENGINE_PACKAGE = "engine_package"
const val AUTO_ENGINE = "auto"
const val SYSTEM_DEFAULT_ENGINE = "system"
private const val GOOGLE_TTS_PACKAGE = "com.google.android.tts"
private const val DEFAULT_SPEED = 1.2f
private const val MIN_SPEED = 1.2f
private const val MAX_SPEED = 3.0f
private const val MAX_SEGMENT_CHARS = 1200
private const val MAX_LOOKAHEAD_PAGES = 3
private const val MAX_SPEECH_WINDOW_CHARS = 6000
private val SENTENCE_TERMINATORS = setOf('.', '!', '?', '。', '!', '?')
private const val REQUEST_TOGGLE = 9101
private const val REQUEST_STOP = 9102
}
}
@@ -0,0 +1,136 @@
package eu.kanade.tachiyomi.ui.reader.tts
import android.content.Context
import eu.kanade.tachiyomi.ui.reader.loader.TextReaderPage
import java.io.Closeable
import java.io.File
import java.io.RandomAccessFile
import java.nio.charset.StandardCharsets
import java.util.UUID
internal object ReaderTtsSessionStore {
data class PageEntry(
val readerPageIndex: Int,
val documentIndex: Int,
val sourceStartOffset: Long,
val sourceEndOffsetExclusive: Long,
val fileOffset: Long,
val byteLength: Int,
)
data class SessionInfo(
val id: String,
val pages: List<PageEntry>,
)
class SessionReader(
private val contentFile: File,
val pages: List<PageEntry>,
) : Closeable {
fun readPage(position: Int): String {
val entry = pages[position]
val bytes = ByteArray(entry.byteLength)
RandomAccessFile(contentFile, "r").use { input ->
input.seek(entry.fileOffset)
input.readFully(bytes)
}
return String(bytes, StandardCharsets.UTF_8)
}
override fun close() = Unit
}
fun create(
context: Context,
pages: List<TextReaderPage>,
): SessionInfo {
val dir = sessionDir(context)
pruneStale(dir)
val id = UUID.randomUUID().toString()
val contentFile = File(dir, "$id.utf8")
val indexFile = File(dir, "$id.idx")
val entries = ArrayList<PageEntry>(pages.size)
RandomAccessFile(contentFile, "rw").use { output ->
pages.forEach { page ->
val text = page.readText()
val bytes = text.toByteArray(StandardCharsets.UTF_8)
val fileOffset = output.filePointer
output.write(bytes)
entries += PageEntry(
readerPageIndex = page.index,
documentIndex = page.anchor.documentIndex,
sourceStartOffset = page.anchor.startOffset,
sourceEndOffsetExclusive = page.anchor.endOffsetExclusive,
fileOffset = fileOffset,
byteLength = bytes.size,
)
}
output.fd.sync()
}
indexFile.bufferedWriter(StandardCharsets.UTF_8).use { writer ->
entries.forEach { entry ->
writer.append(entry.readerPageIndex.toString())
.append('\t')
.append(entry.documentIndex.toString())
.append('\t')
.append(entry.sourceStartOffset.toString())
.append('\t')
.append(entry.sourceEndOffsetExclusive.toString())
.append('\t')
.append(entry.fileOffset.toString())
.append('\t')
.append(entry.byteLength.toString())
.append('\n')
}
}
return SessionInfo(id, entries)
}
fun open(context: Context, id: String): SessionReader? {
val dir = sessionDir(context)
val contentFile = File(dir, "$id.utf8")
val indexFile = File(dir, "$id.idx")
if (!contentFile.isFile || !indexFile.isFile) return null
val pages = indexFile.useLines { lines ->
lines.mapNotNull { line ->
val parts = line.split('\t')
if (parts.size != 6) return@mapNotNull null
PageEntry(
readerPageIndex = parts[0].toIntOrNull() ?: return@mapNotNull null,
documentIndex = parts[1].toIntOrNull() ?: return@mapNotNull null,
sourceStartOffset = parts[2].toLongOrNull() ?: return@mapNotNull null,
sourceEndOffsetExclusive = parts[3].toLongOrNull() ?: return@mapNotNull null,
fileOffset = parts[4].toLongOrNull() ?: return@mapNotNull null,
byteLength = parts[5].toIntOrNull() ?: return@mapNotNull null,
)
}.toList()
}
if (pages.isEmpty()) return null
return SessionReader(contentFile, pages)
}
fun delete(context: Context, id: String?) {
if (id.isNullOrBlank()) return
val dir = sessionDir(context)
File(dir, "$id.utf8").delete()
File(dir, "$id.idx").delete()
}
private fun sessionDir(context: Context): File {
return File(context.cacheDir, "reader_tts_sessions").apply { mkdirs() }
}
private fun pruneStale(dir: File) {
val cutoff = System.currentTimeMillis() - STALE_FILE_AGE_MS
dir.listFiles()
?.filter { it.isFile && it.lastModified() < cutoff }
?.forEach { it.delete() }
}
private const val STALE_FILE_AGE_MS = 24L * 60L * 60L * 1000L
}
@@ -1103,6 +1103,13 @@
<!-- Text reader -->
<string name="pref_category_text_reader">Text</string>
<string name="pref_text_reader_font_size">Font size</string>
<string name="pref_text_reader_tts_speed">TTS speed</string>
<string name="pref_text_reader_tts_engine">TTS engine</string>
<string name="pref_text_reader_tts_engine_auto">Google TTS preferred</string>
<string name="pref_text_reader_tts_engine_system">System default</string>
<string name="pref_text_reader_tts_voice_settings">Voice data settings</string>
<string name="reader_tts_start">Start TTS</string>
<string name="reader_tts_pause">Pause TTS</string>
<string name="pref_text_reader_line_spacing">Line spacing</string>
<string name="pref_text_reader_paragraph_spacing">Paragraph spacing</string>
<string name="pref_text_reader_font_family">Font</string>
@@ -911,6 +911,13 @@
<!-- Text reader -->
<string name="pref_category_text_reader">텍스트</string>
<string name="pref_text_reader_font_size">글자 크기</string>
<string name="pref_text_reader_tts_speed">TTS 배속</string>
<string name="pref_text_reader_tts_engine">TTS 엔진</string>
<string name="pref_text_reader_tts_engine_auto">Google TTS 우선</string>
<string name="pref_text_reader_tts_engine_system">시스템 기본</string>
<string name="pref_text_reader_tts_voice_settings">음성 데이터 설정</string>
<string name="reader_tts_start">TTS 시작</string>
<string name="reader_tts_pause">TTS 일시정지</string>
<string name="pref_text_reader_line_spacing">행간</string>
<string name="pref_text_reader_paragraph_spacing">문단 간격</string>
<string name="pref_text_reader_font_family">글꼴</string>
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.