Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| eca7a3b886 | |||
| ba1b4d2362 | |||
| 023c3bb2f1 | |||
| aec03c6c71 | |||
| c9c119689d | |||
| 38a327cdf6 | |||
| b25679c8de | |||
| dfd57544a9 | |||
| 3a5a4c0fb2 | |||
| 8e113fcbff | |||
| 74cb92278f | |||
| 5de6a8f110 | |||
| d4789c2373 | |||
| 8dc5a0fc0b | |||
| 105551f658 |
@@ -22,3 +22,6 @@
|
|||||||
*.woff binary
|
*.woff binary
|
||||||
*.pyc binary
|
*.pyc binary
|
||||||
*.swp binary
|
*.swp binary
|
||||||
|
|
||||||
|
# Android packages
|
||||||
|
*.apk binary
|
||||||
|
|||||||
@@ -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()}\"")
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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,6 +35,16 @@ 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(
|
||||||
@@ -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(
|
||||||
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())
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -149,11 +149,8 @@ class DownloadProvider(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a list of downloaded directories for the chapters that exist.
|
* Returns downloaded chapter entries that exist, including image directories,
|
||||||
*
|
* CBZ files and standalone EPUB/TXT document files.
|
||||||
* @param chapters the chapters to query.
|
|
||||||
* @param manga the manga of the chapter.
|
|
||||||
* @param source the source of the chapter.
|
|
||||||
*/
|
*/
|
||||||
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()
|
||||||
@@ -161,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,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -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,6 +233,12 @@ 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) {
|
||||||
@@ -259,6 +281,7 @@ 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,
|
||||||
@@ -284,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
|
||||||
@@ -473,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,
|
||||||
@@ -529,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,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -675,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,7 @@ 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.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
|
||||||
@@ -851,15 +852,29 @@ class ReaderViewModel(
|
|||||||
|
|
||||||
val oldPageCount = chapter.pages?.size?.coerceAtLeast(1) ?: 1
|
val oldPageCount = chapter.pages?.size?.coerceAtLeast(1) ?: 1
|
||||||
val requestedPage = chapter.requestedPage.coerceIn(0, oldPageCount - 1)
|
val requestedPage = chapter.requestedPage.coerceIn(0, oldPageCount - 1)
|
||||||
// Anchor at the middle of the visible page so position remains stable
|
val currentTextPage = chapter.pages?.getOrNull(requestedPage) as? TextReaderPage
|
||||||
// when font size/spacing changes the total page count.
|
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)
|
val readingProgress = ((requestedPage + 0.5f) / oldPageCount)
|
||||||
.coerceIn(0f, 0.999999f)
|
.coerceIn(0f, 0.999999f)
|
||||||
|
|
||||||
textRepaginationJob?.cancel()
|
textRepaginationJob?.cancel()
|
||||||
textRepaginationJob = viewModelScope.launchIO {
|
textRepaginationJob = viewModelScope.launchIO {
|
||||||
try {
|
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.
|
// Resource cleanup must survive cancellation by the next slider value.
|
||||||
viewModelScope.launchNonCancellable {
|
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 {
|
return withIOContext {
|
||||||
val newLoader = getPageLoader(chapter)
|
val newLoader = getPageLoader(chapter)
|
||||||
if (!newLoader.usesTextReaderStyle) {
|
if (!newLoader.usesTextReaderStyle) {
|
||||||
@@ -97,9 +101,20 @@ class ChapterLoader(
|
|||||||
|
|
||||||
val oldLoader = chapter.pageLoader
|
val oldLoader = chapter.pageLoader
|
||||||
chapter.pageLoader = newLoader
|
chapter.pageLoader = newLoader
|
||||||
chapter.requestedPage = (readingProgress.coerceIn(0f, 0.999999f) * pages.size)
|
val anchoredPageIndex = readingAnchor?.let { anchor ->
|
||||||
.toInt()
|
val textPages = pages.filterIsInstance<TextReaderPage>()
|
||||||
.coerceIn(0, pages.lastIndex)
|
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)
|
chapter.state = ReaderChapter.State.Loaded(pages)
|
||||||
oldLoader
|
oldLoader
|
||||||
} catch (e: Throwable) {
|
} catch (e: Throwable) {
|
||||||
|
|||||||
@@ -68,21 +68,26 @@ internal class EpubPageLoader(
|
|||||||
.map { it.attr("idref") }
|
.map { it.attr("idref") }
|
||||||
|
|
||||||
val result = mutableListOf<ReaderPage>()
|
val result = mutableListOf<ReaderPage>()
|
||||||
spine.forEach { id ->
|
spine.forEachIndexed { documentIndex, id ->
|
||||||
val href = manifest[id]?.attr("href").orEmpty()
|
val href = manifest[id]?.attr("href").orEmpty()
|
||||||
if (href.isBlank()) return@forEach
|
if (href.isBlank()) return@forEachIndexed
|
||||||
|
|
||||||
openEntry(packageHref, href)?.use { input ->
|
openEntry(packageHref, href)?.use { input ->
|
||||||
val text = extractText(input)
|
val text = extractText(input)
|
||||||
if (text.isBlank()) return@use
|
if (text.isBlank()) return@use
|
||||||
|
|
||||||
StringReader(text).use { textReader ->
|
StringReader(text).use { textReader ->
|
||||||
TextPageRenderer.paginate(textReader, style) { pageText ->
|
TextPageRenderer.paginate(textReader, style) { page ->
|
||||||
val ref = store.append(pageText)
|
val ref = store.append(page.text)
|
||||||
result += TextReaderPage(
|
result += TextReaderPage(
|
||||||
index = result.size,
|
index = result.size,
|
||||||
pageTextProvider = { store.read(ref) },
|
pageTextProvider = { store.read(ref) },
|
||||||
initialStyle = style,
|
initialStyle = style,
|
||||||
|
anchor = TextReaderAnchor(
|
||||||
|
documentIndex = documentIndex,
|
||||||
|
startOffset = page.startOffset,
|
||||||
|
endOffsetExclusive = page.endOffsetExclusive,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,12 +29,17 @@ internal class TextPageLoader(
|
|||||||
return try {
|
return try {
|
||||||
val pages = mutableListOf<ReaderPage>()
|
val pages = mutableListOf<ReaderPage>()
|
||||||
openDecodedReader().use { reader ->
|
openDecodedReader().use { reader ->
|
||||||
TextPageRenderer.paginate(reader, style) { pageText ->
|
TextPageRenderer.paginate(reader, style) { page ->
|
||||||
val ref = store.append(pageText)
|
val ref = store.append(page.text)
|
||||||
pages += TextReaderPage(
|
pages += TextReaderPage(
|
||||||
index = pages.size,
|
index = pages.size,
|
||||||
pageTextProvider = { store.read(ref) },
|
pageTextProvider = { store.read(ref) },
|
||||||
initialStyle = style,
|
initialStyle = style,
|
||||||
|
anchor = TextReaderAnchor(
|
||||||
|
documentIndex = 0,
|
||||||
|
startOffset = page.startOffset,
|
||||||
|
endOffsetExclusive = page.endOffsetExclusive,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ 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
|
||||||
@@ -18,21 +20,31 @@ import java.io.InputStream
|
|||||||
import java.io.Reader
|
import java.io.Reader
|
||||||
import kotlin.math.roundToInt
|
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 MARGIN_DP = 32f
|
private const val MARGIN_DP = 32f
|
||||||
private const val STREAM_BUFFER_CHARS = 64 * 1024
|
private const val STREAM_BUFFER_CHARS = 64 * 1024
|
||||||
private const val STREAM_READ_CHARS = 8 * 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()
|
if (text.isBlank()) return emptyList()
|
||||||
|
|
||||||
return calculatePageSlices(text, style)
|
return calculatePageSlices(text, style)
|
||||||
.mapNotNull { slice ->
|
.mapNotNull { slice -> createPage(text, slice, 0L) }
|
||||||
text.substring(slice.start, slice.endExclusive)
|
.ifEmpty {
|
||||||
.trim()
|
listOf(
|
||||||
.takeIf { it.isNotEmpty() }
|
PaginatedTextPage(
|
||||||
|
text = text,
|
||||||
|
startOffset = 0L,
|
||||||
|
endOffsetExclusive = text.length.toLong(),
|
||||||
|
),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
.ifEmpty { listOf(text) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -43,11 +55,12 @@ internal object TextPageRenderer {
|
|||||||
fun paginate(
|
fun paginate(
|
||||||
reader: Reader,
|
reader: Reader,
|
||||||
style: TextReaderStyle,
|
style: TextReaderStyle,
|
||||||
onPage: (String) -> Unit,
|
onPage: (PaginatedTextPage) -> Unit,
|
||||||
) {
|
) {
|
||||||
val working = StringBuilder(STREAM_BUFFER_CHARS + STREAM_READ_CHARS)
|
val working = StringBuilder(STREAM_BUFFER_CHARS + STREAM_READ_CHARS)
|
||||||
val chars = CharArray(STREAM_READ_CHARS)
|
val chars = CharArray(STREAM_READ_CHARS)
|
||||||
var firstChunk = true
|
var firstChunk = true
|
||||||
|
var workingStartOffset = 0L
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
val read = reader.read(chars)
|
val read = reader.read(chars)
|
||||||
@@ -59,6 +72,7 @@ internal object TextPageRenderer {
|
|||||||
firstChunk = false
|
firstChunk = false
|
||||||
if (chars[0] == '\uFEFF') {
|
if (chars[0] == '\uFEFF') {
|
||||||
offset = 1
|
offset = 1
|
||||||
|
workingStartOffset = 1L
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (offset < read) {
|
if (offset < read) {
|
||||||
@@ -66,33 +80,53 @@ internal object TextPageRenderer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (working.length >= STREAM_BUFFER_CHARS) {
|
if (working.length >= STREAM_BUFFER_CHARS) {
|
||||||
emitCompletePages(working, style, onPage)
|
val consumed = emitCompletePages(working, style, workingStartOffset, onPage)
|
||||||
|
workingStartOffset += consumed
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (working.isNotEmpty()) {
|
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(
|
private fun emitCompletePages(
|
||||||
working: StringBuilder,
|
working: StringBuilder,
|
||||||
style: TextReaderStyle,
|
style: TextReaderStyle,
|
||||||
onPage: (String) -> Unit,
|
baseOffset: Long,
|
||||||
) {
|
onPage: (PaginatedTextPage) -> Unit,
|
||||||
|
): Long {
|
||||||
val text = working.toString()
|
val text = working.toString()
|
||||||
val slices = calculatePageSlices(text, style)
|
val slices = calculatePageSlices(text, style)
|
||||||
if (slices.size <= 1) return
|
if (slices.size <= 1) return 0L
|
||||||
|
|
||||||
for (index in 0 until slices.lastIndex) {
|
for (index in 0 until slices.lastIndex) {
|
||||||
val slice = slices[index]
|
createPage(text, slices[index], baseOffset)?.let(onPage)
|
||||||
text.substring(slice.start, slice.endExclusive)
|
|
||||||
.trim()
|
|
||||||
.takeIf { it.isNotEmpty() }
|
|
||||||
?.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> {
|
private fun calculatePageSlices(text: String, style: TextReaderStyle): List<PageSlice> {
|
||||||
@@ -122,7 +156,12 @@ internal object TextPageRenderer {
|
|||||||
return pages.ifEmpty { listOf(PageSlice(0, text.length)) }
|
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 metrics = resolveLayoutMetrics(style)
|
||||||
val bitmap = Bitmap.createBitmap(metrics.pageWidth, metrics.pageHeight, Bitmap.Config.ARGB_8888)
|
val bitmap = Bitmap.createBitmap(metrics.pageWidth, metrics.pageHeight, Bitmap.Config.ARGB_8888)
|
||||||
val canvas = Canvas(bitmap)
|
val canvas = Canvas(bitmap)
|
||||||
@@ -130,7 +169,13 @@ internal object TextPageRenderer {
|
|||||||
canvas.drawColor(backgroundColor)
|
canvas.drawColor(backgroundColor)
|
||||||
canvas.save()
|
canvas.save()
|
||||||
canvas.translate(metrics.horizontalMargin.toFloat(), metrics.verticalMargin.toFloat())
|
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()
|
canvas.restore()
|
||||||
|
|
||||||
val output = ByteArrayOutputStream()
|
val output = ByteArrayOutputStream()
|
||||||
@@ -143,6 +188,8 @@ internal object TextPageRenderer {
|
|||||||
text: String,
|
text: String,
|
||||||
style: TextReaderStyle,
|
style: TextReaderStyle,
|
||||||
contentWidth: Int,
|
contentWidth: Int,
|
||||||
|
sentenceHighlightRange: IntRange? = null,
|
||||||
|
activeHighlightRange: IntRange? = null,
|
||||||
): StaticLayout {
|
): StaticLayout {
|
||||||
val (_, textColor) = resolveColors(style)
|
val (_, textColor) = resolveColors(style)
|
||||||
val paint = TextPaint().apply {
|
val paint = TextPaint().apply {
|
||||||
@@ -153,11 +200,19 @@ internal object TextPageRenderer {
|
|||||||
?.let { Typeface.create(it, Typeface.NORMAL) }
|
?.let { Typeface.create(it, Typeface.NORMAL) }
|
||||||
?: Typeface.DEFAULT
|
?: Typeface.DEFAULT
|
||||||
}
|
}
|
||||||
val styledText = addParagraphSpacing(text, style.paragraphSpacingPx)
|
val styledText = addTextSpans(
|
||||||
|
text = text,
|
||||||
|
style = style,
|
||||||
|
sentenceHighlightRange = sentenceHighlightRange,
|
||||||
|
activeHighlightRange = activeHighlightRange,
|
||||||
|
)
|
||||||
return StaticLayout.Builder
|
return StaticLayout.Builder
|
||||||
.obtain(styledText, 0, styledText.length, paint, contentWidth)
|
.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()
|
||||||
}
|
}
|
||||||
@@ -195,22 +250,79 @@ internal object TextPageRenderer {
|
|||||||
return background to foreground
|
return background to foreground
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun addParagraphSpacing(text: String, spacing: Int): CharSequence {
|
private fun addTextSpans(
|
||||||
if (spacing <= 0 || '\n' !in text) return text
|
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?,
|
||||||
|
|||||||
@@ -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
|
* A rendered text page whose visual style can be refreshed cheaply while layout-affecting
|
||||||
* changes trigger a debounced chapter repagination to rebuild page boundaries.
|
* 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(
|
internal class TextReaderPage(
|
||||||
index: Int,
|
index: Int,
|
||||||
private val pageTextProvider: () -> String,
|
private val pageTextProvider: () -> String,
|
||||||
initialStyle: TextReaderStyle,
|
initialStyle: TextReaderStyle,
|
||||||
|
val anchor: TextReaderAnchor,
|
||||||
) : ReaderPage(index) {
|
) : ReaderPage(index) {
|
||||||
|
|
||||||
@Volatile
|
@Volatile
|
||||||
private var style: TextReaderStyle = initialStyle
|
private var style: TextReaderStyle = initialStyle
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var sentenceHighlightRange: IntRange? = null
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var activeHighlightRange: IntRange? = null
|
||||||
|
|
||||||
init {
|
init {
|
||||||
stream = { TextPageRenderer.render(pageTextProvider(), style) }
|
stream = {
|
||||||
|
TextPageRenderer.render(
|
||||||
|
text = pageTextProvider(),
|
||||||
|
style = style,
|
||||||
|
sentenceHighlightRange = sentenceHighlightRange,
|
||||||
|
activeHighlightRange = activeHighlightRange,
|
||||||
|
)
|
||||||
|
}
|
||||||
status = Page.State.Ready
|
status = Page.State.Ready
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,9 +52,35 @@ internal class TextReaderPage(
|
|||||||
index: Int,
|
index: Int,
|
||||||
pageText: String,
|
pageText: String,
|
||||||
initialStyle: TextReaderStyle,
|
initialStyle: TextReaderStyle,
|
||||||
) : this(index, { pageText }, initialStyle)
|
anchor: TextReaderAnchor,
|
||||||
|
) : this(index, { pageText }, initialStyle, anchor)
|
||||||
|
|
||||||
fun updateStyle(newStyle: TextReaderStyle) {
|
fun updateStyle(newStyle: TextReaderStyle) {
|
||||||
style = newStyle
|
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,
|
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)
|
private val textUnitsMigrated = preferenceStore.getBoolean("reader_text_units_v2_migrated", false)
|
||||||
|
|
||||||
init {
|
init {
|
||||||
|
|||||||
@@ -36,16 +36,15 @@ class ReaderSettingsViewModel(
|
|||||||
private var textSettingsDirty = false
|
private var textSettingsDirty = false
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Layout-affecting text settings are previewed quickly, then the chapter is
|
* Layout-affecting text settings are applied only after the chapter has been
|
||||||
* repaginated after a short debounce. This keeps the slider responsive while
|
* repaginated. Applying a new style to pages that still use old boundaries
|
||||||
* ensuring the number of characters/lines on a page follows the new style.
|
* can push text below the rendered page and clip the last lines.
|
||||||
*/
|
*/
|
||||||
fun requestTextSettingsReload() {
|
fun requestTextSettingsReload() {
|
||||||
textSettingsDirty = true
|
textSettingsDirty = true
|
||||||
textSettingsReloadJob?.cancel()
|
textSettingsReloadJob?.cancel()
|
||||||
textSettingsReloadJob = viewModelScope.launch {
|
textSettingsReloadJob = viewModelScope.launch {
|
||||||
delay(250)
|
delay(250)
|
||||||
onTextSettingsPreview()
|
|
||||||
textSettingsDirty = false
|
textSettingsDirty = false
|
||||||
onTextSettingsCommit()
|
onTextSettingsCommit()
|
||||||
textSettingsReloadJob = null
|
textSettingsReloadJob = null
|
||||||
@@ -77,7 +76,6 @@ class ReaderSettingsViewModel(
|
|||||||
}
|
}
|
||||||
textSettingsReloadJob?.cancel()
|
textSettingsReloadJob?.cancel()
|
||||||
textSettingsReloadJob = null
|
textSettingsReloadJob = null
|
||||||
onTextSettingsPreview()
|
|
||||||
textSettingsDirty = false
|
textSettingsDirty = false
|
||||||
onTextSettingsCommit()
|
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
|
||||||
|
}
|
||||||
@@ -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,6 +1103,14 @@
|
|||||||
<!-- 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_font_family">Font</string>
|
<string name="pref_text_reader_font_family">Font</string>
|
||||||
|
|||||||
@@ -911,6 +911,14 @@
|
|||||||
<!-- 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_font_family">글꼴</string>
|
<string name="pref_text_reader_font_family">글꼴</string>
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user