Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a2f417d147 | ||
|
|
9dbe30b20c | ||
|
|
9cd8ebc422 | ||
|
|
85d97d5a90 | ||
|
|
f344befbdd | ||
|
|
dbf63c351c | ||
|
|
e8b18ec472 | ||
|
|
37abbf884c | ||
|
|
0084c478a3 | ||
|
|
6990e3c233 | ||
|
|
9f54c0aca0 | ||
|
|
7681590992 | ||
|
|
cde4d89eed | ||
|
|
2e9a52f4af | ||
|
|
2fddacb7e7 | ||
|
|
3e83185e4f | ||
|
|
65925f2a07 | ||
|
|
17c885b3f5 | ||
|
|
89b1115169 | ||
|
|
8e7dcc0307 | ||
|
|
50f201d3c6 | ||
|
|
fe4d569afa | ||
|
|
c7b7ca68ab | ||
|
|
de04b9cbed | ||
|
|
316b10d015 | ||
|
|
44a83a17dd | ||
|
|
1c6a80c43b | ||
|
|
b0f45aaf1b | ||
|
|
ed66ea0d55 | ||
|
|
0eba07b594 | ||
|
|
128275402e | ||
|
|
bad1e89c26 | ||
|
|
75ba13bde2 | ||
|
|
02bde7e644 | ||
|
|
d749352333 | ||
|
|
8bb920caf8 | ||
|
|
df90b4c36f | ||
|
|
44cc0bbaf3 |
No files matched your search
@@ -17,3 +17,7 @@ captures
|
|||||||
!*.xcworkspace/contents.xcworkspacedata
|
!*.xcworkspace/contents.xcworkspacedata
|
||||||
**/xcshareddata/WorkspaceSettings.xcsettings
|
**/xcshareddata/WorkspaceSettings.xcsettings
|
||||||
node_modules/
|
node_modules/
|
||||||
|
/composeApp/release/
|
||||||
|
/test_books/
|
||||||
|
/.junie/
|
||||||
|
/.local/
|
||||||
@@ -31,6 +31,8 @@ in your IDE’s toolbar or build it directly from the terminal:
|
|||||||
|
|
||||||
### Build and Run Desktop (JVM) Application
|
### Build and Run Desktop (JVM) Application
|
||||||
|
|
||||||
|
Desktop offline English/Russian speech: [CPU TTS setup and audition](docs/desktop-tts.md).
|
||||||
|
|
||||||
To build and run the development version of the desktop app, use the run configuration from the run widget
|
To build and run the development version of the desktop app, use the run configuration from the run widget
|
||||||
in your IDE’s toolbar or run it directly from the terminal:
|
in your IDE’s toolbar or run it directly from the terminal:
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,10 @@ import org.jetbrains.compose.desktop.application.dsl.TargetFormat
|
|||||||
import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
|
import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
|
||||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||||
|
|
||||||
|
val appVersionName = "1.1"
|
||||||
|
val appVersionCode = 10
|
||||||
|
val appVersionDisplay = "$appVersionName.$appVersionCode"
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
alias(libs.plugins.kotlinMultiplatform)
|
alias(libs.plugins.kotlinMultiplatform)
|
||||||
alias(libs.plugins.androidApplication)
|
alias(libs.plugins.androidApplication)
|
||||||
@@ -10,6 +14,38 @@ plugins {
|
|||||||
alias(libs.plugins.composeHotReload)
|
alias(libs.plugins.composeHotReload)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
abstract class GenerateAppVersionConstantsTask : DefaultTask() {
|
||||||
|
@get:Input
|
||||||
|
abstract val versionName: Property<String>
|
||||||
|
|
||||||
|
@get:Input
|
||||||
|
abstract val versionCode: Property<Int>
|
||||||
|
|
||||||
|
@get:OutputDirectory
|
||||||
|
abstract val outputDir: DirectoryProperty
|
||||||
|
|
||||||
|
@TaskAction
|
||||||
|
fun generate() {
|
||||||
|
val outputFile = outputDir.file("net/sergeych/toread/AppVersion.kt").get().asFile
|
||||||
|
outputFile.parentFile.mkdirs()
|
||||||
|
outputFile.writeText(
|
||||||
|
"""
|
||||||
|
package net.sergeych.toread
|
||||||
|
|
||||||
|
internal const val AppVersionName = "${versionName.get()}"
|
||||||
|
internal const val AppVersionCode = ${versionCode.get()}
|
||||||
|
internal const val AppVersionDisplay = "${versionName.get()}.${versionCode.get()}"
|
||||||
|
""".trimIndent() + "\n",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val generateAppVersionConstants by tasks.registering(GenerateAppVersionConstantsTask::class) {
|
||||||
|
versionName.set(appVersionName)
|
||||||
|
versionCode.set(appVersionCode)
|
||||||
|
outputDir.set(layout.buildDirectory.dir("generated/appVersion/commonMain/kotlin"))
|
||||||
|
}
|
||||||
|
|
||||||
kotlin {
|
kotlin {
|
||||||
jvmToolchain(17)
|
jvmToolchain(17)
|
||||||
|
|
||||||
@@ -33,6 +69,9 @@ kotlin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
sourceSets {
|
sourceSets {
|
||||||
|
commonMain {
|
||||||
|
kotlin.srcDir(generateAppVersionConstants)
|
||||||
|
}
|
||||||
androidMain.dependencies {
|
androidMain.dependencies {
|
||||||
implementation(libs.compose.uiToolingPreview)
|
implementation(libs.compose.uiToolingPreview)
|
||||||
implementation(libs.androidx.activity.compose)
|
implementation(libs.androidx.activity.compose)
|
||||||
@@ -57,10 +96,29 @@ kotlin {
|
|||||||
jvmMain.dependencies {
|
jvmMain.dependencies {
|
||||||
implementation(compose.desktop.currentOs)
|
implementation(compose.desktop.currentOs)
|
||||||
implementation(libs.kotlinx.coroutinesSwing)
|
implementation(libs.kotlinx.coroutinesSwing)
|
||||||
|
implementation(libs.onnxruntime)
|
||||||
|
implementation(libs.jackson.databind)
|
||||||
|
}
|
||||||
|
jvmTest.dependencies {
|
||||||
|
implementation(libs.kotlinx.coroutinesTest)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tasks.register<JavaExec>("ttsSample") {
|
||||||
|
group = "verification"
|
||||||
|
description = "Generate plain English/Russian WAV samples using the local Supertonic CPU model."
|
||||||
|
dependsOn("jvmMainClasses")
|
||||||
|
mainClass.set("net.sergeych.toread.tts.TtsSampleKt")
|
||||||
|
classpath = configurations["jvmRuntimeClasspath"] + kotlin.targets["jvm"].compilations["main"].output.allOutputs
|
||||||
|
workingDir = rootProject.projectDir
|
||||||
|
args(layout.buildDirectory.dir("tts-samples").get().asFile.absolutePath)
|
||||||
|
if (providers.gradleProperty("ttsPlay").orNull == "true") args("--play")
|
||||||
|
if (providers.gradleProperty("ttsStress").orNull == "true") args("--stress")
|
||||||
|
if (providers.gradleProperty("ttsRuAccent").orNull == "true") args("--ruaccent")
|
||||||
|
if (providers.gradleProperty("ttsSilero").orNull == "true") args("--silero")
|
||||||
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
namespace = "net.sergeych.toread"
|
namespace = "net.sergeych.toread"
|
||||||
compileSdk = libs.versions.android.compileSdk.get().toInt()
|
compileSdk = libs.versions.android.compileSdk.get().toInt()
|
||||||
@@ -69,8 +127,8 @@ android {
|
|||||||
applicationId = "net.sergeych.toread"
|
applicationId = "net.sergeych.toread"
|
||||||
minSdk = libs.versions.android.minSdk.get().toInt()
|
minSdk = libs.versions.android.minSdk.get().toInt()
|
||||||
targetSdk = libs.versions.android.targetSdk.get().toInt()
|
targetSdk = libs.versions.android.targetSdk.get().toInt()
|
||||||
versionCode = 1
|
versionCode = appVersionCode
|
||||||
versionName = "1.0"
|
versionName = appVersionName
|
||||||
}
|
}
|
||||||
packaging {
|
packaging {
|
||||||
resources {
|
resources {
|
||||||
@@ -99,8 +157,24 @@ compose.desktop {
|
|||||||
|
|
||||||
nativeDistributions {
|
nativeDistributions {
|
||||||
targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb)
|
targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb)
|
||||||
packageName = "net.sergeych.toread"
|
packageName = "To Read"
|
||||||
packageVersion = "1.0.0"
|
packageVersion = appVersionDisplay
|
||||||
|
fileAssociation("application/x-fictionbook+xml", "fb2", "FictionBook document")
|
||||||
|
fileAssociation("application/zip", "fb2.zip", "Zipped FictionBook document")
|
||||||
|
|
||||||
|
macOS {
|
||||||
|
iconFile.set(project.file("src/jvmMain/resources/icons/icon.icns"))
|
||||||
|
}
|
||||||
|
windows {
|
||||||
|
iconFile.set(project.file("src/jvmMain/resources/icons/icon.ico"))
|
||||||
|
shortcut = true
|
||||||
|
menu = true
|
||||||
|
}
|
||||||
|
linux {
|
||||||
|
packageName = "to-read"
|
||||||
|
iconFile.set(project.file("src/jvmMain/resources/icons/icon.png"))
|
||||||
|
shortcut = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,6 +9,12 @@
|
|||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||||
|
|
||||||
|
<queries>
|
||||||
|
<intent>
|
||||||
|
<action android:name="android.intent.action.TTS_SERVICE"/>
|
||||||
|
</intent>
|
||||||
|
</queries>
|
||||||
|
|
||||||
<application
|
<application
|
||||||
android:allowBackup="true"
|
android:allowBackup="true"
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_launcher"
|
||||||
@@ -18,6 +24,7 @@
|
|||||||
android:theme="@style/AppTheme">
|
android:theme="@style/AppTheme">
|
||||||
<activity
|
<activity
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
|
android:launchMode="singleTop"
|
||||||
android:name=".MainActivity">
|
android:name=".MainActivity">
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.intent.action.MAIN"/>
|
<action android:name="android.intent.action.MAIN"/>
|
||||||
@@ -33,6 +40,8 @@
|
|||||||
<data android:scheme="content"/>
|
<data android:scheme="content"/>
|
||||||
<data android:scheme="file"/>
|
<data android:scheme="file"/>
|
||||||
<data android:mimeType="application/x-fictionbook+xml"/>
|
<data android:mimeType="application/x-fictionbook+xml"/>
|
||||||
|
<data android:mimeType="application/xml"/>
|
||||||
|
<data android:mimeType="text/xml"/>
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.intent.action.VIEW"/>
|
<action android:name="android.intent.action.VIEW"/>
|
||||||
@@ -42,8 +51,12 @@
|
|||||||
|
|
||||||
<data android:scheme="content" android:mimeType="*/*" android:pathPattern=".*\\.fb2"/>
|
<data android:scheme="content" android:mimeType="*/*" android:pathPattern=".*\\.fb2"/>
|
||||||
<data android:scheme="content" android:mimeType="*/*" android:pathPattern=".*\\.fb2\\.zip"/>
|
<data android:scheme="content" android:mimeType="*/*" android:pathPattern=".*\\.fb2\\.zip"/>
|
||||||
|
<data android:scheme="content" android:mimeType="application/octet-stream" android:pathPattern=".*\\.fb2"/>
|
||||||
|
<data android:scheme="content" android:mimeType="application/octet-stream" android:pathPattern=".*\\.fb2\\.zip"/>
|
||||||
<data android:scheme="file" android:mimeType="*/*" android:pathPattern=".*\\.fb2"/>
|
<data android:scheme="file" android:mimeType="*/*" android:pathPattern=".*\\.fb2"/>
|
||||||
<data android:scheme="file" android:mimeType="*/*" android:pathPattern=".*\\.fb2\\.zip"/>
|
<data android:scheme="file" android:mimeType="*/*" android:pathPattern=".*\\.fb2\\.zip"/>
|
||||||
|
<data android:scheme="file" android:mimeType="application/octet-stream" android:pathPattern=".*\\.fb2"/>
|
||||||
|
<data android:scheme="file" android:mimeType="application/octet-stream" android:pathPattern=".*\\.fb2\\.zip"/>
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
<provider
|
<provider
|
||||||
|
|||||||
|
After Width: | Height: | Size: 82 KiB |
@@ -102,6 +102,14 @@ actual fun defaultLibraryScanPath(): String? =
|
|||||||
?: appContext.filesDir.absolutePath
|
?: appContext.filesDir.absolutePath
|
||||||
|
|
||||||
fun rememberPlatformOpenBookIntent(intent: Intent?) {
|
fun rememberPlatformOpenBookIntent(intent: Intent?) {
|
||||||
|
val uri = intent
|
||||||
|
?.takeIf { it.action == Intent.ACTION_VIEW }
|
||||||
|
?.data
|
||||||
|
if (uri != null && intent.flags and Intent.FLAG_GRANT_READ_URI_PERMISSION != 0) {
|
||||||
|
runCatching {
|
||||||
|
appContext.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||||
|
}
|
||||||
|
}
|
||||||
pendingOpenBookUri = intent
|
pendingOpenBookUri = intent
|
||||||
?.takeIf { it.action == Intent.ACTION_VIEW }
|
?.takeIf { it.action == Intent.ACTION_VIEW }
|
||||||
?.data
|
?.data
|
||||||
@@ -111,9 +119,21 @@ actual suspend fun loadPlatformOpenBookRequest(): PlatformOpenBookRequest? = wit
|
|||||||
val uri = pendingOpenBookUri ?: return@withContext null
|
val uri = pendingOpenBookUri ?: return@withContext null
|
||||||
pendingOpenBookUri = null
|
pendingOpenBookUri = null
|
||||||
val bytes = readStorageUriBytes(uri.toString()) ?: return@withContext null
|
val bytes = readStorageUriBytes(uri.toString()) ?: return@withContext null
|
||||||
|
val displayName = displayNameFor(uri)
|
||||||
|
val sizeBytes = sizeBytesFor(uri) ?: bytes.size.toLong()
|
||||||
|
val importResult = openLibraryDatabase().useLibrary { db ->
|
||||||
|
LibraryScanner(db, ::appendLibraryLog).importExternalFileAndGetResult(
|
||||||
|
bytes = bytes,
|
||||||
|
displayName = displayName,
|
||||||
|
storageUri = uri.toString(),
|
||||||
|
sizeBytes = sizeBytes,
|
||||||
|
lastModifiedMillis = null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
appendLibraryLog("platform open imported=${importResult.imported} fileId=${importResult.fileId} uri=$uri")
|
||||||
PlatformOpenBookRequest(
|
PlatformOpenBookRequest(
|
||||||
id = "platform:${uri}",
|
id = importResult.fileId,
|
||||||
displayName = displayNameFor(uri),
|
displayName = displayName,
|
||||||
bytes = bytes,
|
bytes = bytes,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -131,6 +151,13 @@ actual suspend fun loadLibraryItemsPage(limit: Int, offset: Int): List<LibraryIt
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
actual suspend fun loadRecentlyAddedLibraryItems(sinceImportedAt: Long, limit: Int): List<LibraryItem> = withContext(Dispatchers.IO) {
|
||||||
|
appendLibraryLog("load recently added library items since=$sinceImportedAt limit=$limit")
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.files.listRecentlyAddedLibraryFiles(sinceImportedAt, limit).map { it.toLibraryItem() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
actual suspend fun searchLibraryItems(query: String, limit: Int): List<LibraryItem> = withContext(Dispatchers.IO) {
|
actual suspend fun searchLibraryItems(query: String, limit: Int): List<LibraryItem> = withContext(Dispatchers.IO) {
|
||||||
val prefixes = query.toSearchPrefixes()
|
val prefixes = query.toSearchPrefixes()
|
||||||
if (prefixes.isEmpty()) return@withContext emptyList()
|
if (prefixes.isEmpty()) return@withContext emptyList()
|
||||||
@@ -140,6 +167,8 @@ actual suspend fun searchLibraryItems(query: String, limit: Int): List<LibraryIt
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
actual fun currentLibraryTimeMillis(): Long = System.currentTimeMillis()
|
||||||
|
|
||||||
actual suspend fun loadLibraryItem(fileId: String): LibraryItem? = withContext(Dispatchers.IO) {
|
actual suspend fun loadLibraryItem(fileId: String): LibraryItem? = withContext(Dispatchers.IO) {
|
||||||
openLibraryDatabase().useLibrary { db ->
|
openLibraryDatabase().useLibrary { db ->
|
||||||
db.files.getLibraryFile(fileId)?.toLibraryItem()
|
db.files.getLibraryFile(fileId)?.toLibraryItem()
|
||||||
@@ -189,7 +218,7 @@ actual suspend fun scanLibrarySubtree(
|
|||||||
scanLibraryContentTree(Uri.parse(path), ::emitProgress)
|
scanLibraryContentTree(Uri.parse(path), ::emitProgress)
|
||||||
} else {
|
} else {
|
||||||
if (path.requiresExternalFileAccess() && directoryChooser?.ensureExternalFileAccess() != true) {
|
if (path.requiresExternalFileAccess() && directoryChooser?.ensureExternalFileAccess() != true) {
|
||||||
error("All files access is required to scan $path.")
|
error(strings.allFilesAccessRequired(path))
|
||||||
}
|
}
|
||||||
openLibraryDatabase().useLibrary { db ->
|
openLibraryDatabase().useLibrary { db ->
|
||||||
val summary = LibraryScanner(db, ::appendLibraryLog).scanSubtree(File(path)) {
|
val summary = LibraryScanner(db, ::appendLibraryLog).scanSubtree(File(path)) {
|
||||||
@@ -328,6 +357,12 @@ actual suspend fun markLibraryReadingStatus(fileId: String, status: BookReadingS
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
actual suspend fun markLibraryFavorite(fileId: String, favorite: Boolean): Boolean = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.files.updateFavorite(fileId, favorite)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
actual suspend fun shareLibraryBookFile(fileId: String): Boolean = withContext(Dispatchers.IO) {
|
actual suspend fun shareLibraryBookFile(fileId: String): Boolean = withContext(Dispatchers.IO) {
|
||||||
runCatching {
|
runCatching {
|
||||||
val shareFile = openLibraryDatabase().useLibrary { db ->
|
val shareFile = openLibraryDatabase().useLibrary { db ->
|
||||||
@@ -348,7 +383,7 @@ actual suspend fun shareLibraryBookFile(fileId: String): Boolean = withContext(D
|
|||||||
putExtra(Intent.EXTRA_STREAM, uri)
|
putExtra(Intent.EXTRA_STREAM, uri)
|
||||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||||
}
|
}
|
||||||
val chooser = Intent.createChooser(intent, "Share book").apply {
|
val chooser = Intent.createChooser(intent, strings.shareBook).apply {
|
||||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||||
}
|
}
|
||||||
@@ -357,14 +392,29 @@ actual suspend fun shareLibraryBookFile(fileId: String): Boolean = withContext(D
|
|||||||
}.getOrDefault(false)
|
}.getOrDefault(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
actual suspend fun viewLibraryBookFile(fileId: String): Boolean = false
|
actual suspend fun viewLibraryBookFile(folder: String, fileName: String): Boolean = false
|
||||||
|
|
||||||
|
actual fun openPlatformUrl(url: String): Boolean =
|
||||||
|
runCatching {
|
||||||
|
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply {
|
||||||
|
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
}
|
||||||
|
appContext.startActivity(intent)
|
||||||
|
true
|
||||||
|
}.getOrDefault(false)
|
||||||
|
|
||||||
actual suspend fun loadBookInfoExtras(fileId: String): BookInfoExtras = withContext(Dispatchers.IO) {
|
actual suspend fun loadBookInfoExtras(fileId: String): BookInfoExtras = withContext(Dispatchers.IO) {
|
||||||
openLibraryDatabase().useLibrary { db ->
|
openLibraryDatabase().useLibrary { db ->
|
||||||
val file = db.files.get(fileId) ?: return@useLibrary BookInfoExtras()
|
val file = db.files.get(fileId) ?: return@useLibrary BookInfoExtras()
|
||||||
val clusterId = file.bodyClusterId ?: return@useLibrary BookInfoExtras()
|
val sourceFileName = file.originalFilename ?: file.storageUri?.substringAfterLast('/')
|
||||||
|
val clusterId = file.bodyClusterId ?: return@useLibrary BookInfoExtras(
|
||||||
|
sourceFileName = sourceFileName,
|
||||||
|
sourceFilePath = file.storageUri,
|
||||||
|
)
|
||||||
val readingPosition = db.readingStates.getForBodyCluster(clusterId)?.anchor?.formatHintsJson?.toReadingPosition()
|
val readingPosition = db.readingStates.getForBodyCluster(clusterId)?.anchor?.formatHintsJson?.toReadingPosition()
|
||||||
BookInfoExtras(
|
BookInfoExtras(
|
||||||
|
sourceFileName = sourceFileName,
|
||||||
|
sourceFilePath = file.storageUri,
|
||||||
bookmarks = db.bookmarks.listForBodyCluster(clusterId).map {
|
bookmarks = db.bookmarks.listForBodyCluster(clusterId).map {
|
||||||
BookmarkInfo(
|
BookmarkInfo(
|
||||||
title = it.title,
|
title = it.title,
|
||||||
@@ -411,6 +461,42 @@ actual suspend fun saveThemeMode(mode: ThemeMode) = withContext(Dispatchers.IO)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
actual suspend fun loadReaderFontSettings(): ReaderFontSettings = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
readerFontSettingsFromStorageValue(db.getAppFlag(ReaderFontSettingsFlag))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actual suspend fun saveReaderFontSettings(settings: ReaderFontSettings) = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.setAppFlag(ReaderFontSettingsFlag, settings.toStorageValue())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actual suspend fun loadReaderFullScreen(): Boolean = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.getAppFlag(ReaderFullScreenFlag)?.toBooleanStrictOrNull() ?: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actual suspend fun saveReaderFullScreen(fullScreen: Boolean) = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.setAppFlag(ReaderFullScreenFlag, fullScreen.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actual suspend fun loadReaderPagingOnly(): Boolean = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.getAppFlag(ReaderPagingOnlyFlag)?.toBooleanStrictOrNull() ?: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actual suspend fun saveReaderPagingOnly(enabled: Boolean) = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.setAppFlag(ReaderPagingOnlyFlag, enabled.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
actual suspend fun loadScanDownloadsAutomatically(): Boolean = withContext(Dispatchers.IO) {
|
actual suspend fun loadScanDownloadsAutomatically(): Boolean = withContext(Dispatchers.IO) {
|
||||||
openLibraryDatabase().useLibrary { db ->
|
openLibraryDatabase().useLibrary { db ->
|
||||||
db.getAppFlag(ScanDownloadsAutomaticallyFlag)?.toBooleanStrictOrNull() ?: true
|
db.getAppFlag(ScanDownloadsAutomaticallyFlag)?.toBooleanStrictOrNull() ?: true
|
||||||
@@ -423,6 +509,41 @@ actual suspend fun saveScanDownloadsAutomatically(enabled: Boolean) = withContex
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal actual suspend fun loadLibraryFilter(): LibraryFilter = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
val saved = db.getAppFlag(LibraryFilterFlag)
|
||||||
|
when {
|
||||||
|
saved == null -> {
|
||||||
|
appendLibraryLog("warning library filter was not saved; using ${LibraryFilter.MyLibrary.name}")
|
||||||
|
LibraryFilter.MyLibrary
|
||||||
|
}
|
||||||
|
else -> runCatching { LibraryFilter.valueOf(saved) }
|
||||||
|
.getOrElse {
|
||||||
|
appendLibraryLog("warning invalid saved library filter '$saved'; using ${LibraryFilter.MyLibrary.name}")
|
||||||
|
LibraryFilter.MyLibrary
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal actual suspend fun saveLibraryFilter(filter: LibraryFilter) = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.setAppFlag(LibraryFilterFlag, filter.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actual suspend fun loadAppLocaleTag(): String? = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.getAppFlag(AppLocaleTagFlag)?.takeIf { it.isNotBlank() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actual suspend fun saveAppLocaleTag(localeTag: String?) = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.setAppFlag(AppLocaleTagFlag, localeTag?.takeIf { it.isNotBlank() })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
actual suspend fun loadDownloadsWasScanned(): Boolean = withContext(Dispatchers.IO) {
|
actual suspend fun loadDownloadsWasScanned(): Boolean = withContext(Dispatchers.IO) {
|
||||||
openLibraryDatabase().useLibrary { db ->
|
openLibraryDatabase().useLibrary { db ->
|
||||||
db.getAppFlag(DownloadsWasScannedFlag)?.toBooleanStrictOrNull()
|
db.getAppFlag(DownloadsWasScannedFlag)?.toBooleanStrictOrNull()
|
||||||
@@ -512,7 +633,7 @@ private fun scanLibraryContentTree(
|
|||||||
onProgress(LibraryScanProgress(scanned, imported, skipped, failed, document.name))
|
onProgress(LibraryScanProgress(scanned, imported, skipped, failed, document.name))
|
||||||
val result = runCatching {
|
val result = runCatching {
|
||||||
val bytes = appContext.contentResolver.openInputStream(document.uri)?.use { it.readBytes() }
|
val bytes = appContext.contentResolver.openInputStream(document.uri)?.use { it.readBytes() }
|
||||||
?: error("Could not read ${document.name}")
|
?: error(strings.couldNotRead(document.name))
|
||||||
scanner.importExternalFile(
|
scanner.importExternalFile(
|
||||||
bytes = bytes,
|
bytes = bytes,
|
||||||
displayName = document.name,
|
displayName = document.name,
|
||||||
@@ -644,6 +765,11 @@ private fun displayNameFor(uri: Uri): String =
|
|||||||
if (cursor.moveToFirst()) cursor.getString(0) else null
|
if (cursor.moveToFirst()) cursor.getString(0) else null
|
||||||
} ?: uri.lastPathSegment ?: uri.toString()
|
} ?: uri.lastPathSegment ?: uri.toString()
|
||||||
|
|
||||||
|
private fun sizeBytesFor(uri: Uri): Long? =
|
||||||
|
appContext.contentResolver.query(uri, arrayOf(OpenableColumns.SIZE), null, null, null)?.use { cursor ->
|
||||||
|
if (cursor.moveToFirst() && !cursor.isNull(0)) cursor.getLong(0) else null
|
||||||
|
}
|
||||||
|
|
||||||
private fun LibraryScanSummary.toLibraryScanProgress(): LibraryScanProgress =
|
private fun LibraryScanSummary.toLibraryScanProgress(): LibraryScanProgress =
|
||||||
LibraryScanProgress(
|
LibraryScanProgress(
|
||||||
scannedFiles = scannedFiles,
|
scannedFiles = scannedFiles,
|
||||||
@@ -689,6 +815,7 @@ private fun LibraryFileRecord.toLibraryItem(): LibraryItem =
|
|||||||
storageUri = storageUri,
|
storageUri = storageUri,
|
||||||
lastSeenAt = lastSeenAt,
|
lastSeenAt = lastSeenAt,
|
||||||
readingStatus = readingStatus,
|
readingStatus = readingStatus,
|
||||||
|
favorite = favorite,
|
||||||
lastReadAt = lastReadAt,
|
lastReadAt = lastReadAt,
|
||||||
importedAt = importedAt,
|
importedAt = importedAt,
|
||||||
)
|
)
|
||||||
@@ -749,14 +876,37 @@ private fun libraryLogFile(): File =
|
|||||||
File(appContext.filesDir, "logs/toread.log")
|
File(appContext.filesDir, "logs/toread.log")
|
||||||
|
|
||||||
private fun ReadingPosition.toFormatHintsJson(): String =
|
private fun ReadingPosition.toFormatHintsJson(): String =
|
||||||
"""{"firstVisibleItemIndex":$itemIndex,"firstVisibleItemScrollOffset":$scrollOffset}"""
|
buildString {
|
||||||
|
append("""{"firstVisibleItemIndex":$itemIndex,"firstVisibleItemScrollOffset":$scrollOffset""")
|
||||||
|
readAloudSentenceIndex?.let { append(""","readAloudSentenceIndex":$it""") }
|
||||||
|
if (backStack.isNotEmpty()) {
|
||||||
|
append(""","backStack":[""")
|
||||||
|
append(backStack.take(MaxStoredReadingBackStack).joinToString(",") { it.toFormatHintsJson() })
|
||||||
|
append("]")
|
||||||
|
}
|
||||||
|
append("}")
|
||||||
|
}
|
||||||
|
|
||||||
private fun String.toReadingPosition(): ReadingPosition? {
|
private fun String.toReadingPosition(): ReadingPosition? {
|
||||||
|
val position = toReadingPositionObject() ?: return null
|
||||||
|
val backStackJson = Regex(""""backStack"\s*:\s*\[(.*)]""").find(this)?.groupValues?.getOrNull(1)
|
||||||
|
val backStack = backStackJson
|
||||||
|
?.let { ReadingPositionObjectRegex.findAll(it).mapNotNull { match -> match.value.toReadingPositionObject() }.toList() }
|
||||||
|
.orEmpty()
|
||||||
|
.take(MaxStoredReadingBackStack)
|
||||||
|
return position.copy(backStack = backStack)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun String.toReadingPositionObject(): ReadingPosition? {
|
||||||
val index = Regex(""""firstVisibleItemIndex"\s*:\s*(\d+)""").find(this)?.groupValues?.getOrNull(1)?.toIntOrNull()
|
val index = Regex(""""firstVisibleItemIndex"\s*:\s*(\d+)""").find(this)?.groupValues?.getOrNull(1)?.toIntOrNull()
|
||||||
val offset = Regex(""""firstVisibleItemScrollOffset"\s*:\s*(\d+)""").find(this)?.groupValues?.getOrNull(1)?.toIntOrNull()
|
val offset = Regex(""""firstVisibleItemScrollOffset"\s*:\s*(\d+)""").find(this)?.groupValues?.getOrNull(1)?.toIntOrNull()
|
||||||
return if (index != null && offset != null) ReadingPosition(index, offset) else null
|
val sentenceIndex = Regex(""""readAloudSentenceIndex"\s*:\s*(\d+)""").find(this)?.groupValues?.getOrNull(1)?.toIntOrNull()
|
||||||
|
return if (index != null && offset != null) ReadingPosition(index, offset, sentenceIndex) else null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val ReadingPositionObjectRegex = Regex("""[{][^{}]*[}]""")
|
||||||
|
private const val MaxStoredReadingBackStack = 10
|
||||||
|
|
||||||
private fun String.toSearchPrefixes(): List<String> =
|
private fun String.toSearchPrefixes(): List<String> =
|
||||||
SearchPrefixRegex.findAll(lowercase()).map { it.value }.distinct().toList()
|
SearchPrefixRegex.findAll(lowercase()).map { it.value }.distinct().toList()
|
||||||
|
|
||||||
@@ -764,5 +914,10 @@ private val SearchPrefixRegex = Regex("""[\p{L}\p{N}]+""")
|
|||||||
|
|
||||||
private const val ActiveReadingFileIdFlag = "active_reading_file_id"
|
private const val ActiveReadingFileIdFlag = "active_reading_file_id"
|
||||||
private const val ThemeModeFlag = "theme_mode"
|
private const val ThemeModeFlag = "theme_mode"
|
||||||
|
private const val ReaderFontSettingsFlag = "reader_font_settings"
|
||||||
|
private const val ReaderFullScreenFlag = "reader_full_screen"
|
||||||
|
private const val ReaderPagingOnlyFlag = "reader_paging_only"
|
||||||
private const val ScanDownloadsAutomaticallyFlag = "scan_downloads_automatically"
|
private const val ScanDownloadsAutomaticallyFlag = "scan_downloads_automatically"
|
||||||
|
private const val LibraryFilterFlag = "library_filter"
|
||||||
|
private const val AppLocaleTagFlag = "app_locale_tag"
|
||||||
private const val DownloadsWasScannedFlag = "downloads_was_scanned"
|
private const val DownloadsWasScannedFlag = "downloads_was_scanned"
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package net.sergeych.toread
|
||||||
|
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
internal actual fun platformLocaleTags(): List<String> =
|
||||||
|
listOf(Locale.getDefault().toLanguageTag())
|
||||||
@@ -4,6 +4,7 @@ import android.Manifest
|
|||||||
import android.app.AlertDialog
|
import android.app.AlertDialog
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
|
import android.graphics.Color
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
@@ -23,6 +24,8 @@ import androidx.compose.runtime.Composable
|
|||||||
import androidx.compose.ui.tooling.preview.Preview
|
import androidx.compose.ui.tooling.preview.Preview
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.core.view.WindowCompat
|
import androidx.core.view.WindowCompat
|
||||||
|
import androidx.core.view.WindowInsetsCompat
|
||||||
|
import androidx.core.view.WindowInsetsControllerCompat
|
||||||
import androidx.lifecycle.lifecycleScope
|
import androidx.lifecycle.lifecycleScope
|
||||||
import kotlinx.coroutines.CompletableDeferred
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
@@ -55,7 +58,7 @@ class MainActivity : ComponentActivity(), AndroidLibraryDirectoryChooser {
|
|||||||
}
|
}
|
||||||
notificationPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) {}
|
notificationPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) {}
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
WindowCompat.setDecorFitsSystemWindows(window, true)
|
configureEdgeToEdgeBookWindow()
|
||||||
initToreadPlatform(this, this)
|
initToreadPlatform(this, this)
|
||||||
rememberPlatformOpenBookIntent(intent)
|
rememberPlatformOpenBookIntent(intent)
|
||||||
|
|
||||||
@@ -67,6 +70,11 @@ class MainActivity : ComponentActivity(), AndroidLibraryDirectoryChooser {
|
|||||||
requestNotificationPermissionIfNeeded()
|
requestNotificationPermissionIfNeeded()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||||
|
super.onWindowFocusChanged(hasFocus)
|
||||||
|
if (hasFocus) hideNavigationBar()
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun chooseDirectory(): String? {
|
override suspend fun chooseDirectory(): String? {
|
||||||
val result = CompletableDeferred<String?>()
|
val result = CompletableDeferred<String?>()
|
||||||
runOnUiThread {
|
runOnUiThread {
|
||||||
@@ -82,8 +90,8 @@ class MainActivity : ComponentActivity(), AndroidLibraryDirectoryChooser {
|
|||||||
private fun showDirectoryChoice(result: CompletableDeferred<String?>) {
|
private fun showDirectoryChoice(result: CompletableDeferred<String?>) {
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||||
AlertDialog.Builder(this)
|
AlertDialog.Builder(this)
|
||||||
.setTitle("Choose library folder")
|
.setTitle(strings.chooseLibraryFolder)
|
||||||
.setItems(arrayOf("Downloads", "Other folder...")) { _, which ->
|
.setItems(arrayOf(strings.downloads, strings.otherFolder)) { _, which ->
|
||||||
when (which) {
|
when (which) {
|
||||||
0 -> chooseDownloadsDirectory(result)
|
0 -> chooseDownloadsDirectory(result)
|
||||||
else -> launchSystemDirectoryPicker(result)
|
else -> launchSystemDirectoryPicker(result)
|
||||||
@@ -175,6 +183,27 @@ class MainActivity : ComponentActivity(), AndroidLibraryDirectoryChooser {
|
|||||||
notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun configureEdgeToEdgeBookWindow() {
|
||||||
|
WindowCompat.setDecorFitsSystemWindows(window, false)
|
||||||
|
window.navigationBarColor = Color.TRANSPARENT
|
||||||
|
window.statusBarColor = Color.TRANSPARENT
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||||
|
window.navigationBarDividerColor = Color.TRANSPARENT
|
||||||
|
}
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
|
window.isNavigationBarContrastEnforced = false
|
||||||
|
window.isStatusBarContrastEnforced = false
|
||||||
|
}
|
||||||
|
hideNavigationBar()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hideNavigationBar() {
|
||||||
|
WindowCompat.getInsetsController(window, window.decorView).apply {
|
||||||
|
systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
|
||||||
|
hide(WindowInsetsCompat.Type.navigationBars())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun downloadsPath(): String =
|
private fun downloadsPath(): String =
|
||||||
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)?.absolutePath
|
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)?.absolutePath
|
||||||
?: Environment.getExternalStorageDirectory().absolutePath
|
?: Environment.getExternalStorageDirectory().absolutePath
|
||||||
@@ -185,7 +214,7 @@ private fun AndroidAppWindow(content: @Composable () -> Unit) {
|
|||||||
androidx.compose.foundation.layout.Box(
|
androidx.compose.foundation.layout.Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Vertical)),
|
.windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Top)),
|
||||||
) {
|
) {
|
||||||
content()
|
content()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,9 +15,12 @@ import android.os.Bundle
|
|||||||
import android.os.IBinder
|
import android.os.IBinder
|
||||||
import android.speech.tts.TextToSpeech
|
import android.speech.tts.TextToSpeech
|
||||||
import android.speech.tts.UtteranceProgressListener
|
import android.speech.tts.UtteranceProgressListener
|
||||||
|
import android.util.Log
|
||||||
import androidx.core.app.NotificationCompat
|
import androidx.core.app.NotificationCompat
|
||||||
import androidx.core.app.NotificationManagerCompat
|
import androidx.core.app.NotificationManagerCompat
|
||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
|
import java.util.Locale
|
||||||
|
import java.util.concurrent.atomic.AtomicLong
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
@@ -25,14 +28,17 @@ import kotlinx.coroutines.cancel
|
|||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
|
||||||
actual object ReadAloudPlatform {
|
actual object ReadAloudPlatform {
|
||||||
actual val isSupported: Boolean = true
|
actual val isSupported: Boolean = true
|
||||||
actual val state: StateFlow<ReadAloudState> = AndroidReadAloudEngine.state
|
actual val state: StateFlow<ReadAloudState> = AndroidReadAloudEngine.state
|
||||||
|
actual val settingsState: StateFlow<ReadAloudSettingsState> = AndroidReadAloudEngine.settingsState
|
||||||
|
|
||||||
actual fun prepare(bookTitle: String, sentences: List<ReadAloudSentence>, startIndex: Int) {
|
actual fun prepare(fileId: String, bookTitle: String, sentences: List<ReadAloudSentence>, startIndex: Int) {
|
||||||
val context = androidAppContext() ?: return
|
val context = androidAppContext() ?: return
|
||||||
AndroidReadAloudEngine.prepare(context, bookTitle, sentences, startIndex)
|
AndroidReadAloudEngine.prepare(context, fileId, bookTitle, sentences, startIndex)
|
||||||
ReadAloudService.start(context)
|
ReadAloudService.start(context)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,25 +55,70 @@ actual object ReadAloudPlatform {
|
|||||||
actual fun skip(delta: Int) {
|
actual fun skip(delta: Int) {
|
||||||
AndroidReadAloudEngine.skip(delta)
|
AndroidReadAloudEngine.skip(delta)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
actual fun refreshSettings() {
|
||||||
|
val context = androidAppContext() ?: return
|
||||||
|
AndroidReadAloudEngine.refreshSettings(context)
|
||||||
|
}
|
||||||
|
|
||||||
|
actual fun selectEngine(engineId: String?) {
|
||||||
|
val context = androidAppContext() ?: return
|
||||||
|
AndroidReadAloudEngine.selectEngine(context, engineId)
|
||||||
|
}
|
||||||
|
|
||||||
|
actual fun selectVoice(voiceId: String?) {
|
||||||
|
val context = androidAppContext() ?: return
|
||||||
|
AndroidReadAloudEngine.selectVoice(context, voiceId)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private object AndroidReadAloudEngine {
|
private object AndroidReadAloudEngine {
|
||||||
private const val UtterancePrefix = "read-aloud-"
|
|
||||||
private const val BeforePausePrefix = "read-aloud-before-"
|
private const val BeforePausePrefix = "read-aloud-before-"
|
||||||
private const val SpeakPrefix = "read-aloud-speak-"
|
private const val SpeakPrefix = "read-aloud-speak-"
|
||||||
private const val AfterPausePrefix = "read-aloud-after-"
|
private const val AfterPausePrefix = "read-aloud-after-"
|
||||||
|
private const val SettingsPrefs = "read_aloud_tts"
|
||||||
|
private const val SelectedEngineKey = "selected_engine"
|
||||||
|
private const val EngineChoiceMadeKey = "engine_choice_made"
|
||||||
|
private const val SelectedVoiceKey = "selected_voice"
|
||||||
|
private const val TextReplacementsKey = "text_replacements"
|
||||||
|
private const val EmptyTextReplacementsJson = "[]"
|
||||||
|
private val RussianLocale = Locale.forLanguageTag("ru-RU")
|
||||||
|
|
||||||
private val mutableState = MutableStateFlow(ReadAloudState())
|
private val mutableState = MutableStateFlow(ReadAloudState())
|
||||||
val state: StateFlow<ReadAloudState> = mutableState
|
val state: StateFlow<ReadAloudState> = mutableState
|
||||||
|
private val mutableSettingsState = MutableStateFlow(ReadAloudSettingsState())
|
||||||
|
val settingsState: StateFlow<ReadAloudSettingsState> = mutableSettingsState
|
||||||
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||||
|
private val positionSaveMutex = Mutex()
|
||||||
|
private val positionSaveVersion = AtomicLong()
|
||||||
|
|
||||||
private var tts: TextToSpeech? = null
|
private var tts: TextToSpeech? = null
|
||||||
private var ttsReady = false
|
private var ttsReady = false
|
||||||
|
private var ttsEngineId: String? = null
|
||||||
|
private var engineProbe: TextToSpeech? = null
|
||||||
|
private var voiceProbe: TextToSpeech? = null
|
||||||
|
private var ttsGeneration = 0L
|
||||||
|
private var engineProbeGeneration = 0L
|
||||||
|
private var voiceProbeGeneration = 0L
|
||||||
private var shouldSpeakWhenReady = false
|
private var shouldSpeakWhenReady = false
|
||||||
|
private var fileId: String? = null
|
||||||
private var bookTitle: String = ""
|
private var bookTitle: String = ""
|
||||||
private var sentences: List<ReadAloudSentence> = emptyList()
|
private var sentences: List<ReadAloudSentence> = emptyList()
|
||||||
private var currentIndex: Int = 0
|
private var currentIndex: Int = 0
|
||||||
|
private var playbackGeneration = 0L
|
||||||
|
private var blockNumber = 0L
|
||||||
|
private var activeUtteranceId: String? = null
|
||||||
|
private var blocks: Iterator<ReadAloudBlock>? = null
|
||||||
|
private val queuedBlocks = linkedMapOf<String, ReadAloudBlock>()
|
||||||
|
|
||||||
fun prepare(context: Context, title: String, queue: List<ReadAloudSentence>, startIndex: Int) {
|
private fun beforeId(id: String) = "$BeforePausePrefix$id"
|
||||||
|
private fun afterId(id: String) = "$AfterPausePrefix$id"
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun prepare(context: Context, fileId: String, title: String, queue: List<ReadAloudSentence>, startIndex: Int) {
|
||||||
|
shouldSpeakWhenReady = false
|
||||||
|
cancelQueue()
|
||||||
|
this.fileId = fileId
|
||||||
bookTitle = title
|
bookTitle = title
|
||||||
sentences = queue
|
sentences = queue
|
||||||
currentIndex = startIndex.coerceIn(queue.indices.takeIf { queue.isNotEmpty() } ?: 0..0)
|
currentIndex = startIndex.coerceIn(queue.indices.takeIf { queue.isNotEmpty() } ?: 0..0)
|
||||||
@@ -79,66 +130,194 @@ private object AndroidReadAloudEngine {
|
|||||||
ensureTts(context.applicationContext)
|
ensureTts(context.applicationContext)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
fun play(context: Context) {
|
fun play(context: Context) {
|
||||||
if (sentences.isEmpty()) return
|
if (sentences.isEmpty()) return
|
||||||
ensureTts(context.applicationContext)
|
ensureTts(context.applicationContext)
|
||||||
if (!ttsReady) {
|
if (!ttsReady) {
|
||||||
shouldSpeakWhenReady = true
|
shouldSpeakWhenReady = true
|
||||||
mutableState.value = mutableState.value.copy(active = true, playing = true, sentenceIndex = currentIndex)
|
mutableState.value = mutableState.value.copy(
|
||||||
|
active = true,
|
||||||
|
playing = true,
|
||||||
|
buffering = true,
|
||||||
|
sentenceIndex = sentences.getOrNull(currentIndex)?.index,
|
||||||
|
)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
speakCurrent()
|
speakCurrent()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
fun stop() {
|
fun stop() {
|
||||||
shouldSpeakWhenReady = false
|
shouldSpeakWhenReady = false
|
||||||
tts?.stop()
|
cancelQueue()
|
||||||
mutableState.value = ReadAloudState()
|
mutableState.value = ReadAloudState()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
fun skip(delta: Int) {
|
fun skip(delta: Int) {
|
||||||
if (sentences.isEmpty()) return
|
if (sentences.isEmpty()) return
|
||||||
val wasPlaying = mutableState.value.playing
|
val wasPlaying = mutableState.value.playing
|
||||||
currentIndex = (currentIndex + delta).coerceIn(sentences.indices)
|
currentIndex = (currentIndex + delta).coerceIn(sentences.indices)
|
||||||
|
val sentence = sentences.getOrNull(currentIndex)
|
||||||
mutableState.value = mutableState.value.copy(
|
mutableState.value = mutableState.value.copy(
|
||||||
active = true,
|
active = true,
|
||||||
playing = wasPlaying,
|
playing = wasPlaying,
|
||||||
sentenceIndex = currentIndex,
|
sentenceIndex = sentence?.index ?: currentIndex,
|
||||||
)
|
)
|
||||||
|
sentence?.let(::saveSentencePosition)
|
||||||
if (wasPlaying && ttsReady) {
|
if (wasPlaying && ttsReady) {
|
||||||
speakCurrent()
|
speakCurrent()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun ensureTts(context: Context) {
|
@Synchronized
|
||||||
if (tts != null) return
|
fun refreshSettings(context: Context) {
|
||||||
tts = TextToSpeech(context) { status ->
|
val appContext = context.applicationContext
|
||||||
ttsReady = status == TextToSpeech.SUCCESS
|
mutableSettingsState.value = mutableSettingsState.value.copy(
|
||||||
if (ttsReady) {
|
textReplacements = userTextReplacements(appContext),
|
||||||
tts?.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
|
loading = true,
|
||||||
override fun onStart(utteranceId: String?) = Unit
|
message = null,
|
||||||
|
)
|
||||||
|
val generation = ++engineProbeGeneration
|
||||||
|
engineProbe?.shutdown()
|
||||||
|
engineProbe = TextToSpeech(appContext) { status ->
|
||||||
|
// Dispatch even if onInit fires synchronously inside the constructor.
|
||||||
|
scope.launch(Dispatchers.Main) { handleEngineProbeInit(appContext, generation, status) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun onDone(utteranceId: String?) {
|
@Synchronized
|
||||||
handleUtteranceDone(utteranceId)
|
private fun handleEngineProbeInit(context: Context, generation: Long, status: Int) {
|
||||||
}
|
if (generation != engineProbeGeneration) return
|
||||||
|
val probe = engineProbe ?: return
|
||||||
@Deprecated("Deprecated in Java")
|
if (status != TextToSpeech.SUCCESS) {
|
||||||
override fun onError(utteranceId: String?) {
|
mutableSettingsState.value = mutableSettingsState.value.copy(
|
||||||
stop()
|
loading = false, message = strings.couldNotLoadAndroidTtsEngines,
|
||||||
}
|
)
|
||||||
|
probe.shutdown()
|
||||||
override fun onError(utteranceId: String?, errorCode: Int) {
|
engineProbe = null
|
||||||
stop()
|
return
|
||||||
}
|
}
|
||||||
})
|
val engines = probe.engines.orEmpty()
|
||||||
if (shouldSpeakWhenReady) {
|
.map { ReadAloudEngineOption(id = it.name, label = it.label ?: it.name) }
|
||||||
shouldSpeakWhenReady = false
|
.sortedBy { it.label.lowercase() }
|
||||||
speakCurrent()
|
var selectedEngine = selectedEngineId(context)
|
||||||
}
|
if (selectedEngine == null && !context.readAloudPrefs().getBoolean(EngineChoiceMadeKey, false)) {
|
||||||
} else {
|
selectedEngine = engines.firstOrNull { it.isRhVoice() }?.id
|
||||||
stop()
|
if (selectedEngine != null) {
|
||||||
|
context.readAloudPrefs().edit().putString(SelectedEngineKey, selectedEngine).apply()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
mutableSettingsState.value = mutableSettingsState.value.copy(
|
||||||
|
engines = engines, selectedEngineId = selectedEngine,
|
||||||
|
)
|
||||||
|
probe.shutdown()
|
||||||
|
engineProbe = null
|
||||||
|
refreshVoices(context, selectedEngine)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun selectEngine(context: Context, engineId: String?) {
|
||||||
|
val appContext = context.applicationContext
|
||||||
|
appContext.readAloudPrefs()
|
||||||
|
.edit()
|
||||||
|
.putBoolean(EngineChoiceMadeKey, true)
|
||||||
|
.putStringOrRemove(SelectedEngineKey, engineId)
|
||||||
|
.remove(SelectedVoiceKey)
|
||||||
|
.apply()
|
||||||
|
val wasPlaying = mutableState.value.playing
|
||||||
|
resetTts()
|
||||||
|
mutableSettingsState.value = mutableSettingsState.value.copy(
|
||||||
|
selectedEngineId = engineId,
|
||||||
|
selectedVoiceId = null,
|
||||||
|
voices = emptyList(),
|
||||||
|
loading = true,
|
||||||
|
message = null,
|
||||||
|
)
|
||||||
|
refreshVoices(appContext, engineId)
|
||||||
|
if (wasPlaying) play(appContext)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun selectVoice(context: Context, voiceId: String?) {
|
||||||
|
val appContext = context.applicationContext
|
||||||
|
appContext.readAloudPrefs()
|
||||||
|
.edit()
|
||||||
|
.putStringOrRemove(SelectedVoiceKey, voiceId)
|
||||||
|
.apply()
|
||||||
|
mutableSettingsState.value = mutableSettingsState.value.copy(selectedVoiceId = voiceId)
|
||||||
|
applyTtsConfiguration(appContext)
|
||||||
|
if (mutableState.value.playing && ttsReady) {
|
||||||
|
speakCurrent()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ensureTts(context: Context) {
|
||||||
|
val appContext = context.applicationContext
|
||||||
|
val selectedEngine = selectedEngineId(appContext)
|
||||||
|
if (tts != null && ttsEngineId == selectedEngine) return
|
||||||
|
resetTts()
|
||||||
|
ttsEngineId = selectedEngine
|
||||||
|
val generation = ttsGeneration
|
||||||
|
tts = if (selectedEngine == null) {
|
||||||
|
TextToSpeech(appContext) { status ->
|
||||||
|
scope.launch(Dispatchers.Main) { handleTtsInit(appContext, generation, status) }
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
TextToSpeech(
|
||||||
|
appContext,
|
||||||
|
{ status -> scope.launch(Dispatchers.Main) { handleTtsInit(appContext, generation, status) } },
|
||||||
|
selectedEngine,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
private fun handleTtsInit(context: Context, generation: Long, status: Int) {
|
||||||
|
if (generation != ttsGeneration) return
|
||||||
|
ttsReady = status == TextToSpeech.SUCCESS
|
||||||
|
if (ttsReady) {
|
||||||
|
applyTtsConfiguration(context)
|
||||||
|
Log.i("YereedTts", "Initialized requested engine=${ttsEngineId ?: "system default"}, voice=${tts?.voice?.name}")
|
||||||
|
tts?.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
|
||||||
|
override fun onStart(utteranceId: String?) {
|
||||||
|
handleUtteranceStart(utteranceId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onRangeStart(utteranceId: String?, start: Int, end: Int, frame: Int) {
|
||||||
|
handleUtteranceRange(utteranceId, start)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDone(utteranceId: String?) {
|
||||||
|
handleUtteranceDone(utteranceId)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Deprecated("Deprecated in Java")
|
||||||
|
override fun onError(utteranceId: String?) {
|
||||||
|
handleUtteranceError(utteranceId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onError(utteranceId: String?, errorCode: Int) {
|
||||||
|
handleUtteranceError(utteranceId)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if (shouldSpeakWhenReady) {
|
||||||
|
shouldSpeakWhenReady = false
|
||||||
|
speakCurrent()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
stop()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cancelQueue() {
|
||||||
|
// Invalidate callbacks before stopping: a late event must not affect the new queue.
|
||||||
|
playbackGeneration++
|
||||||
|
blocks = null
|
||||||
|
activeUtteranceId = null
|
||||||
|
queuedBlocks.clear()
|
||||||
|
tts?.stop()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun speakCurrent() {
|
private fun speakCurrent() {
|
||||||
@@ -146,44 +325,200 @@ private object AndroidReadAloudEngine {
|
|||||||
stop()
|
stop()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
cancelQueue()
|
||||||
mutableState.value = ReadAloudState(active = true, playing = true, sentenceIndex = sentence.index)
|
mutableState.value = ReadAloudState(active = true, playing = true, sentenceIndex = sentence.index)
|
||||||
val params = Bundle().apply {
|
saveSentencePosition(sentence)
|
||||||
putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "$SpeakPrefix$currentIndex")
|
blocks = readAloudBlocks(
|
||||||
|
sentences, currentIndex, minOf(4_000, TextToSpeech.getMaxSpeechInputLength()),
|
||||||
|
).iterator()
|
||||||
|
fillQueue()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun fillQueue() {
|
||||||
|
val engine = tts ?: return
|
||||||
|
val remaining = blocks ?: return
|
||||||
|
// Keep the current block and two successors submitted, before playback ends.
|
||||||
|
while (queuedBlocks.size < 3 && remaining.hasNext()) {
|
||||||
|
val block = remaining.next()
|
||||||
|
val id = "$SpeakPrefix$playbackGeneration-${blockNumber++}"
|
||||||
|
queuedBlocks[id] = block
|
||||||
|
val beforeResult = if (block.pauseBeforeMillis > 0) {
|
||||||
|
engine.playSilentUtterance(block.pauseBeforeMillis, TextToSpeech.QUEUE_ADD, beforeId(id))
|
||||||
|
} else TextToSpeech.SUCCESS
|
||||||
|
val speechResult = engine.speak(block.text, TextToSpeech.QUEUE_ADD, Bundle(), id)
|
||||||
|
val afterResult = if (block.pauseAfterMillis > 0) {
|
||||||
|
engine.playSilentUtterance(block.pauseAfterMillis, TextToSpeech.QUEUE_ADD, afterId(id))
|
||||||
|
} else TextToSpeech.SUCCESS
|
||||||
|
if (beforeResult == TextToSpeech.ERROR || speechResult == TextToSpeech.ERROR ||
|
||||||
|
afterResult == TextToSpeech.ERROR) {
|
||||||
|
stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
val queueMode = if (sentence.pauseBeforeMillis > 0) {
|
if (queuedBlocks.isEmpty()) stop()
|
||||||
tts?.playSilentUtterance(sentence.pauseBeforeMillis, TextToSpeech.QUEUE_FLUSH, "$BeforePausePrefix$currentIndex")
|
}
|
||||||
TextToSpeech.QUEUE_ADD
|
|
||||||
} else {
|
private fun updatePosition(position: Int) {
|
||||||
TextToSpeech.QUEUE_FLUSH
|
if (currentIndex == position && mutableState.value.sentenceIndex == sentences[position].index) return
|
||||||
|
currentIndex = position
|
||||||
|
val sentence = sentences[position]
|
||||||
|
mutableState.value = mutableState.value.copy(sentenceIndex = sentence.index)
|
||||||
|
saveSentencePosition(sentence)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
private fun handleUtteranceStart(utteranceId: String?) {
|
||||||
|
if (!mutableState.value.playing) return
|
||||||
|
val block = queuedBlocks[utteranceId] ?: return
|
||||||
|
activeUtteranceId = utteranceId
|
||||||
|
updatePosition(block.ranges.first().position)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
private fun handleUtteranceRange(utteranceId: String?, offset: Int) {
|
||||||
|
if (!mutableState.value.playing || utteranceId != activeUtteranceId) return
|
||||||
|
val block = queuedBlocks[utteranceId] ?: return
|
||||||
|
updatePosition(block.positionAt(offset))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
private fun handleUtteranceDone(utteranceId: String?) {
|
||||||
|
if (!mutableState.value.playing || utteranceId == null) return
|
||||||
|
val isAfter = utteranceId.startsWith(AfterPausePrefix)
|
||||||
|
val id = if (isAfter) utteranceId.removePrefix(AfterPausePrefix) else utteranceId
|
||||||
|
val block = queuedBlocks[id] ?: return
|
||||||
|
if (!isAfter) {
|
||||||
|
if (activeUtteranceId == id) updatePosition(block.ranges.last().position)
|
||||||
|
if (block.pauseAfterMillis > 0) return
|
||||||
}
|
}
|
||||||
tts?.speak(sentence.text, queueMode, params, "$SpeakPrefix$currentIndex")
|
queuedBlocks.remove(id)
|
||||||
if (sentence.pauseAfterMillis > 0) {
|
fillQueue()
|
||||||
tts?.playSilentUtterance(sentence.pauseAfterMillis, TextToSpeech.QUEUE_ADD, "$AfterPausePrefix$currentIndex")
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
private fun handleUtteranceError(utteranceId: String?) {
|
||||||
|
val id = utteranceId?.removePrefix(BeforePausePrefix)?.removePrefix(AfterPausePrefix)
|
||||||
|
if (queuedBlocks.containsKey(id)) stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun notificationTitle(): String = bookTitle.ifBlank { strings.readAloud }
|
||||||
|
|
||||||
|
private fun saveSentencePosition(sentence: ReadAloudSentence) {
|
||||||
|
val activeFileId = fileId ?: return
|
||||||
|
val saveVersion = positionSaveVersion.incrementAndGet()
|
||||||
|
scope.launch {
|
||||||
|
positionSaveMutex.withLock {
|
||||||
|
if (saveVersion != positionSaveVersion.get()) return@withLock
|
||||||
|
runCatching {
|
||||||
|
saveLibraryReadingPosition(activeFileId, ReadingPosition(sentence.itemIndex, 0, sentence.index))
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleUtteranceDone(utteranceId: String?) {
|
private fun refreshVoices(context: Context, engineId: String?) {
|
||||||
if (!mutableState.value.playing) return
|
val generation = ++voiceProbeGeneration
|
||||||
val speakIndex = utteranceId?.removePrefix(SpeakPrefix)?.takeIf { it != utteranceId }?.toIntOrNull()
|
voiceProbe?.shutdown()
|
||||||
val afterIndex = utteranceId?.removePrefix(AfterPausePrefix)?.takeIf { it != utteranceId }?.toIntOrNull()
|
voiceProbe = TextToSpeech(context, { status ->
|
||||||
val finishedIndex = afterIndex ?: speakIndex ?: return
|
scope.launch(Dispatchers.Main) { handleVoiceProbeInit(context, generation, status) }
|
||||||
if (finishedIndex != currentIndex) return
|
}, engineId)
|
||||||
val currentSentence = sentences.getOrNull(currentIndex) ?: run {
|
}
|
||||||
stop()
|
|
||||||
|
@Synchronized
|
||||||
|
private fun handleVoiceProbeInit(context: Context, generation: Long, status: Int) {
|
||||||
|
if (generation != voiceProbeGeneration) return
|
||||||
|
val probe = voiceProbe ?: return
|
||||||
|
if (status != TextToSpeech.SUCCESS) {
|
||||||
|
mutableSettingsState.value = mutableSettingsState.value.copy(
|
||||||
|
loading = false,
|
||||||
|
message = strings.couldNotLoadSelectedTtsVoices,
|
||||||
|
)
|
||||||
|
probe.shutdown()
|
||||||
|
if (voiceProbe === probe) voiceProbe = null
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (speakIndex != null && currentSentence.pauseAfterMillis > 0) {
|
|
||||||
return
|
val voices = probe.voices.orEmpty()
|
||||||
|
.mapNotNull { voice ->
|
||||||
|
val locale = voice.locale ?: return@mapNotNull null
|
||||||
|
ReadAloudVoiceOption(
|
||||||
|
id = voice.name,
|
||||||
|
label = voice.name,
|
||||||
|
localeTag = locale.toLanguageTag(),
|
||||||
|
networkRequired = voice.isNetworkConnectionRequired,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
.filter { !it.networkRequired }
|
||||||
|
.sortedWith(
|
||||||
|
compareByDescending<ReadAloudVoiceOption> { it.localeTag.startsWith("ru", ignoreCase = true) }
|
||||||
|
.thenBy { it.localeTag }
|
||||||
|
.thenBy { it.label.lowercase() },
|
||||||
|
)
|
||||||
|
val savedVoice = selectedVoiceId(context).takeIf { saved ->
|
||||||
|
saved != null && voices.any { it.id == saved }
|
||||||
}
|
}
|
||||||
if (currentIndex < sentences.lastIndex) {
|
mutableSettingsState.value = mutableSettingsState.value.copy(
|
||||||
currentIndex += 1
|
voices = voices,
|
||||||
speakCurrent()
|
selectedVoiceId = savedVoice,
|
||||||
|
loading = false,
|
||||||
|
message = if (voices.isEmpty()) strings.noOfflineVoices else null,
|
||||||
|
)
|
||||||
|
if (savedVoice == null && selectedVoiceId(context) != null) {
|
||||||
|
context.readAloudPrefs().edit().remove(SelectedVoiceKey).apply()
|
||||||
|
}
|
||||||
|
probe.shutdown()
|
||||||
|
if (voiceProbe === probe) voiceProbe = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun applyTtsConfiguration(context: Context) {
|
||||||
|
val selectedVoice = selectedVoiceId(context)
|
||||||
|
val voice = selectedVoice?.let { voiceName ->
|
||||||
|
tts?.voices?.firstOrNull { it.name == voiceName && !it.isNetworkConnectionRequired }
|
||||||
|
}
|
||||||
|
if (voice != null) {
|
||||||
|
tts?.voice = voice
|
||||||
} else {
|
} else {
|
||||||
stop()
|
tts?.setLanguage(RussianLocale)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun resetTts() {
|
||||||
|
ttsGeneration++
|
||||||
|
shouldSpeakWhenReady = false
|
||||||
|
ttsReady = false
|
||||||
|
ttsEngineId = null
|
||||||
|
cancelQueue()
|
||||||
|
tts?.shutdown()
|
||||||
|
tts = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun selectedEngineId(context: Context): String? =
|
||||||
|
context.readAloudPrefs().getString(SelectedEngineKey, null)
|
||||||
|
|
||||||
|
private fun selectedVoiceId(context: Context): String? =
|
||||||
|
context.readAloudPrefs().getString(SelectedVoiceKey, null)
|
||||||
|
|
||||||
|
private fun userTextReplacements(context: Context): List<ReadAloudTextReplacement> {
|
||||||
|
val prefs = context.readAloudPrefs()
|
||||||
|
if (!prefs.contains(TextReplacementsKey)) {
|
||||||
|
prefs.edit().putString(TextReplacementsKey, EmptyTextReplacementsJson).apply()
|
||||||
|
}
|
||||||
|
return emptyList()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Context.readAloudPrefs() =
|
||||||
|
getSharedPreferences(SettingsPrefs, Context.MODE_PRIVATE)
|
||||||
|
|
||||||
|
private fun ReadAloudEngineOption.isRhVoice(): Boolean =
|
||||||
|
id.contains("rhvoice", ignoreCase = true) || label.contains("RHVoice", ignoreCase = true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun android.content.SharedPreferences.Editor.putStringOrRemove(
|
||||||
|
key: String,
|
||||||
|
value: String?,
|
||||||
|
): android.content.SharedPreferences.Editor =
|
||||||
|
if (value == null) remove(key) else putString(key, value)
|
||||||
|
|
||||||
class ReadAloudService : Service() {
|
class ReadAloudService : Service() {
|
||||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||||
|
|
||||||
@@ -229,20 +564,20 @@ class ReadAloudService : Service() {
|
|||||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
)
|
)
|
||||||
val playStopAction = if (state.playing) ActionStop else ActionPlay
|
val playStopAction = if (state.playing) ActionStop else ActionPlay
|
||||||
val playStopTitle = if (state.playing) "Stop" else "Play"
|
val playStopTitle = if (state.playing) strings.stop else strings.play
|
||||||
val playStopIcon = if (state.playing) android.R.drawable.ic_media_pause else android.R.drawable.ic_media_play
|
val playStopIcon = if (state.playing) android.R.drawable.ic_media_pause else android.R.drawable.ic_media_play
|
||||||
|
|
||||||
return NotificationCompat.Builder(this, ChannelId)
|
return NotificationCompat.Builder(this, ChannelId)
|
||||||
.setSmallIcon(R.drawable.ic_launcher_background)
|
.setSmallIcon(R.drawable.ic_launcher_background)
|
||||||
.setContentTitle("Read aloud")
|
.setContentTitle(AndroidReadAloudEngine.notificationTitle())
|
||||||
.setContentText("Reading in the background")
|
.setContentText(strings.readingInBackground)
|
||||||
.setContentIntent(contentIntent)
|
.setContentIntent(contentIntent)
|
||||||
.setOngoing(state.playing)
|
.setOngoing(state.playing)
|
||||||
.setOnlyAlertOnce(true)
|
.setOnlyAlertOnce(true)
|
||||||
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||||
.addAction(android.R.drawable.ic_media_previous, "Previous", serviceIntent(ActionBack))
|
.addAction(android.R.drawable.ic_media_previous, strings.previous, serviceIntent(ActionBack))
|
||||||
.addAction(playStopIcon, playStopTitle, serviceIntent(playStopAction))
|
.addAction(playStopIcon, playStopTitle, serviceIntent(playStopAction))
|
||||||
.addAction(android.R.drawable.ic_media_next, "Next", serviceIntent(ActionForward))
|
.addAction(android.R.drawable.ic_media_next, strings.next, serviceIntent(ActionForward))
|
||||||
.build()
|
.build()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -267,7 +602,7 @@ class ReadAloudService : Service() {
|
|||||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||||
val channel = NotificationChannel(
|
val channel = NotificationChannel(
|
||||||
ChannelId,
|
ChannelId,
|
||||||
"Read aloud",
|
strings.readAloud,
|
||||||
NotificationManager.IMPORTANCE_LOW,
|
NotificationManager.IMPORTANCE_LOW,
|
||||||
)
|
)
|
||||||
getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
|
getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
|
||||||
|
|||||||
@@ -1,65 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<!--
|
|
||||||
Adaptive icon foreground: 108dp x 108dp canvas.
|
|
||||||
Safe zone: inner 72dp circle (18dp..90dp). Book (200x260) scaled 0.2769x:
|
|
||||||
translateX=26.31, translateY=18. Star sub-group at book coords (67,59) scale 0.888x.
|
|
||||||
-->
|
|
||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
android:width="108dp"
|
|
||||||
android:height="108dp"
|
|
||||||
android:viewportWidth="108"
|
|
||||||
android:viewportHeight="108">
|
|
||||||
|
|
||||||
<group
|
|
||||||
android:translateX="26.31"
|
|
||||||
android:translateY="18"
|
|
||||||
android:scaleX="0.2769"
|
|
||||||
android:scaleY="0.2769">
|
|
||||||
|
|
||||||
<!-- Pages stack -->
|
|
||||||
<path android:fillColor="#e8e4d8"
|
|
||||||
android:pathData="M36,18 H178 V248 H36 Z"/>
|
|
||||||
<path android:fillColor="#ece9df"
|
|
||||||
android:pathData="M34,16 H176 V246 H34 Z"/>
|
|
||||||
<path android:fillColor="#f0ede3"
|
|
||||||
android:pathData="M32,14 H174 V244 H32 Z"/>
|
|
||||||
|
|
||||||
<!-- Spine -->
|
|
||||||
<path android:fillColor="#1a3d52"
|
|
||||||
android:pathData="M18,14 H36 V244 H18 Z"/>
|
|
||||||
<path android:fillColor="#00000000"
|
|
||||||
android:strokeColor="#30000000"
|
|
||||||
android:strokeWidth="1"
|
|
||||||
android:pathData="M35,14 V244"/>
|
|
||||||
|
|
||||||
<!-- Cover -->
|
|
||||||
<path android:fillColor="#2c5f7a"
|
|
||||||
android:pathData="M32,14 H174 V244 H32 Z"/>
|
|
||||||
|
|
||||||
<!-- Cover border -->
|
|
||||||
<path android:fillColor="#00000000"
|
|
||||||
android:strokeColor="#30ffffff"
|
|
||||||
android:strokeWidth="1.5"
|
|
||||||
android:pathData="M40,22 H166 V236 H40 Z"/>
|
|
||||||
|
|
||||||
<!-- Star arms -->
|
|
||||||
<group
|
|
||||||
android:translateX="67"
|
|
||||||
android:translateY="59"
|
|
||||||
android:scaleX="0.888"
|
|
||||||
android:scaleY="0.888">
|
|
||||||
<path android:fillColor="#6197b4"
|
|
||||||
android:pathData="m 32.120065,25.957965 -15.0296,-9.2912 c -0.3066,-0.187 -0.6532,0.1603 -0.4666,0.4676 l 8.9112,14.4745 c 0.2399,0.3874 0.5665,0.7013 0.9597,0.9284 l 14.0032,8.0555 V 0.34209525 c 0,-0.394094 -0.5532,-0.474248 -0.6665,-0.1002 z"/>
|
|
||||||
<path android:fillColor="#bdccd6"
|
|
||||||
android:pathData="m 25.901665,48.988865 -9.271,15.0556 c -0.1866,0.3073 0.16,0.6546 0.4665,0.4676 l 14.4431,-8.9305 c 0.3866,-0.2405 0.6999,-0.5678 0.9265,-0.9619 l 8.038,-14.0336 H 0.34134532 c -0.393231,0 -0.473212,0.5544 -0.09997,0.6679 z"/>
|
|
||||||
<path android:fillColor="#94bfcf"
|
|
||||||
android:pathData="m 55.101065,32.189965 9.2711,-15.0623 c 0.1866,-0.3072 -0.16,-0.6546 -0.4666,-0.4675 l -14.4431,8.9371 c -0.3865,0.2405 -0.6998,0.5678 -0.9264,0.9619 l -8.038,14.027 h 40.1634 c 0.3932,0 0.4732,-0.5544 0.1,-0.668 z"/>
|
|
||||||
<path android:fillColor="#eee9d9"
|
|
||||||
android:pathData="m 54.507965,48.641565 -14.0099,-8.0555 v 40.2507 c 0,0.3941 0.5532,0.4742 0.6665,0.1002 l 7.7181,-25.7094 15.0296,9.2912 c 0.3066,0.187 0.6532,-0.1603 0.4665,-0.4676 l -8.9177,-14.4812 c -0.2333,-0.3807 -0.5666,-0.7013 -0.9531,-0.9284 z"/>
|
|
||||||
</group>
|
|
||||||
|
|
||||||
<!-- Bottom spine accent -->
|
|
||||||
<path android:fillColor="#0e2030"
|
|
||||||
android:pathData="M18,228 H36 V244 H18 Z"/>
|
|
||||||
</group>
|
|
||||||
</vector>
|
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:aapt="http://schemas.android.com/aapt"
|
||||||
|
android:width="108dp"
|
||||||
|
android:height="108dp"
|
||||||
|
android:viewportWidth="512"
|
||||||
|
android:viewportHeight="512">
|
||||||
|
<group android:scaleX="0.84"
|
||||||
|
android:scaleY="0.84"
|
||||||
|
android:translateX="40.96"
|
||||||
|
android:translateY="40.96">
|
||||||
|
<path
|
||||||
|
android:pathData="M0,0h512v512h-512z">
|
||||||
|
<aapt:attr name="android:fillColor">
|
||||||
|
<gradient
|
||||||
|
android:centerX="230.4"
|
||||||
|
android:centerY="179.2"
|
||||||
|
android:gradientRadius="384"
|
||||||
|
android:type="radial">
|
||||||
|
<item android:offset="0" android:color="#FF2E6B8A"/>
|
||||||
|
<item android:offset="1" android:color="#FF0D2535"/>
|
||||||
|
</gradient>
|
||||||
|
</aapt:attr>
|
||||||
|
</path>
|
||||||
|
<path
|
||||||
|
android:pathData="M116.79,259.93a145.45,160 0,1 0,290.9 0a145.45,160 0,1 0,-290.9 0z"
|
||||||
|
android:strokeAlpha="0.25"
|
||||||
|
android:strokeWidth="0.727253"
|
||||||
|
android:fillColor="#2e6b8a"
|
||||||
|
android:fillAlpha="0.25"/>
|
||||||
|
<path
|
||||||
|
android:pathData="M156.06,140.66L372.78,140.66A7.27,7.27 0,0 1,380.05 147.93L380.05,364.65A7.27,7.27 0,0 1,372.78 371.92L156.06,371.92A7.27,7.27 0,0 1,148.79 364.65L148.79,147.93A7.27,7.27 0,0 1,156.06 140.66z">
|
||||||
|
<aapt:attr name="android:fillColor">
|
||||||
|
<gradient
|
||||||
|
android:startX="148.79"
|
||||||
|
android:startY="140.66"
|
||||||
|
android:endX="380.05"
|
||||||
|
android:endY="140.66"
|
||||||
|
android:type="linear">
|
||||||
|
<item android:offset="0" android:color="#FFF0EDE3"/>
|
||||||
|
<item android:offset="1" android:color="#FFE8E4D8"/>
|
||||||
|
</gradient>
|
||||||
|
</aapt:attr>
|
||||||
|
</path>
|
||||||
|
<path
|
||||||
|
android:pathData="M150.24,134.84L366.96,134.84A7.27,7.27 0,0 1,374.24 142.11L374.24,358.83A7.27,7.27 0,0 1,366.96 366.1L150.24,366.1A7.27,7.27 0,0 1,142.97 358.83L142.97,142.11A7.27,7.27 0,0 1,150.24 134.84z"
|
||||||
|
android:fillColor="#ece9df"/>
|
||||||
|
<path
|
||||||
|
android:pathData="M144.42,129.02L361.15,129.02A7.27,7.27 0,0 1,368.42 136.29L368.42,353.01A7.27,7.27 0,0 1,361.15 360.29L144.42,360.29A7.27,7.27 0,0 1,137.15 353.01L137.15,136.29A7.27,7.27 0,0 1,144.42 129.02z"
|
||||||
|
android:fillColor="#f0ede3"/>
|
||||||
|
<path
|
||||||
|
android:pathData="M129,128.77L155.69,128.77A7.85,7.85 0,0 1,163.53 136.61L163.53,382.98A7.85,7.85 0,0 1,155.69 390.83L129,390.83A7.85,7.85 0,0 1,121.15 382.98L121.15,136.61A7.85,7.85 0,0 1,129 128.77z"
|
||||||
|
android:strokeWidth="0.755863"
|
||||||
|
android:strokeColor="#00000000">
|
||||||
|
<aapt:attr name="android:fillColor">
|
||||||
|
<gradient
|
||||||
|
android:startX="121.15"
|
||||||
|
android:startY="128.77"
|
||||||
|
android:endX="163.53"
|
||||||
|
android:endY="128.77"
|
||||||
|
android:type="linear">
|
||||||
|
<item android:offset="0" android:color="#FF122C3C"/>
|
||||||
|
<item android:offset="1" android:color="#FF2E6B8A"/>
|
||||||
|
</gradient>
|
||||||
|
</aapt:attr>
|
||||||
|
</path>
|
||||||
|
<path
|
||||||
|
android:pathData="M158.97,129.02L380.05,129.02A7.27,7.27 0,0 1,387.33 136.29L387.33,383.56A7.27,7.27 0,0 1,380.05 390.83L158.97,390.83A7.27,7.27 0,0 1,151.7 383.56L151.7,136.29A7.27,7.27 0,0 1,158.97 129.02z"
|
||||||
|
android:strokeWidth="0.727253">
|
||||||
|
<aapt:attr name="android:fillColor">
|
||||||
|
<gradient
|
||||||
|
android:startX="151.7"
|
||||||
|
android:startY="129.02"
|
||||||
|
android:endX="387.33"
|
||||||
|
android:endY="390.83"
|
||||||
|
android:type="linear">
|
||||||
|
<item android:offset="0" android:color="#FF3A82A6"/>
|
||||||
|
<item android:offset="1" android:color="#FF1A3D52"/>
|
||||||
|
</gradient>
|
||||||
|
</aapt:attr>
|
||||||
|
</path>
|
||||||
|
<path
|
||||||
|
android:pathData="M158.97,129.02L380.05,129.02A7.27,7.27 0,0 1,387.33 136.29L387.33,383.56A7.27,7.27 0,0 1,380.05 390.83L158.97,390.83A7.27,7.27 0,0 1,151.7 383.56L151.7,136.29A7.27,7.27 0,0 1,158.97 129.02z"
|
||||||
|
android:strokeWidth="0.727253">
|
||||||
|
<aapt:attr name="android:fillColor">
|
||||||
|
<gradient
|
||||||
|
android:startX="151.7"
|
||||||
|
android:startY="129.02"
|
||||||
|
android:endX="222.39"
|
||||||
|
android:endY="390.83"
|
||||||
|
android:type="linear">
|
||||||
|
<item android:offset="0" android:color="#2DFFFFFF"/>
|
||||||
|
<item android:offset="1" android:color="#00FFFFFF"/>
|
||||||
|
</gradient>
|
||||||
|
</aapt:attr>
|
||||||
|
</path>
|
||||||
|
<path
|
||||||
|
android:pathData="M160.42,136.29L160.42,383.56"
|
||||||
|
android:strokeWidth="1.45451"
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:strokeColor="#30000000"/>
|
||||||
|
<path
|
||||||
|
android:pathData="M166.93,141.3L373.24,141.3A4.69,4.69 0,0 1,377.93 145.99L377.93,377.33A4.69,4.69 0,0 1,373.24 382.01L166.93,382.01A4.69,4.69 0,0 1,162.24 377.33L162.24,145.99A4.69,4.69 0,0 1,166.93 141.3z"
|
||||||
|
android:strokeAlpha="0.104098"
|
||||||
|
android:strokeWidth="3.10595"
|
||||||
|
android:fillColor="#00000000"
|
||||||
|
android:strokeColor="#000000"/>
|
||||||
|
<path
|
||||||
|
android:pathData="m249.01,223.24 l-37.71,-23.31c-0.77,-0.47 -1.64,0.4 -1.17,1.17l22.36,36.32c0.6,0.97 1.42,1.76 2.41,2.33l35.13,20.21L270.03,158.97c0,-0.99 -1.39,-1.19 -1.67,-0.25z"
|
||||||
|
android:fillColor="#6197b4"/>
|
||||||
|
<path
|
||||||
|
android:pathData="m233.41,281.02 l-23.26,37.77c-0.47,0.77 0.4,1.64 1.17,1.17l36.24,-22.41c0.97,-0.6 1.76,-1.42 2.32,-2.41l20.17,-35.21L169.28,259.94c-0.99,0 -1.19,1.39 -0.25,1.68z"
|
||||||
|
android:fillColor="#bdccd6"/>
|
||||||
|
<path
|
||||||
|
android:pathData="m306.67,238.88 l23.26,-37.79c0.47,-0.77 -0.4,-1.64 -1.17,-1.17l-36.24,22.42c-0.97,0.6 -1.76,1.42 -2.32,2.41l-20.17,35.19l100.77,0c0.99,0 1.19,-1.39 0.25,-1.68z"
|
||||||
|
android:fillColor="#94bfcf"/>
|
||||||
|
<path
|
||||||
|
android:pathData="m305.19,280.15 l-35.15,-20.21l0,100.99c0,0.99 1.39,1.19 1.67,0.25l19.36,-64.51 37.71,23.31c0.77,0.47 1.64,-0.4 1.17,-1.17l-22.37,-36.33c-0.59,-0.96 -1.42,-1.76 -2.39,-2.33z"
|
||||||
|
android:fillColor="#eee9d9"/>
|
||||||
|
</group>
|
||||||
|
</vector>
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
<background android:drawable="@drawable/ic_launcher_background"/>
|
<background android:drawable="@mipmap/ic_launcher_background"/>
|
||||||
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
|
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
|
||||||
</adaptive-icon>
|
</adaptive-icon>
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
<background android:drawable="@drawable/ic_launcher_background"/>
|
<background android:drawable="@mipmap/ic_launcher_background"/>
|
||||||
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
|
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
|
||||||
</adaptive-icon>
|
</adaptive-icon>
|
||||||
|
Before Width: | Height: | Size: 6.0 KiB |
|
After Width: | Height: | Size: 3.0 KiB |
|
After Width: | Height: | Size: 40 B |
|
Before Width: | Height: | Size: 6.0 KiB |
|
After Width: | Height: | Size: 4.7 KiB |
|
Before Width: | Height: | Size: 3.1 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 40 B |
|
Before Width: | Height: | Size: 3.1 KiB |
|
After Width: | Height: | Size: 2.8 KiB |
|
Before Width: | Height: | Size: 9.9 KiB |
|
After Width: | Height: | Size: 4.3 KiB |
|
After Width: | Height: | Size: 42 B |
|
Before Width: | Height: | Size: 9.9 KiB |
|
After Width: | Height: | Size: 6.7 KiB |
|
Before Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 7.5 KiB |
|
After Width: | Height: | Size: 48 B |
|
Before Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 48 B |
|
Before Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,3 @@
|
|||||||
|
<resources>
|
||||||
|
<string name="app_name">Читать</string>
|
||||||
|
</resources>
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
<resources>
|
<resources>
|
||||||
<string name="app_name">toread</string>
|
<string name="app_name">To Read</string>
|
||||||
</resources>
|
</resources>
|
||||||
@@ -1,14 +1,19 @@
|
|||||||
package net.sergeych.toread
|
package net.sergeych.toread
|
||||||
|
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.widthIn
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.ui.graphics.ImageBitmap
|
import androidx.compose.ui.graphics.ImageBitmap
|
||||||
|
import androidx.compose.material3.ButtonDefaults
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Surface
|
import androidx.compose.material3.Surface
|
||||||
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.CompositionLocalProvider
|
||||||
import androidx.compose.runtime.DisposableEffect
|
import androidx.compose.runtime.DisposableEffect
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
@@ -20,17 +25,55 @@ import androidx.compose.ui.Alignment
|
|||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.tooling.preview.Preview
|
import androidx.compose.ui.tooling.preview.Preview
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.Lifecycle
|
||||||
|
import androidx.lifecycle.LifecycleEventObserver
|
||||||
|
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
private const val DefaultToastDurationMillis = 1_600L
|
||||||
|
private const val DeleteUndoDurationMillis = 5_000L
|
||||||
|
private const val ScanResultToastDurationMillis = 5_000L
|
||||||
|
private const val BackgroundLibraryPageSize = 50
|
||||||
|
|
||||||
|
private data class AppToastData(
|
||||||
|
val id: Long,
|
||||||
|
val message: String,
|
||||||
|
val actionLabel: String? = null,
|
||||||
|
val onAction: (() -> Unit)? = null,
|
||||||
|
val durationMillis: Long = DefaultToastDurationMillis,
|
||||||
|
)
|
||||||
|
|
||||||
|
private data class PendingLibraryDelete(
|
||||||
|
val id: Long,
|
||||||
|
val request: LibraryDeleteRequest,
|
||||||
|
val restore: () -> Unit,
|
||||||
|
)
|
||||||
|
|
||||||
|
internal data class LibraryItemRefreshRequest(
|
||||||
|
val id: Long,
|
||||||
|
val fileId: String,
|
||||||
|
)
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
@Preview
|
@Preview
|
||||||
fun App() {
|
fun App() {
|
||||||
var themeMode by remember { mutableStateOf(ThemeMode.SYSTEM) }
|
var themeMode by remember { mutableStateOf(ThemeMode.SYSTEM) }
|
||||||
var systemDark by remember { mutableStateOf(isPlatformDarkTheme()) }
|
var systemDark by remember { mutableStateOf(isPlatformDarkTheme()) }
|
||||||
var toastMessage by remember { mutableStateOf<String?>(null) }
|
var localePreferenceLoaded by remember { mutableStateOf(false) }
|
||||||
|
var toast by remember { mutableStateOf<AppToastData?>(null) }
|
||||||
|
var nextToastId by remember { mutableStateOf(0L) }
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
|
fun showToast(
|
||||||
|
message: String,
|
||||||
|
actionLabel: String? = null,
|
||||||
|
onAction: (() -> Unit)? = null,
|
||||||
|
durationMillis: Long = DefaultToastDurationMillis,
|
||||||
|
) {
|
||||||
|
nextToastId += 1
|
||||||
|
toast = AppToastData(nextToastId, message, actionLabel, onAction, durationMillis)
|
||||||
|
}
|
||||||
val useDark = when (themeMode) {
|
val useDark = when (themeMode) {
|
||||||
ThemeMode.LIGHT -> false
|
ThemeMode.LIGHT -> false
|
||||||
ThemeMode.DARK -> true
|
ThemeMode.DARK -> true
|
||||||
@@ -46,63 +89,272 @@ fun App() {
|
|||||||
themeMode = loadThemeMode()
|
themeMode = loadThemeMode()
|
||||||
}
|
}
|
||||||
|
|
||||||
LaunchedEffect(toastMessage) {
|
LaunchedEffect(Unit) {
|
||||||
if (toastMessage != null) {
|
selectedAppLocaleTag = loadAppLocaleTag()?.takeIf { saved ->
|
||||||
delay(1600)
|
availableAppLanguages.any { it.localeTag == saved }
|
||||||
toastMessage = null
|
}
|
||||||
|
localePreferenceLoaded = true
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(toast?.id) {
|
||||||
|
val current = toast ?: return@LaunchedEffect
|
||||||
|
delay(current.durationMillis)
|
||||||
|
if (toast?.id == current.id) {
|
||||||
|
toast = null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
MaterialTheme(colorScheme = if (useDark) darkReaderColorScheme() else lightReaderColorScheme()) {
|
MaterialTheme(colorScheme = if (useDark) darkReaderColorScheme() else lightReaderColorScheme()) {
|
||||||
Box(Modifier.fillMaxSize()) {
|
CompositionLocalProvider(LocalReaderThemeIsDark provides useDark) {
|
||||||
Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
|
Box(Modifier.fillMaxSize()) {
|
||||||
BookReaderApp(
|
Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
|
||||||
onThemeToggle = {
|
if (localePreferenceLoaded) {
|
||||||
val next = themeMode.next()
|
BookReaderApp(
|
||||||
themeMode = next
|
onThemeToggle = {
|
||||||
toastMessage = "Theme: ${next.displayName}"
|
val next = themeMode.next()
|
||||||
scope.launch {
|
themeMode = next
|
||||||
saveThemeMode(next)
|
showToast(strings.themeChanged(next))
|
||||||
}
|
scope.launch {
|
||||||
},
|
saveThemeMode(next)
|
||||||
)
|
}
|
||||||
|
},
|
||||||
|
onShowToast = ::showToast,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
LoadingScreen(strings.loadingOpeningBook)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AppToast(toast, modifier = Modifier.align(Alignment.BottomCenter))
|
||||||
}
|
}
|
||||||
AppToast(toastMessage, modifier = Modifier.align(Alignment.BottomCenter))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun AppToast(message: String?, modifier: Modifier = Modifier) {
|
private fun AppToast(toast: AppToastData?, modifier: Modifier = Modifier) {
|
||||||
if (message != null) {
|
if (toast != null) {
|
||||||
Surface(
|
Surface(
|
||||||
modifier = modifier.padding(bottom = 24.dp),
|
modifier = modifier.padding(horizontal = 16.dp, vertical = 24.dp),
|
||||||
shape = RoundedCornerShape(8.dp),
|
shape = RoundedCornerShape(8.dp),
|
||||||
color = MaterialTheme.colorScheme.inverseSurface,
|
color = MaterialTheme.colorScheme.inverseSurface,
|
||||||
tonalElevation = 6.dp,
|
tonalElevation = 6.dp,
|
||||||
) {
|
) {
|
||||||
Text(
|
Row(
|
||||||
message,
|
modifier = Modifier
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
.widthIn(max = 520.dp)
|
||||||
color = MaterialTheme.colorScheme.inverseOnSurface,
|
.padding(start = 16.dp, end = if (toast.actionLabel == null) 16.dp else 8.dp, top = 8.dp, bottom = 8.dp),
|
||||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
)
|
) {
|
||||||
|
Text(
|
||||||
|
toast.message,
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.inverseOnSurface,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
|
if (toast.actionLabel != null && toast.onAction != null) {
|
||||||
|
TextButton(
|
||||||
|
onClick = toast.onAction,
|
||||||
|
colors = ButtonDefaults.textButtonColors(
|
||||||
|
contentColor = MaterialTheme.colorScheme.inversePrimary,
|
||||||
|
),
|
||||||
|
) {
|
||||||
|
Text(toast.actionLabel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun BookReaderApp(onThemeToggle: () -> Unit) {
|
private fun BookReaderApp(
|
||||||
var state by remember { mutableStateOf<AppState>(AppState.LoadingLibrary) }
|
onThemeToggle: () -> Unit,
|
||||||
|
onShowToast: (
|
||||||
|
message: String,
|
||||||
|
actionLabel: String?,
|
||||||
|
onAction: (() -> Unit)?,
|
||||||
|
durationMillis: Long,
|
||||||
|
) -> Unit,
|
||||||
|
) {
|
||||||
|
var state by remember { mutableStateOf<AppState>(AppState.LoadingStartup) }
|
||||||
|
var libraryBackState by remember { mutableStateOf<AppState.Library?>(null) }
|
||||||
var activeScan by remember { mutableStateOf<LibraryScanProgress?>(null) }
|
var activeScan by remember { mutableStateOf<LibraryScanProgress?>(null) }
|
||||||
var scanJob by remember { mutableStateOf<Job?>(null) }
|
var scanJob by remember { mutableStateOf<Job?>(null) }
|
||||||
|
var pendingDelete by remember { mutableStateOf<PendingLibraryDelete?>(null) }
|
||||||
|
var pendingDeleteJob by remember { mutableStateOf<Job?>(null) }
|
||||||
|
var hiddenDeletedFileIds by remember { mutableStateOf<Set<String>>(emptySet()) }
|
||||||
|
var nextDeleteId by remember { mutableStateOf(0L) }
|
||||||
|
var nextLibraryItemRefreshId by remember { mutableStateOf(0L) }
|
||||||
|
var libraryItemRefreshRequest by remember { mutableStateOf<LibraryItemRefreshRequest?>(null) }
|
||||||
var imageViewer by remember { mutableStateOf<ViewedBookImage?>(null) }
|
var imageViewer by remember { mutableStateOf<ViewedBookImage?>(null) }
|
||||||
|
var resumeGeneration by remember { mutableStateOf(0L) }
|
||||||
|
var downloadsRescanRequestGeneration by remember { mutableStateOf(0L) }
|
||||||
|
val lifecycleOwner = LocalLifecycleOwner.current
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
|
|
||||||
|
fun refreshLibraryItem(fileId: String) {
|
||||||
|
nextLibraryItemRefreshId += 1
|
||||||
|
libraryItemRefreshRequest = LibraryItemRefreshRequest(nextLibraryItemRefreshId, fileId)
|
||||||
|
}
|
||||||
|
|
||||||
LaunchedEffect(Unit) {
|
LaunchedEffect(Unit) {
|
||||||
state = loadStartupState()
|
state = loadStartupState()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
DisposableEffect(lifecycleOwner) {
|
||||||
|
val observer = LifecycleEventObserver { _, event ->
|
||||||
|
if (event == Lifecycle.Event.ON_RESUME) {
|
||||||
|
resumeGeneration += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lifecycleOwner.lifecycle.addObserver(observer)
|
||||||
|
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(Unit) {
|
||||||
|
while (true) {
|
||||||
|
delay(500)
|
||||||
|
val requestResult = runCatching { loadPlatformOpenBookRequest() }
|
||||||
|
if (requestResult.isFailure) {
|
||||||
|
val scanPath = when (val current = state) {
|
||||||
|
is AppState.Library -> current.scanPath
|
||||||
|
is AppState.Scan -> current.scanPath
|
||||||
|
is AppState.Reader -> current.scanPath
|
||||||
|
is AppState.BookInfo -> current.scanPath
|
||||||
|
is AppState.Error, AppState.LoadingStartup -> defaultLibraryScanPath().orEmpty()
|
||||||
|
}
|
||||||
|
state = AppState.Library(
|
||||||
|
emptyList(),
|
||||||
|
scanPath,
|
||||||
|
requestResult.exceptionOrNull()?.message ?: strings.couldNotOpenLibrary,
|
||||||
|
loadLibraryFilter(),
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
val request = requestResult.getOrNull() ?: continue
|
||||||
|
val scanPath = when (val current = state) {
|
||||||
|
is AppState.Library -> current.scanPath
|
||||||
|
is AppState.Scan -> current.scanPath
|
||||||
|
is AppState.Reader -> current.scanPath
|
||||||
|
is AppState.BookInfo -> current.scanPath
|
||||||
|
is AppState.Error, AppState.LoadingStartup -> defaultLibraryScanPath().orEmpty()
|
||||||
|
}
|
||||||
|
val nextState = runCatching {
|
||||||
|
val book = parseBookInBackground(request.bytes, request.displayName)
|
||||||
|
saveActiveReadingFileId(request.id)
|
||||||
|
AppState.Reader(
|
||||||
|
fileId = request.id,
|
||||||
|
book = book,
|
||||||
|
libraryItems = emptyList(),
|
||||||
|
scanPath = scanPath,
|
||||||
|
selectedFilter = when (val current = state) {
|
||||||
|
is AppState.Library -> current.selectedFilter
|
||||||
|
is AppState.Scan -> current.selectedFilter
|
||||||
|
is AppState.Reader -> current.selectedFilter
|
||||||
|
is AppState.BookInfo -> current.selectedFilter
|
||||||
|
is AppState.Error, AppState.LoadingStartup -> loadLibraryFilter()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}.getOrElse {
|
||||||
|
AppState.Library(emptyList(), scanPath, it.message ?: strings.couldNotOpen(request.displayName), loadLibraryFilter())
|
||||||
|
}
|
||||||
|
libraryBackState = when (val current = state) {
|
||||||
|
is AppState.Library -> current
|
||||||
|
is AppState.Scan -> AppState.Library(current.items, current.scanPath, current.message, current.selectedFilter)
|
||||||
|
is AppState.Reader, is AppState.BookInfo -> libraryBackState
|
||||||
|
is AppState.Error, AppState.LoadingStartup -> null
|
||||||
|
}
|
||||||
|
state = nextState
|
||||||
|
refreshLibraryItem(request.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val activeBookState = when (val current = state) {
|
||||||
|
is AppState.Reader -> current.fileId to current.libraryItems.isEmpty()
|
||||||
|
is AppState.BookInfo -> current.fileId to current.libraryItems.isEmpty()
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
LaunchedEffect(activeBookState?.first, activeBookState?.second) {
|
||||||
|
val (fileId, needsLibraryItems) = activeBookState ?: return@LaunchedEffect
|
||||||
|
if (!needsLibraryItems) return@LaunchedEffect
|
||||||
|
runCatching { loadLibraryItemsPage(BackgroundLibraryPageSize, 0) }
|
||||||
|
.onSuccess { items ->
|
||||||
|
state = when (val current = state) {
|
||||||
|
is AppState.Reader ->
|
||||||
|
if (current.fileId == fileId && current.libraryItems.isEmpty()) {
|
||||||
|
current.copy(libraryItems = items)
|
||||||
|
} else {
|
||||||
|
current
|
||||||
|
}
|
||||||
|
is AppState.BookInfo ->
|
||||||
|
if (current.fileId == fileId && current.libraryItems.isEmpty()) {
|
||||||
|
current.copy(libraryItems = items)
|
||||||
|
} else {
|
||||||
|
current
|
||||||
|
}
|
||||||
|
else -> current
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun commitPendingDelete(delete: PendingLibraryDelete) {
|
||||||
|
scope.launch {
|
||||||
|
val result = deleteLibraryBook(delete.request.fileId, delete.request.title)
|
||||||
|
if (!result.deleted) {
|
||||||
|
delete.restore()
|
||||||
|
onShowToast(result.message, null, null, DefaultToastDurationMillis)
|
||||||
|
} else {
|
||||||
|
hiddenDeletedFileIds = hiddenDeletedFileIds + delete.request.fileId
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun requestDelete(
|
||||||
|
request: LibraryDeleteRequest,
|
||||||
|
remove: () -> Unit,
|
||||||
|
restore: () -> Unit,
|
||||||
|
) {
|
||||||
|
pendingDeleteJob?.cancel()
|
||||||
|
pendingDelete?.let(::commitPendingDelete)
|
||||||
|
|
||||||
|
nextDeleteId += 1
|
||||||
|
val deleteId = nextDeleteId
|
||||||
|
val nextDelete = PendingLibraryDelete(deleteId, request, restore)
|
||||||
|
pendingDelete = nextDelete
|
||||||
|
hiddenDeletedFileIds = hiddenDeletedFileIds - request.fileId
|
||||||
|
remove()
|
||||||
|
|
||||||
|
pendingDeleteJob = scope.launch {
|
||||||
|
delay(DeleteUndoDurationMillis)
|
||||||
|
val result = deleteLibraryBook(request.fileId, request.title)
|
||||||
|
if (pendingDelete?.id == deleteId) {
|
||||||
|
pendingDelete = null
|
||||||
|
pendingDeleteJob = null
|
||||||
|
if (!result.deleted) {
|
||||||
|
restore()
|
||||||
|
onShowToast(result.message, null, null, DefaultToastDurationMillis)
|
||||||
|
} else {
|
||||||
|
hiddenDeletedFileIds = hiddenDeletedFileIds + request.fileId
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onShowToast(
|
||||||
|
strings.removed(request.title),
|
||||||
|
strings.undo,
|
||||||
|
{
|
||||||
|
if (pendingDelete?.id == deleteId) {
|
||||||
|
pendingDeleteJob?.cancel()
|
||||||
|
pendingDeleteJob = null
|
||||||
|
pendingDelete = null
|
||||||
|
restore()
|
||||||
|
onShowToast(strings.restored(request.title), null, null, DefaultToastDurationMillis)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
DeleteUndoDurationMillis,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fun navigateBack() {
|
fun navigateBack() {
|
||||||
imageViewer?.let {
|
imageViewer?.let {
|
||||||
imageViewer = null
|
imageViewer = null
|
||||||
@@ -115,21 +367,32 @@ private fun BookReaderApp(onThemeToggle: () -> Unit) {
|
|||||||
libraryItems = current.libraryItems,
|
libraryItems = current.libraryItems,
|
||||||
scanPath = current.scanPath,
|
scanPath = current.scanPath,
|
||||||
message = current.message,
|
message = current.message,
|
||||||
|
selectedFilter = current.selectedFilter,
|
||||||
)
|
)
|
||||||
is AppState.Reader -> {
|
is AppState.Reader -> {
|
||||||
scope.launch { saveActiveReadingFileId(null) }
|
scope.launch { saveActiveReadingFileId(null) }
|
||||||
AppState.Library(emptyList(), current.scanPath, current.message)
|
refreshLibraryItem(current.fileId)
|
||||||
|
val backState = libraryBackState?.copy(message = current.message)
|
||||||
|
?: AppState.Library(
|
||||||
|
current.libraryItems,
|
||||||
|
current.scanPath,
|
||||||
|
current.message,
|
||||||
|
current.selectedFilter,
|
||||||
|
)
|
||||||
|
libraryBackState = null
|
||||||
|
downloadsRescanRequestGeneration += 1
|
||||||
|
backState
|
||||||
}
|
}
|
||||||
is AppState.Scan -> AppState.Library(current.items, current.scanPath, current.message)
|
is AppState.Scan -> AppState.Library(current.items, current.scanPath, current.message, current.selectedFilter)
|
||||||
is AppState.Error -> AppState.LoadingLibrary
|
is AppState.Error -> AppState.LoadingStartup
|
||||||
is AppState.Library, AppState.LoadingLibrary -> current
|
is AppState.Library, AppState.LoadingStartup -> current
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val navigationDepth = when (state) {
|
val navigationDepth = when (state) {
|
||||||
is AppState.BookInfo -> 2
|
is AppState.BookInfo -> 2
|
||||||
is AppState.Error, is AppState.Reader, is AppState.Scan -> 1
|
is AppState.Error, is AppState.Reader, is AppState.Scan -> 1
|
||||||
is AppState.Library, AppState.LoadingLibrary -> 0
|
is AppState.Library, AppState.LoadingStartup -> 0
|
||||||
} + if (imageViewer != null) 1 else 0
|
} + if (imageViewer != null) 1 else 0
|
||||||
|
|
||||||
PlatformBackHandler(
|
PlatformBackHandler(
|
||||||
@@ -138,7 +401,23 @@ private fun BookReaderApp(onThemeToggle: () -> Unit) {
|
|||||||
onBack = ::navigateBack,
|
onBack = ::navigateBack,
|
||||||
)
|
)
|
||||||
|
|
||||||
fun startScan(path: String) {
|
fun setLibraryFilter(filter: LibraryFilter) {
|
||||||
|
state = when (val current = state) {
|
||||||
|
is AppState.Library -> current.copy(selectedFilter = filter)
|
||||||
|
is AppState.Scan -> current.copy(selectedFilter = filter)
|
||||||
|
else -> current
|
||||||
|
}
|
||||||
|
libraryBackState = libraryBackState?.copy(selectedFilter = filter)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun saveAndSetLibraryFilter(filter: LibraryFilter) {
|
||||||
|
setLibraryFilter(filter)
|
||||||
|
scope.launch {
|
||||||
|
saveLibraryFilter(filter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun startScan(path: String, userInitiated: Boolean) {
|
||||||
if (scanJob?.isActive == true) return
|
if (scanJob?.isActive == true) return
|
||||||
activeScan = LibraryScanProgress(0, 0, 0, 0)
|
activeScan = LibraryScanProgress(0, 0, 0, 0)
|
||||||
scanJob = scope.launch {
|
scanJob = scope.launch {
|
||||||
@@ -154,24 +433,39 @@ private fun BookReaderApp(onThemeToggle: () -> Unit) {
|
|||||||
if (isDownloadsScanPath(path)) {
|
if (isDownloadsScanPath(path)) {
|
||||||
saveDownloadsWasScanned(true)
|
saveDownloadsWasScanned(true)
|
||||||
}
|
}
|
||||||
"Scanned ${it.scannedFiles}, imported ${it.importedFiles}, skipped ${it.skippedFiles}, failed ${it.failedFiles}."
|
strings.scanReport(it.scannedFiles, it.importedFiles, it.skippedFiles, it.failedFiles)
|
||||||
},
|
},
|
||||||
onFailure = { it.message ?: "Scan failed." },
|
onFailure = { it.message ?: strings.scanFailed },
|
||||||
)
|
)
|
||||||
|
val importedFiles = report.getOrNull()?.importedFiles
|
||||||
|
when {
|
||||||
|
importedFiles == null -> Unit
|
||||||
|
importedFiles > 0 -> {
|
||||||
|
onShowToast(
|
||||||
|
strings.newBooksAdded(importedFiles),
|
||||||
|
strings.show,
|
||||||
|
{ saveAndSetLibraryFilter(LibraryFilter.RecentlyAdded) },
|
||||||
|
ScanResultToastDurationMillis,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
userInitiated -> {
|
||||||
|
onShowToast(strings.noNewBooksFound, null, null, DefaultToastDurationMillis)
|
||||||
|
}
|
||||||
|
}
|
||||||
scanJob = null
|
scanJob = null
|
||||||
activeScan = null
|
activeScan = null
|
||||||
state = when (val current = state) {
|
state = when (val current = state) {
|
||||||
is AppState.Library -> if (report.getOrNull()?.hasLibraryChanges() == true) {
|
is AppState.Library -> current.copy(
|
||||||
loadLibraryState(message, path)
|
scanPath = path,
|
||||||
} else {
|
message = message,
|
||||||
current.copy(scanPath = path, message = message)
|
)
|
||||||
}
|
is AppState.Scan -> AppState.Library(
|
||||||
is AppState.Scan -> if (report.getOrNull()?.hasLibraryChanges() == true) {
|
current.items,
|
||||||
loadLibraryState(message, path)
|
path,
|
||||||
} else {
|
message,
|
||||||
AppState.Library(current.items, path, message)
|
selectedFilter = current.selectedFilter,
|
||||||
}
|
)
|
||||||
AppState.LoadingLibrary -> loadLibraryState(message, path)
|
AppState.LoadingStartup -> loadLibraryState(message, path)
|
||||||
is AppState.Reader -> current.copy(message = message)
|
is AppState.Reader -> current.copy(message = message)
|
||||||
is AppState.BookInfo -> current.copy(message = message)
|
is AppState.BookInfo -> current.copy(message = message)
|
||||||
is AppState.Error -> current
|
is AppState.Error -> current
|
||||||
@@ -179,50 +473,91 @@ private fun BookReaderApp(onThemeToggle: () -> Unit) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
when (val current = state) {
|
LaunchedEffect(resumeGeneration, downloadsRescanRequestGeneration, state !is AppState.LoadingStartup) {
|
||||||
AppState.LoadingLibrary -> LoadingScreen("Opening library")
|
if (state is AppState.LoadingStartup || activeScan != null || scanJob?.isActive == true) return@LaunchedEffect
|
||||||
is AppState.Library -> LibraryScreen(
|
if (!loadScanDownloadsAutomatically() || !loadDownloadsWasScanned()) return@LaunchedEffect
|
||||||
state = current,
|
val path = downloadsScanPath() ?: return@LaunchedEffect
|
||||||
activeScan = activeScan,
|
state = state.withMessage(strings.scanningDownloads)
|
||||||
onStateChange = { state = it },
|
startScan(path, userInitiated = false)
|
||||||
onNavigateToScan = { state = AppState.Scan(current.items, current.scanPath, current.message) },
|
}
|
||||||
onStartScan = ::startScan,
|
|
||||||
)
|
Box(Modifier.fillMaxSize()) {
|
||||||
is AppState.Scan -> ScanScreen(
|
val currentLibraryState = when (val current = state) {
|
||||||
state = current,
|
is AppState.Library -> current
|
||||||
activeScan = activeScan,
|
is AppState.Reader, is AppState.BookInfo -> libraryBackState
|
||||||
onStateChange = { state = it },
|
else -> null
|
||||||
onStartScan = { path ->
|
}
|
||||||
startScan(path)
|
currentLibraryState?.let { libraryState ->
|
||||||
state = AppState.Library(current.items, path, "Scanning...")
|
LibraryScreen(
|
||||||
},
|
state = libraryState,
|
||||||
)
|
activeScan = activeScan,
|
||||||
is AppState.Reader -> BookView(
|
itemRefreshRequest = libraryItemRefreshRequest,
|
||||||
fileId = current.fileId,
|
hiddenFileIds = hiddenDeletedFileIds + pendingDelete?.request?.fileId?.let(::setOf).orEmpty(),
|
||||||
book = current.book,
|
onStateChange = { next ->
|
||||||
onImageOpen = { imageViewer = it },
|
val currentState = state
|
||||||
onThemeToggle = onThemeToggle,
|
if (next is AppState.Reader && currentState is AppState.Library) {
|
||||||
onBookInfo = {
|
libraryBackState = currentState
|
||||||
state = AppState.BookInfo(
|
}
|
||||||
fileId = current.fileId,
|
state = next
|
||||||
book = current.book,
|
},
|
||||||
libraryItems = current.libraryItems,
|
onLibraryFilterChange = ::setLibraryFilter,
|
||||||
scanPath = current.scanPath,
|
onNavigateToScan = {
|
||||||
message = current.message,
|
libraryBackState = null
|
||||||
)
|
state = AppState.Scan(
|
||||||
},
|
libraryState.items,
|
||||||
onDeleted = { message ->
|
libraryState.scanPath,
|
||||||
state = AppState.Library(emptyList(), current.scanPath, message)
|
libraryState.message,
|
||||||
},
|
libraryState.selectedFilter,
|
||||||
onBack = ::navigateBack,
|
)
|
||||||
)
|
},
|
||||||
is AppState.BookInfo -> BookInfoScreen(
|
onDeleteRequested = ::requestDelete,
|
||||||
fileId = current.fileId,
|
)
|
||||||
book = current.book,
|
}
|
||||||
onImageOpen = { imageViewer = it },
|
|
||||||
onBack = ::navigateBack,
|
when (val current = state) {
|
||||||
)
|
AppState.LoadingStartup -> LoadingScreen(strings.loadingOpeningBook)
|
||||||
is AppState.Error -> ErrorScreen(current.message, onBack = ::navigateBack)
|
is AppState.Library -> Unit
|
||||||
|
is AppState.Scan -> ScanScreen(
|
||||||
|
state = current,
|
||||||
|
activeScan = activeScan,
|
||||||
|
onStateChange = { state = it },
|
||||||
|
onStartScan = { path ->
|
||||||
|
startScan(path, userInitiated = true)
|
||||||
|
state = AppState.Library(current.items, path, strings.scanning, current.selectedFilter)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
is AppState.Reader -> BookView(
|
||||||
|
fileId = current.fileId,
|
||||||
|
book = current.book,
|
||||||
|
onImageOpen = { imageViewer = it },
|
||||||
|
onThemeToggle = onThemeToggle,
|
||||||
|
onBookChanged = ::refreshLibraryItem,
|
||||||
|
onBookInfo = {
|
||||||
|
state = AppState.BookInfo(
|
||||||
|
fileId = current.fileId,
|
||||||
|
book = current.book,
|
||||||
|
libraryItems = current.libraryItems,
|
||||||
|
scanPath = current.scanPath,
|
||||||
|
message = current.message,
|
||||||
|
selectedFilter = current.selectedFilter,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
onDeleted = { message ->
|
||||||
|
state = libraryBackState?.copy(message = message)
|
||||||
|
?: AppState.Library(emptyList(), current.scanPath, message, current.selectedFilter)
|
||||||
|
libraryBackState = null
|
||||||
|
},
|
||||||
|
onDeleteRequested = ::requestDelete,
|
||||||
|
onBack = ::navigateBack,
|
||||||
|
)
|
||||||
|
is AppState.BookInfo -> BookInfoScreen(
|
||||||
|
fileId = current.fileId,
|
||||||
|
book = current.book,
|
||||||
|
onImageOpen = { imageViewer = it },
|
||||||
|
onBack = ::navigateBack,
|
||||||
|
)
|
||||||
|
is AppState.Error -> ErrorScreen(current.message, onBack = ::navigateBack)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
imageViewer?.let { image ->
|
imageViewer?.let { image ->
|
||||||
@@ -240,5 +575,11 @@ internal data class ViewedBookImage(
|
|||||||
val title: String,
|
val title: String,
|
||||||
)
|
)
|
||||||
|
|
||||||
private fun LibraryScanReport.hasLibraryChanges(): Boolean =
|
private fun AppState.withMessage(message: String): AppState =
|
||||||
importedFiles > 0
|
when (this) {
|
||||||
|
is AppState.Library -> copy(message = message)
|
||||||
|
is AppState.Scan -> copy(message = message)
|
||||||
|
is AppState.Reader -> copy(message = message)
|
||||||
|
is AppState.BookInfo -> copy(message = message)
|
||||||
|
is AppState.Error, AppState.LoadingStartup -> this
|
||||||
|
}
|
||||||
@@ -2,19 +2,23 @@ package net.sergeych.toread
|
|||||||
|
|
||||||
import net.sergeych.toread.fb2.Fb2Book
|
import net.sergeych.toread.fb2.Fb2Book
|
||||||
import net.sergeych.toread.fb2.Fb2Format
|
import net.sergeych.toread.fb2.Fb2Format
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
internal sealed interface AppState {
|
internal sealed interface AppState {
|
||||||
data object LoadingLibrary : AppState
|
data object LoadingStartup : AppState
|
||||||
data class Library(
|
data class Library(
|
||||||
val items: List<LibraryItem>,
|
val items: List<LibraryItem>,
|
||||||
val scanPath: String,
|
val scanPath: String,
|
||||||
val message: String? = null,
|
val message: String? = null,
|
||||||
|
val selectedFilter: LibraryFilter = LibraryFilter.MyLibrary,
|
||||||
) : AppState
|
) : AppState
|
||||||
|
|
||||||
data class Scan(
|
data class Scan(
|
||||||
val items: List<LibraryItem>,
|
val items: List<LibraryItem>,
|
||||||
val scanPath: String,
|
val scanPath: String,
|
||||||
val message: String? = null,
|
val message: String? = null,
|
||||||
|
val selectedFilter: LibraryFilter = LibraryFilter.MyLibrary,
|
||||||
) : AppState
|
) : AppState
|
||||||
|
|
||||||
data class Reader(
|
data class Reader(
|
||||||
@@ -23,6 +27,7 @@ internal sealed interface AppState {
|
|||||||
val libraryItems: List<LibraryItem>,
|
val libraryItems: List<LibraryItem>,
|
||||||
val scanPath: String,
|
val scanPath: String,
|
||||||
val message: String? = null,
|
val message: String? = null,
|
||||||
|
val selectedFilter: LibraryFilter = LibraryFilter.MyLibrary,
|
||||||
) : AppState
|
) : AppState
|
||||||
|
|
||||||
data class BookInfo(
|
data class BookInfo(
|
||||||
@@ -31,55 +36,75 @@ internal sealed interface AppState {
|
|||||||
val libraryItems: List<LibraryItem>,
|
val libraryItems: List<LibraryItem>,
|
||||||
val scanPath: String,
|
val scanPath: String,
|
||||||
val message: String? = null,
|
val message: String? = null,
|
||||||
|
val selectedFilter: LibraryFilter = LibraryFilter.MyLibrary,
|
||||||
) : AppState
|
) : AppState
|
||||||
|
|
||||||
data class Error(val message: String) : AppState
|
data class Error(val message: String) : AppState
|
||||||
}
|
}
|
||||||
|
|
||||||
internal suspend fun loadStartupState(): AppState {
|
internal suspend fun loadStartupState(): AppState {
|
||||||
val library = loadLibraryState()
|
val scanPath = try {
|
||||||
if (library !is AppState.Library) return library
|
defaultLibraryScanPath().orEmpty()
|
||||||
loadPlatformOpenBookRequest()?.let { request ->
|
} catch (t: Throwable) {
|
||||||
|
return AppState.Error(t.message ?: strings.couldNotOpenLibrary)
|
||||||
|
}
|
||||||
|
val libraryFilter = loadLibraryFilter()
|
||||||
|
val platformRequest = runCatching { loadPlatformOpenBookRequest() }.getOrElse {
|
||||||
|
return AppState.Library(emptyList(), scanPath, it.message ?: strings.couldNotOpenLibrary, libraryFilter)
|
||||||
|
}
|
||||||
|
platformRequest?.let { request ->
|
||||||
return runCatching {
|
return runCatching {
|
||||||
|
val book = parseBookInBackground(request.bytes, request.displayName)
|
||||||
|
saveActiveReadingFileId(request.id)
|
||||||
AppState.Reader(
|
AppState.Reader(
|
||||||
fileId = request.id,
|
fileId = request.id,
|
||||||
book = Fb2Format.parse(request.bytes, request.displayName),
|
book = book,
|
||||||
libraryItems = library.items,
|
libraryItems = emptyList(),
|
||||||
scanPath = library.scanPath,
|
scanPath = scanPath,
|
||||||
message = library.message,
|
selectedFilter = libraryFilter,
|
||||||
)
|
)
|
||||||
}.getOrElse {
|
}.getOrElse {
|
||||||
AppState.Library(library.items, library.scanPath, it.message ?: "Could not open ${request.displayName}.")
|
AppState.Library(emptyList(), scanPath, it.message ?: strings.couldNotOpen(request.displayName), libraryFilter)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val activeFileId = loadActiveReadingFileId() ?: return library
|
val activeFileId = loadActiveReadingFileId() ?: return AppState.Library(emptyList(), scanPath, selectedFilter = libraryFilter)
|
||||||
val item = loadLibraryItem(activeFileId)
|
val item = loadLibraryItem(activeFileId)
|
||||||
if (item == null) {
|
if (item == null) {
|
||||||
saveActiveReadingFileId(null)
|
saveActiveReadingFileId(null)
|
||||||
return library
|
return AppState.Library(emptyList(), scanPath, selectedFilter = libraryFilter)
|
||||||
}
|
}
|
||||||
return runCatching {
|
return runCatching {
|
||||||
val bytes = openLibraryBook(activeFileId) ?: error("Book file is not available.")
|
val bytes = openLibraryBook(activeFileId) ?: error(strings.bookFileNotAvailable)
|
||||||
AppState.Reader(
|
AppState.Reader(
|
||||||
fileId = activeFileId,
|
fileId = activeFileId,
|
||||||
book = Fb2Format.parse(bytes, item.storageUri ?: item.title),
|
book = parseBookInBackground(bytes, item.storageUri ?: item.title),
|
||||||
libraryItems = library.items,
|
libraryItems = emptyList(),
|
||||||
scanPath = library.scanPath,
|
scanPath = scanPath,
|
||||||
message = library.message,
|
selectedFilter = libraryFilter,
|
||||||
)
|
)
|
||||||
}.getOrElse {
|
}.getOrElse {
|
||||||
saveActiveReadingFileId(null)
|
saveActiveReadingFileId(null)
|
||||||
AppState.Library(library.items, library.scanPath, it.message ?: "Could not reopen last book.")
|
AppState.Library(emptyList(), scanPath, it.message ?: strings.couldNotReopenLastBook(), libraryFilter)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal suspend fun loadLibraryState(message: String? = null, scanPath: String? = null): AppState =
|
internal suspend fun loadLibraryState(
|
||||||
|
message: String? = null,
|
||||||
|
scanPath: String? = null,
|
||||||
|
selectedFilter: LibraryFilter? = null,
|
||||||
|
): AppState =
|
||||||
runCatching {
|
runCatching {
|
||||||
AppState.Library(
|
AppState.Library(
|
||||||
items = emptyList(),
|
items = emptyList(),
|
||||||
scanPath = scanPath ?: defaultLibraryScanPath().orEmpty(),
|
scanPath = scanPath ?: defaultLibraryScanPath().orEmpty(),
|
||||||
message = message,
|
message = message,
|
||||||
|
selectedFilter = selectedFilter ?: loadLibraryFilter(),
|
||||||
)
|
)
|
||||||
}.getOrElse {
|
}.getOrElse {
|
||||||
AppState.Error(it.message ?: "Could not open library.")
|
AppState.Error(it.message ?: strings.couldNotOpenLibrary)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal suspend fun parseBookInBackground(input: ByteArray, fileName: String? = null): Fb2Book =
|
||||||
|
withContext(Dispatchers.Default) {
|
||||||
|
Fb2Format.parse(input, fileName)
|
||||||
}
|
}
|
||||||
@@ -51,10 +51,10 @@ internal fun BookInfoScreen(
|
|||||||
Scaffold(
|
Scaffold(
|
||||||
topBar = {
|
topBar = {
|
||||||
CenterAlignedTopAppBar(
|
CenterAlignedTopAppBar(
|
||||||
title = { Text("Book info") },
|
title = { Text(strings.bookInfo) },
|
||||||
navigationIcon = {
|
navigationIcon = {
|
||||||
IconButton(onClick = onBack) {
|
IconButton(onClick = onBack) {
|
||||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back to reader")
|
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = strings.backToReader)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
colors = themedTopAppBarColors(),
|
colors = themedTopAppBarColors(),
|
||||||
@@ -70,46 +70,56 @@ internal fun BookInfoScreen(
|
|||||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
) {
|
) {
|
||||||
item {
|
item {
|
||||||
InfoSection("Title Info") {
|
InfoSection(strings.titleInfo) {
|
||||||
CoverAndTitle(book, onImageOpen = onImageOpen)
|
CoverAndTitle(book, onImageOpen = onImageOpen)
|
||||||
DetailLine("Title", book.title)
|
DetailLine(strings.title, book.title)
|
||||||
DetailLine("Authors", book.authors.joinToString { it.displayName }.ifBlank { "Unknown author" })
|
DetailLine(strings.authors, book.authors.joinToString { it.displayName }.ifBlank { strings.unknownAuthor })
|
||||||
DetailLine("Language", book.language?.uppercase() ?: "Not specified")
|
DetailLine(strings.language, book.language?.uppercase() ?: strings.notSpecified)
|
||||||
DetailLine("Date", book.date ?: "Not specified")
|
DetailLine(strings.date, book.date ?: strings.notSpecified)
|
||||||
DetailLine("Genres", book.genres.joinToString().ifBlank { "Not specified" })
|
DetailLine(strings.genres, book.genres.joinToString().ifBlank { strings.notSpecified })
|
||||||
DetailLine("Source", book.sourceLanguage?.uppercase() ?: "Not specified")
|
DetailLine(strings.source, book.sourceLanguage?.uppercase() ?: strings.notSpecified)
|
||||||
if (book.annotation.isNullOrBlank().not()) {
|
if (book.annotation.isNullOrBlank().not()) {
|
||||||
Text(book.annotation.orEmpty(), style = MaterialTheme.typography.bodyMedium, lineHeight = 20.sp)
|
Text(book.annotation.orEmpty(), style = MaterialTheme.typography.bodyMedium, lineHeight = 20.sp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
item {
|
item {
|
||||||
InfoSection("Statistics") {
|
InfoSection(strings.statistics) {
|
||||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||||
StatBlock("Words", stats.words.formatCompact())
|
StatBlock(strings.words, stats.words.formatCompact())
|
||||||
StatBlock("Sections", stats.sections.toString())
|
StatBlock(strings.sections, stats.sections.toString())
|
||||||
StatBlock("Images", stats.images.toString())
|
StatBlock(strings.images, stats.images.toString())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
item {
|
item {
|
||||||
InfoSection("Last Reading Position") {
|
InfoSection(strings.sourceFile) {
|
||||||
|
if (extras == null) {
|
||||||
|
Text(strings.loading, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
} else {
|
||||||
|
DetailLine(strings.fileName, extras?.sourceFileName?.ifBlank { null } ?: strings.notSpecified)
|
||||||
|
DetailLine(strings.filePath, extras?.sourceFilePath?.ifBlank { null } ?: strings.notSpecified)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
InfoSection(strings.lastReadingPosition) {
|
||||||
val position = extras?.lastReadingPosition
|
val position = extras?.lastReadingPosition
|
||||||
if (position == null) {
|
if (position == null) {
|
||||||
Text("No saved position", style = MaterialTheme.typography.bodyMedium)
|
Text(strings.noSavedPosition, style = MaterialTheme.typography.bodyMedium)
|
||||||
} else {
|
} else {
|
||||||
DetailLine("List item", position.itemIndex.toString())
|
DetailLine(strings.listItem, position.itemIndex.toString())
|
||||||
DetailLine("Scroll offset", "${position.scrollOffset}px")
|
DetailLine(strings.scrollOffset, "${position.scrollOffset}px")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
item {
|
item {
|
||||||
InfoSection("Bookmarks") {
|
InfoSection(strings.bookmarks) {
|
||||||
val bookmarks = extras?.bookmarks.orEmpty()
|
val bookmarks = extras?.bookmarks.orEmpty()
|
||||||
if (extras == null) {
|
if (extras == null) {
|
||||||
Text("Loading...", style = MaterialTheme.typography.bodyMedium)
|
Text(strings.loading, style = MaterialTheme.typography.bodyMedium)
|
||||||
} else if (bookmarks.isEmpty()) {
|
} else if (bookmarks.isEmpty()) {
|
||||||
Text("No bookmarks", style = MaterialTheme.typography.bodyMedium)
|
Text(strings.noBookmarks, style = MaterialTheme.typography.bodyMedium)
|
||||||
} else {
|
} else {
|
||||||
bookmarks.forEach { bookmark ->
|
bookmarks.forEach { bookmark ->
|
||||||
BookmarkInfoLine(bookmark)
|
BookmarkInfoLine(bookmark)
|
||||||
@@ -118,12 +128,12 @@ internal fun BookInfoScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
item {
|
item {
|
||||||
InfoSection("Notes") {
|
InfoSection(strings.notes) {
|
||||||
val notes = extras?.notes.orEmpty()
|
val notes = extras?.notes.orEmpty()
|
||||||
if (extras == null) {
|
if (extras == null) {
|
||||||
Text("Loading...", style = MaterialTheme.typography.bodyMedium)
|
Text(strings.loading, style = MaterialTheme.typography.bodyMedium)
|
||||||
} else if (notes.isEmpty()) {
|
} else if (notes.isEmpty()) {
|
||||||
Text("No notes", style = MaterialTheme.typography.bodyMedium)
|
Text(strings.noNotes, style = MaterialTheme.typography.bodyMedium)
|
||||||
} else {
|
} else {
|
||||||
notes.forEach { note ->
|
notes.forEach { note ->
|
||||||
NoteInfoLine(note)
|
NoteInfoLine(note)
|
||||||
@@ -148,7 +158,7 @@ private fun InfoSection(title: String, content: @Composable ColumnScope.() -> Un
|
|||||||
@Composable
|
@Composable
|
||||||
private fun BookmarkInfoLine(bookmark: BookmarkInfo) {
|
private fun BookmarkInfoLine(bookmark: BookmarkInfo) {
|
||||||
Column(verticalArrangement = Arrangement.spacedBy(2.dp), modifier = Modifier.fillMaxWidth()) {
|
Column(verticalArrangement = Arrangement.spacedBy(2.dp), modifier = Modifier.fillMaxWidth()) {
|
||||||
Text(bookmark.title?.ifBlank { null } ?: "Bookmark", style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold)
|
Text(bookmark.title?.ifBlank { null } ?: strings.bookmark, style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold)
|
||||||
bookmark.selectedText?.ifBlank { null }?.let {
|
bookmark.selectedText?.ifBlank { null }?.let {
|
||||||
Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.secondary, maxLines = 3)
|
Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.secondary, maxLines = 3)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,8 +6,11 @@ import androidx.compose.foundation.gestures.detectDragGestures
|
|||||||
import androidx.compose.foundation.gestures.rememberTransformableState
|
import androidx.compose.foundation.gestures.rememberTransformableState
|
||||||
import androidx.compose.foundation.gestures.transformable
|
import androidx.compose.foundation.gestures.transformable
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.WindowInsets
|
import androidx.compose.foundation.layout.WindowInsets
|
||||||
|
import androidx.compose.foundation.layout.aspectRatio
|
||||||
|
import androidx.compose.foundation.layout.fillMaxHeight
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.height
|
import androidx.compose.foundation.layout.height
|
||||||
@@ -35,7 +38,6 @@ import androidx.compose.runtime.setValue
|
|||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.geometry.Offset
|
import androidx.compose.ui.geometry.Offset
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.graphics.graphicsLayer
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
import androidx.compose.ui.focus.FocusRequester
|
import androidx.compose.ui.focus.FocusRequester
|
||||||
import androidx.compose.ui.focus.focusRequester
|
import androidx.compose.ui.focus.focusRequester
|
||||||
@@ -66,6 +68,8 @@ internal fun ImageViewer(
|
|||||||
val focusRequester = remember { FocusRequester() }
|
val focusRequester = remember { FocusRequester() }
|
||||||
val snackbarHostState = remember { SnackbarHostState() }
|
val snackbarHostState = remember { SnackbarHostState() }
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
|
val imageBackgroundColor = readerImageBackgroundColor()
|
||||||
|
val imageAspectRatio = image.bitmap.width.toFloat() / image.bitmap.height.toFloat()
|
||||||
|
|
||||||
fun setScale(next: Float) {
|
fun setScale(next: Float) {
|
||||||
scale = next.coerceIn(MinImageScale, MaxImageScale)
|
scale = next.coerceIn(MinImageScale, MaxImageScale)
|
||||||
@@ -88,9 +92,9 @@ internal fun ImageViewer(
|
|||||||
fun copyImage() {
|
fun copyImage() {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val message = if (copyImageToClipboard(image.bytes, image.mimeType, image.title)) {
|
val message = if (copyImageToClipboard(image.bytes, image.mimeType, image.title)) {
|
||||||
"Image copied"
|
strings.imageCopied
|
||||||
} else {
|
} else {
|
||||||
"Copy failed"
|
strings.copyFailed
|
||||||
}
|
}
|
||||||
snackbarHostState.showSnackbar(message, duration = SnackbarDuration.Short)
|
snackbarHostState.showSnackbar(message, duration = SnackbarDuration.Short)
|
||||||
}
|
}
|
||||||
@@ -110,7 +114,7 @@ internal fun ImageViewer(
|
|||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
IconButton(onClick = onBack) {
|
IconButton(onClick = onBack) {
|
||||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
|
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = strings.back)
|
||||||
}
|
}
|
||||||
Text(
|
Text(
|
||||||
image.title,
|
image.title,
|
||||||
@@ -119,25 +123,25 @@ internal fun ImageViewer(
|
|||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
IconButton(onClick = { setScale(scale * 1.25f) }) {
|
IconButton(onClick = { setScale(scale * 1.25f) }) {
|
||||||
Icon(Icons.Filled.ZoomIn, contentDescription = "Zoom in")
|
Icon(Icons.Filled.ZoomIn, contentDescription = strings.zoomIn)
|
||||||
}
|
}
|
||||||
IconButton(onClick = { setScale(scale / 1.25f) }, enabled = scale > MinImageScale) {
|
IconButton(onClick = { setScale(scale / 1.25f) }, enabled = scale > MinImageScale) {
|
||||||
Icon(Icons.Filled.ZoomOut, contentDescription = "Zoom out")
|
Icon(Icons.Filled.ZoomOut, contentDescription = strings.zoomOut)
|
||||||
}
|
}
|
||||||
IconButton(
|
IconButton(
|
||||||
onClick = ::copyImage,
|
onClick = ::copyImage,
|
||||||
) {
|
) {
|
||||||
Icon(Icons.Filled.ContentCopy, contentDescription = "Copy image")
|
Icon(Icons.Filled.ContentCopy, contentDescription = strings.copyImage)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
) { padding ->
|
) { padding ->
|
||||||
Box(
|
BoxWithConstraints(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.padding(padding)
|
.padding(padding)
|
||||||
.background(Color.Black)
|
.background(readerBackground())
|
||||||
.focusRequester(focusRequester)
|
.focusRequester(focusRequester)
|
||||||
.onPreviewKeyEvent { event ->
|
.onPreviewKeyEvent { event ->
|
||||||
if (event.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
|
if (event.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
|
||||||
@@ -171,19 +175,28 @@ internal fun ImageViewer(
|
|||||||
},
|
},
|
||||||
contentAlignment = Alignment.Center,
|
contentAlignment = Alignment.Center,
|
||||||
) {
|
) {
|
||||||
Image(
|
val imageModifier = if (maxWidth / maxHeight > imageAspectRatio) {
|
||||||
bitmap = image.bitmap,
|
Modifier.fillMaxHeight().aspectRatio(imageAspectRatio)
|
||||||
contentDescription = image.title,
|
} else {
|
||||||
modifier = Modifier
|
Modifier.fillMaxWidth().aspectRatio(imageAspectRatio)
|
||||||
.fillMaxSize()
|
}
|
||||||
|
Box(
|
||||||
|
modifier = imageModifier
|
||||||
.graphicsLayer {
|
.graphicsLayer {
|
||||||
scaleX = scale
|
scaleX = scale
|
||||||
scaleY = scale
|
scaleY = scale
|
||||||
translationX = offset.x
|
translationX = offset.x
|
||||||
translationY = offset.y
|
translationY = offset.y
|
||||||
},
|
}
|
||||||
contentScale = ContentScale.Fit,
|
.background(imageBackgroundColor),
|
||||||
)
|
) {
|
||||||
|
Image(
|
||||||
|
bitmap = image.bitmap,
|
||||||
|
contentDescription = image.title,
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
contentScale = ContentScale.Fit,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,10 @@
|
|||||||
package net.sergeych.toread
|
package net.sergeych.toread
|
||||||
|
|
||||||
|
internal data class LibraryDeleteRequest(
|
||||||
|
val fileId: String,
|
||||||
|
val title: String,
|
||||||
|
)
|
||||||
|
|
||||||
internal data class LibraryDeleteResult(
|
internal data class LibraryDeleteResult(
|
||||||
val deleted: Boolean,
|
val deleted: Boolean,
|
||||||
val message: String,
|
val message: String,
|
||||||
@@ -9,6 +14,6 @@ internal suspend fun deleteLibraryBook(fileId: String, title: String): LibraryDe
|
|||||||
val deleted = runCatching { deleteLibraryItem(fileId) }.getOrDefault(false)
|
val deleted = runCatching { deleteLibraryItem(fileId) }.getOrDefault(false)
|
||||||
return LibraryDeleteResult(
|
return LibraryDeleteResult(
|
||||||
deleted = deleted,
|
deleted = deleted,
|
||||||
message = if (deleted) "Removed $title." else "Could not remove $title.",
|
message = if (deleted) strings.removed(title) else strings.couldNotRemove(title),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,7 @@ package net.sergeych.toread
|
|||||||
import net.sergeych.toread.fb2.Fb2Binary
|
import net.sergeych.toread.fb2.Fb2Binary
|
||||||
import net.sergeych.toread.fb2.Fb2Book
|
import net.sergeych.toread.fb2.Fb2Book
|
||||||
import net.sergeych.toread.storage.BookReadingStatus
|
import net.sergeych.toread.storage.BookReadingStatus
|
||||||
|
import kotlin.math.abs
|
||||||
|
|
||||||
data class LibraryItem(
|
data class LibraryItem(
|
||||||
val fileId: String,
|
val fileId: String,
|
||||||
@@ -16,6 +17,7 @@ data class LibraryItem(
|
|||||||
val storageUri: String?,
|
val storageUri: String?,
|
||||||
val lastSeenAt: Long?,
|
val lastSeenAt: Long?,
|
||||||
val readingStatus: BookReadingStatus = BookReadingStatus.NEW,
|
val readingStatus: BookReadingStatus = BookReadingStatus.NEW,
|
||||||
|
val favorite: Boolean = false,
|
||||||
val lastReadAt: Long? = null,
|
val lastReadAt: Long? = null,
|
||||||
val importedAt: Long? = null,
|
val importedAt: Long? = null,
|
||||||
val coverImage: ByteArray? = null,
|
val coverImage: ByteArray? = null,
|
||||||
@@ -59,9 +61,28 @@ data class PlatformOpenBookRequest(
|
|||||||
data class ReadingPosition(
|
data class ReadingPosition(
|
||||||
val itemIndex: Int,
|
val itemIndex: Int,
|
||||||
val scrollOffset: Int,
|
val scrollOffset: Int,
|
||||||
|
val readAloudSentenceIndex: Int? = null,
|
||||||
|
val backStack: List<ReadingPosition> = emptyList(),
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ReaderFontSettings(
|
||||||
|
val fontSizeSp: Float = defaultReaderFontSizeSp(),
|
||||||
|
val lineHeightSp: Float = DefaultReaderLineHeightSp,
|
||||||
|
val fontWeight: Int = defaultReaderFontWeight(),
|
||||||
|
val fontName: String? = null,
|
||||||
|
val lightBackgroundArgb: Long? = null,
|
||||||
|
val lightTextArgb: Long? = null,
|
||||||
|
val darkBackgroundArgb: Long? = null,
|
||||||
|
val darkTextArgb: Long? = null,
|
||||||
|
val lightCustomBackgroundArgb: Long? = null,
|
||||||
|
val lightCustomTextArgb: Long? = null,
|
||||||
|
val darkCustomBackgroundArgb: Long? = null,
|
||||||
|
val darkCustomTextArgb: Long? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
data class BookInfoExtras(
|
data class BookInfoExtras(
|
||||||
|
val sourceFileName: String? = null,
|
||||||
|
val sourceFilePath: String? = null,
|
||||||
val bookmarks: List<BookmarkInfo> = emptyList(),
|
val bookmarks: List<BookmarkInfo> = emptyList(),
|
||||||
val notes: List<NoteInfo> = emptyList(),
|
val notes: List<NoteInfo> = emptyList(),
|
||||||
val lastReadingPosition: ReadingPosition? = null,
|
val lastReadingPosition: ReadingPosition? = null,
|
||||||
@@ -96,8 +117,12 @@ expect suspend fun loadLibraryItems(): List<LibraryItem>
|
|||||||
|
|
||||||
expect suspend fun loadLibraryItemsPage(limit: Int, offset: Int): List<LibraryItem>
|
expect suspend fun loadLibraryItemsPage(limit: Int, offset: Int): List<LibraryItem>
|
||||||
|
|
||||||
|
expect suspend fun loadRecentlyAddedLibraryItems(sinceImportedAt: Long, limit: Int = 50): List<LibraryItem>
|
||||||
|
|
||||||
expect suspend fun searchLibraryItems(query: String, limit: Int = 100): List<LibraryItem>
|
expect suspend fun searchLibraryItems(query: String, limit: Int = 100): List<LibraryItem>
|
||||||
|
|
||||||
|
expect fun currentLibraryTimeMillis(): Long
|
||||||
|
|
||||||
expect suspend fun loadLibraryItem(fileId: String): LibraryItem?
|
expect suspend fun loadLibraryItem(fileId: String): LibraryItem?
|
||||||
|
|
||||||
expect suspend fun loadLibraryItemCover(fileId: String): LibraryCover?
|
expect suspend fun loadLibraryItemCover(fileId: String): LibraryCover?
|
||||||
@@ -120,9 +145,13 @@ expect suspend fun clearLibraryReadingPosition(fileId: String)
|
|||||||
|
|
||||||
expect suspend fun markLibraryReadingStatus(fileId: String, status: BookReadingStatus): Boolean
|
expect suspend fun markLibraryReadingStatus(fileId: String, status: BookReadingStatus): Boolean
|
||||||
|
|
||||||
|
expect suspend fun markLibraryFavorite(fileId: String, favorite: Boolean): Boolean
|
||||||
|
|
||||||
expect suspend fun shareLibraryBookFile(fileId: String): Boolean
|
expect suspend fun shareLibraryBookFile(fileId: String): Boolean
|
||||||
|
|
||||||
expect suspend fun viewLibraryBookFile(fileId: String): Boolean
|
expect suspend fun viewLibraryBookFile(folder: String, fileName: String): Boolean
|
||||||
|
|
||||||
|
expect fun openPlatformUrl(url: String): Boolean
|
||||||
|
|
||||||
expect suspend fun loadBookInfoExtras(fileId: String): BookInfoExtras
|
expect suspend fun loadBookInfoExtras(fileId: String): BookInfoExtras
|
||||||
|
|
||||||
@@ -134,10 +163,30 @@ expect suspend fun loadThemeMode(): ThemeMode
|
|||||||
|
|
||||||
expect suspend fun saveThemeMode(mode: ThemeMode)
|
expect suspend fun saveThemeMode(mode: ThemeMode)
|
||||||
|
|
||||||
|
expect suspend fun loadReaderFontSettings(): ReaderFontSettings
|
||||||
|
|
||||||
|
expect suspend fun saveReaderFontSettings(settings: ReaderFontSettings)
|
||||||
|
|
||||||
|
expect suspend fun loadReaderFullScreen(): Boolean
|
||||||
|
|
||||||
|
expect suspend fun saveReaderFullScreen(fullScreen: Boolean)
|
||||||
|
|
||||||
|
expect suspend fun loadReaderPagingOnly(): Boolean
|
||||||
|
|
||||||
|
expect suspend fun saveReaderPagingOnly(enabled: Boolean)
|
||||||
|
|
||||||
expect suspend fun loadScanDownloadsAutomatically(): Boolean
|
expect suspend fun loadScanDownloadsAutomatically(): Boolean
|
||||||
|
|
||||||
expect suspend fun saveScanDownloadsAutomatically(enabled: Boolean)
|
expect suspend fun saveScanDownloadsAutomatically(enabled: Boolean)
|
||||||
|
|
||||||
|
internal expect suspend fun loadLibraryFilter(): LibraryFilter
|
||||||
|
|
||||||
|
internal expect suspend fun saveLibraryFilter(filter: LibraryFilter)
|
||||||
|
|
||||||
|
expect suspend fun loadAppLocaleTag(): String?
|
||||||
|
|
||||||
|
expect suspend fun saveAppLocaleTag(localeTag: String?)
|
||||||
|
|
||||||
expect suspend fun loadDownloadsWasScanned(): Boolean
|
expect suspend fun loadDownloadsWasScanned(): Boolean
|
||||||
|
|
||||||
expect suspend fun saveDownloadsWasScanned(scanned: Boolean)
|
expect suspend fun saveDownloadsWasScanned(scanned: Boolean)
|
||||||
@@ -158,3 +207,198 @@ internal fun Fb2Book.libraryCoverBinary(): Fb2Binary? {
|
|||||||
val image = coverImages.firstOrNull() ?: bodyImages.firstOrNull()
|
val image = coverImages.firstOrNull() ?: bodyImages.firstOrNull()
|
||||||
return image?.let(::binaryFor)
|
return image?.let(::binaryFor)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun canShareLibraryBookFile(): Boolean =
|
||||||
|
getPlatform().name.startsWith("Android")
|
||||||
|
|
||||||
|
internal suspend fun shareLibraryBook(fileId: String): String =
|
||||||
|
if (shareLibraryBookFile(fileId)) strings.shareOpened() else strings.couldNotShareBook()
|
||||||
|
|
||||||
|
internal fun canViewLibraryBookFile(): Boolean =
|
||||||
|
getPlatform().name.startsWith("Java")
|
||||||
|
|
||||||
|
internal suspend fun viewLibraryBook(fileId: String): String {
|
||||||
|
val location = loadLibraryItem(fileId)?.storageUri?.toLibraryBookFileLocation()
|
||||||
|
?: return strings.couldNotOpenFileLocation()
|
||||||
|
return if (viewLibraryBookFile(location.folder, location.fileName)) {
|
||||||
|
strings.openedFileLocation()
|
||||||
|
} else {
|
||||||
|
strings.couldNotOpenFileLocation()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private data class LibraryBookFileLocation(
|
||||||
|
val folder: String,
|
||||||
|
val fileName: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun String.toLibraryBookFileLocation(): LibraryBookFileLocation? {
|
||||||
|
val separatorIndex = maxOf(lastIndexOf('/'), lastIndexOf('\\'))
|
||||||
|
if (separatorIndex < 0 || separatorIndex >= lastIndex) return null
|
||||||
|
return LibraryBookFileLocation(
|
||||||
|
folder = if (separatorIndex == 0) substring(0, 1) else substring(0, separatorIndex),
|
||||||
|
fileName = substring(separatorIndex + 1),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal const val DefaultReaderLineHeightSp = 26f
|
||||||
|
internal const val ReaderFontSizeStepSp = 1f
|
||||||
|
internal const val ReaderLineHeightStepSp = 1f
|
||||||
|
|
||||||
|
private const val MinReaderFontSizeSp = 14f
|
||||||
|
private const val MaxReaderFontSizeSp = 34f
|
||||||
|
private const val MinReaderLineHeightSp = 18f
|
||||||
|
private const val MaxReaderLineHeightSp = 48f
|
||||||
|
private const val MinReaderFontWeight = 100
|
||||||
|
private const val MaxReaderFontWeight = 900
|
||||||
|
private val ReaderFontWeightSteps = listOf(100, 200, 300, 400, 500, 600, 700, 800, 900)
|
||||||
|
|
||||||
|
internal fun defaultReaderFontSettings(): ReaderFontSettings = ReaderFontSettings()
|
||||||
|
|
||||||
|
internal fun defaultReaderFontSizeSp(): Float =
|
||||||
|
if (getPlatform().name.startsWith("Android")) 20f else 18f
|
||||||
|
|
||||||
|
internal fun defaultReaderFontWeight(): Int =
|
||||||
|
if (getPlatform().name.startsWith("Android")) 350 else 400
|
||||||
|
|
||||||
|
internal fun ReaderFontSettings.coerced(): ReaderFontSettings =
|
||||||
|
copy(
|
||||||
|
fontSizeSp = fontSizeSp.coerceIn(MinReaderFontSizeSp, MaxReaderFontSizeSp),
|
||||||
|
lineHeightSp = lineHeightSp.coerceIn(MinReaderLineHeightSp, MaxReaderLineHeightSp),
|
||||||
|
fontWeight = fontWeight.coerceIn(MinReaderFontWeight, MaxReaderFontWeight),
|
||||||
|
fontName = fontName?.takeIf { it.isNotBlank() },
|
||||||
|
lightBackgroundArgb = lightBackgroundArgb?.coerceArgb(),
|
||||||
|
lightTextArgb = lightTextArgb?.coerceArgb(),
|
||||||
|
darkBackgroundArgb = darkBackgroundArgb?.coerceArgb(),
|
||||||
|
darkTextArgb = darkTextArgb?.coerceArgb(),
|
||||||
|
lightCustomBackgroundArgb = lightCustomBackgroundArgb?.coerceArgb(),
|
||||||
|
lightCustomTextArgb = lightCustomTextArgb?.coerceArgb(),
|
||||||
|
darkCustomBackgroundArgb = darkCustomBackgroundArgb?.coerceArgb(),
|
||||||
|
darkCustomTextArgb = darkCustomTextArgb?.coerceArgb(),
|
||||||
|
)
|
||||||
|
|
||||||
|
internal fun ReaderFontSettings.adjustFontSize(steps: Int): ReaderFontSettings {
|
||||||
|
val current = coerced()
|
||||||
|
val nextFontSize = (current.fontSizeSp + steps * ReaderFontSizeStepSp)
|
||||||
|
.coerceIn(MinReaderFontSizeSp, MaxReaderFontSizeSp)
|
||||||
|
val scale = if (current.fontSizeSp > 0f) nextFontSize / current.fontSizeSp else 1f
|
||||||
|
return current.copy(
|
||||||
|
fontSizeSp = nextFontSize,
|
||||||
|
lineHeightSp = (current.lineHeightSp * scale).coerceIn(MinReaderLineHeightSp, MaxReaderLineHeightSp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ReaderFontSettings.adjustLineHeight(steps: Int): ReaderFontSettings =
|
||||||
|
coerced().let { current ->
|
||||||
|
current.copy(
|
||||||
|
lineHeightSp = (current.lineHeightSp + steps * ReaderLineHeightStepSp)
|
||||||
|
.coerceIn(MinReaderLineHeightSp, MaxReaderLineHeightSp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ReaderFontSettings.adjustFontWeight(steps: Int): ReaderFontSettings {
|
||||||
|
val current = coerced()
|
||||||
|
if (steps == 0) return current
|
||||||
|
|
||||||
|
var nextWeight = current.fontWeight
|
||||||
|
repeat(abs(steps)) {
|
||||||
|
nextWeight = current.fontWeight + if (steps > 0) 50 else -50
|
||||||
|
if( nextWeight == 100 || nextWeight == 900 ) return@repeat
|
||||||
|
}
|
||||||
|
return current.copy(fontWeight = nextWeight)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ReaderFontSettings.toStorageValue(): String =
|
||||||
|
coerced().let { current ->
|
||||||
|
listOf(
|
||||||
|
current.fontSizeSp.toString(),
|
||||||
|
current.lineHeightSp.toString(),
|
||||||
|
current.fontWeight.toString(),
|
||||||
|
current.fontName.orEmpty(),
|
||||||
|
current.lightBackgroundArgb?.toStorageArgb().orEmpty(),
|
||||||
|
current.lightTextArgb?.toStorageArgb().orEmpty(),
|
||||||
|
current.darkBackgroundArgb?.toStorageArgb().orEmpty(),
|
||||||
|
current.darkTextArgb?.toStorageArgb().orEmpty(),
|
||||||
|
current.lightCustomBackgroundArgb?.toStorageArgb().orEmpty(),
|
||||||
|
current.lightCustomTextArgb?.toStorageArgb().orEmpty(),
|
||||||
|
current.darkCustomBackgroundArgb?.toStorageArgb().orEmpty(),
|
||||||
|
current.darkCustomTextArgb?.toStorageArgb().orEmpty(),
|
||||||
|
).joinToString("|")
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun readerFontSettingsFromStorageValue(value: String?): ReaderFontSettings {
|
||||||
|
val defaults = defaultReaderFontSettings()
|
||||||
|
val parts = value?.split("|") ?: return defaults
|
||||||
|
return ReaderFontSettings(
|
||||||
|
fontSizeSp = parts.getOrNull(0)?.toFloatOrNull() ?: defaults.fontSizeSp,
|
||||||
|
lineHeightSp = parts.getOrNull(1)?.toFloatOrNull() ?: defaults.lineHeightSp,
|
||||||
|
fontWeight = parts.getOrNull(2)?.toIntOrNull() ?: defaults.fontWeight,
|
||||||
|
fontName = parts.getOrNull(3)?.takeIf { it.isNotBlank() } ?: defaults.fontName,
|
||||||
|
lightBackgroundArgb = parts.getOrNull(4)?.storageArgbOrNull(),
|
||||||
|
lightTextArgb = parts.getOrNull(5)?.storageArgbOrNull(),
|
||||||
|
darkBackgroundArgb = parts.getOrNull(6)?.storageArgbOrNull(),
|
||||||
|
darkTextArgb = parts.getOrNull(7)?.storageArgbOrNull(),
|
||||||
|
lightCustomBackgroundArgb = parts.getOrNull(8)?.storageArgbOrNull(),
|
||||||
|
lightCustomTextArgb = parts.getOrNull(9)?.storageArgbOrNull(),
|
||||||
|
darkCustomBackgroundArgb = parts.getOrNull(10)?.storageArgbOrNull(),
|
||||||
|
darkCustomTextArgb = parts.getOrNull(11)?.storageArgbOrNull(),
|
||||||
|
).coerced()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ReaderFontSettings.withThemeBackgroundArgb(useDarkTheme: Boolean, argb: Long?): ReaderFontSettings =
|
||||||
|
if (useDarkTheme) copy(darkBackgroundArgb = argb?.coerceArgb()) else copy(lightBackgroundArgb = argb?.coerceArgb())
|
||||||
|
|
||||||
|
internal fun ReaderFontSettings.withThemeTextArgb(useDarkTheme: Boolean, argb: Long?): ReaderFontSettings =
|
||||||
|
if (useDarkTheme) copy(darkTextArgb = argb?.coerceArgb()) else copy(lightTextArgb = argb?.coerceArgb())
|
||||||
|
|
||||||
|
internal fun ReaderFontSettings.withThemeCustomBackgroundArgb(useDarkTheme: Boolean, argb: Long?): ReaderFontSettings =
|
||||||
|
if (useDarkTheme) {
|
||||||
|
copy(darkCustomBackgroundArgb = argb?.coerceArgb(), darkBackgroundArgb = argb?.coerceArgb())
|
||||||
|
} else {
|
||||||
|
copy(lightCustomBackgroundArgb = argb?.coerceArgb(), lightBackgroundArgb = argb?.coerceArgb())
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ReaderFontSettings.withThemeCustomTextArgb(useDarkTheme: Boolean, argb: Long?): ReaderFontSettings =
|
||||||
|
if (useDarkTheme) {
|
||||||
|
copy(darkCustomTextArgb = argb?.coerceArgb(), darkTextArgb = argb?.coerceArgb())
|
||||||
|
} else {
|
||||||
|
copy(lightCustomTextArgb = argb?.coerceArgb(), lightTextArgb = argb?.coerceArgb())
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ReaderFontSettings.themeBackgroundArgb(useDarkTheme: Boolean): Long? =
|
||||||
|
if (useDarkTheme) darkBackgroundArgb else lightBackgroundArgb
|
||||||
|
|
||||||
|
internal fun ReaderFontSettings.themeTextArgb(useDarkTheme: Boolean): Long? =
|
||||||
|
if (useDarkTheme) darkTextArgb else lightTextArgb
|
||||||
|
|
||||||
|
internal fun ReaderFontSettings.themeCustomBackgroundArgb(useDarkTheme: Boolean): Long? =
|
||||||
|
if (useDarkTheme) darkCustomBackgroundArgb else lightCustomBackgroundArgb
|
||||||
|
|
||||||
|
internal fun ReaderFontSettings.themeCustomTextArgb(useDarkTheme: Boolean): Long? =
|
||||||
|
if (useDarkTheme) darkCustomTextArgb else lightCustomTextArgb
|
||||||
|
|
||||||
|
internal fun ReaderFontSettings.resetThemeColorScheme(useDarkTheme: Boolean): ReaderFontSettings =
|
||||||
|
if (useDarkTheme) {
|
||||||
|
copy(
|
||||||
|
darkBackgroundArgb = null,
|
||||||
|
darkTextArgb = null,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
copy(
|
||||||
|
lightBackgroundArgb = null,
|
||||||
|
lightTextArgb = null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Long.coerceArgb(): Long =
|
||||||
|
coerceIn(0x00000000L, 0xFFFFFFFFL)
|
||||||
|
|
||||||
|
private fun Long.toStorageArgb(): String =
|
||||||
|
coerceArgb().toString(16).padStart(8, '0').uppercase()
|
||||||
|
|
||||||
|
private fun String.storageArgbOrNull(): Long? =
|
||||||
|
trim()
|
||||||
|
.removePrefix("#")
|
||||||
|
.takeIf { it.length == 8 }
|
||||||
|
?.toLongOrNull(16)
|
||||||
|
?.coerceArgb()
|
||||||
@@ -0,0 +1,507 @@
|
|||||||
|
package net.sergeych.toread
|
||||||
|
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import net.sergeych.toread.storage.BookReadingStatus
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
|
internal enum class AppLanguage(val localeTag: String) {
|
||||||
|
English("en"),
|
||||||
|
Russian("ru"),
|
||||||
|
}
|
||||||
|
|
||||||
|
internal val availableAppLanguages: List<AppLanguage> = AppLanguage.entries
|
||||||
|
|
||||||
|
internal var selectedAppLocaleTag: String? by mutableStateOf(null)
|
||||||
|
|
||||||
|
internal val appLanguage: AppLanguage
|
||||||
|
get() = if (effectiveAppLocaleTags().any { it.isRussianLanguageTag() }) {
|
||||||
|
AppLanguage.Russian
|
||||||
|
} else {
|
||||||
|
AppLanguage.English
|
||||||
|
}
|
||||||
|
|
||||||
|
internal val strings: AppStrings
|
||||||
|
get() = when (appLanguage) {
|
||||||
|
AppLanguage.English -> EnglishStrings
|
||||||
|
AppLanguage.Russian -> RussianStrings
|
||||||
|
}
|
||||||
|
|
||||||
|
internal expect fun platformLocaleTags(): List<String>
|
||||||
|
|
||||||
|
private fun effectiveAppLocaleTags(): List<String> =
|
||||||
|
selectedAppLocaleTag?.let(::listOf) ?: platformLocaleTags()
|
||||||
|
|
||||||
|
private fun String.isRussianLanguageTag(): Boolean =
|
||||||
|
substringBefore('-').substringBefore('_').equals("ru", ignoreCase = true)
|
||||||
|
|
||||||
|
internal open class AppStrings {
|
||||||
|
open val appName = "To Read"
|
||||||
|
open val loadingOpeningBook = "Opening book"
|
||||||
|
open val scanning = "Scanning..."
|
||||||
|
open val scanningDownloads = "Scanning Downloads..."
|
||||||
|
open val undo = "Undo"
|
||||||
|
open val retry = "Retry"
|
||||||
|
open val done = "Done"
|
||||||
|
open val cancel = "Cancel"
|
||||||
|
|
||||||
|
open val libraryError = "Library error"
|
||||||
|
open val couldNotOpenLibrary = "Could not open library."
|
||||||
|
open val couldNotLoadLibrary = "Could not load library."
|
||||||
|
open val couldNotOpenBook = "Could not open book."
|
||||||
|
open val couldNotUpdateBook = "Could not update book."
|
||||||
|
open val bookFileNotAvailable = "Book file is not available."
|
||||||
|
open val scanFailed = "Scan failed."
|
||||||
|
open val searchFailed = "Search failed."
|
||||||
|
open val libraryRescanFailed = "Library rescan failed."
|
||||||
|
open val rescanningLibrary = "Rescanning library..."
|
||||||
|
|
||||||
|
open val theme = "Theme"
|
||||||
|
open val themeLight = "Light"
|
||||||
|
open val themeDark = "Dark"
|
||||||
|
open val themeSystem = "System"
|
||||||
|
|
||||||
|
open val libraryOptions = "Library options"
|
||||||
|
open val scanDownloadsAutomatically = "Scan Downloads automatically"
|
||||||
|
open val locale = "Locale"
|
||||||
|
open val systemLocale = "Default"
|
||||||
|
open fun appVersion(version: String): String = "Version $version"
|
||||||
|
open val scanFolder = "Scan folder"
|
||||||
|
open val chooseLibraryFilter = "Choose library filter"
|
||||||
|
open val searchLibrary = "Search library"
|
||||||
|
open val closeSearch = "Close search"
|
||||||
|
open val clearSearch = "Clear search"
|
||||||
|
open val noMatches = "No matches"
|
||||||
|
open val scanFolderOrChooseFilter = "Scan a folder or choose another library filter."
|
||||||
|
open val favorite = "Favorite"
|
||||||
|
open val unknownAuthor = "Unknown author"
|
||||||
|
open val noMetadata = "No metadata"
|
||||||
|
open val lastReadPrefix = "Last read"
|
||||||
|
open val open = "Open"
|
||||||
|
open val markAsRead = "Mark as read"
|
||||||
|
open val markAsUnread = "Mark as unread"
|
||||||
|
open val markToRead = "Mark to read"
|
||||||
|
open val removeToRead = "Remove to read"
|
||||||
|
open val removeMarks = "Remove marks"
|
||||||
|
open val notInterested = "Not interested"
|
||||||
|
open val clearMarks = "Clear marks"
|
||||||
|
open val addFavorite = "Add favorite"
|
||||||
|
open val removeFavorite = "Remove favorite"
|
||||||
|
open val delete = "Delete"
|
||||||
|
|
||||||
|
open val filterReadingNow = "Reading now"
|
||||||
|
open val filterRecentlyAdded = "Recently added"
|
||||||
|
open val filterMyLibrary = "My library"
|
||||||
|
open val filterToRead = "To read"
|
||||||
|
open val filterRead = "Read"
|
||||||
|
|
||||||
|
open val scan = "Scan"
|
||||||
|
open val rootFolder = "Root folder"
|
||||||
|
open val choose = "Choose"
|
||||||
|
open val logPrefix = "Log"
|
||||||
|
|
||||||
|
open val bookInfo = "Book info"
|
||||||
|
open val back = "Back"
|
||||||
|
open val backToLibrary = "Back to library"
|
||||||
|
open val backToReader = "Back to reader"
|
||||||
|
open val titleInfo = "Title Info"
|
||||||
|
open val title = "Title"
|
||||||
|
open val authors = "Authors"
|
||||||
|
open val language = "Language"
|
||||||
|
open val date = "Date"
|
||||||
|
open val genres = "Genres"
|
||||||
|
open val source = "Source"
|
||||||
|
open val translator = "Translator"
|
||||||
|
open val notSpecified = "Not specified"
|
||||||
|
open val statistics = "Statistics"
|
||||||
|
open val words = "Words"
|
||||||
|
open val sections = "Sections"
|
||||||
|
open val images = "Images"
|
||||||
|
open val sourceFile = "Source file"
|
||||||
|
open val fileName = "File name"
|
||||||
|
open val filePath = "Path"
|
||||||
|
open val lastReadingPosition = "Last Reading Position"
|
||||||
|
open val noSavedPosition = "No saved position"
|
||||||
|
open val listItem = "List item"
|
||||||
|
open val scrollOffset = "Scroll offset"
|
||||||
|
open val bookmarks = "Bookmarks"
|
||||||
|
open val bookmark = "Bookmark"
|
||||||
|
open val noBookmarks = "No bookmarks"
|
||||||
|
open val notes = "Notes"
|
||||||
|
open val noNotes = "No notes"
|
||||||
|
open val loading = "Loading..."
|
||||||
|
open val noImage = "No image"
|
||||||
|
|
||||||
|
open val readerTheme = "Theme"
|
||||||
|
open val tableOfContents = "Contents"
|
||||||
|
open val backToLastPosition = "Back"
|
||||||
|
open val readAloud = "Read aloud"
|
||||||
|
open val readerMenu = "Book reader menu"
|
||||||
|
open val info = "Info..."
|
||||||
|
open val readerSettings = "Settings"
|
||||||
|
open val fullScreen = "Full screen"
|
||||||
|
open val readerFontSizeIncrease = "Increase font size"
|
||||||
|
open val readerFontSizeDecrease = "Decrease font size"
|
||||||
|
open val readerLineHeightIncrease = "Increase line spacing"
|
||||||
|
open val readerLineHeightDecrease = "Decrease line spacing"
|
||||||
|
open val readerFontWeightIncrease = "Increase font weight"
|
||||||
|
open val readerFontWeightDecrease = "Decrease font weight"
|
||||||
|
open val resetReaderFontSettings = "Reset font settings"
|
||||||
|
open val revertColorScheme = "Revert color scheme"
|
||||||
|
open val readerBackgroundColor = "Reader background color"
|
||||||
|
open val readerTextColor = "Reader text color"
|
||||||
|
open val extraReaderSettings = "Extra reader settings"
|
||||||
|
open val customColor = "Custom color"
|
||||||
|
open val red = "R"
|
||||||
|
open val green = "G"
|
||||||
|
open val blue = "B"
|
||||||
|
open val readerColors = "Colors"
|
||||||
|
open val readerTypography = "Typography"
|
||||||
|
open val readerLayout = "Layout"
|
||||||
|
open val readerNavigation = "Navigation"
|
||||||
|
open val readerPagingOnly = "Paging only (no free scroll)"
|
||||||
|
open val readerProgress = "Progress"
|
||||||
|
open val closeReaderSettings = "Close reader settings"
|
||||||
|
open val share = "Share"
|
||||||
|
open val viewFile = "View file"
|
||||||
|
open val previousSentence = "Previous sentence"
|
||||||
|
open val stopReading = "Stop reading"
|
||||||
|
open val startReading = "Start reading"
|
||||||
|
open val nextSentence = "Next sentence"
|
||||||
|
open val readAloudSettings = "Read aloud settings"
|
||||||
|
open val ttsEngine = "TTS engine"
|
||||||
|
open val systemDefault = "System default"
|
||||||
|
open val offlineVoice = "Offline voice"
|
||||||
|
open val autoRussian = "Auto Russian"
|
||||||
|
open val loadingVoices = "Loading voices..."
|
||||||
|
open val preparingSpeech = "Preparing speech…"
|
||||||
|
open val offlineSpeechModelMissing = "Download the offline speech model first; see the desktop setup guide."
|
||||||
|
open val speechPlaybackFailed = "Speech playback failed. Check the offline model and audio output, then try again."
|
||||||
|
|
||||||
|
open val imageCopied = "Image copied"
|
||||||
|
open val copyFailed = "Copy failed"
|
||||||
|
open val zoomIn = "Zoom in"
|
||||||
|
open val zoomOut = "Zoom out"
|
||||||
|
open val copyImage = "Copy image"
|
||||||
|
|
||||||
|
open val chooseLibraryFolder = "Choose library folder"
|
||||||
|
open val downloads = "Downloads"
|
||||||
|
open val otherFolder = "Other folder..."
|
||||||
|
open val play = "Play"
|
||||||
|
open val stop = "Stop"
|
||||||
|
open val previous = "Previous"
|
||||||
|
open val next = "Next"
|
||||||
|
open val readingInBackground = "Reading in the background"
|
||||||
|
open val shareBook = "Share book"
|
||||||
|
open val couldNotLoadAndroidTtsEngines = "Could not load Android TTS engines."
|
||||||
|
open val couldNotLoadSelectedTtsVoices = "Could not load voices for the selected TTS engine."
|
||||||
|
open val noOfflineVoices = "No offline voices reported by the selected TTS engine."
|
||||||
|
|
||||||
|
open fun themeChanged(mode: ThemeMode): String = "$theme: ${mode.localizedName()}"
|
||||||
|
open fun removed(title: String): String = "Removed $title."
|
||||||
|
open fun restored(title: String): String = "Restored $title."
|
||||||
|
open fun couldNotRemove(title: String): String = "Could not remove $title."
|
||||||
|
open fun couldNotOpen(displayName: String): String = "Could not open $displayName."
|
||||||
|
open fun couldNotReopenLastBook(): String = "Could not reopen last book."
|
||||||
|
open fun scanReport(scanned: Int, imported: Int, skipped: Int, failed: Int): String =
|
||||||
|
"Scanned $scanned, imported $imported, skipped $skipped, failed $failed."
|
||||||
|
open val noNewBooksFound = "Nothing new has been found."
|
||||||
|
open val show = "Show"
|
||||||
|
open fun newBooksAdded(count: Int): String =
|
||||||
|
if (count == 1) "1 new book added." else "$count new books added."
|
||||||
|
open fun rescanReport(scanned: Int, updated: Int, failed: Int): String =
|
||||||
|
"Rescanned $scanned, updated $updated, failed $failed."
|
||||||
|
open fun checkingFile(currentFile: String?, scanned: Int, imported: Int, skipped: Int, failed: Int): String =
|
||||||
|
buildString {
|
||||||
|
append("Checking")
|
||||||
|
currentFile?.takeIf(String::isNotBlank)?.let { append(" $it") }
|
||||||
|
append(". Found $scanned supported files")
|
||||||
|
append(", imported $imported")
|
||||||
|
append(", skipped $skipped")
|
||||||
|
append(", failed $failed.")
|
||||||
|
}
|
||||||
|
open fun importedSkippedFailed(imported: Int, skipped: Int, failed: Int): String =
|
||||||
|
"Imported $imported, skipped $skipped, failed $failed"
|
||||||
|
open fun scannedBooks(scanned: Int): String = "Scanned $scanned books"
|
||||||
|
open fun scannedProgress(scanned: Int, total: Int, percent: Int): String =
|
||||||
|
"Scanned $scanned of $total, $percent% done"
|
||||||
|
open fun noBooksIn(filterLabel: String): String = "No books in ${filterLabel.lowercase()}"
|
||||||
|
open fun bookMenuFor(title: String): String = "Book menu for $title"
|
||||||
|
open fun markedAsRead(title: String? = null): String = title?.let { "Marked $it as read." } ?: "Marked as read."
|
||||||
|
open fun markedAsUnread(title: String): String = "Marked $title as unread."
|
||||||
|
open fun markedToRead(title: String? = null): String = title?.let { "Marked $it to read." } ?: "Marked to read."
|
||||||
|
open fun markedNotInterested(title: String? = null): String =
|
||||||
|
title?.let { "Marked $it as not interested." } ?: "Marked as not interested."
|
||||||
|
open fun removedMarks(title: String? = null): String = title?.let { "Removed marks from $it." } ?: "Cleared marks."
|
||||||
|
open fun addedToFavorites(title: String? = null): String =
|
||||||
|
title?.let { "Added $it to favorites." } ?: "Added to favorites."
|
||||||
|
open fun removedFromFavorites(title: String? = null): String =
|
||||||
|
title?.let { "Removed $it from favorites." } ?: "Removed from favorites."
|
||||||
|
open fun couldNotUpdate(title: String): String = "Could not update $title."
|
||||||
|
open fun shareOpened(): String = "Share opened."
|
||||||
|
open fun couldNotShareBook(): String = "Could not share book."
|
||||||
|
open fun openedFileLocation(): String = "Opened file location."
|
||||||
|
open fun couldNotOpenFileLocation(): String = "Could not open file location."
|
||||||
|
open fun allFilesAccessRequired(path: String): String = "All files access is required to scan $path."
|
||||||
|
open fun couldNotRead(name: String): String = "Could not read $name"
|
||||||
|
open fun progressLabel(progress: Double?): String =
|
||||||
|
progress?.let { "Progress ${(it * 100).roundToInt()}%" } ?: "Progress not recorded"
|
||||||
|
open fun appLanguageName(language: AppLanguage): String =
|
||||||
|
when (language) {
|
||||||
|
AppLanguage.English -> "English"
|
||||||
|
AppLanguage.Russian -> "Russian"
|
||||||
|
}
|
||||||
|
open fun sectionFallback(index: Int): String = "Section ${index + 1}"
|
||||||
|
open fun readingStatus(status: BookReadingStatus): String =
|
||||||
|
when (status) {
|
||||||
|
BookReadingStatus.NEW -> "New"
|
||||||
|
BookReadingStatus.TO_READ -> "To read"
|
||||||
|
BookReadingStatus.READING -> "Reading"
|
||||||
|
BookReadingStatus.READ -> "Read"
|
||||||
|
BookReadingStatus.NOT_INTERESTED -> "Not interested"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal object EnglishStrings : AppStrings()
|
||||||
|
|
||||||
|
internal object RussianStrings : AppStrings() {
|
||||||
|
override val appName = "Читать"
|
||||||
|
override val loadingOpeningBook = "Открываем книгу"
|
||||||
|
override val scanning = "Сканируем..."
|
||||||
|
override val scanningDownloads = "Сканируем Загрузки..."
|
||||||
|
override val undo = "Отменить"
|
||||||
|
override val retry = "Повторить"
|
||||||
|
override val done = "Готово"
|
||||||
|
override val cancel = "Отмена"
|
||||||
|
|
||||||
|
override val libraryError = "Ошибка библиотеки"
|
||||||
|
override val couldNotOpenLibrary = "Не удалось открыть библиотеку."
|
||||||
|
override val couldNotLoadLibrary = "Не удалось загрузить библиотеку."
|
||||||
|
override val couldNotOpenBook = "Не удалось открыть книгу."
|
||||||
|
override val couldNotUpdateBook = "Не удалось обновить книгу."
|
||||||
|
override val bookFileNotAvailable = "Файл книги недоступен."
|
||||||
|
override val scanFailed = "Импорт не удался."
|
||||||
|
override val searchFailed = "Поиск не удался."
|
||||||
|
override val libraryRescanFailed = "Повторное сканирование библиотеки не удалось."
|
||||||
|
override val rescanningLibrary = "Пересканируем библиотеку..."
|
||||||
|
|
||||||
|
override val theme = "Тема"
|
||||||
|
override val themeLight = "светлая"
|
||||||
|
override val themeDark = "темная"
|
||||||
|
override val themeSystem = "системная"
|
||||||
|
|
||||||
|
override val libraryOptions = "Параметры библиотеки"
|
||||||
|
override val scanDownloadsAutomatically = "Автоматически сканировать Загрузки"
|
||||||
|
override val locale = "Локализация"
|
||||||
|
override val systemLocale = "Системная"
|
||||||
|
override fun appVersion(version: String): String = "Версия $version"
|
||||||
|
override val scanFolder = "Сканировать папку"
|
||||||
|
override val chooseLibraryFilter = "Выбрать фильтр библиотеки"
|
||||||
|
override val searchLibrary = "Поиск"
|
||||||
|
override val closeSearch = "Закрыть поиск"
|
||||||
|
override val clearSearch = "Очистить поиск"
|
||||||
|
override val noMatches = "Ничего не найдено"
|
||||||
|
override val scanFolderOrChooseFilter = "Импортируйте папку или выберите другой фильтр библиотеки."
|
||||||
|
override val favorite = "Избранное"
|
||||||
|
override val unknownAuthor = "Автор неизвестен"
|
||||||
|
override val noMetadata = "Нет метаданных"
|
||||||
|
override val lastReadPrefix = "Читали"
|
||||||
|
override val open = "Открыть"
|
||||||
|
override val markAsRead = "Отметить прочитанной"
|
||||||
|
override val markAsUnread = "Отметить непрочитанной"
|
||||||
|
override val markToRead = "Отложить к чтению"
|
||||||
|
override val removeToRead = "Убрать из отложенного"
|
||||||
|
override val removeMarks = "Снять отметки"
|
||||||
|
override val notInterested = "Не интересно"
|
||||||
|
override val clearMarks = "Очистить отметки"
|
||||||
|
override val addFavorite = "Добавить в избранное"
|
||||||
|
override val removeFavorite = "Убрать из избранного"
|
||||||
|
override val delete = "Удалить"
|
||||||
|
|
||||||
|
override val filterReadingNow = "Сейчас читаю"
|
||||||
|
override val filterRecentlyAdded = "Недавно добавленные"
|
||||||
|
override val filterMyLibrary = "Моя библиотека"
|
||||||
|
override val filterToRead = "К чтению"
|
||||||
|
override val filterRead = "Прочитанные"
|
||||||
|
|
||||||
|
override val scan = "Импорт"
|
||||||
|
override val rootFolder = "Корневая папка"
|
||||||
|
override val choose = "Выбрать"
|
||||||
|
override val logPrefix = "Лог"
|
||||||
|
|
||||||
|
override val bookInfo = "Информация о книге"
|
||||||
|
override val back = "Назад"
|
||||||
|
override val backToLibrary = "Вернуться в библиотеку"
|
||||||
|
override val backToReader = "Вернуться к чтению"
|
||||||
|
override val titleInfo = "Описание"
|
||||||
|
override val title = "Название"
|
||||||
|
override val authors = "Авторы"
|
||||||
|
override val language = "Язык"
|
||||||
|
override val date = "Дата"
|
||||||
|
override val genres = "Жанры"
|
||||||
|
override val source = "Исходный язык"
|
||||||
|
override val translator = "Переводчик"
|
||||||
|
override val notSpecified = "Не указано"
|
||||||
|
override val statistics = "Статистика"
|
||||||
|
override val words = "Слова"
|
||||||
|
override val sections = "Разделы"
|
||||||
|
override val images = "Иллюстрации"
|
||||||
|
override val sourceFile = "Исходный файл"
|
||||||
|
override val fileName = "Имя файла"
|
||||||
|
override val filePath = "Путь"
|
||||||
|
override val lastReadingPosition = "Последняя позиция чтения"
|
||||||
|
override val noSavedPosition = "Позиция не сохранена"
|
||||||
|
override val listItem = "Элемент списка"
|
||||||
|
override val scrollOffset = "Смещение прокрутки"
|
||||||
|
override val bookmarks = "Закладки"
|
||||||
|
override val bookmark = "Закладка"
|
||||||
|
override val noBookmarks = "Закладок нет"
|
||||||
|
override val notes = "Заметки"
|
||||||
|
override val noNotes = "Заметок нет"
|
||||||
|
override val loading = "Загрузка..."
|
||||||
|
override val noImage = "Нет изображения"
|
||||||
|
|
||||||
|
override val readerTheme = "Тема"
|
||||||
|
override val tableOfContents = "Содержание"
|
||||||
|
override val backToLastPosition = "Назад"
|
||||||
|
override val readAloud = "Читать вслух"
|
||||||
|
override val readerMenu = "Меню чтения"
|
||||||
|
override val info = "Информация..."
|
||||||
|
override val readerSettings = "Настройки"
|
||||||
|
override val fullScreen = "На весь экран"
|
||||||
|
override val readerFontSizeIncrease = "Увеличить шрифт"
|
||||||
|
override val readerFontSizeDecrease = "Уменьшить шрифт"
|
||||||
|
override val readerLineHeightIncrease = "Увеличить межстрочный интервал"
|
||||||
|
override val readerLineHeightDecrease = "Уменьшить межстрочный интервал"
|
||||||
|
override val readerFontWeightIncrease = "Увеличить насыщенность шрифта"
|
||||||
|
override val readerFontWeightDecrease = "Уменьшить насыщенность шрифта"
|
||||||
|
override val resetReaderFontSettings = "Сбросить настройки шрифта"
|
||||||
|
override val revertColorScheme = "Вернуть цветовую схему"
|
||||||
|
override val readerBackgroundColor = "Цвет фона чтения"
|
||||||
|
override val readerTextColor = "Цвет текста чтения"
|
||||||
|
override val extraReaderSettings = "Дополнительные настройки"
|
||||||
|
override val customColor = "Свой цвет"
|
||||||
|
override val red = "К"
|
||||||
|
override val green = "З"
|
||||||
|
override val blue = "С"
|
||||||
|
override val readerColors = "Цвета"
|
||||||
|
override val readerTypography = "Типографика"
|
||||||
|
override val readerLayout = "Макет"
|
||||||
|
override val readerNavigation = "Навигация"
|
||||||
|
override val readerPagingOnly = "Постраничный режим (без прокрутки)"
|
||||||
|
override val readerProgress = "Прогресс"
|
||||||
|
override val closeReaderSettings = "Закрыть настройки чтения"
|
||||||
|
override val share = "Поделиться"
|
||||||
|
override val viewFile = "Показать файл"
|
||||||
|
override val previousSentence = "Предыдущее предложение"
|
||||||
|
override val stopReading = "Остановить чтение"
|
||||||
|
override val startReading = "Начать чтение"
|
||||||
|
override val nextSentence = "Следующее предложение"
|
||||||
|
override val readAloudSettings = "Настройки чтения вслух"
|
||||||
|
override val ttsEngine = "Движок TTS"
|
||||||
|
override val systemDefault = "Системный по умолчанию"
|
||||||
|
override val offlineVoice = "Офлайн-голос"
|
||||||
|
override val autoRussian = "Авто: русский"
|
||||||
|
override val loadingVoices = "Загружаем голоса..."
|
||||||
|
override val preparingSpeech = "Подготавливаем речь…"
|
||||||
|
override val offlineSpeechModelMissing = "Сначала загрузите офлайн-модель речи по инструкции для компьютера."
|
||||||
|
override val speechPlaybackFailed = "Не удалось воспроизвести речь. Проверьте офлайн-модель и вывод звука и попробуйте снова."
|
||||||
|
|
||||||
|
override val imageCopied = "Изображение скопировано"
|
||||||
|
override val copyFailed = "Не удалось скопировать"
|
||||||
|
override val zoomIn = "Увеличить"
|
||||||
|
override val zoomOut = "Уменьшить"
|
||||||
|
override val copyImage = "Скопировать изображение"
|
||||||
|
|
||||||
|
override val chooseLibraryFolder = "Выберите папку библиотеки"
|
||||||
|
override val downloads = "Загрузки"
|
||||||
|
override val otherFolder = "Другая папка..."
|
||||||
|
override val play = "Пуск"
|
||||||
|
override val stop = "Стоп"
|
||||||
|
override val previous = "Назад"
|
||||||
|
override val next = "Вперед"
|
||||||
|
override val readingInBackground = "Чтение в фоне"
|
||||||
|
override val shareBook = "Поделиться книгой"
|
||||||
|
override val couldNotLoadAndroidTtsEngines = "Не удалось загрузить Android TTS-движки."
|
||||||
|
override val couldNotLoadSelectedTtsVoices = "Не удалось загрузить голоса для выбранного TTS-движка."
|
||||||
|
override val noOfflineVoices = "Выбранный TTS-движок не сообщил об офлайн-голосах."
|
||||||
|
|
||||||
|
override fun themeChanged(mode: ThemeMode): String = "$theme: ${mode.localizedName()}"
|
||||||
|
override fun removed(title: String): String = "Удалено: $title."
|
||||||
|
override fun restored(title: String): String = "Восстановлено: $title."
|
||||||
|
override fun couldNotRemove(title: String): String = "Не удалось удалить: $title."
|
||||||
|
override fun couldNotOpen(displayName: String): String = "Не удалось открыть $displayName."
|
||||||
|
override fun couldNotReopenLastBook(): String = "Не удалось открыть последнюю книгу."
|
||||||
|
override fun scanReport(scanned: Int, imported: Int, skipped: Int, failed: Int): String =
|
||||||
|
"Проверено: $scanned, импортировано: $imported, пропущено: $skipped, ошибок: $failed."
|
||||||
|
override val noNewBooksFound = "Ничего нового не найдено."
|
||||||
|
override val show = "Показать"
|
||||||
|
override fun newBooksAdded(count: Int): String =
|
||||||
|
when {
|
||||||
|
count % 10 == 1 && count % 100 != 11 -> "$count новая книга добавлена."
|
||||||
|
count % 10 in 2..4 && count % 100 !in 12..14 -> "$count новые книги добавлены."
|
||||||
|
else -> "$count новых книг добавлено."
|
||||||
|
}
|
||||||
|
override fun rescanReport(scanned: Int, updated: Int, failed: Int): String =
|
||||||
|
"Пересканировано: $scanned, обновлено: $updated, ошибок: $failed."
|
||||||
|
override fun checkingFile(currentFile: String?, scanned: Int, imported: Int, skipped: Int, failed: Int): String =
|
||||||
|
buildString {
|
||||||
|
append("Проверяем")
|
||||||
|
currentFile?.takeIf(String::isNotBlank)?.let { append(" $it") }
|
||||||
|
append(". Найдено поддерживаемых файлов: $scanned")
|
||||||
|
append(", импортировано: $imported")
|
||||||
|
append(", пропущено: $skipped")
|
||||||
|
append(", ошибок: $failed.")
|
||||||
|
}
|
||||||
|
override fun importedSkippedFailed(imported: Int, skipped: Int, failed: Int): String =
|
||||||
|
"Импортировано: $imported, пропущено: $skipped, ошибок: $failed"
|
||||||
|
override fun scannedBooks(scanned: Int): String = "Импортировано книг: $scanned"
|
||||||
|
override fun scannedProgress(scanned: Int, total: Int, percent: Int): String =
|
||||||
|
"Импорт: $scanned из $total, готово $percent%"
|
||||||
|
override fun noBooksIn(filterLabel: String): String = "Нет книг: ${filterLabel.lowercase()}"
|
||||||
|
override fun bookMenuFor(title: String): String = "Меню книги: $title"
|
||||||
|
override fun markedAsRead(title: String?): String =
|
||||||
|
title?.let { "Отмечено как прочитанное: $it." } ?: "Отмечено как прочитанное."
|
||||||
|
override fun markedAsUnread(title: String): String = "Отмечено как непрочитанное: $title."
|
||||||
|
override fun markedToRead(title: String?): String =
|
||||||
|
title?.let { "Отложено к чтению: $it." } ?: "Отложено к чтению."
|
||||||
|
override fun markedNotInterested(title: String?): String =
|
||||||
|
title?.let { "Отмечено как неинтересное: $it." } ?: "Отмечено как неинтересное."
|
||||||
|
override fun removedMarks(title: String?): String =
|
||||||
|
title?.let { "Сняты отметки: $it." } ?: "Отметки сняты."
|
||||||
|
override fun addedToFavorites(title: String?): String =
|
||||||
|
title?.let { "Добавлено в избранное: $it." } ?: "Добавлено в избранное."
|
||||||
|
override fun removedFromFavorites(title: String?): String =
|
||||||
|
title?.let { "Убрано из избранного: $it." } ?: "Убрано из избранного."
|
||||||
|
override fun couldNotUpdate(title: String): String = "Не удалось обновить: $title."
|
||||||
|
override fun shareOpened(): String = "Открыто окно отправки."
|
||||||
|
override fun couldNotShareBook(): String = "Не удалось поделиться книгой."
|
||||||
|
override fun openedFileLocation(): String = "Расположение файла открыто."
|
||||||
|
override fun couldNotOpenFileLocation(): String = "Не удалось открыть расположение файла."
|
||||||
|
override fun allFilesAccessRequired(path: String): String = "Для сканирования $path нужен доступ ко всем файлам."
|
||||||
|
override fun couldNotRead(name: String): String = "Не удалось прочитать $name"
|
||||||
|
override fun progressLabel(progress: Double?): String =
|
||||||
|
progress?.let { "Прогресс ${(it * 100).roundToInt()}%" } ?: "Прогресс не записан"
|
||||||
|
override fun appLanguageName(language: AppLanguage): String =
|
||||||
|
when (language) {
|
||||||
|
AppLanguage.English -> "Английский"
|
||||||
|
AppLanguage.Russian -> "Русский"
|
||||||
|
}
|
||||||
|
override fun sectionFallback(index: Int): String = "Раздел ${index + 1}"
|
||||||
|
override fun readingStatus(status: BookReadingStatus): String =
|
||||||
|
when (status) {
|
||||||
|
BookReadingStatus.NEW -> "Новая"
|
||||||
|
BookReadingStatus.TO_READ -> "К чтению"
|
||||||
|
BookReadingStatus.READING -> "Читаю"
|
||||||
|
BookReadingStatus.READ -> "Прочитана"
|
||||||
|
BookReadingStatus.NOT_INTERESTED -> "Не интересно"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ThemeMode.localizedName(): String =
|
||||||
|
when (this) {
|
||||||
|
ThemeMode.LIGHT -> strings.themeLight
|
||||||
|
ThemeMode.DARK -> strings.themeDark
|
||||||
|
ThemeMode.SYSTEM -> strings.themeSystem
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package net.sergeych.toread
|
||||||
|
|
||||||
|
internal data class ReadAloudBlockRange(val position: Int, val start: Int, val endExclusive: Int)
|
||||||
|
|
||||||
|
internal data class ReadAloudBlock(
|
||||||
|
val text: String,
|
||||||
|
val ranges: List<ReadAloudBlockRange>,
|
||||||
|
val pauseBeforeMillis: Long,
|
||||||
|
val pauseAfterMillis: Long,
|
||||||
|
) {
|
||||||
|
fun positionAt(offset: Int): Int =
|
||||||
|
ranges.lastOrNull { it.start <= offset }?.position ?: ranges.first().position
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Paragraph-sized requests. Android's hard limit counts UTF-16 characters, never UTF-8 bytes.
|
||||||
|
* Whole sentences are retained whenever they fit. An oversized sentence is split at whitespace,
|
||||||
|
* or, for an oversized word, between Unicode code points (never inside a surrogate pair).
|
||||||
|
*/
|
||||||
|
internal fun readAloudBlocks(
|
||||||
|
sentences: List<ReadAloudSentence>,
|
||||||
|
startIndex: Int,
|
||||||
|
maxLength: Int,
|
||||||
|
): Sequence<ReadAloudBlock> = sequence {
|
||||||
|
require(maxLength >= 2)
|
||||||
|
var text = StringBuilder()
|
||||||
|
var ranges = mutableListOf<ReadAloudBlockRange>()
|
||||||
|
var before = 0L
|
||||||
|
var after = 0L
|
||||||
|
var item: Int? = null
|
||||||
|
|
||||||
|
suspend fun SequenceScope<ReadAloudBlock>.flush() {
|
||||||
|
if (ranges.isEmpty()) return
|
||||||
|
yield(ReadAloudBlock(text.toString(), ranges.toList(), before, after))
|
||||||
|
text = StringBuilder()
|
||||||
|
ranges = mutableListOf()
|
||||||
|
before = 0L
|
||||||
|
after = 0L
|
||||||
|
}
|
||||||
|
|
||||||
|
for (position in startIndex.coerceAtLeast(0) until sentences.size) {
|
||||||
|
val sentence = sentences[position]
|
||||||
|
if (item != sentence.itemIndex || sentence.pauseBeforeMillis > 0 || after > 0) flush()
|
||||||
|
item = sentence.itemIndex
|
||||||
|
var offset = 0
|
||||||
|
val spoken = sentence.spokenText
|
||||||
|
while (offset < spoken.length) {
|
||||||
|
// Do not split a sentence just to fill the previous block.
|
||||||
|
if (text.isNotEmpty() && text.length + 1 + spoken.length - offset > maxLength) flush()
|
||||||
|
if (ranges.isEmpty()) before = if (offset == 0) sentence.pauseBeforeMillis else 0L
|
||||||
|
var end = minOf(spoken.length, offset + maxLength)
|
||||||
|
if (end < spoken.length) {
|
||||||
|
if (spoken[end - 1].isHighSurrogate() && spoken[end].isLowSurrogate()) end--
|
||||||
|
val whitespace = (end - 1 downTo offset + 1).firstOrNull { spoken[it].isWhitespace() }
|
||||||
|
if (whitespace != null) end = whitespace
|
||||||
|
}
|
||||||
|
if (text.isNotEmpty()) text.append(' ')
|
||||||
|
val start = text.length
|
||||||
|
text.append(spoken.substring(offset, end))
|
||||||
|
ranges += ReadAloudBlockRange(position, start, text.length)
|
||||||
|
offset = end
|
||||||
|
while (offset < spoken.length && spoken[offset].isWhitespace()) offset++
|
||||||
|
after = if (offset == spoken.length) sentence.pauseAfterMillis else 0L
|
||||||
|
if (offset < spoken.length || text.length >= maxLength || after > 0) flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flush()
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ data class ReadAloudSentence(
|
|||||||
val start: Int,
|
val start: Int,
|
||||||
val endExclusive: Int,
|
val endExclusive: Int,
|
||||||
val text: String,
|
val text: String,
|
||||||
|
val spokenText: String = text,
|
||||||
val pauseBeforeMillis: Long = 0,
|
val pauseBeforeMillis: Long = 0,
|
||||||
val pauseAfterMillis: Long = 0,
|
val pauseAfterMillis: Long = 0,
|
||||||
)
|
)
|
||||||
@@ -16,14 +17,48 @@ data class ReadAloudState(
|
|||||||
val active: Boolean = false,
|
val active: Boolean = false,
|
||||||
val playing: Boolean = false,
|
val playing: Boolean = false,
|
||||||
val sentenceIndex: Int? = null,
|
val sentenceIndex: Int? = null,
|
||||||
|
val buffering: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ReadAloudEngineOption(
|
||||||
|
val id: String,
|
||||||
|
val label: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ReadAloudVoiceOption(
|
||||||
|
val id: String,
|
||||||
|
val label: String,
|
||||||
|
val localeTag: String,
|
||||||
|
val networkRequired: Boolean,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ReadAloudTextReplacement(
|
||||||
|
val from: String,
|
||||||
|
val to: String,
|
||||||
|
val caseSensitive: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ReadAloudSettingsState(
|
||||||
|
val engines: List<ReadAloudEngineOption> = emptyList(),
|
||||||
|
val selectedEngineId: String? = null,
|
||||||
|
val voices: List<ReadAloudVoiceOption> = emptyList(),
|
||||||
|
val selectedVoiceId: String? = null,
|
||||||
|
val textReplacements: List<ReadAloudTextReplacement> = emptyList(),
|
||||||
|
val loading: Boolean = false,
|
||||||
|
val message: String? = null,
|
||||||
|
val usesSystemDefaults: Boolean = true,
|
||||||
)
|
)
|
||||||
|
|
||||||
expect object ReadAloudPlatform {
|
expect object ReadAloudPlatform {
|
||||||
val isSupported: Boolean
|
val isSupported: Boolean
|
||||||
val state: StateFlow<ReadAloudState>
|
val state: StateFlow<ReadAloudState>
|
||||||
|
val settingsState: StateFlow<ReadAloudSettingsState>
|
||||||
|
|
||||||
fun prepare(bookTitle: String, sentences: List<ReadAloudSentence>, startIndex: Int)
|
fun prepare(fileId: String, bookTitle: String, sentences: List<ReadAloudSentence>, startIndex: Int)
|
||||||
fun play()
|
fun play()
|
||||||
fun stop()
|
fun stop()
|
||||||
fun skip(delta: Int)
|
fun skip(delta: Int)
|
||||||
|
fun refreshSettings()
|
||||||
|
fun selectEngine(engineId: String?)
|
||||||
|
fun selectVoice(voiceId: String?)
|
||||||
}
|
}
|
||||||
@@ -55,10 +55,10 @@ internal fun ScanScreen(
|
|||||||
Scaffold(
|
Scaffold(
|
||||||
topBar = {
|
topBar = {
|
||||||
CenterAlignedTopAppBar(
|
CenterAlignedTopAppBar(
|
||||||
title = { Text("Scan") },
|
title = { Text(strings.scan) },
|
||||||
navigationIcon = {
|
navigationIcon = {
|
||||||
IconButton(onClick = { onStateChange(AppState.Library(state.items, scanPath, message)) }) {
|
IconButton(onClick = { onStateChange(AppState.Library(state.items, scanPath, message, state.selectedFilter)) }) {
|
||||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back to library")
|
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = strings.backToLibrary)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
colors = themedTopAppBarColors(),
|
colors = themedTopAppBarColors(),
|
||||||
@@ -83,21 +83,21 @@ internal fun ScanScreen(
|
|||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = scanPath,
|
value = scanPath,
|
||||||
onValueChange = { scanPath = it },
|
onValueChange = { scanPath = it },
|
||||||
label = { Text("Root folder") },
|
label = { Text(strings.rootFolder) },
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
)
|
)
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) {
|
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
Button(
|
Button(
|
||||||
onClick = {
|
onClick = {
|
||||||
message = "Scanning..."
|
message = strings.scanning
|
||||||
onStartScan(scanPath)
|
onStartScan(scanPath)
|
||||||
},
|
},
|
||||||
enabled = !busy && scanPath.isNotBlank(),
|
enabled = !busy && scanPath.isNotBlank(),
|
||||||
) {
|
) {
|
||||||
Icon(Icons.Filled.Scanner, contentDescription = null)
|
Icon(Icons.Filled.Scanner, contentDescription = null)
|
||||||
Spacer(Modifier.width(8.dp))
|
Spacer(Modifier.width(8.dp))
|
||||||
Text("Scan")
|
Text(strings.scan)
|
||||||
}
|
}
|
||||||
FilledTonalButton(
|
FilledTonalButton(
|
||||||
onClick = {
|
onClick = {
|
||||||
@@ -109,7 +109,7 @@ internal fun ScanScreen(
|
|||||||
) {
|
) {
|
||||||
Icon(Icons.Filled.FolderOpen, contentDescription = null)
|
Icon(Icons.Filled.FolderOpen, contentDescription = null)
|
||||||
Spacer(Modifier.width(8.dp))
|
Spacer(Modifier.width(8.dp))
|
||||||
Text("Choose")
|
Text(strings.choose)
|
||||||
}
|
}
|
||||||
if (busy) {
|
if (busy) {
|
||||||
CircularProgressIndicator(modifier = Modifier.width(24.dp).height(24.dp), strokeWidth = 2.dp)
|
CircularProgressIndicator(modifier = Modifier.width(24.dp).height(24.dp), strokeWidth = 2.dp)
|
||||||
@@ -126,7 +126,7 @@ internal fun ScanScreen(
|
|||||||
Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.secondary)
|
Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.secondary)
|
||||||
}
|
}
|
||||||
libraryLogPath()?.let {
|
libraryLogPath()?.let {
|
||||||
Text("Log: $it", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.outline)
|
Text("${strings.logPrefix}: $it", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.outline)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -136,12 +136,4 @@ internal fun ScanScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun LibraryScanProgress.toScanMessage(): String =
|
private fun LibraryScanProgress.toScanMessage(): String =
|
||||||
buildString {
|
strings.checkingFile(currentFile, scannedFiles, importedFiles, skippedFiles, failedFiles)
|
||||||
append("Checking")
|
|
||||||
currentFile?.takeIf(String::isNotBlank)?.let { append(" $it") }
|
|
||||||
append(". Found $scannedFiles supported files")
|
|
||||||
append(", imported $importedFiles")
|
|
||||||
append(", skipped $skippedFiles")
|
|
||||||
append(", failed $failedFiles")
|
|
||||||
append(".")
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package net.sergeych.toread
|
package net.sergeych.toread
|
||||||
|
|
||||||
|
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.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
@@ -22,15 +23,48 @@ import androidx.compose.runtime.Composable
|
|||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.graphics.Brush
|
import androidx.compose.ui.graphics.Brush
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.graphics.SolidColor
|
import androidx.compose.ui.graphics.SolidColor
|
||||||
|
import androidx.compose.ui.graphics.lerp
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
internal fun LoadingScreen(message: String) {
|
internal fun LoadingScreen(message: String) {
|
||||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
Box(
|
||||||
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(14.dp)) {
|
Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.background(MaterialTheme.colorScheme.background),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
LoadingPanel(message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun LoadingOverlay(message: String, modifier: Modifier = Modifier) {
|
||||||
|
Box(
|
||||||
|
modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.background(MaterialTheme.colorScheme.background.copy(alpha = 0.58f)),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
LoadingPanel(message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun LoadingPanel(message: String) {
|
||||||
|
Card(
|
||||||
|
shape = RoundedCornerShape(8.dp),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.padding(horizontal = 20.dp, vertical = 18.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
) {
|
||||||
CircularProgressIndicator()
|
CircularProgressIndicator()
|
||||||
Text(message, style = MaterialTheme.typography.bodyMedium)
|
Text(message, style = MaterialTheme.typography.bodyMedium)
|
||||||
}
|
}
|
||||||
@@ -42,10 +76,10 @@ internal fun ErrorScreen(message: String, onBack: () -> Unit) {
|
|||||||
Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) {
|
Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) {
|
||||||
Card(shape = RoundedCornerShape(8.dp), colors = quietCardColors()) {
|
Card(shape = RoundedCornerShape(8.dp), colors = quietCardColors()) {
|
||||||
Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
Text("Library error", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
|
Text(strings.libraryError, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
|
||||||
Text(message, style = MaterialTheme.typography.bodyMedium)
|
Text(message, style = MaterialTheme.typography.bodyMedium)
|
||||||
TextButton(onClick = onBack) {
|
TextButton(onClick = onBack) {
|
||||||
Text("Retry")
|
Text(strings.retry)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -107,9 +141,27 @@ internal fun themedTopAppBarColors(): TopAppBarColors =
|
|||||||
@Composable
|
@Composable
|
||||||
internal fun readerBackground(): Brush = SolidColor(MaterialTheme.colorScheme.background)
|
internal fun readerBackground(): Brush = SolidColor(MaterialTheme.colorScheme.background)
|
||||||
|
|
||||||
|
internal fun Long.toComposeColor(): Color =
|
||||||
|
Color(
|
||||||
|
alpha = ((this shr 24) and 0xFF).toInt(),
|
||||||
|
red = ((this shr 16) and 0xFF).toInt(),
|
||||||
|
green = ((this shr 8) and 0xFF).toInt(),
|
||||||
|
blue = (this and 0xFF).toInt(),
|
||||||
|
)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun readerImageBackgroundColor(): Color {
|
||||||
|
val surface = MaterialTheme.colorScheme.surface
|
||||||
|
return if (surface.isVisuallyDark()) lerp(surface, Color.White, 0.5f) else surface
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Color.isVisuallyDark(): Boolean {
|
||||||
|
val luminance = 0.2126f * red + 0.7152f * green + 0.0722f * blue
|
||||||
|
return luminance < 0.5f
|
||||||
|
}
|
||||||
|
|
||||||
internal fun Int.formatCompact(): String =
|
internal fun Int.formatCompact(): String =
|
||||||
if (this >= 10_000) "${(this / 1000.0).roundToInt()}k" else toString()
|
if (this >= 10_000) "${(this / 1000.0).roundToInt()}k" else toString()
|
||||||
|
|
||||||
internal fun Double?.progressLabel(): String =
|
internal fun Double?.progressLabel(): String =
|
||||||
this?.let { "Progress ${(it * 100).roundToInt()}%" } ?: "Progress not recorded"
|
strings.progressLabel(this)
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
package net.sergeych.toread
|
package net.sergeych.toread
|
||||||
|
|
||||||
|
import androidx.compose.runtime.compositionLocalOf
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
|
|
||||||
|
internal val LocalReaderThemeIsDark = compositionLocalOf { false }
|
||||||
|
|
||||||
internal fun ThemeMode.next(): ThemeMode =
|
internal fun ThemeMode.next(): ThemeMode =
|
||||||
when (this) {
|
when (this) {
|
||||||
ThemeMode.SYSTEM -> ThemeMode.LIGHT
|
ThemeMode.SYSTEM -> ThemeMode.LIGHT
|
||||||
@@ -9,13 +12,6 @@ internal fun ThemeMode.next(): ThemeMode =
|
|||||||
ThemeMode.DARK -> ThemeMode.SYSTEM
|
ThemeMode.DARK -> ThemeMode.SYSTEM
|
||||||
}
|
}
|
||||||
|
|
||||||
internal val ThemeMode.displayName: String
|
|
||||||
get() = when (this) {
|
|
||||||
ThemeMode.LIGHT -> "Light"
|
|
||||||
ThemeMode.DARK -> "Dark"
|
|
||||||
ThemeMode.SYSTEM -> "System"
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun lightReaderColorScheme() = androidx.compose.material3.lightColorScheme(
|
internal fun lightReaderColorScheme() = androidx.compose.material3.lightColorScheme(
|
||||||
primary = Color(0xFF425D56),
|
primary = Color(0xFF425D56),
|
||||||
onPrimary = Color.White,
|
onPrimary = Color.White,
|
||||||
@@ -28,6 +24,9 @@ internal fun lightReaderColorScheme() = androidx.compose.material3.lightColorSch
|
|||||||
surface = Color(0xFFFFFBF5),
|
surface = Color(0xFFFFFBF5),
|
||||||
surfaceVariant = Color(0xFFE7DFD3),
|
surfaceVariant = Color(0xFFE7DFD3),
|
||||||
onSurface = Color(0xFF24211D),
|
onSurface = Color(0xFF24211D),
|
||||||
|
inverseSurface = Color(0xFF3A322C),
|
||||||
|
inverseOnSurface = Color(0xFFF7F2EA),
|
||||||
|
inversePrimary = Color(0xFFAFCFC4),
|
||||||
outline = Color(0xFF8C8174),
|
outline = Color(0xFF8C8174),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -43,5 +42,8 @@ internal fun darkReaderColorScheme() = androidx.compose.material3.darkColorSchem
|
|||||||
surface = Color(0xFF211D19),
|
surface = Color(0xFF211D19),
|
||||||
surfaceVariant = Color(0xFF4E463D),
|
surfaceVariant = Color(0xFF4E463D),
|
||||||
onSurface = Color(0xFFECE0D4),
|
onSurface = Color(0xFFECE0D4),
|
||||||
|
inverseSurface = Color(0xFFECE0D4),
|
||||||
|
inverseOnSurface = Color(0xFF24211D),
|
||||||
|
inversePrimary = Color(0xFF425D56),
|
||||||
outline = Color(0xFFA99E91),
|
outline = Color(0xFFA99E91),
|
||||||
)
|
)
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package net.sergeych.toread
|
||||||
|
|
||||||
|
import net.sergeych.toread.storage.BookReadingStatus
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
|
||||||
|
class LibraryScreenItemListTest {
|
||||||
|
@Test
|
||||||
|
fun myLibraryShowsAllBooksExceptNotInterested() {
|
||||||
|
val items = listOf(
|
||||||
|
libraryItem("file-reading", "Reading", BookReadingStatus.READING),
|
||||||
|
libraryItem("file-to-read", "To Read", BookReadingStatus.TO_READ),
|
||||||
|
libraryItem("file-read", "Read", BookReadingStatus.READ),
|
||||||
|
libraryItem("file-new", "New", BookReadingStatus.NEW),
|
||||||
|
libraryItem("file-not-interested", "Not Interested", BookReadingStatus.NOT_INTERESTED),
|
||||||
|
)
|
||||||
|
|
||||||
|
val filtered = items.myLibraryItems()
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
listOf("file-new", "file-read", "file-reading", "file-to-read"),
|
||||||
|
filtered.map { it.fileId },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun libraryItem(
|
||||||
|
fileId: String,
|
||||||
|
title: String,
|
||||||
|
readingStatus: BookReadingStatus = BookReadingStatus.NEW,
|
||||||
|
): LibraryItem =
|
||||||
|
LibraryItem(
|
||||||
|
fileId = fileId,
|
||||||
|
bookId = "book-$fileId",
|
||||||
|
title = title,
|
||||||
|
format = "fb2",
|
||||||
|
sizeBytes = null,
|
||||||
|
storageUri = null,
|
||||||
|
lastSeenAt = null,
|
||||||
|
readingStatus = readingStatus,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package net.sergeych.toread
|
||||||
|
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
|
class ReadAloudBlocksTest {
|
||||||
|
private fun sentence(index: Int, item: Int, text: String, before: Long = 0, after: Long = 0) =
|
||||||
|
ReadAloudSentence(index, item, 0, text.length, text, pauseBeforeMillis = before, pauseAfterMillis = after)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun paragraphsKeepContextAndRangesUseSpokenText() {
|
||||||
|
val queue = listOf(
|
||||||
|
sentence(0, 1, "Первое.").copy(spokenText = "Пе́рвое."),
|
||||||
|
sentence(1, 1, "Второе."), sentence(2, 2, "Другой абзац."),
|
||||||
|
)
|
||||||
|
val blocks = readAloudBlocks(queue, 0, 4_000).toList()
|
||||||
|
assertEquals(listOf("Пе́рвое. Второе.", "Другой абзац."), blocks.map { it.text })
|
||||||
|
assertEquals(0, blocks[0].positionAt(0))
|
||||||
|
assertEquals(1, blocks[0].positionAt(9))
|
||||||
|
assertEquals(listOf("Второе.", "Другой абзац."), readAloudBlocks(queue, 1, 4_000).map { it.text }.toList())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun longParagraphBreaksBetweenSentencesAndCountsCharacters() {
|
||||||
|
val queue = (0..9).map { sentence(it, 1, "я".repeat(998) + ".") }
|
||||||
|
val blocks = readAloudBlocks(queue, 0, 4_000).toList()
|
||||||
|
assertEquals(listOf(3_999, 3_999, 1_999), blocks.map { it.text.length })
|
||||||
|
assertEquals((0..9).toList(), blocks.flatMap { it.ranges }.map { it.position })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun oversizedSentenceSplitsAtWordsAndNeverCutsSurrogatePairs() {
|
||||||
|
val words = List(20) { "Привет😀" }
|
||||||
|
val blocks = readAloudBlocks(listOf(sentence(0, 0, words.joinToString(" "))), 0, 30).toList()
|
||||||
|
assertEquals(words.joinToString(" "), blocks.joinToString(" ") { it.text })
|
||||||
|
assertTrue(blocks.all { it.text.length <= 30 })
|
||||||
|
val cyrillic = "я".repeat(9_001) + "."
|
||||||
|
val cyrillicBlocks = readAloudBlocks(listOf(sentence(0, 0, cyrillic)), 0, 4_000).toList()
|
||||||
|
assertEquals(cyrillic, cyrillicBlocks.joinToString("") { it.text })
|
||||||
|
assertEquals(listOf(4_000, 4_000, 1_002), cyrillicBlocks.map { it.text.length })
|
||||||
|
val giantWord = "😀".repeat(4_001)
|
||||||
|
val split = readAloudBlocks(listOf(sentence(0, 0, giantWord)), 0, 3_999).toList()
|
||||||
|
assertEquals(giantWord, split.joinToString("") { it.text })
|
||||||
|
assertTrue(split.all { it.text.length <= 3_999 && !it.text.last().isHighSurrogate() })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun pausesAndStartingPositionArePreserved() {
|
||||||
|
val queue = listOf(sentence(0, 0, "Skip."), sentence(1, 0, "Heading.", 1000, 600),
|
||||||
|
sentence(2, 1, "Wait.", after = 350), sentence(3, 1, "Go."))
|
||||||
|
val blocks = readAloudBlocks(queue, 1, 4_000).toList()
|
||||||
|
assertEquals(listOf("Heading.", "Wait.", "Go."), blocks.map { it.text })
|
||||||
|
assertEquals(listOf(1000L, 0L, 0L), blocks.map { it.pauseBeforeMillis })
|
||||||
|
assertEquals(listOf(600L, 350L, 0L), blocks.map { it.pauseAfterMillis })
|
||||||
|
assertEquals(listOf(1, 2, 3), blocks.map { it.ranges.first().position })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,378 @@
|
|||||||
|
package net.sergeych.toread
|
||||||
|
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import net.sergeych.toread.fb2.Fb2Block
|
||||||
|
import net.sergeych.toread.fb2.Fb2Book
|
||||||
|
import net.sergeych.toread.fb2.Fb2Epigraph
|
||||||
|
import net.sergeych.toread.fb2.Fb2EpigraphBlock
|
||||||
|
import net.sergeych.toread.fb2.Fb2ImageRef
|
||||||
|
import net.sergeych.toread.fb2.Fb2Poem
|
||||||
|
import net.sergeych.toread.fb2.Fb2PoemBlock
|
||||||
|
import net.sergeych.toread.fb2.Fb2Section
|
||||||
|
import net.sergeych.toread.fb2.Fb2Stanza
|
||||||
|
import net.sergeych.toread.fb2.Fb2Text
|
||||||
|
import net.sergeych.toread.fb2.Fb2TextSpan
|
||||||
|
|
||||||
|
class ReadAloudContentPlanTest {
|
||||||
|
@Test
|
||||||
|
fun starBreakAddsPauseBeforeNextSpokenSentence() {
|
||||||
|
val plan = buildReaderContentPlan(
|
||||||
|
Fb2Book(
|
||||||
|
title = "Book",
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(
|
||||||
|
blocks = listOf(
|
||||||
|
paragraph("Before."),
|
||||||
|
paragraph("* * *"),
|
||||||
|
paragraph("After."),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(listOf("Before.", "After."), plan.sentences.map { it.text })
|
||||||
|
assertEquals(0L, plan.sentences[0].pauseBeforeMillis)
|
||||||
|
assertEquals(1_200L, plan.sentences[1].pauseBeforeMillis)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun ellipsisIsCollapsedForSpeechAndAddsShortPause() {
|
||||||
|
val plan = buildReaderContentPlan(
|
||||||
|
Fb2Book(
|
||||||
|
title = "Book",
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(blocks = listOf(paragraph("Wait... Go.. Stop… Done."))),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
listOf("Wait...", "Go..", "Stop…", "Done."),
|
||||||
|
plan.sentences.map { it.text },
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
listOf("Wait.", "Go.", "Stop.", "Done."),
|
||||||
|
plan.sentences.map { it.spokenText },
|
||||||
|
)
|
||||||
|
assertEquals(listOf(350L, 350L, 350L, 0L), plan.sentences.map { it.pauseAfterMillis })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun dotsAfterQuestionOrExclamationAreRemovedForSpeech() {
|
||||||
|
val plan = buildReaderContentPlan(
|
||||||
|
Fb2Book(
|
||||||
|
title = "Book",
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(blocks = listOf(paragraph("What?.. No!.. Done."))),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
listOf("What?..", "No!..", "Done."),
|
||||||
|
plan.sentences.map { it.text },
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
listOf("What?", "No!", "Done."),
|
||||||
|
plan.sentences.map { it.spokenText },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun hardcodedReadAloudReplacementCanMarkStress() {
|
||||||
|
val plan = buildReaderContentPlan(
|
||||||
|
Fb2Book(
|
||||||
|
title = "Book",
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(blocks = listOf(paragraph("Господа, идите."))),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals("Господа, идите.", plan.sentences.single().text)
|
||||||
|
assertEquals("Господа́, идите.", plan.sentences.single().spokenText)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun hardcodedReadAloudReplacementsAreCaseSensitive() {
|
||||||
|
val plan = buildReaderContentPlan(
|
||||||
|
Fb2Book(
|
||||||
|
title = "Book",
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(blocks = listOf(paragraph("ГОСПОДА, идите."))),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals("ГОСПОДА, идите.", plan.sentences.single().spokenText)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun stressMarkersSupportRussianAndEnglishVowels() {
|
||||||
|
val plan = buildReaderContentPlan(
|
||||||
|
Fb2Book(
|
||||||
|
title = "Book",
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(
|
||||||
|
blocks = listOf(
|
||||||
|
paragraph(
|
||||||
|
"/а/е/ё/и/о/у/ы/э/ю/я " +
|
||||||
|
"/А/Е/Ё/И/О/У/Ы/Э/Ю/Я " +
|
||||||
|
"'a'e'i'o'u'y " +
|
||||||
|
"'A'E'I'O'U'Y.",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"а́е́ё́и́о́у́ы́э́ю́я́ " +
|
||||||
|
"А́Е́Ё́И́О́У́Ы́Э́Ю́Я́ " +
|
||||||
|
"áéíóúý " +
|
||||||
|
"ÁÉÍÓÚÝ.",
|
||||||
|
plan.sentences.single().spokenText,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun stressMarkersIgnoreNonStressableLetters() {
|
||||||
|
val plan = buildReaderContentPlan(
|
||||||
|
Fb2Book(
|
||||||
|
title = "Book",
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(blocks = listOf(paragraph("/б 'z /1."))),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals("/б 'z /1.", plan.sentences.single().spokenText)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun poemVersesAreIncludedInReadAloudPlan() {
|
||||||
|
val plan = buildReaderContentPlan(
|
||||||
|
Fb2Book(
|
||||||
|
title = "Book",
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(
|
||||||
|
blocks = listOf(
|
||||||
|
Fb2Block.Poem(
|
||||||
|
Fb2Poem(
|
||||||
|
blocks = listOf(
|
||||||
|
Fb2PoemBlock.Stanza(
|
||||||
|
Fb2Stanza(
|
||||||
|
verses = listOf(
|
||||||
|
text("Line one."),
|
||||||
|
text("Line two."),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(listOf("Line one.", "Line two."), plan.sentences.map { it.text })
|
||||||
|
assertEquals(1, plan.elements.filterIsInstance<ReaderElement.Poem>().size)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun epigraphsAreIncludedInReaderPlan() {
|
||||||
|
val plan = buildReaderContentPlan(
|
||||||
|
Fb2Book(
|
||||||
|
title = "Book",
|
||||||
|
bodyEpigraphs = listOf(
|
||||||
|
Fb2Epigraph(
|
||||||
|
blocks = listOf(Fb2EpigraphBlock.Paragraph(text("Body quote."))),
|
||||||
|
textAuthors = listOf(text("Body author.")),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(
|
||||||
|
blocks = listOf(
|
||||||
|
Fb2Block.Epigraph(
|
||||||
|
Fb2Epigraph(
|
||||||
|
blocks = listOf(Fb2EpigraphBlock.Paragraph(text("Section quote."))),
|
||||||
|
textAuthors = listOf(text("Section author.")),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(2, plan.elements.filterIsInstance<ReaderElement.Epigraph>().size)
|
||||||
|
assertEquals(
|
||||||
|
listOf("Body quote.", "Body author.", "Section quote.", "Section author."),
|
||||||
|
plan.sentences.map { it.text },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun wrapperOnlyTopSectionDoesNotIndentChildParagraphs() {
|
||||||
|
val plan = buildReaderContentPlan(
|
||||||
|
Fb2Book(
|
||||||
|
title = "Book",
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(
|
||||||
|
title = "Wrapper title",
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(
|
||||||
|
title = "Chapter",
|
||||||
|
blocks = listOf(paragraph("Chapter text.")),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(0, plan.elements.filterIsInstance<ReaderElement.Paragraph>().single().depth)
|
||||||
|
assertEquals(
|
||||||
|
listOf(0, 0),
|
||||||
|
plan.elements.filterIsInstance<ReaderElement.SectionTitle>().map { it.depth },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun titleOnlyPartSectionDoesNotIndentChaptersAfterFrontMatter() {
|
||||||
|
val plan = buildReaderContentPlan(
|
||||||
|
Fb2Book(
|
||||||
|
title = "Book",
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(
|
||||||
|
title = "Copyright",
|
||||||
|
blocks = listOf(paragraph("Copyright text.")),
|
||||||
|
),
|
||||||
|
Fb2Section(
|
||||||
|
title = "Part one",
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(
|
||||||
|
title = "Chapter one",
|
||||||
|
blocks = listOf(paragraph("Chapter text.")),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
listOf(0, 0),
|
||||||
|
plan.elements.filterIsInstance<ReaderElement.Paragraph>().map { it.depth },
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
listOf(0, 0, 0),
|
||||||
|
plan.elements.filterIsInstance<ReaderElement.SectionTitle>().map { it.depth },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun imageOnlyPartStructureDoesNotIndentWholeBook() {
|
||||||
|
val plan = buildReaderContentPlan(
|
||||||
|
Fb2Book(
|
||||||
|
title = "Book",
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(
|
||||||
|
title = "Wrapper title",
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(
|
||||||
|
images = listOf(Fb2ImageRef("#front.jpg")),
|
||||||
|
),
|
||||||
|
Fb2Section(
|
||||||
|
title = "Part one",
|
||||||
|
blocks = listOf(Fb2Block.Image(Fb2ImageRef("#part.png"))),
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(
|
||||||
|
title = "Chapter one",
|
||||||
|
blocks = listOf(paragraph("Chapter text.")),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(0, plan.elements.filterIsInstance<ReaderElement.Paragraph>().single().depth)
|
||||||
|
assertEquals(
|
||||||
|
listOf(0, 0, 0),
|
||||||
|
plan.elements.filterIsInstance<ReaderElement.SectionTitle>().map { it.depth },
|
||||||
|
)
|
||||||
|
assertEquals(listOf(0, 0, 0, 0), plan.tocEntries.map { it.depth })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun realNestedSectionsKeepRelativeIndent() {
|
||||||
|
val plan = buildReaderContentPlan(
|
||||||
|
Fb2Book(
|
||||||
|
title = "Book",
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(
|
||||||
|
title = "Part",
|
||||||
|
blocks = listOf(paragraph("Part text.")),
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(
|
||||||
|
title = "Nested chapter",
|
||||||
|
blocks = listOf(paragraph("Nested text.")),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
listOf(0, 1),
|
||||||
|
plan.elements.filterIsInstance<ReaderElement.Paragraph>().map { it.depth },
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
listOf(0, 1),
|
||||||
|
plan.elements.filterIsInstance<ReaderElement.SectionTitle>().map { it.depth },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun contentPlanIncludesClickableTableOfContentsEntries() {
|
||||||
|
val plan = buildReaderContentPlan(
|
||||||
|
Fb2Book(
|
||||||
|
title = "Book",
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(
|
||||||
|
title = "Part",
|
||||||
|
sections = listOf(
|
||||||
|
Fb2Section(
|
||||||
|
title = "Chapter",
|
||||||
|
blocks = listOf(paragraph("Chapter text.")),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Fb2Section(blocks = listOf(paragraph("Untitled text."))),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(listOf("Part", "Chapter", "Section 2"), plan.tocEntries.map { it.title })
|
||||||
|
assertEquals(listOf(0, 0, 0), plan.tocEntries.map { it.depth })
|
||||||
|
assertEquals(
|
||||||
|
plan.elements.filterIsInstance<ReaderElement.SectionTitle>().first(),
|
||||||
|
plan.elements[plan.tocEntries.first().itemIndex],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun paragraph(text: String): Fb2Block.Paragraph =
|
||||||
|
Fb2Block.Paragraph(text(text))
|
||||||
|
|
||||||
|
private fun text(text: String): Fb2Text =
|
||||||
|
Fb2Text(listOf(Fb2TextSpan(text)))
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package net.sergeych.toread
|
||||||
|
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
|
||||||
|
class ReaderLinkDetectionTest {
|
||||||
|
@Test
|
||||||
|
fun detectsWebUrlsAndTrimsSentencePunctuation() {
|
||||||
|
val text = "See http://example.org/path?q=1, then https://site.test/end."
|
||||||
|
|
||||||
|
val urls = text.webUrlRanges().map { text.substring(it) }
|
||||||
|
|
||||||
|
assertEquals(listOf("http://example.org/path?q=1", "https://site.test/end"), urls)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun ignoresNonWebUrls() {
|
||||||
|
val text = "ftp://files.test https://secure.test"
|
||||||
|
|
||||||
|
val urls = text.webUrlRanges().map { text.substring(it) }
|
||||||
|
|
||||||
|
assertEquals(listOf("https://secure.test"), urls)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,6 +20,7 @@ import java.awt.datatransfer.Transferable
|
|||||||
import java.awt.datatransfer.UnsupportedFlavorException
|
import java.awt.datatransfer.UnsupportedFlavorException
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.ByteArrayInputStream
|
import java.io.ByteArrayInputStream
|
||||||
|
import java.net.URI
|
||||||
import javax.imageio.ImageIO
|
import javax.imageio.ImageIO
|
||||||
import java.text.SimpleDateFormat
|
import java.text.SimpleDateFormat
|
||||||
import java.util.Date
|
import java.util.Date
|
||||||
@@ -36,6 +37,14 @@ import kotlinx.coroutines.Dispatchers
|
|||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
|
private var pendingOpenBookFile: File? = null
|
||||||
|
|
||||||
|
fun rememberPlatformOpenBookArguments(args: Array<String>) {
|
||||||
|
pendingOpenBookFile = args.asSequence()
|
||||||
|
.map(::File)
|
||||||
|
.firstOrNull { it.isFile && it.name.isSupportedBookFile() }
|
||||||
|
}
|
||||||
|
|
||||||
actual fun loadDefaultBookBytes(): ByteArray? {
|
actual fun loadDefaultBookBytes(): ByteArray? {
|
||||||
var current = File(System.getProperty("user.dir")).absoluteFile
|
var current = File(System.getProperty("user.dir")).absoluteFile
|
||||||
while (true) {
|
while (true) {
|
||||||
@@ -70,12 +79,31 @@ actual suspend fun copyImageToClipboard(bytes: ByteArray, mimeType: String, labe
|
|||||||
|
|
||||||
actual fun defaultLibraryScanPath(): String? = findProjectRoot()?.let { File(it, "test_books").absolutePath }
|
actual fun defaultLibraryScanPath(): String? = findProjectRoot()?.let { File(it, "test_books").absolutePath }
|
||||||
|
|
||||||
actual suspend fun loadPlatformOpenBookRequest(): PlatformOpenBookRequest? = null
|
actual suspend fun loadPlatformOpenBookRequest(): PlatformOpenBookRequest? = withContext(Dispatchers.IO) {
|
||||||
|
val file = pendingOpenBookFile ?: return@withContext null
|
||||||
|
pendingOpenBookFile = null
|
||||||
|
val bytes = file.readBytes()
|
||||||
|
val importResult = openLibraryDatabase().useLibrary { db ->
|
||||||
|
LibraryScanner(db, ::appendLibraryLog).importExternalFileAndGetResult(
|
||||||
|
bytes = bytes,
|
||||||
|
displayName = file.name,
|
||||||
|
storageUri = file.absolutePath,
|
||||||
|
sizeBytes = file.length(),
|
||||||
|
lastModifiedMillis = file.lastModified(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
appendLibraryLog("platform open imported=${importResult.imported} fileId=${importResult.fileId} path=${file.absolutePath}")
|
||||||
|
PlatformOpenBookRequest(
|
||||||
|
id = importResult.fileId,
|
||||||
|
displayName = file.name,
|
||||||
|
bytes = bytes,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
actual suspend fun chooseLibraryScanDirectory(): String? = withContext(Dispatchers.IO) {
|
actual suspend fun chooseLibraryScanDirectory(): String? = withContext(Dispatchers.IO) {
|
||||||
val chooser = JFileChooser(defaultLibraryScanPath())
|
val chooser = JFileChooser(defaultLibraryScanPath())
|
||||||
chooser.fileSelectionMode = JFileChooser.DIRECTORIES_ONLY
|
chooser.fileSelectionMode = JFileChooser.DIRECTORIES_ONLY
|
||||||
chooser.dialogTitle = "Choose library folder"
|
chooser.dialogTitle = strings.chooseLibraryFolder
|
||||||
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
|
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
|
||||||
chooser.selectedFile.absolutePath
|
chooser.selectedFile.absolutePath
|
||||||
} else {
|
} else {
|
||||||
@@ -94,6 +122,13 @@ actual suspend fun loadLibraryItemsPage(limit: Int, offset: Int): List<LibraryIt
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
actual suspend fun loadRecentlyAddedLibraryItems(sinceImportedAt: Long, limit: Int): List<LibraryItem> = withContext(Dispatchers.IO) {
|
||||||
|
appendLibraryLog("load recently added library items since=$sinceImportedAt limit=$limit")
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.files.listRecentlyAddedLibraryFiles(sinceImportedAt, limit).map { it.toLibraryItem() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
actual suspend fun searchLibraryItems(query: String, limit: Int): List<LibraryItem> = withContext(Dispatchers.IO) {
|
actual suspend fun searchLibraryItems(query: String, limit: Int): List<LibraryItem> = withContext(Dispatchers.IO) {
|
||||||
val prefixes = query.toSearchPrefixes()
|
val prefixes = query.toSearchPrefixes()
|
||||||
if (prefixes.isEmpty()) return@withContext emptyList()
|
if (prefixes.isEmpty()) return@withContext emptyList()
|
||||||
@@ -103,6 +138,8 @@ actual suspend fun searchLibraryItems(query: String, limit: Int): List<LibraryIt
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
actual fun currentLibraryTimeMillis(): Long = System.currentTimeMillis()
|
||||||
|
|
||||||
actual suspend fun loadLibraryItem(fileId: String): LibraryItem? = withContext(Dispatchers.IO) {
|
actual suspend fun loadLibraryItem(fileId: String): LibraryItem? = withContext(Dispatchers.IO) {
|
||||||
openLibraryDatabase().useLibrary { db ->
|
openLibraryDatabase().useLibrary { db ->
|
||||||
db.files.getLibraryFile(fileId)?.toLibraryItem()
|
db.files.getLibraryFile(fileId)?.toLibraryItem()
|
||||||
@@ -276,30 +313,84 @@ actual suspend fun markLibraryReadingStatus(fileId: String, status: BookReadingS
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
actual suspend fun markLibraryFavorite(fileId: String, favorite: Boolean): Boolean = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.files.updateFavorite(fileId, favorite)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
actual suspend fun shareLibraryBookFile(fileId: String): Boolean = false
|
actual suspend fun shareLibraryBookFile(fileId: String): Boolean = false
|
||||||
|
|
||||||
actual suspend fun viewLibraryBookFile(fileId: String): Boolean = withContext(Dispatchers.IO) {
|
actual suspend fun viewLibraryBookFile(folder: String, fileName: String): Boolean = withContext(Dispatchers.IO) {
|
||||||
runCatching {
|
runCatching {
|
||||||
if (!Desktop.isDesktopSupported()) return@withContext false
|
val directory = File(folder).takeIf { it.isDirectory } ?: return@withContext false
|
||||||
val file = openLibraryDatabase().useLibrary { db ->
|
val file = File(directory, fileName).takeIf { it.isFile } ?: return@withContext false
|
||||||
db.files.get(fileId)?.storageUri?.let(::File)?.takeIf { it.isFile }
|
selectOrOpenBookFile(directory, file)
|
||||||
} ?: return@withContext false
|
|
||||||
val desktop = Desktop.getDesktop()
|
|
||||||
if (desktop.isSupported(Desktop.Action.BROWSE_FILE_DIR)) {
|
|
||||||
desktop.browseFileDirectory(file)
|
|
||||||
} else {
|
|
||||||
desktop.open(file.parentFile ?: file)
|
|
||||||
}
|
|
||||||
true
|
|
||||||
}.getOrDefault(false)
|
}.getOrDefault(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
actual fun openPlatformUrl(url: String): Boolean =
|
||||||
|
runCatching {
|
||||||
|
if (!Desktop.isDesktopSupported() || !Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
|
||||||
|
return@runCatching false
|
||||||
|
}
|
||||||
|
Desktop.getDesktop().browse(URI(url))
|
||||||
|
true
|
||||||
|
}.getOrDefault(false)
|
||||||
|
|
||||||
|
private fun selectOrOpenBookFile(directory: File, file: File): Boolean {
|
||||||
|
if (isLinuxDesktop() && trySelectLinuxFile(file)) return true
|
||||||
|
if (!Desktop.isDesktopSupported()) return false
|
||||||
|
|
||||||
|
val desktop = Desktop.getDesktop()
|
||||||
|
return when {
|
||||||
|
desktop.isSupported(Desktop.Action.BROWSE_FILE_DIR) -> {
|
||||||
|
desktop.browseFileDirectory(file)
|
||||||
|
true
|
||||||
|
}
|
||||||
|
desktop.isSupported(Desktop.Action.OPEN) -> {
|
||||||
|
desktop.open(directory)
|
||||||
|
true
|
||||||
|
}
|
||||||
|
else -> false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isLinuxDesktop(): Boolean =
|
||||||
|
System.getProperty("os.name").orEmpty().lowercase(Locale.ROOT).contains("linux")
|
||||||
|
|
||||||
|
private fun trySelectLinuxFile(file: File): Boolean =
|
||||||
|
runCatching {
|
||||||
|
val process = ProcessBuilder(
|
||||||
|
"dbus-send",
|
||||||
|
"--session",
|
||||||
|
"--dest=org.freedesktop.FileManager1",
|
||||||
|
"--type=method_call",
|
||||||
|
"/org/freedesktop/FileManager1",
|
||||||
|
"org.freedesktop.FileManager1.ShowItems",
|
||||||
|
"array:string:${file.toURI()}",
|
||||||
|
"string:",
|
||||||
|
).start()
|
||||||
|
if (process.waitFor(2, TimeUnit.SECONDS)) {
|
||||||
|
process.exitValue() == 0
|
||||||
|
} else {
|
||||||
|
process.destroyForcibly()
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}.getOrDefault(false)
|
||||||
|
|
||||||
actual suspend fun loadBookInfoExtras(fileId: String): BookInfoExtras = withContext(Dispatchers.IO) {
|
actual suspend fun loadBookInfoExtras(fileId: String): BookInfoExtras = withContext(Dispatchers.IO) {
|
||||||
openLibraryDatabase().useLibrary { db ->
|
openLibraryDatabase().useLibrary { db ->
|
||||||
val file = db.files.get(fileId) ?: return@useLibrary BookInfoExtras()
|
val file = db.files.get(fileId) ?: return@useLibrary BookInfoExtras()
|
||||||
val clusterId = file.bodyClusterId ?: return@useLibrary BookInfoExtras()
|
val sourceFileName = file.originalFilename ?: file.storageUri?.substringAfterLast(File.separatorChar)
|
||||||
|
val clusterId = file.bodyClusterId ?: return@useLibrary BookInfoExtras(
|
||||||
|
sourceFileName = sourceFileName,
|
||||||
|
sourceFilePath = file.storageUri,
|
||||||
|
)
|
||||||
val readingPosition = db.readingStates.getForBodyCluster(clusterId)?.anchor?.formatHintsJson?.toReadingPosition()
|
val readingPosition = db.readingStates.getForBodyCluster(clusterId)?.anchor?.formatHintsJson?.toReadingPosition()
|
||||||
BookInfoExtras(
|
BookInfoExtras(
|
||||||
|
sourceFileName = sourceFileName,
|
||||||
|
sourceFilePath = file.storageUri,
|
||||||
bookmarks = db.bookmarks.listForBodyCluster(clusterId).map {
|
bookmarks = db.bookmarks.listForBodyCluster(clusterId).map {
|
||||||
BookmarkInfo(
|
BookmarkInfo(
|
||||||
title = it.title,
|
title = it.title,
|
||||||
@@ -346,6 +437,42 @@ actual suspend fun saveThemeMode(mode: ThemeMode) = withContext(Dispatchers.IO)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
actual suspend fun loadReaderFontSettings(): ReaderFontSettings = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
readerFontSettingsFromStorageValue(db.getAppFlag(ReaderFontSettingsFlag))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actual suspend fun saveReaderFontSettings(settings: ReaderFontSettings) = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.setAppFlag(ReaderFontSettingsFlag, settings.toStorageValue())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actual suspend fun loadReaderFullScreen(): Boolean = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.getAppFlag(ReaderFullScreenFlag)?.toBooleanStrictOrNull() ?: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actual suspend fun saveReaderFullScreen(fullScreen: Boolean) = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.setAppFlag(ReaderFullScreenFlag, fullScreen.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actual suspend fun loadReaderPagingOnly(): Boolean = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.getAppFlag(ReaderPagingOnlyFlag)?.toBooleanStrictOrNull() ?: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actual suspend fun saveReaderPagingOnly(enabled: Boolean) = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.setAppFlag(ReaderPagingOnlyFlag, enabled.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
actual suspend fun loadScanDownloadsAutomatically(): Boolean = withContext(Dispatchers.IO) {
|
actual suspend fun loadScanDownloadsAutomatically(): Boolean = withContext(Dispatchers.IO) {
|
||||||
openLibraryDatabase().useLibrary { db ->
|
openLibraryDatabase().useLibrary { db ->
|
||||||
db.getAppFlag(ScanDownloadsAutomaticallyFlag)?.toBooleanStrictOrNull() ?: true
|
db.getAppFlag(ScanDownloadsAutomaticallyFlag)?.toBooleanStrictOrNull() ?: true
|
||||||
@@ -358,6 +485,41 @@ actual suspend fun saveScanDownloadsAutomatically(enabled: Boolean) = withContex
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal actual suspend fun loadLibraryFilter(): LibraryFilter = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
val saved = db.getAppFlag(LibraryFilterFlag)
|
||||||
|
when {
|
||||||
|
saved == null -> {
|
||||||
|
appendLibraryLog("warning library filter was not saved; using ${LibraryFilter.MyLibrary.name}")
|
||||||
|
LibraryFilter.MyLibrary
|
||||||
|
}
|
||||||
|
else -> runCatching { LibraryFilter.valueOf(saved) }
|
||||||
|
.getOrElse {
|
||||||
|
appendLibraryLog("warning invalid saved library filter '$saved'; using ${LibraryFilter.MyLibrary.name}")
|
||||||
|
LibraryFilter.MyLibrary
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal actual suspend fun saveLibraryFilter(filter: LibraryFilter) = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.setAppFlag(LibraryFilterFlag, filter.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actual suspend fun loadAppLocaleTag(): String? = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.getAppFlag(AppLocaleTagFlag)?.takeIf { it.isNotBlank() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actual suspend fun saveAppLocaleTag(localeTag: String?) = withContext(Dispatchers.IO) {
|
||||||
|
openLibraryDatabase().useLibrary { db ->
|
||||||
|
db.setAppFlag(AppLocaleTagFlag, localeTag?.takeIf { it.isNotBlank() })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
actual suspend fun loadDownloadsWasScanned(): Boolean = withContext(Dispatchers.IO) {
|
actual suspend fun loadDownloadsWasScanned(): Boolean = withContext(Dispatchers.IO) {
|
||||||
openLibraryDatabase().useLibrary { db ->
|
openLibraryDatabase().useLibrary { db ->
|
||||||
db.getAppFlag(DownloadsWasScannedFlag)?.toBooleanStrictOrNull()
|
db.getAppFlag(DownloadsWasScannedFlag)?.toBooleanStrictOrNull()
|
||||||
@@ -486,6 +648,7 @@ private fun LibraryFileRecord.toLibraryItem(): LibraryItem =
|
|||||||
storageUri = storageUri,
|
storageUri = storageUri,
|
||||||
lastSeenAt = lastSeenAt,
|
lastSeenAt = lastSeenAt,
|
||||||
readingStatus = readingStatus,
|
readingStatus = readingStatus,
|
||||||
|
favorite = favorite,
|
||||||
lastReadAt = lastReadAt,
|
lastReadAt = lastReadAt,
|
||||||
importedAt = importedAt,
|
importedAt = importedAt,
|
||||||
)
|
)
|
||||||
@@ -546,14 +709,37 @@ private fun libraryLogFile(): File =
|
|||||||
File(System.getProperty("user.home"), ".toread/toread.log")
|
File(System.getProperty("user.home"), ".toread/toread.log")
|
||||||
|
|
||||||
private fun ReadingPosition.toFormatHintsJson(): String =
|
private fun ReadingPosition.toFormatHintsJson(): String =
|
||||||
"""{"firstVisibleItemIndex":$itemIndex,"firstVisibleItemScrollOffset":$scrollOffset}"""
|
buildString {
|
||||||
|
append("""{"firstVisibleItemIndex":$itemIndex,"firstVisibleItemScrollOffset":$scrollOffset""")
|
||||||
|
readAloudSentenceIndex?.let { append(""","readAloudSentenceIndex":$it""") }
|
||||||
|
if (backStack.isNotEmpty()) {
|
||||||
|
append(""","backStack":[""")
|
||||||
|
append(backStack.take(MaxStoredReadingBackStack).joinToString(",") { it.toFormatHintsJson() })
|
||||||
|
append("]")
|
||||||
|
}
|
||||||
|
append("}")
|
||||||
|
}
|
||||||
|
|
||||||
private fun String.toReadingPosition(): ReadingPosition? {
|
private fun String.toReadingPosition(): ReadingPosition? {
|
||||||
|
val position = toReadingPositionObject() ?: return null
|
||||||
|
val backStackJson = Regex(""""backStack"\s*:\s*\[(.*)]""").find(this)?.groupValues?.getOrNull(1)
|
||||||
|
val backStack = backStackJson
|
||||||
|
?.let { ReadingPositionObjectRegex.findAll(it).mapNotNull { match -> match.value.toReadingPositionObject() }.toList() }
|
||||||
|
.orEmpty()
|
||||||
|
.take(MaxStoredReadingBackStack)
|
||||||
|
return position.copy(backStack = backStack)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun String.toReadingPositionObject(): ReadingPosition? {
|
||||||
val index = Regex(""""firstVisibleItemIndex"\s*:\s*(\d+)""").find(this)?.groupValues?.getOrNull(1)?.toIntOrNull()
|
val index = Regex(""""firstVisibleItemIndex"\s*:\s*(\d+)""").find(this)?.groupValues?.getOrNull(1)?.toIntOrNull()
|
||||||
val offset = Regex(""""firstVisibleItemScrollOffset"\s*:\s*(\d+)""").find(this)?.groupValues?.getOrNull(1)?.toIntOrNull()
|
val offset = Regex(""""firstVisibleItemScrollOffset"\s*:\s*(\d+)""").find(this)?.groupValues?.getOrNull(1)?.toIntOrNull()
|
||||||
return if (index != null && offset != null) ReadingPosition(index, offset) else null
|
val sentenceIndex = Regex(""""readAloudSentenceIndex"\s*:\s*(\d+)""").find(this)?.groupValues?.getOrNull(1)?.toIntOrNull()
|
||||||
|
return if (index != null && offset != null) ReadingPosition(index, offset, sentenceIndex) else null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val ReadingPositionObjectRegex = Regex("""[{][^{}]*[}]""")
|
||||||
|
private const val MaxStoredReadingBackStack = 10
|
||||||
|
|
||||||
private fun String.toSearchPrefixes(): List<String> =
|
private fun String.toSearchPrefixes(): List<String> =
|
||||||
SearchPrefixRegex.findAll(lowercase()).map { it.value }.distinct().toList()
|
SearchPrefixRegex.findAll(lowercase()).map { it.value }.distinct().toList()
|
||||||
|
|
||||||
@@ -570,7 +756,15 @@ private fun runCommand(vararg command: String): String? =
|
|||||||
}
|
}
|
||||||
}.getOrNull()
|
}.getOrNull()
|
||||||
|
|
||||||
|
private fun String.isSupportedBookFile(): Boolean =
|
||||||
|
endsWith(".fb2", ignoreCase = true) || endsWith(".fb2.zip", ignoreCase = true)
|
||||||
|
|
||||||
private const val ActiveReadingFileIdFlag = "active_reading_file_id"
|
private const val ActiveReadingFileIdFlag = "active_reading_file_id"
|
||||||
private const val ThemeModeFlag = "theme_mode"
|
private const val ThemeModeFlag = "theme_mode"
|
||||||
|
private const val ReaderFontSettingsFlag = "reader_font_settings"
|
||||||
|
private const val ReaderFullScreenFlag = "reader_full_screen"
|
||||||
|
private const val ReaderPagingOnlyFlag = "reader_paging_only"
|
||||||
private const val ScanDownloadsAutomaticallyFlag = "scan_downloads_automatically"
|
private const val ScanDownloadsAutomaticallyFlag = "scan_downloads_automatically"
|
||||||
|
private const val LibraryFilterFlag = "library_filter"
|
||||||
|
private const val AppLocaleTagFlag = "app_locale_tag"
|
||||||
private const val DownloadsWasScannedFlag = "downloads_was_scanned"
|
private const val DownloadsWasScannedFlag = "downloads_was_scanned"
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package net.sergeych.toread
|
||||||
|
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
internal actual fun platformLocaleTags(): List<String> =
|
||||||
|
listOf(Locale.getDefault().toLanguageTag())
|
||||||
@@ -1,15 +1,54 @@
|
|||||||
package net.sergeych.toread
|
package net.sergeych.toread
|
||||||
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.currentCoroutineContext
|
||||||
|
import kotlinx.coroutines.ensureActive
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import net.sergeych.toread.tts.DesktopReadAloudPlayer
|
||||||
|
import net.sergeych.toread.tts.SpeechAudio
|
||||||
|
import net.sergeych.toread.tts.RuAccentProcess
|
||||||
|
import net.sergeych.toread.tts.SileroProcess
|
||||||
|
import net.sergeych.toread.tts.SupertonicTts
|
||||||
|
import net.sergeych.toread.tts.playDesktopAudio
|
||||||
|
|
||||||
actual object ReadAloudPlatform {
|
actual object ReadAloudPlatform {
|
||||||
actual val isSupported: Boolean = false
|
actual val isSupported: Boolean = true
|
||||||
private val mutableState = MutableStateFlow(ReadAloudState())
|
private val inferenceLock = Mutex()
|
||||||
actual val state: StateFlow<ReadAloudState> = mutableState
|
private var synthesizer: SupertonicTts? = null
|
||||||
|
private val accentor = if (RuAccentProcess.isInstalled()) RuAccentProcess() else null
|
||||||
|
private val silero = if (SileroProcess.isInstalled()) SileroProcess() else null
|
||||||
|
private val player = DesktopReadAloudPlayer(
|
||||||
|
scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate),
|
||||||
|
synthesize = { text, voice ->
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
inferenceLock.withLock {
|
||||||
|
val context = currentCoroutineContext()
|
||||||
|
context.ensureActive()
|
||||||
|
val engine = synthesizer ?: SupertonicTts().also { synthesizer = it }
|
||||||
|
context.ensureActive()
|
||||||
|
SpeechAudio(engine.synthesize(text, voice, checkCancelled = { context.ensureActive() }), engine.sampleRate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
playAudio = ::playDesktopAudio,
|
||||||
|
installed = { SupertonicTts.isInstalled() },
|
||||||
|
accentuate = accentor?.let { processor -> { text -> processor.accentuate(text) } },
|
||||||
|
silero = silero?.let { processor -> { text, voice -> processor.synthesize(text, voice) } },
|
||||||
|
)
|
||||||
|
actual val state: StateFlow<ReadAloudState> = player.state
|
||||||
|
actual val settingsState: StateFlow<ReadAloudSettingsState> = player.settingsState
|
||||||
|
|
||||||
actual fun prepare(bookTitle: String, sentences: List<ReadAloudSentence>, startIndex: Int) = Unit
|
actual fun prepare(fileId: String, bookTitle: String, sentences: List<ReadAloudSentence>, startIndex: Int) =
|
||||||
actual fun play() = Unit
|
player.prepare(sentences, startIndex)
|
||||||
actual fun stop() = Unit
|
actual fun play() = player.play()
|
||||||
actual fun skip(delta: Int) = Unit
|
actual fun stop() = player.stop()
|
||||||
|
actual fun skip(delta: Int) = player.skip(delta)
|
||||||
|
actual fun refreshSettings() = player.refreshSettings()
|
||||||
|
actual fun selectEngine(engineId: String?) = player.selectEngine(engineId)
|
||||||
|
actual fun selectVoice(voiceId: String?) = player.selectVoice(voiceId)
|
||||||
}
|
}
|
||||||
@@ -3,11 +3,14 @@ package net.sergeych.toread
|
|||||||
import androidx.compose.ui.window.Window
|
import androidx.compose.ui.window.Window
|
||||||
import androidx.compose.ui.window.application
|
import androidx.compose.ui.window.application
|
||||||
|
|
||||||
fun main() = application {
|
fun main(args: Array<String>) {
|
||||||
Window(
|
rememberPlatformOpenBookArguments(args)
|
||||||
onCloseRequest = ::exitApplication,
|
application {
|
||||||
title = "toread",
|
Window(
|
||||||
) {
|
onCloseRequest = ::exitApplication,
|
||||||
App()
|
title = strings.appName,
|
||||||
|
) {
|
||||||
|
App()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package net.sergeych.toread.tts
|
||||||
|
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.currentCoroutineContext
|
||||||
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
|
import kotlinx.coroutines.ensureActive
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.ByteArrayInputStream
|
||||||
|
import java.io.File
|
||||||
|
import javax.sound.sampled.AudioFileFormat
|
||||||
|
import javax.sound.sampled.AudioFormat
|
||||||
|
import javax.sound.sampled.AudioInputStream
|
||||||
|
import javax.sound.sampled.AudioSystem
|
||||||
|
import javax.sound.sampled.LineEvent
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
import kotlin.coroutines.resume
|
||||||
|
|
||||||
|
internal fun SpeechAudio.pcm16(): ByteArray = ByteArray(samples.size * 2).also { bytes ->
|
||||||
|
samples.forEachIndexed { index, sample ->
|
||||||
|
val pcm = (sample.takeIf { it.isFinite() }?.coerceIn(-1f, 1f)?.times(32767) ?: 0f).toInt()
|
||||||
|
bytes[index * 2] = pcm.toByte()
|
||||||
|
bytes[index * 2 + 1] = (pcm shr 8).toByte()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal suspend fun playDesktopAudio(audio: SpeechAudio) = withContext(Dispatchers.IO) {
|
||||||
|
val format = AudioFormat(audio.sampleRate.toFloat(), 16, 1, true, false)
|
||||||
|
val pcm = audio.pcm16()
|
||||||
|
val clip = AudioSystem.getClip()
|
||||||
|
try {
|
||||||
|
currentCoroutineContext().ensureActive()
|
||||||
|
clip.open(format, pcm, 0, pcm.size)
|
||||||
|
suspendCancellableCoroutine<Unit> { continuation ->
|
||||||
|
val completed = AtomicBoolean(false)
|
||||||
|
clip.addLineListener { event ->
|
||||||
|
if (event.type == LineEvent.Type.STOP && completed.compareAndSet(false, true)) {
|
||||||
|
continuation.resume(Unit)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continuation.invokeOnCancellation {
|
||||||
|
clip.stop()
|
||||||
|
clip.close()
|
||||||
|
}
|
||||||
|
if (continuation.isActive) clip.start()
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
clip.stop()
|
||||||
|
clip.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun SpeechAudio.writeWav(file: File) {
|
||||||
|
file.parentFile?.mkdirs()
|
||||||
|
val format = AudioFormat(sampleRate.toFloat(), 16, 1, true, false)
|
||||||
|
AudioInputStream(ByteArrayInputStream(pcm16()), format, samples.size.toLong()).use {
|
||||||
|
AudioSystem.write(it, AudioFileFormat.Type.WAVE, file)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun joinSpeechAudio(parts: List<SpeechAudio>): SpeechAudio {
|
||||||
|
require(parts.isNotEmpty()) { "No speech to play" }
|
||||||
|
if (parts.size == 1) return parts.single()
|
||||||
|
val rate = parts.first().sampleRate
|
||||||
|
require(parts.all { it.sampleRate == rate }) { "Mismatched speech sample rates" }
|
||||||
|
val pause = rate / 10
|
||||||
|
val samples = FloatArray(parts.sumOf { it.samples.size } + pause * (parts.size - 1))
|
||||||
|
var offset = 0
|
||||||
|
parts.forEach { part -> part.samples.copyInto(samples, offset); offset += part.samples.size + pause }
|
||||||
|
return SpeechAudio(samples, rate)
|
||||||
|
}
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
package net.sergeych.toread.tts
|
||||||
|
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.async
|
||||||
|
import kotlinx.coroutines.coroutineScope
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import net.sergeych.toread.ReadAloudEngineOption
|
||||||
|
import net.sergeych.toread.ReadAloudSentence
|
||||||
|
import net.sergeych.toread.ReadAloudSettingsState
|
||||||
|
import net.sergeych.toread.ReadAloudState
|
||||||
|
import net.sergeych.toread.ReadAloudVoiceOption
|
||||||
|
import net.sergeych.toread.strings
|
||||||
|
|
||||||
|
internal data class SpeechAudio(val samples: FloatArray, val sampleRate: Int)
|
||||||
|
|
||||||
|
/** Commands and state changes run on the UI dispatcher; inference/audio run off-thread.
|
||||||
|
* A playback job owns its lookahead, so stop/skip/voice changes cannot publish stale audio.
|
||||||
|
*/
|
||||||
|
internal class DesktopReadAloudPlayer(
|
||||||
|
private val scope: CoroutineScope,
|
||||||
|
private val synthesize: suspend (String, String) -> SpeechAudio,
|
||||||
|
private val playAudio: suspend (SpeechAudio) -> Unit,
|
||||||
|
private val installed: () -> Boolean,
|
||||||
|
private val accentuate: (suspend (String) -> String)? = null,
|
||||||
|
private val silero: (suspend (String, String) -> SpeechAudio)? = null,
|
||||||
|
) {
|
||||||
|
private fun voices(engine: String) = if (engine == "silero")
|
||||||
|
SileroProcess.voices.map { ReadAloudVoiceOption(it, it.replaceFirstChar(Char::uppercase), "ru (English: F1)", false) }
|
||||||
|
else SupertonicTts.voices.map { ReadAloudVoiceOption(it, it, "en / ru", false) }
|
||||||
|
private val defaultEngine = if (silero != null) "silero" else if (accentuate != null) "supertonic-3-ruaccent" else "supertonic-3"
|
||||||
|
private val mutableState = MutableStateFlow(ReadAloudState())
|
||||||
|
val state = mutableState.asStateFlow()
|
||||||
|
private val mutableSettings = MutableStateFlow(ReadAloudSettingsState(
|
||||||
|
engines = (if (silero != null) listOf(ReadAloudEngineOption("silero", "Silero (RU) / Supertonic (EN)")) else emptyList()) +
|
||||||
|
listOf(ReadAloudEngineOption("supertonic-3", "Supertonic 3")) +
|
||||||
|
if (accentuate != null) listOf(ReadAloudEngineOption("supertonic-3-ruaccent", "Supertonic 3 + RUAccent")) else emptyList(),
|
||||||
|
selectedEngineId = defaultEngine,
|
||||||
|
voices = voices(defaultEngine),
|
||||||
|
selectedVoiceId = if (silero != null) "xenia" else "F1",
|
||||||
|
usesSystemDefaults = false,
|
||||||
|
))
|
||||||
|
val settingsState = mutableSettings.asStateFlow()
|
||||||
|
private var queue = emptyList<ReadAloudSentence>()
|
||||||
|
private var index = 0
|
||||||
|
private var playback: Job? = null
|
||||||
|
|
||||||
|
fun prepare(sentences: List<ReadAloudSentence>, startIndex: Int) {
|
||||||
|
stop()
|
||||||
|
queue = sentences.toList()
|
||||||
|
index = if (queue.isEmpty()) 0 else startIndex.coerceIn(queue.indices)
|
||||||
|
mutableState.value = ReadAloudState(active = queue.isNotEmpty(), sentenceIndex = queue.getOrNull(index)?.index)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun play() {
|
||||||
|
if (queue.isEmpty()) return
|
||||||
|
playback?.cancel()
|
||||||
|
mutableSettings.value = mutableSettings.value.copy(message = null)
|
||||||
|
if (!installed()) {
|
||||||
|
mutableState.value = mutableState.value.copy(active = true, playing = false, buffering = false)
|
||||||
|
mutableSettings.value = mutableSettings.value.copy(message = strings.offlineSpeechModelMissing)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val voice = mutableSettings.value.selectedVoiceId ?: "F1"
|
||||||
|
val useSilero = mutableSettings.value.selectedEngineId == "silero"
|
||||||
|
val useAccents = mutableSettings.value.selectedEngineId == "supertonic-3-ruaccent"
|
||||||
|
suspend fun render(text: String): SpeechAudio {
|
||||||
|
if (useSilero) return if (SupertonicTts.languageOf(text) == "ru") silero!!.invoke(text, voice)
|
||||||
|
else synthesize(text, "F1")
|
||||||
|
val prepared = if (useAccents) accentuate!!.invoke(text) else text
|
||||||
|
// Accent marks increase character count; re-chunk before entering the TTS model.
|
||||||
|
return joinSpeechAudio(SupertonicTts.chunks(SupertonicTts.russianStressToUnicode(prepared)).map { synthesize(it, voice) })
|
||||||
|
}
|
||||||
|
val chunks = queue.asSequence().withIndex().drop(index).flatMap { (position, sentence) ->
|
||||||
|
val parts = SupertonicTts.chunks(sentence.spokenText)
|
||||||
|
parts.asSequence().mapIndexed { chunkIndex, text ->
|
||||||
|
Chunk(position, sentence, text, chunkIndex == 0, chunkIndex == parts.lastIndex)
|
||||||
|
}
|
||||||
|
}.iterator()
|
||||||
|
mutableState.value = mutableState.value.copy(active = true, playing = true, buffering = true)
|
||||||
|
playback = scope.launch {
|
||||||
|
try {
|
||||||
|
coroutineScope {
|
||||||
|
// Keep at most one audio chunk ahead of the currently playing chunk.
|
||||||
|
var next = if (chunks.hasNext()) chunks.next() else null
|
||||||
|
var pending = next?.let { chunk -> async { render(chunk.text) } }
|
||||||
|
while (next != null) {
|
||||||
|
val current = next
|
||||||
|
mutableState.value = mutableState.value.copy(buffering = pending?.isCompleted != true)
|
||||||
|
val audio = pending!!.await()
|
||||||
|
next = if (chunks.hasNext()) chunks.next() else null
|
||||||
|
pending = next?.let { chunk -> async { render(chunk.text) } }
|
||||||
|
index = current.position
|
||||||
|
mutableState.value = ReadAloudState(active = true, playing = true, sentenceIndex = current.sentence.index)
|
||||||
|
if (current.first) delay(current.sentence.pauseBeforeMillis)
|
||||||
|
playAudio(audio)
|
||||||
|
if (current.last) delay(current.sentence.pauseAfterMillis)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mutableState.value = ReadAloudState()
|
||||||
|
} catch (cancelled: CancellationException) {
|
||||||
|
throw cancelled
|
||||||
|
} catch (error: Exception) {
|
||||||
|
System.err.println("Desktop TTS failed: ${error.javaClass.simpleName}: ${error.message}")
|
||||||
|
mutableState.value = mutableState.value.copy(playing = false, buffering = false)
|
||||||
|
mutableSettings.value = mutableSettings.value.copy(message = strings.speechPlaybackFailed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stop() {
|
||||||
|
playback?.cancel()
|
||||||
|
playback = null
|
||||||
|
mutableState.value = ReadAloudState()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun skip(delta: Int) {
|
||||||
|
if (queue.isEmpty()) return
|
||||||
|
val wasPlaying = mutableState.value.playing
|
||||||
|
playback?.cancel()
|
||||||
|
index = (index.toLong() + delta).coerceIn(0, queue.lastIndex.toLong()).toInt()
|
||||||
|
mutableState.value = ReadAloudState(active = true, sentenceIndex = queue[index].index)
|
||||||
|
if (wasPlaying) play()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun selectVoice(id: String?) {
|
||||||
|
val voice = id ?: if (mutableSettings.value.selectedEngineId == "silero") "xenia" else "F1"
|
||||||
|
if (mutableSettings.value.voices.none { it.id == voice } || voice == mutableSettings.value.selectedVoiceId) return
|
||||||
|
mutableSettings.value = mutableSettings.value.copy(selectedVoiceId = voice)
|
||||||
|
if (mutableState.value.playing) play()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun selectEngine(id: String?) {
|
||||||
|
val engine = id ?: defaultEngine
|
||||||
|
if (mutableSettings.value.engines.none { it.id == engine } || engine == mutableSettings.value.selectedEngineId) return
|
||||||
|
val options = voices(engine)
|
||||||
|
mutableSettings.value = mutableSettings.value.copy(selectedEngineId = engine, voices = options,
|
||||||
|
selectedVoiceId = mutableSettings.value.selectedVoiceId?.takeIf { id -> options.any { it.id == id } }
|
||||||
|
?: if (engine == "silero") "xenia" else "F1")
|
||||||
|
if (mutableState.value.playing) play()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun refreshSettings() {
|
||||||
|
mutableSettings.value = mutableSettings.value.copy(message = if (installed()) null else strings.offlineSpeechModelMissing)
|
||||||
|
}
|
||||||
|
|
||||||
|
private data class Chunk(
|
||||||
|
val position: Int,
|
||||||
|
val sentence: ReadAloudSentence,
|
||||||
|
val text: String,
|
||||||
|
val first: Boolean,
|
||||||
|
val last: Boolean,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package net.sergeych.toread.tts
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.async
|
||||||
|
import kotlinx.coroutines.coroutineScope
|
||||||
|
import kotlinx.coroutines.currentCoroutineContext
|
||||||
|
import kotlinx.coroutines.ensureActive
|
||||||
|
import kotlinx.coroutines.isActive
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.coroutines.withTimeout
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.BufferedWriter
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/** Optional desktop-only CPU accentor. Persistent local process, no HTTP or remote text service. */
|
||||||
|
internal class RuAccentProcess(private val directory: File = installationDirectory()) : AutoCloseable {
|
||||||
|
private val mapper = ObjectMapper()
|
||||||
|
private val lock = Mutex()
|
||||||
|
@Volatile private var worker: Worker? = null
|
||||||
|
|
||||||
|
init {
|
||||||
|
Runtime.getRuntime().addShutdownHook(Thread { close() })
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun accentuate(text: String): String {
|
||||||
|
// Respect explicitly supplied stress; English needs no Russian processor.
|
||||||
|
if (SupertonicTts.languageOf(text) == "en" || '\u0301' in text || Regex("\\+[аеёиоуыэюяАЕЁИОУЫЭЮЯ]").containsMatchIn(text)) return text
|
||||||
|
return lock.withLock {
|
||||||
|
try {
|
||||||
|
currentCoroutineContext().ensureActive()
|
||||||
|
val current = worker?.takeIf { it.process.isAlive } ?: startWorker().also { worker = it }
|
||||||
|
withTimeout(90_000) {
|
||||||
|
coroutineScope {
|
||||||
|
val response = async(Dispatchers.IO) {
|
||||||
|
if (!current.ready) {
|
||||||
|
val ready = current.output.readLine() ?: error("RuAccent exited while loading")
|
||||||
|
check(mapper.readTree(ready)["ready"]?.asBoolean() == true) { "RuAccent did not initialize" }
|
||||||
|
current.ready = true
|
||||||
|
}
|
||||||
|
current.input.write(mapper.writeValueAsString(mapOf("text" to text)))
|
||||||
|
current.input.newLine()
|
||||||
|
current.input.flush()
|
||||||
|
val line = current.output.readLine() ?: error("RuAccent exited during inference")
|
||||||
|
val result = mapper.readTree(line)
|
||||||
|
check(result["error"] == null) { "RuAccent inference failed" }
|
||||||
|
result["text"]?.asText()?.takeIf { it.isNotBlank() } ?: error("Empty RuAccent response")
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
response.await()
|
||||||
|
} finally {
|
||||||
|
// A blocked pipe read cannot be interrupted reliably; killing the
|
||||||
|
// cancelled worker unblocks it before the next request acquires the lock.
|
||||||
|
if (!isActive) current.process.destroyForcibly()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error: Exception) {
|
||||||
|
close()
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startWorker(): Worker {
|
||||||
|
val runtime = mapper.readTree(File(directory, "runtime.json"))
|
||||||
|
val process = ProcessBuilder(runtime["python"].asText(), "-u", File(directory, "worker.py").path, directory.path)
|
||||||
|
.redirectError(ProcessBuilder.Redirect.INHERIT)
|
||||||
|
.apply {
|
||||||
|
environment()["HF_HUB_OFFLINE"] = "1"
|
||||||
|
environment()["TRANSFORMERS_OFFLINE"] = "1"
|
||||||
|
environment()["HF_HUB_DISABLE_TELEMETRY"] = "1"
|
||||||
|
}.start()
|
||||||
|
return Worker(process, process.inputStream.bufferedReader(Charsets.UTF_8), process.outputStream.bufferedWriter(Charsets.UTF_8))
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun close() {
|
||||||
|
worker?.process?.destroyForcibly()
|
||||||
|
worker = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Worker(val process: Process, val output: BufferedReader, val input: BufferedWriter, var ready: Boolean = false)
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun installationDirectory(): File = System.getenv("YEREED_RUACCENT_HOME")?.let(::File)
|
||||||
|
?: File(SupertonicTts.modelDirectory().parentFile, "ruaccent")
|
||||||
|
fun isInstalled(): Boolean = File(installationDirectory(), "runtime.json").isFile && File(installationDirectory(), "worker.py").isFile
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
package net.sergeych.toread.tts
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.async
|
||||||
|
import kotlinx.coroutines.coroutineScope
|
||||||
|
import kotlinx.coroutines.currentCoroutineContext
|
||||||
|
import kotlinx.coroutines.ensureActive
|
||||||
|
import kotlinx.coroutines.isActive
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.coroutines.withTimeout
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.BufferedWriter
|
||||||
|
import java.io.File
|
||||||
|
import java.nio.ByteBuffer
|
||||||
|
import java.nio.ByteOrder
|
||||||
|
import java.util.Base64
|
||||||
|
|
||||||
|
/** Desktop-only CPU Silero synthesizer. Persistent local process, no HTTP or remote text service. */
|
||||||
|
internal class SileroProcess(private val directory: File = installationDirectory()) : AutoCloseable {
|
||||||
|
private val mapper = ObjectMapper()
|
||||||
|
private val lock = Mutex()
|
||||||
|
@Volatile private var worker: Worker? = null
|
||||||
|
|
||||||
|
init {
|
||||||
|
Runtime.getRuntime().addShutdownHook(Thread { close() })
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun synthesize(text: String, voice: String): SpeechAudio {
|
||||||
|
return lock.withLock {
|
||||||
|
try {
|
||||||
|
currentCoroutineContext().ensureActive()
|
||||||
|
val current = worker?.takeIf { it.process.isAlive } ?: startWorker().also { worker = it }
|
||||||
|
withTimeout(90_000) {
|
||||||
|
coroutineScope {
|
||||||
|
val response = async(Dispatchers.IO) {
|
||||||
|
if (!current.ready) {
|
||||||
|
val ready = current.output.readLine() ?: error("Silero exited while loading")
|
||||||
|
check(mapper.readTree(ready)["ready"]?.asBoolean() == true) { "Silero did not initialize" }
|
||||||
|
current.ready = true
|
||||||
|
}
|
||||||
|
current.input.write(mapper.writeValueAsString(mapOf("text" to text, "voice" to voice)))
|
||||||
|
current.input.newLine()
|
||||||
|
current.input.flush()
|
||||||
|
val line = current.output.readLine() ?: error("Silero exited during inference")
|
||||||
|
val result = mapper.readTree(line)
|
||||||
|
check(result["error"] == null) { "Silero inference failed" }
|
||||||
|
val bytes = Base64.getDecoder().decode(result["audio"].asText())
|
||||||
|
check(bytes.isNotEmpty() && bytes.size % 4 == 0) { "Invalid Silero audio" }
|
||||||
|
val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer()
|
||||||
|
val samples = FloatArray(buffer.remaining()).also { buffer.get(it) }
|
||||||
|
check(samples.all { it.isFinite() }) { "Non-finite Silero audio" }
|
||||||
|
SpeechAudio(samples, result["sampleRate"].asInt().also { check(it == 48000) })
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
response.await()
|
||||||
|
} finally {
|
||||||
|
// A blocked pipe read cannot be interrupted reliably; killing the
|
||||||
|
// cancelled worker unblocks it before the next request acquires the lock.
|
||||||
|
if (!isActive) current.process.destroyForcibly()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error: Exception) {
|
||||||
|
close()
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startWorker(): Worker {
|
||||||
|
val runtime = mapper.readTree(File(directory, "runtime.json"))
|
||||||
|
val script = SileroProcess::class.java.getResourceAsStream("/tts/silero-worker.py")!!.use { it.reader().readText() }
|
||||||
|
val process = ProcessBuilder(runtime["python"].asText(), "-u", "-c", script, directory.path)
|
||||||
|
.redirectError(ProcessBuilder.Redirect.INHERIT)
|
||||||
|
.apply {
|
||||||
|
environment()["HF_HUB_OFFLINE"] = "1"
|
||||||
|
environment()["TRANSFORMERS_OFFLINE"] = "1"
|
||||||
|
environment()["HF_HUB_DISABLE_TELEMETRY"] = "1"
|
||||||
|
}.start()
|
||||||
|
return Worker(process, process.inputStream.bufferedReader(Charsets.UTF_8), process.outputStream.bufferedWriter(Charsets.UTF_8))
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun close() {
|
||||||
|
worker?.process?.destroyForcibly()
|
||||||
|
worker = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Worker(val process: Process, val output: BufferedReader, val input: BufferedWriter, var ready: Boolean = false)
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val voices = listOf("xenia", "baya", "aidar", "kseniya", "eugene")
|
||||||
|
fun installationDirectory(): File = System.getenv("YEREED_SILERO_HOME")?.let(::File)
|
||||||
|
?: File(SupertonicTts.modelDirectory().parentFile, "silero-v5_5-ru")
|
||||||
|
fun isInstalled(): Boolean = File(installationDirectory(), "runtime.json").isFile && File(installationDirectory(), "model.pt").length() > 0
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
package net.sergeych.toread.tts
|
||||||
|
|
||||||
|
import ai.onnxruntime.OnnxTensor
|
||||||
|
import ai.onnxruntime.OrtEnvironment
|
||||||
|
import ai.onnxruntime.OrtSession
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper
|
||||||
|
import java.io.File
|
||||||
|
import java.nio.FloatBuffer
|
||||||
|
import java.text.Normalizer
|
||||||
|
import java.util.Random
|
||||||
|
|
||||||
|
/** CPU-only, single-utterance adaptation of Supertone's MIT Java example.
|
||||||
|
* See docs/licenses/supertonic-code-MIT.txt. Call from one worker at a time.
|
||||||
|
*/
|
||||||
|
internal class SupertonicTts(val directory: File = modelDirectory()) : AutoCloseable {
|
||||||
|
private val mapper = ObjectMapper()
|
||||||
|
private val environment = OrtEnvironment.getEnvironment()
|
||||||
|
private val config = mapper.readTree(File(directory, "onnx/tts.json"))
|
||||||
|
private val indexer = mapper.readTree(File(directory, "onnx/unicode_indexer.json"))
|
||||||
|
.map { it.asLong() }.toLongArray()
|
||||||
|
val sampleRate: Int = config["ae"]["sample_rate"].asInt()
|
||||||
|
private val compression = config["ttl"]["chunk_compress_factor"].asInt()
|
||||||
|
private val chunkSize = config["ae"]["base_chunk_size"].asInt() * compression
|
||||||
|
private val latentDimension = config["ttl"]["latent_dim"].asInt() * compression
|
||||||
|
private val sessions = mutableListOf<OrtSession>()
|
||||||
|
private val styles = mutableMapOf<String, JsonNode>()
|
||||||
|
|
||||||
|
init {
|
||||||
|
try {
|
||||||
|
OrtSession.SessionOptions().use { options ->
|
||||||
|
// The standard (non-GPU) ONNX artifact uses CPUExecutionProvider only.
|
||||||
|
options.setIntraOpNumThreads(4.coerceAtMost(Runtime.getRuntime().availableProcessors()))
|
||||||
|
options.setInterOpNumThreads(1)
|
||||||
|
for (name in listOf("duration_predictor", "text_encoder", "vector_estimator", "vocoder")) {
|
||||||
|
sessions += environment.createSession(File(directory, "onnx/$name.onnx").path, options)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error: Throwable) {
|
||||||
|
close()
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun synthesize(
|
||||||
|
text: String,
|
||||||
|
voice: String = "F1",
|
||||||
|
language: String = languageOf(text),
|
||||||
|
seed: Long? = null,
|
||||||
|
checkCancelled: () -> Unit = {},
|
||||||
|
): FloatArray {
|
||||||
|
require(voice in voices) { "Unknown voice: $voice" }
|
||||||
|
require(language in listOf("en", "ru", "na")) { "Unsupported language: $language" }
|
||||||
|
require(text.isNotBlank() && text.length <= MAX_CHARS) { "Expected 1–$MAX_CHARS characters" }
|
||||||
|
checkCancelled()
|
||||||
|
val prepared = prepareText(text, language)
|
||||||
|
// Unknown symbols become spaces, never invalid (-1) embedding indices.
|
||||||
|
val ids = prepared.codePoints().toArray().map { point ->
|
||||||
|
indexer.getOrNull(point)?.takeIf { it >= 0 } ?: indexer[' '.code]
|
||||||
|
}.toLongArray()
|
||||||
|
val style = styles.getOrPut(voice) { mapper.readTree(File(directory, "voice_styles/$voice.json")) }
|
||||||
|
NativeResources().use { resources ->
|
||||||
|
fun tensor(value: Any) = resources.keep(OnnxTensor.createTensor(environment, value))
|
||||||
|
fun styleTensor(name: String): OnnxTensor {
|
||||||
|
val node = style[name]
|
||||||
|
val values = node["data"].flatMap { batch -> batch.flatMap { row -> row.map { it.floatValue() } } }
|
||||||
|
return resources.keep(OnnxTensor.createTensor(
|
||||||
|
environment, FloatBuffer.wrap(values.toFloatArray()), node["dims"].map { it.asLong() }.toLongArray(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
val textIds = tensor(arrayOf(ids))
|
||||||
|
val textMask = tensor(arrayOf(arrayOf(FloatArray(ids.size) { 1f })))
|
||||||
|
val styleDp = styleTensor("style_dp")
|
||||||
|
val styleTtl = styleTensor("style_ttl")
|
||||||
|
val duration = sessions[0].run(mapOf(
|
||||||
|
"text_ids" to textIds, "text_mask" to textMask, "style_dp" to styleDp,
|
||||||
|
)).use { result -> (result[0] as OnnxTensor).floatBuffer.get(0) / 1.05f }
|
||||||
|
check(duration.isFinite() && duration > 0 && duration <= 60) { "Invalid speech duration: $duration" }
|
||||||
|
checkCancelled()
|
||||||
|
val sampleCount = (duration * sampleRate).toInt()
|
||||||
|
val latentLength = (sampleCount + chunkSize - 1) / chunkSize
|
||||||
|
val random = seed?.let(::Random) ?: Random()
|
||||||
|
var latent = arrayOf(Array(latentDimension) { FloatArray(latentLength) { random.nextGaussian().toFloat() } })
|
||||||
|
val latentMask = tensor(arrayOf(arrayOf(FloatArray(latentLength) { 1f })))
|
||||||
|
val totalSteps = tensor(floatArrayOf(8f))
|
||||||
|
val encoded = resources.keep(sessions[1].run(mapOf(
|
||||||
|
"text_ids" to textIds, "text_mask" to textMask, "style_ttl" to styleTtl,
|
||||||
|
)))
|
||||||
|
val embedding = encoded[0] as OnnxTensor
|
||||||
|
repeat(8) { step ->
|
||||||
|
checkCancelled()
|
||||||
|
OnnxTensor.createTensor(environment, latent).use { noisy ->
|
||||||
|
OnnxTensor.createTensor(environment, floatArrayOf(step.toFloat())).use { currentStep ->
|
||||||
|
sessions[2].run(mapOf(
|
||||||
|
"noisy_latent" to noisy, "text_emb" to embedding, "style_ttl" to styleTtl,
|
||||||
|
"latent_mask" to latentMask, "text_mask" to textMask,
|
||||||
|
"current_step" to currentStep, "total_step" to totalSteps,
|
||||||
|
)).use { result ->
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
latent = result[0].value as Array<Array<FloatArray>>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
checkCancelled()
|
||||||
|
OnnxTensor.createTensor(environment, latent).use { finalLatent ->
|
||||||
|
return sessions[3].run(mapOf("latent" to finalLatent)).use { result ->
|
||||||
|
val samples = (result[0] as OnnxTensor).floatBuffer
|
||||||
|
check(samples.remaining() >= sampleCount) { "Truncated speech waveform" }
|
||||||
|
FloatArray(sampleCount).also { samples.get(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun close() {
|
||||||
|
sessions.asReversed().forEach { runCatching { it.close() } }
|
||||||
|
sessions.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val MAX_CHARS = 300
|
||||||
|
val voices = listOf("F1", "F2", "F3", "F4", "F5", "M1", "M2", "M3", "M4", "M5")
|
||||||
|
|
||||||
|
fun modelDirectory(): File {
|
||||||
|
val override = System.getProperty("yereed.tts.modelDir") ?: System.getenv("YEREED_TTS_MODEL_DIR")
|
||||||
|
if (!override.isNullOrBlank()) return File(override)
|
||||||
|
generateSequence(File(System.getProperty("user.dir")).absoluteFile) { it.parentFile }.forEach { root ->
|
||||||
|
File(root, ".local/tts/supertonic-3").takeIf { it.isDirectory }?.let { return it }
|
||||||
|
}
|
||||||
|
return File(System.getProperty("user.home"), ".toread/tts/supertonic-3")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isInstalled(directory: File = modelDirectory()): Boolean =
|
||||||
|
(listOf("onnx/tts.json", "onnx/unicode_indexer.json") +
|
||||||
|
listOf("duration_predictor", "text_encoder", "vector_estimator", "vocoder").map { "onnx/$it.onnx" } +
|
||||||
|
voices.map { "voice_styles/$it.json" }).all { File(directory, it).length() > 0 }
|
||||||
|
|
||||||
|
fun languageOf(text: String): String {
|
||||||
|
val russian = text.any { it in 'А'..'я' || it == 'ё' || it == 'Ё' }
|
||||||
|
val english = text.any { it in 'a'..'z' || it in 'A'..'Z' }
|
||||||
|
return when {
|
||||||
|
russian && english -> "na"
|
||||||
|
russian -> "ru"
|
||||||
|
else -> "en"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bounded chunks preserve every non-whitespace character, including long unbroken words. */
|
||||||
|
fun chunks(text: String): List<String> = buildList {
|
||||||
|
var remaining = text.trim()
|
||||||
|
while (remaining.length > MAX_CHARS) {
|
||||||
|
var end = remaining.lastIndexOfAny(charArrayOf(' ', '\n', '\t'), MAX_CHARS)
|
||||||
|
if (end <= 0) end = MAX_CHARS
|
||||||
|
if (Character.isHighSurrogate(remaining[end - 1])) end--
|
||||||
|
while (end > 0 && Character.getType(remaining[end]) == Character.NON_SPACING_MARK.toInt()) end--
|
||||||
|
require(end > 0) { "Oversized combining-character sequence" }
|
||||||
|
add(remaining.substring(0, end).trim())
|
||||||
|
remaining = remaining.substring(end).trimStart()
|
||||||
|
}
|
||||||
|
if (remaining.isNotEmpty()) add(remaining)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun prepareText(text: String, language: String): String {
|
||||||
|
var normalized = Normalizer.normalize(russianStressToUnicode(text), Normalizer.Form.NFKD)
|
||||||
|
.replace(Regex("[–‑—]"), "-")
|
||||||
|
.replace(Regex("[“”]"), "\"")
|
||||||
|
.replace(Regex("[‘’´`]"), "'")
|
||||||
|
.replace(Regex("[_\\[\\]|/#→←<>]"), " ")
|
||||||
|
.replace(Regex("[♥☆♡©\\\\]"), "")
|
||||||
|
.replace(Regex("[\\x{1F000}-\\x{1FAFF}\\x{2600}-\\x{27BF}]"), "")
|
||||||
|
if (language == "en") normalized = normalized.replace("@", " at ")
|
||||||
|
.replace("e.g.,", "for example, ").replace("i.e.,", "that is, ")
|
||||||
|
normalized = normalized.replace(Regex("\\s+"), " ").trim()
|
||||||
|
.replace(Regex(" +([,.!?;:'])"), "$1")
|
||||||
|
if (normalized.isEmpty() || normalized.last() !in ".!?;:,'\")]}…»") normalized += "."
|
||||||
|
return "<$language>$normalized</$language>"
|
||||||
|
}
|
||||||
|
|
||||||
|
/** RUAccent/Silero notation -> Cyrillic vowel plus U+0301, never a Latin lookalike. */
|
||||||
|
internal fun russianStressToUnicode(text: String): String =
|
||||||
|
text.replace(Regex("\\+([аеёиоуыэюяАЕЁИОУЫЭЮЯ])")) { it.groupValues[1] + "\u0301" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class NativeResources : AutoCloseable {
|
||||||
|
private val values = mutableListOf<AutoCloseable>()
|
||||||
|
fun <T : AutoCloseable> keep(value: T): T = value.also { values += it }
|
||||||
|
override fun close() = values.asReversed().forEach { runCatching { it.close() } }
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package net.sergeych.toread.tts
|
||||||
|
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import java.io.File
|
||||||
|
import java.util.Locale
|
||||||
|
import kotlin.system.measureNanoTime
|
||||||
|
|
||||||
|
/** Reproducible audition without opening the library, altering books, or contacting a service. */
|
||||||
|
fun main(args: Array<String>) = runBlocking {
|
||||||
|
val output = File(args.firstOrNull() ?: "build/tts-samples")
|
||||||
|
if ("--silero" in args) {
|
||||||
|
check(SileroProcess.isInstalled()) { "Install the Silero desktop runtime first." }
|
||||||
|
SileroProcess().use { engine ->
|
||||||
|
for ((label, text) in listOf(
|
||||||
|
"library" to "На двери висел старый замок, а вдали виднелся замок на холме.",
|
||||||
|
"yo" to "Ежик шел по лесу. Ребенок пьет теплое молоко.",
|
||||||
|
)) {
|
||||||
|
val audio = engine.synthesize(text, "xenia")
|
||||||
|
check(audio.samples.any { kotlin.math.abs(it) > 0.001f })
|
||||||
|
val file = File(output, "silero-desktop-$label.wav")
|
||||||
|
audio.writeWav(file)
|
||||||
|
println("Silero desktop worker: ${file.absolutePath}; ${audio.samples.size.toDouble() / audio.sampleRate}s")
|
||||||
|
if ("--play" in args) playDesktopAudio(audio)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return@runBlocking
|
||||||
|
}
|
||||||
|
check(SupertonicTts.isInstalled()) { "Run python3 scripts/download-tts-model.py first." }
|
||||||
|
lateinit var engine: SupertonicTts
|
||||||
|
val loadTime = measureNanoTime { engine = SupertonicTts() } / 1e9
|
||||||
|
println("Supertonic 3; CPU only; up to 4 threads; 8 steps; model load: %.3f s".format(Locale.ROOT, loadTime))
|
||||||
|
val stressTrial = "--stress" in args
|
||||||
|
val ruaccentTrial = "--ruaccent" in args
|
||||||
|
val russianText = "В библиотеке было тихо. Она открыла книгу и начала читать. За окном шёл осенний дождь. На двери висел старый замок, а вдали виднелся замок на холме. Завтра, подумала она, мы наконец доберёмся до моря."
|
||||||
|
val accentor = if (ruaccentTrial) RuAccentProcess() else null
|
||||||
|
val samples = if (ruaccentTrial) linkedMapOf("ru-plain" to russianText, "ru-ruaccent" to russianText) else if (stressTrial) linkedMapOf(
|
||||||
|
"ru-plain" to "Перед нами старый замок. Они стояли около замка.",
|
||||||
|
"ru-castle" to "П+еред н+ами ст+арый з+амок. Он+и сто+яли +около з+амка.",
|
||||||
|
"ru-lock" to "П+еред н+ами ст+арый зам+ок. Он+и сто+яли +около замк+а.",
|
||||||
|
) else linkedMapOf(
|
||||||
|
"en" to "The library was quiet. She opened the book and began to read. Outside, the autumn rain tapped softly against the window. Tomorrow, she thought, they would finally reach the coast.",
|
||||||
|
"ru" to russianText,
|
||||||
|
)
|
||||||
|
engine.use {
|
||||||
|
try {
|
||||||
|
for (voice in if (stressTrial || ruaccentTrial) listOf("F1") else listOf("F1", "M1")) for ((label, text) in samples) {
|
||||||
|
val language = if (stressTrial || ruaccentTrial) "ru" else label
|
||||||
|
val accentStart = System.nanoTime()
|
||||||
|
val accented = if (label == "ru-ruaccent") accentor!!.accentuate(text) else text
|
||||||
|
if (label == "ru-ruaccent") println("RuAccent (including first load): %.3f s".format(Locale.ROOT, (System.nanoTime() - accentStart) / 1e9))
|
||||||
|
val spoken = SupertonicTts.russianStressToUnicode(accented)
|
||||||
|
lateinit var audio: SpeechAudio
|
||||||
|
val elapsed = measureNanoTime {
|
||||||
|
audio = joinSpeechAudio(SupertonicTts.chunks(spoken).map { chunk ->
|
||||||
|
SpeechAudio(engine.synthesize(chunk, voice, language, seed = 42), engine.sampleRate)
|
||||||
|
})
|
||||||
|
} / 1e9
|
||||||
|
val duration = audio.samples.size.toDouble() / audio.sampleRate
|
||||||
|
check(audio.samples.all { it.isFinite() } && audio.samples.any { kotlin.math.abs(it) > 0.001f }) {
|
||||||
|
"Invalid or silent model output"
|
||||||
|
}
|
||||||
|
val file = File(output, "$label-$voice.wav")
|
||||||
|
audio.writeWav(file)
|
||||||
|
File(output, "$label-$voice.txt").writeText(spoken + "\n")
|
||||||
|
println("$label/$voice: %.3f s synthesis, %.3f s audio, RTF %.3f; %s".format(
|
||||||
|
Locale.ROOT, elapsed, duration, elapsed / duration, file.absolutePath,
|
||||||
|
))
|
||||||
|
if ("--play" in args) playDesktopAudio(audio)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
accentor?.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2025 Supertone Inc.
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
|
After Width: | Height: | Size: 134 KiB |
|
After Width: | Height: | Size: 212 KiB |
@@ -0,0 +1,56 @@
|
|||||||
|
"""Local stdin/stdout JSON protocol. Book text never leaves this process tree."""
|
||||||
|
import contextlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
os.environ.update(HF_HUB_OFFLINE="1", TRANSFORMERS_OFFLINE="1", HF_HUB_DISABLE_TELEMETRY="1", TOKENIZERS_PARALLELISM="false")
|
||||||
|
|
||||||
|
|
||||||
|
def load(model):
|
||||||
|
# Bound ORT worker counts before RUAccent imports its session constructor.
|
||||||
|
import onnxruntime as ort
|
||||||
|
original = ort.InferenceSession
|
||||||
|
|
||||||
|
def cpu_session(path, *args, **kwargs):
|
||||||
|
options = ort.SessionOptions()
|
||||||
|
options.intra_op_num_threads = 4
|
||||||
|
options.inter_op_num_threads = 1
|
||||||
|
kwargs["sess_options"] = options
|
||||||
|
kwargs["providers"] = ["CPUExecutionProvider"]
|
||||||
|
return original(path, *args, **kwargs)
|
||||||
|
|
||||||
|
ort.InferenceSession = cpu_session
|
||||||
|
from ruaccent import RUAccent
|
||||||
|
accentor = RUAccent()
|
||||||
|
accentor.load(omograph_model_size="turbo3.1", use_dictionary=True, device="CPU", workdir=str(model), tiny_mode=False)
|
||||||
|
return accentor
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
with contextlib.redirect_stdout(sys.stderr):
|
||||||
|
accentor = load(Path(sys.argv[1]))
|
||||||
|
if "--check" in sys.argv:
|
||||||
|
with contextlib.redirect_stdout(sys.stderr):
|
||||||
|
result = accentor.process_all("На двери висит замок.")
|
||||||
|
print(result, flush=True)
|
||||||
|
return
|
||||||
|
print(json.dumps({"ready": True}), flush=True)
|
||||||
|
for line in sys.stdin:
|
||||||
|
try:
|
||||||
|
text = json.loads(line)["text"]
|
||||||
|
if not isinstance(text, str) or len(text) > 2000:
|
||||||
|
raise ValueError("Expected text of at most 2000 characters")
|
||||||
|
start = time.monotonic()
|
||||||
|
with contextlib.redirect_stdout(sys.stderr):
|
||||||
|
accented = accentor.process_all(text)
|
||||||
|
print(json.dumps({"text": accented, "seconds": time.monotonic() - start}, ensure_ascii=False), flush=True)
|
||||||
|
except Exception as error:
|
||||||
|
# Do not echo private input or exception text into application logs.
|
||||||
|
print(json.dumps({"error": type(error).__name__}), flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
"""Persistent CPU-only Silero worker; local JSON lines, float32 audio in base64."""
|
||||||
|
import array
|
||||||
|
import base64
|
||||||
|
import contextlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
|
||||||
|
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
||||||
|
os.environ["TORCH_HOME"] = str(Path(sys.argv[1]).parent / "torch")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
with contextlib.redirect_stdout(sys.stderr):
|
||||||
|
import torch
|
||||||
|
torch.set_num_threads(4)
|
||||||
|
torch.set_num_interop_threads(1)
|
||||||
|
model = torch.package.PackageImporter(str(Path(sys.argv[1]) / "model.pt")).load_pickle("tts_models", "model")
|
||||||
|
model.to(torch.device("cpu"))
|
||||||
|
print(json.dumps({"ready": True}), flush=True)
|
||||||
|
for line in sys.stdin:
|
||||||
|
try:
|
||||||
|
request = json.loads(line)
|
||||||
|
text = request["text"]
|
||||||
|
voice = request["voice"]
|
||||||
|
if not isinstance(text, str) or not 0 < len(text) <= 2000 or voice not in model.speakers:
|
||||||
|
raise ValueError("Invalid speech request")
|
||||||
|
# Preserve explicit reader/book stress in Silero's native notation.
|
||||||
|
text = re.sub(r"([аеёиоуыэюяАЕЁИОУЫЭЮЯ])\u0301", r"+\1", text)
|
||||||
|
with contextlib.redirect_stdout(sys.stderr), torch.inference_mode():
|
||||||
|
audio = model.apply_tts(text=text, speaker=voice, sample_rate=48000,
|
||||||
|
put_accent=True, put_yo=True,
|
||||||
|
put_stress_homo=True, put_yo_homo=True).detach().cpu().flatten()
|
||||||
|
if not audio.numel() or not torch.isfinite(audio).all():
|
||||||
|
raise ValueError("Invalid model audio")
|
||||||
|
samples = array.array("f", audio.tolist())
|
||||||
|
if sys.byteorder != "little":
|
||||||
|
samples.byteswap()
|
||||||
|
print(json.dumps({"sampleRate": 48000, "audio": base64.b64encode(samples.tobytes()).decode("ascii")}), flush=True)
|
||||||
|
except Exception as error:
|
||||||
|
print(json.dumps({"error": type(error).__name__}), flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
package net.sergeych.toread.tts
|
||||||
|
|
||||||
|
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||||
|
import kotlinx.coroutines.awaitCancellation
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.test.advanceUntilIdle
|
||||||
|
import kotlinx.coroutines.test.runCurrent
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import net.sergeych.toread.ReadAloudSentence
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertFalse
|
||||||
|
import kotlin.test.assertNotNull
|
||||||
|
import kotlin.test.assertNull
|
||||||
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
|
class DesktopReadAloudPlayerTest {
|
||||||
|
private fun sentence(index: Int, text: String) = ReadAloudSentence(index, index, 0, text.length, text)
|
||||||
|
private fun audio(id: Int) = SpeechAudio(floatArrayOf(id.toFloat()), 24000)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun sileroDefaultsToXeniaRoutesEnglishAndResetsVoiceOnEngineChange() = runTest {
|
||||||
|
val calls = mutableListOf<String>()
|
||||||
|
var accented = false
|
||||||
|
val player = DesktopReadAloudPlayer(this, { text, voice -> calls += "super:$voice:$text"; audio(1) },
|
||||||
|
{}, { true }, { accented = true; it }, { text, voice -> calls += "silero:$voice:$text"; audio(1) })
|
||||||
|
assertEquals("silero", player.settingsState.value.selectedEngineId)
|
||||||
|
assertEquals("xenia", player.settingsState.value.selectedVoiceId)
|
||||||
|
player.prepare(listOf(sentence(0, "Привет."), sentence(1, "Hello."), sentence(2, "Привет, John.")), 0)
|
||||||
|
player.play()
|
||||||
|
advanceUntilIdle()
|
||||||
|
assertEquals(listOf("silero:xenia:Привет.", "super:F1:Hello.", "super:F1:Привет, John."), calls)
|
||||||
|
assertFalse(accented)
|
||||||
|
player.selectVoice("F1")
|
||||||
|
assertEquals("xenia", player.settingsState.value.selectedVoiceId)
|
||||||
|
player.selectEngine("supertonic-3")
|
||||||
|
assertEquals("F1", player.settingsState.value.selectedVoiceId)
|
||||||
|
player.selectEngine("silero")
|
||||||
|
assertEquals("xenia", player.settingsState.value.selectedVoiceId)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun switchingAwayFromSileroCancelsPendingSpeech() = runTest {
|
||||||
|
var cancelled = false
|
||||||
|
var played = 0
|
||||||
|
val player = DesktopReadAloudPlayer(this, { _, _ -> audio(1) }, { played++ }, { true },
|
||||||
|
silero = { _, _ -> try { awaitCancellation() } finally { cancelled = true } })
|
||||||
|
player.prepare(listOf(sentence(0, "Привет.")), 0)
|
||||||
|
player.play()
|
||||||
|
runCurrent()
|
||||||
|
player.selectEngine("supertonic-3")
|
||||||
|
advanceUntilIdle()
|
||||||
|
assertTrue(cancelled)
|
||||||
|
assertEquals(1, played)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun stopDuringSynthesisDiscardsAudioAndDoesNotReportAnError() = runTest {
|
||||||
|
var started = false
|
||||||
|
var played = false
|
||||||
|
val player = DesktopReadAloudPlayer(this, { _, _ -> started = true; awaitCancellation() }, { played = true }, { true })
|
||||||
|
player.prepare(listOf(sentence(7, "First.")), 0)
|
||||||
|
player.play()
|
||||||
|
runCurrent()
|
||||||
|
assertTrue(started)
|
||||||
|
assertTrue(player.state.value.buffering)
|
||||||
|
player.stop()
|
||||||
|
runCurrent()
|
||||||
|
assertFalse(played)
|
||||||
|
assertFalse(player.state.value.active)
|
||||||
|
assertNull(player.settingsState.value.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun skipCancelsOldSynthesisAndStartsRequestedSentence() = runTest {
|
||||||
|
val played = mutableListOf<Int>()
|
||||||
|
val player = DesktopReadAloudPlayer(this, { text, _ ->
|
||||||
|
if (text == "First.") awaitCancellation() else audio(2)
|
||||||
|
}, { played += it.samples[0].toInt(); awaitCancellation() }, { true })
|
||||||
|
player.prepare(listOf(sentence(10, "First."), sentence(20, "Second.")), 0)
|
||||||
|
player.play()
|
||||||
|
runCurrent()
|
||||||
|
player.skip(1)
|
||||||
|
runCurrent()
|
||||||
|
assertEquals(listOf(2), played)
|
||||||
|
assertEquals(20, player.state.value.sentenceIndex)
|
||||||
|
player.stop()
|
||||||
|
runCurrent()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun voiceChangeCancelsPlaybackAndRestartsCurrentSentence() = runTest {
|
||||||
|
val voices = mutableListOf<String>()
|
||||||
|
var cancelledAudio = 0
|
||||||
|
val player = DesktopReadAloudPlayer(this, { _, voice -> voices += voice; audio(1) }, {
|
||||||
|
try { awaitCancellation() } finally { cancelledAudio++ }
|
||||||
|
}, { true })
|
||||||
|
player.prepare(listOf(sentence(3, "Hello.")), 0)
|
||||||
|
player.play()
|
||||||
|
runCurrent()
|
||||||
|
player.selectVoice("M1")
|
||||||
|
runCurrent()
|
||||||
|
assertEquals(listOf("F1", "M1"), voices)
|
||||||
|
assertEquals(1, cancelledAudio)
|
||||||
|
assertEquals(3, player.state.value.sentenceIndex)
|
||||||
|
player.stop()
|
||||||
|
runCurrent()
|
||||||
|
assertEquals(2, cancelledAudio)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun lookaheadDoesNotAdvanceHighlightBeforePlayback() = runTest {
|
||||||
|
val synthesized = mutableListOf<String>()
|
||||||
|
val player = DesktopReadAloudPlayer(this, { text, _ -> synthesized += text; audio(1) }, {
|
||||||
|
awaitCancellation()
|
||||||
|
}, { true })
|
||||||
|
player.prepare(listOf(sentence(4, "First."), sentence(8, "Second."), sentence(12, "Third.")), 0)
|
||||||
|
player.play()
|
||||||
|
runCurrent()
|
||||||
|
assertEquals(listOf("First.", "Second."), synthesized)
|
||||||
|
assertEquals(4, player.state.value.sentenceIndex)
|
||||||
|
player.stop()
|
||||||
|
runCurrent()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun fullQueueUsesSpokenTextAndFinishes() = runTest {
|
||||||
|
val synthesized = mutableListOf<String>()
|
||||||
|
val player = DesktopReadAloudPlayer(this, { text, _ -> synthesized += text; audio(1) }, { delay(10) }, { true })
|
||||||
|
player.prepare(listOf(sentence(0, "1").copy(spokenText = "One.", pauseBeforeMillis = 20), sentence(1, "Two.")), 0)
|
||||||
|
player.play()
|
||||||
|
advanceUntilIdle()
|
||||||
|
assertEquals(listOf("One.", "Two."), synthesized)
|
||||||
|
assertFalse(player.state.value.playing)
|
||||||
|
assertFalse(player.state.value.active)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun accentStageCanBeComparedWithPlainEngineAndNeverChangesOriginalText() = runTest {
|
||||||
|
val inputs = mutableListOf<String>()
|
||||||
|
val original = sentence(0, "замок")
|
||||||
|
val player = DesktopReadAloudPlayer(this, { text, _ -> inputs += text; audio(1) }, {}, { true }, { "з+амок" })
|
||||||
|
player.prepare(listOf(original), 0)
|
||||||
|
player.play()
|
||||||
|
advanceUntilIdle()
|
||||||
|
assertEquals(listOf("за\u0301мок"), inputs)
|
||||||
|
assertEquals("замок", original.spokenText)
|
||||||
|
player.selectEngine("supertonic-3")
|
||||||
|
player.play()
|
||||||
|
advanceUntilIdle()
|
||||||
|
assertEquals(listOf("за\u0301мок", "замок"), inputs)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun accentedTextIsRechunkedToFitTtsWithoutDiscardingMarks() = runTest {
|
||||||
|
val inputs = mutableListOf<String>()
|
||||||
|
val marked = "а\u0301 ".repeat(110).trim()
|
||||||
|
val player = DesktopReadAloudPlayer(this, { text, _ -> inputs += text; audio(1) }, {}, { true }, { marked })
|
||||||
|
player.prepare(listOf(sentence(0, "а ".repeat(110))), 0)
|
||||||
|
player.play()
|
||||||
|
advanceUntilIdle()
|
||||||
|
assertTrue(inputs.size > 1)
|
||||||
|
assertTrue(inputs.all { it.length <= 300 })
|
||||||
|
assertEquals(marked.replace(" ", ""), inputs.joinToString("").replace(" ", ""))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun missingModelAndInferenceErrorsRemainVisibleAndRetryable() = runTest {
|
||||||
|
var installed = false
|
||||||
|
var calls = 0
|
||||||
|
val player = DesktopReadAloudPlayer(this, { _, _ -> calls++; error("bad model") }, {}, { installed })
|
||||||
|
player.prepare(listOf(sentence(0, "Hello.")), 0)
|
||||||
|
player.play()
|
||||||
|
assertEquals(0, calls)
|
||||||
|
assertFalse(player.state.value.playing)
|
||||||
|
assertNotNull(player.settingsState.value.message)
|
||||||
|
installed = true
|
||||||
|
player.play()
|
||||||
|
advanceUntilIdle()
|
||||||
|
assertEquals(1, calls)
|
||||||
|
assertTrue(player.state.value.active)
|
||||||
|
assertFalse(player.state.value.buffering)
|
||||||
|
assertNotNull(player.settingsState.value.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package net.sergeych.toread.tts
|
||||||
|
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
|
class SupertonicTextTest {
|
||||||
|
@Test
|
||||||
|
fun longSentencesAndUnbrokenWordsAreBoundedWithoutLosingText() {
|
||||||
|
for (text in listOf("Слово ".repeat(150), "a".repeat(601), "a".repeat(299) + "😀" + "b".repeat(301), "а".repeat(300) + "\u0301" + "а".repeat(50))) {
|
||||||
|
val chunks = SupertonicTts.chunks(text)
|
||||||
|
assertTrue(chunks.all { it.length <= 300 && it.isNotBlank() })
|
||||||
|
assertEquals(text.filterNot(Char::isWhitespace), chunks.joinToString("").filterNot(Char::isWhitespace))
|
||||||
|
assertTrue(chunks.none { Character.isHighSurrogate(it.last()) || Character.isLowSurrogate(it.first()) })
|
||||||
|
assertTrue(chunks.none { it.first() == '\u0301' })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun languageSelectionHandlesRussianEnglishAndMixedText() {
|
||||||
|
assertEquals("ru", SupertonicTts.languageOf("Ёж шёл домой."))
|
||||||
|
assertEquals("en", SupertonicTts.languageOf("The library."))
|
||||||
|
assertEquals("na", SupertonicTts.languageOf("Он сказал Hello."))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun preprocessingDoesNotInsertPredictedStress() {
|
||||||
|
assertEquals("<ru>На двери висит замок.</ru>", SupertonicTts.prepareText("На двери висит замок", "ru"))
|
||||||
|
assertEquals("<en>Hello!</en>", SupertonicTts.prepareText("Hello !", "en"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun ruaccentStressBecomesCombiningAcuteOnCyrillicVowels() {
|
||||||
|
assertEquals("за\u0301мок замо\u0301к Ё\u0301лка", SupertonicTts.russianStressToUnicode("з+амок зам+ок +Ёлка"))
|
||||||
|
assertEquals("2+2 +a +б а\u0301", SupertonicTts.russianStressToUnicode("2+2 +a +б а\u0301"))
|
||||||
|
assertEquals("<ru>За\u0301мок.</ru>", SupertonicTts.prepareText("З+амок", "ru"))
|
||||||
|
assertEquals("<ru>За\u0301мок.</ru>", SupertonicTts.prepareText("За\u0301мок", "ru"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun pcmConversionClipsAndHandlesNonFiniteSamples() {
|
||||||
|
val bytes = SpeechAudio(floatArrayOf(-2f, 2f, Float.NaN), 44100).pcm16()
|
||||||
|
assertEquals(listOf(1, 128, 255, 127, 0, 0), bytes.map { it.toInt() and 255 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,8 +24,12 @@ actual suspend fun loadLibraryItems(): List<LibraryItem> = emptyList()
|
|||||||
|
|
||||||
actual suspend fun loadLibraryItemsPage(limit: Int, offset: Int): List<LibraryItem> = emptyList()
|
actual suspend fun loadLibraryItemsPage(limit: Int, offset: Int): List<LibraryItem> = emptyList()
|
||||||
|
|
||||||
|
actual suspend fun loadRecentlyAddedLibraryItems(sinceImportedAt: Long, limit: Int): List<LibraryItem> = emptyList()
|
||||||
|
|
||||||
actual suspend fun searchLibraryItems(query: String, limit: Int): List<LibraryItem> = emptyList()
|
actual suspend fun searchLibraryItems(query: String, limit: Int): List<LibraryItem> = emptyList()
|
||||||
|
|
||||||
|
actual fun currentLibraryTimeMillis(): Long = 0L
|
||||||
|
|
||||||
actual suspend fun loadLibraryItem(fileId: String): LibraryItem? = null
|
actual suspend fun loadLibraryItem(fileId: String): LibraryItem? = null
|
||||||
|
|
||||||
actual suspend fun loadLibraryItemCover(fileId: String): LibraryCover? = null
|
actual suspend fun loadLibraryItemCover(fileId: String): LibraryCover? = null
|
||||||
@@ -53,9 +57,14 @@ actual suspend fun clearLibraryReadingPosition(fileId: String) = Unit
|
|||||||
|
|
||||||
actual suspend fun markLibraryReadingStatus(fileId: String, status: BookReadingStatus): Boolean = false
|
actual suspend fun markLibraryReadingStatus(fileId: String, status: BookReadingStatus): Boolean = false
|
||||||
|
|
||||||
|
actual suspend fun markLibraryFavorite(fileId: String, favorite: Boolean): Boolean = false
|
||||||
|
|
||||||
actual suspend fun shareLibraryBookFile(fileId: String): Boolean = false
|
actual suspend fun shareLibraryBookFile(fileId: String): Boolean = false
|
||||||
|
|
||||||
actual suspend fun viewLibraryBookFile(fileId: String): Boolean = false
|
actual suspend fun viewLibraryBookFile(folder: String, fileName: String): Boolean = false
|
||||||
|
|
||||||
|
actual fun openPlatformUrl(url: String): Boolean =
|
||||||
|
window.open(url, target = "_blank") != null
|
||||||
|
|
||||||
actual suspend fun loadBookInfoExtras(fileId: String): BookInfoExtras = BookInfoExtras()
|
actual suspend fun loadBookInfoExtras(fileId: String): BookInfoExtras = BookInfoExtras()
|
||||||
|
|
||||||
@@ -67,10 +76,59 @@ actual suspend fun loadThemeMode(): ThemeMode = ThemeMode.SYSTEM
|
|||||||
|
|
||||||
actual suspend fun saveThemeMode(mode: ThemeMode) = Unit
|
actual suspend fun saveThemeMode(mode: ThemeMode) = Unit
|
||||||
|
|
||||||
|
actual suspend fun loadReaderFontSettings(): ReaderFontSettings =
|
||||||
|
readerFontSettingsFromStorageValue(window.localStorage.getItem(ReaderFontSettingsStorageKey))
|
||||||
|
|
||||||
|
actual suspend fun saveReaderFontSettings(settings: ReaderFontSettings) {
|
||||||
|
window.localStorage.setItem(ReaderFontSettingsStorageKey, settings.toStorageValue())
|
||||||
|
}
|
||||||
|
|
||||||
|
actual suspend fun loadReaderFullScreen(): Boolean =
|
||||||
|
window.localStorage.getItem(ReaderFullScreenStorageKey)?.toBooleanStrictOrNull() ?: false
|
||||||
|
|
||||||
|
actual suspend fun saveReaderFullScreen(fullScreen: Boolean) {
|
||||||
|
window.localStorage.setItem(ReaderFullScreenStorageKey, fullScreen.toString())
|
||||||
|
}
|
||||||
|
|
||||||
|
actual suspend fun loadReaderPagingOnly(): Boolean =
|
||||||
|
window.localStorage.getItem(ReaderPagingOnlyStorageKey)?.toBooleanStrictOrNull() ?: false
|
||||||
|
|
||||||
|
actual suspend fun saveReaderPagingOnly(enabled: Boolean) {
|
||||||
|
window.localStorage.setItem(ReaderPagingOnlyStorageKey, enabled.toString())
|
||||||
|
}
|
||||||
|
|
||||||
actual suspend fun loadScanDownloadsAutomatically(): Boolean = true
|
actual suspend fun loadScanDownloadsAutomatically(): Boolean = true
|
||||||
|
|
||||||
actual suspend fun saveScanDownloadsAutomatically(enabled: Boolean) = Unit
|
actual suspend fun saveScanDownloadsAutomatically(enabled: Boolean) = Unit
|
||||||
|
|
||||||
|
internal actual suspend fun loadLibraryFilter(): LibraryFilter =
|
||||||
|
when (val saved = window.localStorage.getItem(LibraryFilterStorageKey)) {
|
||||||
|
null -> {
|
||||||
|
warnLibraryFilterFallback("library filter was not saved")
|
||||||
|
LibraryFilter.MyLibrary
|
||||||
|
}
|
||||||
|
else -> runCatching { LibraryFilter.valueOf(saved) }
|
||||||
|
.getOrElse {
|
||||||
|
warnLibraryFilterFallback("invalid saved library filter '$saved'")
|
||||||
|
LibraryFilter.MyLibrary
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal actual suspend fun saveLibraryFilter(filter: LibraryFilter) {
|
||||||
|
window.localStorage.setItem(LibraryFilterStorageKey, filter.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
actual suspend fun loadAppLocaleTag(): String? =
|
||||||
|
window.localStorage.getItem(AppLocaleStorageKey)?.takeIf { it.isNotBlank() }
|
||||||
|
|
||||||
|
actual suspend fun saveAppLocaleTag(localeTag: String?) {
|
||||||
|
if (localeTag.isNullOrBlank()) {
|
||||||
|
window.localStorage.removeItem(AppLocaleStorageKey)
|
||||||
|
} else {
|
||||||
|
window.localStorage.setItem(AppLocaleStorageKey, localeTag)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
actual suspend fun loadDownloadsWasScanned(): Boolean = false
|
actual suspend fun loadDownloadsWasScanned(): Boolean = false
|
||||||
|
|
||||||
actual suspend fun saveDownloadsWasScanned(scanned: Boolean) = Unit
|
actual suspend fun saveDownloadsWasScanned(scanned: Boolean) = Unit
|
||||||
@@ -93,6 +151,16 @@ actual fun watchPlatformDarkTheme(onChange: (Boolean) -> Unit): () -> Unit {
|
|||||||
|
|
||||||
actual fun libraryLogPath(): String? = null
|
actual fun libraryLogPath(): String? = null
|
||||||
|
|
||||||
|
private fun warnLibraryFilterFallback(reason: String) {
|
||||||
|
println("warning $reason; using ${LibraryFilter.MyLibrary.name}")
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val AppLocaleStorageKey = "toread.appLocaleTag"
|
||||||
|
private const val LibraryFilterStorageKey = "toread.libraryFilter"
|
||||||
|
private const val ReaderFontSettingsStorageKey = "toread.readerFontSettings"
|
||||||
|
private const val ReaderFullScreenStorageKey = "toread.readerFullScreen"
|
||||||
|
private const val ReaderPagingOnlyStorageKey = "toread.readerPagingOnly"
|
||||||
|
|
||||||
actual fun formatLibraryLastReadTime(millis: Long): String {
|
actual fun formatLibraryLastReadTime(millis: Long): String {
|
||||||
val totalMinutes = millis / 60_000L
|
val totalMinutes = millis / 60_000L
|
||||||
val minute = (totalMinutes % 60).toString().padStart(2, '0')
|
val minute = (totalMinutes % 60).toString().padStart(2, '0')
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package net.sergeych.toread
|
||||||
|
|
||||||
|
import kotlinx.browser.window
|
||||||
|
|
||||||
|
internal actual fun platformLocaleTags(): List<String> =
|
||||||
|
listOf(window.navigator.language)
|
||||||
@@ -7,9 +7,14 @@ actual object ReadAloudPlatform {
|
|||||||
actual val isSupported: Boolean = false
|
actual val isSupported: Boolean = false
|
||||||
private val mutableState = MutableStateFlow(ReadAloudState())
|
private val mutableState = MutableStateFlow(ReadAloudState())
|
||||||
actual val state: StateFlow<ReadAloudState> = mutableState
|
actual val state: StateFlow<ReadAloudState> = mutableState
|
||||||
|
private val mutableSettingsState = MutableStateFlow(ReadAloudSettingsState())
|
||||||
|
actual val settingsState: StateFlow<ReadAloudSettingsState> = mutableSettingsState
|
||||||
|
|
||||||
actual fun prepare(bookTitle: String, sentences: List<ReadAloudSentence>, startIndex: Int) = Unit
|
actual fun prepare(fileId: String, bookTitle: String, sentences: List<ReadAloudSentence>, startIndex: Int) = Unit
|
||||||
actual fun play() = Unit
|
actual fun play() = Unit
|
||||||
actual fun stop() = Unit
|
actual fun stop() = Unit
|
||||||
actual fun skip(delta: Int) = Unit
|
actual fun skip(delta: Int) = Unit
|
||||||
|
actual fun refreshSettings() = Unit
|
||||||
|
actual fun selectEngine(engineId: String?) = Unit
|
||||||
|
actual fun selectVoice(voiceId: String?) = Unit
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
# Desktop CPU speech trial
|
||||||
|
|
||||||
|
Desktop Read aloud defaults to **Silero v5_5_ru / Xenia** for Russian when its
|
||||||
|
local runtime is installed. Silero runs in a persistent CPU-only Python process
|
||||||
|
and handles its own stress and ё restoration. English and mixed-script chunks
|
||||||
|
use Supertonic 3 / F1 through ONNX Runtime's CPU provider. Mixed passages retain
|
||||||
|
Supertonic's Russian pronunciation limitations. Plain Supertonic is retained as an audition baseline. Initial listening feedback
|
||||||
|
found its Russian word stress unacceptable. An optional RUAccent CPU stage now
|
||||||
|
adds stress and restores ё before synthesis; its +vowel notation is converted to
|
||||||
|
a Cyrillic vowel followed by U+0301. Manual minimal-pair listening showed stress
|
||||||
|
changes, but this is not a comprehensive pronunciation-quality evaluation.
|
||||||
|
Android retains its existing system TTS implementation.
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
From the repository root:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 scripts/download-tts-model.py
|
||||||
|
./gradlew :composeApp:run
|
||||||
|
```
|
||||||
|
|
||||||
|
The script downloads about 401 MB into the ignored `.local/tts/supertonic-3`
|
||||||
|
directory. Downloads are revision-pinned and verified against the committed file
|
||||||
|
manifest. It reuses valid files and replaces incomplete downloads only after hash
|
||||||
|
verification. No Python packages are needed. The model license is saved alongside
|
||||||
|
its weights.
|
||||||
|
|
||||||
|
Open a book and choose **Read aloud** from the reader menu. Playback highlights the
|
||||||
|
current sentence, follows the reading position, and exposes Stop, previous/next
|
||||||
|
sentence, and voice settings. Silero offers Xenia (default), Baya, Aidar, Kseniya
|
||||||
|
and Eugene. The Supertonic engines offer F1–F5 and M1–M5. Engine and voice choices
|
||||||
|
last for this application session; each launch starts with Xenia if installed.
|
||||||
|
|
||||||
|
The model loads lazily on first playback. One chunk is prepared ahead while audio
|
||||||
|
plays. Stop, skipping, and voice changes cancel the old playback and lookahead;
|
||||||
|
Supertonic inference checks cancellation between model stages/denoising steps;
|
||||||
|
cancelling Silero inference terminates its worker, which restarts on demand. Long
|
||||||
|
sentences are split at whitespace into at most 300-character chunks. English and
|
||||||
|
Russian are selected from their scripts; mixed-script chunks use the model's
|
||||||
|
language-agnostic `na` mode. This heuristic is not general language detection.
|
||||||
|
|
||||||
|
For a model installed elsewhere, set `YEREED_TTS_MODEL_DIR` (or JVM property
|
||||||
|
`yereed.tts.modelDir`) to the directory containing `onnx/` and `voice_styles/`.
|
||||||
|
Without an override the app searches parent directories for the workspace model,
|
||||||
|
then falls back to `~/.toread/tts/supertonic-3`. Packaged applications can use that
|
||||||
|
home-directory location. The application itself never downloads models or sends
|
||||||
|
text over the network. The first Gradle build and model setup require downloads.
|
||||||
|
|
||||||
|
## Optional RUAccent stage (desktop trial)
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 scripts/setup-ruaccent.py
|
||||||
|
./gradlew :composeApp:run
|
||||||
|
```
|
||||||
|
|
||||||
|
This creates a private Python 3.12 runtime under `.local/ruaccent-runtime` and
|
||||||
|
fetches about 726 MB of revision-pinned RUAccent assets into `.local/tts/ruaccent`.
|
||||||
|
It does not change system Python. The bootstrap supports Linux x86_64 directly;
|
||||||
|
on other systems install `uv` first. The dependency versions and model hashes
|
||||||
|
are recorded under `scripts/`. This desktop trial uses RUAccent 1.5.8.3,
|
||||||
|
`turbo3.1`, the full dictionary/rule pipeline, and CPU execution with four threads.
|
||||||
|
This is a desktop quality experiment, not an Android footprint recommendation.
|
||||||
|
|
||||||
|
After setup, restart the reader. **Supertonic 3 + RUAccent** becomes the default
|
||||||
|
engine; select **Supertonic 3** in read-aloud settings for a direct comparison.
|
||||||
|
English bypasses the accentor. Already marked Russian chunks are preserved.
|
||||||
|
The accentor is a persistent local child process communicating over stdin/stdout;
|
||||||
|
Hugging Face and Transformers run in offline mode. Book contents are never sent
|
||||||
|
to a server. Set `YEREED_RUACCENT_HOME` to override its installation directory.
|
||||||
|
Stop/skip kills a pending accentor request when necessary; the next request
|
||||||
|
restarts the worker. Displayed book text and stored files are unchanged.
|
||||||
|
|
||||||
|
The model recognizes U+0301, and preprocessing preserves it. For example,
|
||||||
|
`з+амок` becomes `за́мок`, not a Latin accented-vowel substitution. Predicted
|
||||||
|
stress can still be wrong; model-token support does not guarantee compliance.
|
||||||
|
|
||||||
|
## Audition / benchmark
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./gradlew :composeApp:ttsSample
|
||||||
|
# Also play the four samples through the desktop audio device:
|
||||||
|
./gradlew :composeApp:ttsSample -PttsPlay=true
|
||||||
|
# Controlled manual stress pairs, same words/noise seed:
|
||||||
|
./gradlew :composeApp:ttsSample -PttsStress=true -PttsPlay=true
|
||||||
|
# Original plain Russian passage, then RUAccent + Supertonic:
|
||||||
|
./gradlew :composeApp:ttsSample -PttsRuAccent=true -PttsPlay=true
|
||||||
|
```
|
||||||
|
|
||||||
|
WAV files and their exact unaccented texts go to `composeApp/build/tts-samples/`.
|
||||||
|
The sample task uses the same inference and audio code as the reader without
|
||||||
|
opening or changing the library. It prints model-load time, synthesis time,
|
||||||
|
audio duration, and real-time factor (generation seconds / audio seconds).
|
||||||
|
|
||||||
|
Initial measurements on an Intel Core Ultra 9 275HX, four CPU threads, eight
|
||||||
|
steps, speed 1.05: 1.075 seconds model load; English/Russian F1/M1 samples generated
|
||||||
|
11.6–15.3 seconds of audio in 2.4–3.3 seconds (RTF 0.20–0.24). These are short
|
||||||
|
local samples, not phone/battery or long-book benchmarks. Synthesis completion
|
||||||
|
and non-silent waveforms do not establish pronunciation quality.
|
||||||
|
|
||||||
|
## Dependencies and provenance
|
||||||
|
|
||||||
|
- [Supertonic source](https://github.com/supertone-oss-archive/supertonic): the
|
||||||
|
Kotlin inference code adapts the MIT Java example; attribution is in
|
||||||
|
[licenses/supertonic-code-MIT.txt](licenses/supertonic-code-MIT.txt).
|
||||||
|
- [Supertonic 3 model](https://huggingface.co/supertone-oss-archive/supertonic-3):
|
||||||
|
revision `aafc6e32416a594460b32413efc49d7fe4ce6d46`, OpenRAIL-M weights.
|
||||||
|
Upstream development/support ended in September 2026.
|
||||||
|
- ONNX Runtime 1.23.1, standard CPU artifact; no CUDA/GPU provider.
|
||||||
|
- JSON loading uses Jackson; PCM playback uses Java Sound.
|
||||||
|
|
||||||
|
Run `./gradlew :composeApp:jvmTest` for text-boundary, PCM conversion, queue,
|
||||||
|
lookahead, cancellation, voice-change, and missing-model/error tests, together
|
||||||
|
with existing desktop/common tests. Model inference is exercised separately by
|
||||||
|
`ttsSample`, so ordinary tests do not download weights or use speakers.
|
||||||
|
|
||||||
|
The isolated virtual-display capture did not provide a usable UI image; rendered
|
||||||
|
GUI verification remains incomplete. No further screen access is used.
|
||||||
|
|
||||||
|
RUAccent measurements on the same host: about 5.9 seconds cold load, 30–43 ms
|
||||||
|
for the two warm short passages, and about 2.1 GiB resident memory for the full
|
||||||
|
accentor worker alone. The combined passage took 2.98 seconds of TTS synthesis
|
||||||
|
for 16.42 seconds of audio, excluding accentor startup. In that passage RUAccent
|
||||||
|
incorrectly chose `за́мок` for the door lock; on a shorter explicit door-lock
|
||||||
|
sentence it chose `замо́к`. These are limited observations, not an accuracy score.
|
||||||
|
|
||||||
|
## Silero Russian audition
|
||||||
|
|
||||||
|
User listening feedback rejected Supertonic's Russian quality. A separate CPU
|
||||||
|
audition uses official Silero `v5_5_ru`, with its own stress, ё, stress-homograph
|
||||||
|
and ё-homograph processing enabled. It does not use RUAccent. The same model is
|
||||||
|
now the preferred desktop Russian engine. The Russian model is CC BY-NC-SA 4.0, unlike Silero's MIT CIS
|
||||||
|
base models; see [upstream](https://github.com/snakers4/silero-models).
|
||||||
|
|
||||||
|
Setup from the repository root (requires `uv`; our existing local copy is
|
||||||
|
`.local/tools/uv`):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
export UV_CACHE_DIR="$PWD/.local/uv-cache"
|
||||||
|
export UV_PYTHON_INSTALL_DIR="$PWD/.local/python"
|
||||||
|
export UV_SYSTEM_CERTS=true
|
||||||
|
.local/tools/uv venv --python 3.12.14 .local/silero-runtime
|
||||||
|
.local/tools/uv pip sync --python .local/silero-runtime/bin/python scripts/silero-requirements.txt --index-url https://download.pytorch.org/whl/cpu
|
||||||
|
mkdir -p .local/tts/silero-v5_5-ru
|
||||||
|
curl -fL https://models.silero.ai/models/tts/ru/v5_5_ru.pt -o .local/tts/silero-v5_5-ru/model.pt.part
|
||||||
|
mv .local/tts/silero-v5_5-ru/model.pt.part .local/tts/silero-v5_5-ru/model.pt
|
||||||
|
.local/silero-runtime/bin/python scripts/silero-sample.py
|
||||||
|
python3 - <<'PY'
|
||||||
|
from pathlib import Path
|
||||||
|
import json
|
||||||
|
root = Path.cwd()
|
||||||
|
(root / '.local/tts/silero-v5_5-ru/runtime.json').write_text(json.dumps({
|
||||||
|
'python': str(root / '.local/silero-runtime/bin/python')
|
||||||
|
}) + '\n')
|
||||||
|
PY
|
||||||
|
# Restart the reader after setup, or check its actual Kotlin/Python bridge:
|
||||||
|
./gradlew :composeApp:ttsSample -PttsSilero=true
|
||||||
|
```
|
||||||
|
|
||||||
|
Outputs: `composeApp/build/tts-samples/silero-*.wav`, matching input `.txt`
|
||||||
|
files, and `silero-benchmark.json` with timings, settings and the downloaded
|
||||||
|
model's SHA-256. The script uses CPU-only PyTorch, four threads and 48 kHz PCM.
|
||||||
|
Default voices are Xenia, Baya and Aidar; `--voices xenia` limits the audition.
|
||||||
|
Each reads the earlier library passage and a separate unaccented ё/context
|
||||||
|
challenge. Pronunciation quality must be judged by listening.
|
||||||
|
|
||||||
|
The desktop integration discovers `silero-v5_5-ru` beside the Supertonic model
|
||||||
|
directory; `YEREED_SILERO_HOME` can override it. `runtime.json` points to the
|
||||||
|
isolated Python executable. The worker script is bundled in the application;
|
||||||
|
model loading and inference are local. Both models are needed for bilingual use.
|
||||||
|
|
||||||
|
Initial audition on the same desktop: model load 0.38 seconds; six samples
|
||||||
|
generated 13.2–15.5 seconds of audio in 0.36–0.82 seconds (RTF 0.027–0.059,
|
||||||
|
including the first synthesis). All outputs were finite and non-silent.
|
||||||
|
Downloaded model SHA-256:
|
||||||
|
`50081637b602126ee06cb3bc8a744d25651d2da149ee8864b9a379bfdd934437`.
|
||||||
@@ -20,7 +20,7 @@ The common API is `Fb2Format.parse(input: ByteArray, fileName: String? = null)`.
|
|||||||
Import detection:
|
Import detection:
|
||||||
|
|
||||||
- A file is treated as ZIP when its bytes start with the ZIP local-file signature `PK\003\004` or the provided filename ends with `.zip`.
|
- A file is treated as ZIP when its bytes start with the ZIP local-file signature `PK\003\004` or the provided filename ends with `.zip`.
|
||||||
- Otherwise bytes are decoded according to the XML declaration when supported. UTF-8 is the default, and unsupported or missing encodings fall back to UTF-8. `windows-1251` is supported for legacy FB2 files.
|
- Otherwise bytes are decoded according to the XML declaration when supported. UTF-8 is the default, and unsupported or missing encodings fall back to UTF-8. `windows-1251` and `windows-1252` are supported for legacy FB2 files.
|
||||||
- In ZIP archives, the first entry ending with `.fb2` is used. If no such entry exists, the first non-directory entry is used.
|
- In ZIP archives, the first entry ending with `.fb2` is used. If no such entry exists, the first non-directory entry is used.
|
||||||
|
|
||||||
ZIP support:
|
ZIP support:
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2025 Supertone Inc.
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
# Russian Hyphenation Rules
|
||||||
|
|
||||||
|
This document defines the rule set for the Russian hyphenation plugin. The
|
||||||
|
implementation should return the original word with soft hyphens inserted at
|
||||||
|
preferred transfer points. Tests may render soft hyphens as `-` for readability.
|
||||||
|
|
||||||
|
The goal is not perfect dictionary hyphenation. The goal is a deterministic,
|
||||||
|
readable rule set that avoids invalid transfers and produces better break points
|
||||||
|
than the current vowel/consonant heuristic.
|
||||||
|
|
||||||
|
## Character Classes
|
||||||
|
|
||||||
|
Use lowercase character checks for classification.
|
||||||
|
|
||||||
|
- Vowels: `а е ё и о у ы э ю я`
|
||||||
|
- Consonants: Russian letters except vowels, `ь`, `ъ`, and `й`
|
||||||
|
- Non-syllabic letters: `ь ъ`
|
||||||
|
- Semivowel: `й`
|
||||||
|
|
||||||
|
Only hyphenate words made of Russian letters. Leave mixed words, words with
|
||||||
|
digits, existing soft hyphens, and abbreviations unchanged. Short words are
|
||||||
|
hyphenated only when they pass the same legal side-length and vowel filters as
|
||||||
|
longer words.
|
||||||
|
|
||||||
|
## Hard Legal Filters
|
||||||
|
|
||||||
|
A candidate break is illegal if any of these is true:
|
||||||
|
|
||||||
|
- Either side would have fewer than 2 letters.
|
||||||
|
- Either side would contain no vowel.
|
||||||
|
- The right side starts with `ь`, `ъ`, `й`, or `ы`.
|
||||||
|
- The left side ends before `ь` or `ъ`; that is, do not split `под-ъезд` or
|
||||||
|
`бол-ьшой`. Prefer `подъ-езд`, `боль-шой`.
|
||||||
|
- The left side ends before `й`; that is, do not split `ма-йор` or `во-йна`.
|
||||||
|
Prefer `май-ор`, `вой-на`.
|
||||||
|
- The break separates a consonant from a following vowel: reject `люб-овь`,
|
||||||
|
`паст-ух`, `реб-ята`. Prefer `лю-бовь`, `па-стух` or `пас-тух`, `ре-бята`
|
||||||
|
or `ребя-та`.
|
||||||
|
|
||||||
|
## Candidate Generation
|
||||||
|
|
||||||
|
Work between adjacent vowel nuclei. For each span from one vowel to the next,
|
||||||
|
choose preferred break candidates from the consonant cluster between them.
|
||||||
|
|
||||||
|
### Adjacent Vowels
|
||||||
|
|
||||||
|
If two vowels are adjacent, allow a break between them when both resulting parts
|
||||||
|
pass the legal filters.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- `поэт` -> `по-эт`
|
||||||
|
- `академия` -> `ака-де-мия` and not `а-кадемия` or `академи-я`
|
||||||
|
|
||||||
|
### One Consonant Between Vowels
|
||||||
|
|
||||||
|
For `V C V`, break before the consonant.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- `молоко` -> `мо-ло-ко`
|
||||||
|
- `корова` -> `ко-ро-ва`
|
||||||
|
- `переход` -> `пе-ре-ход`
|
||||||
|
|
||||||
|
### Two Consonants Between Vowels
|
||||||
|
|
||||||
|
For `V C C V`, prefer a break between the consonants.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- `лампа` -> `лам-па`
|
||||||
|
- `гордый` -> `гор-дый`
|
||||||
|
- `письмо` -> `пись-мо`
|
||||||
|
|
||||||
|
If the cluster contains `й`, `ь`, or `ъ`, keep that letter on the left and break
|
||||||
|
after it when legal.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- `майор` -> `май-ор`
|
||||||
|
- `подъезд` -> `подъ-езд`
|
||||||
|
- `большой` -> `боль-шой`
|
||||||
|
|
||||||
|
### Three Or More Consonants Between Vowels
|
||||||
|
|
||||||
|
For longer clusters, prefer the latest break that still leaves a pronounceable
|
||||||
|
left part, but keep common inseparable starts on the right:
|
||||||
|
|
||||||
|
- Keep `ст`, `ск`, `сп`, `сн`, `сл`, `см`, `св` together on the right when
|
||||||
|
possible.
|
||||||
|
- Keep stop/liquid pairs together on the right when possible: `бр`, `бл`,
|
||||||
|
`вр`, `вл`, `гр`, `гл`, `др`, `тр`, `кр`, `кл`, `пр`, `пл`, `фр`, `фл`.
|
||||||
|
- Otherwise prefer splitting before the last consonant in the cluster.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- `сестра` -> `се-стра`
|
||||||
|
- `острый` should not use `о-стрый`, because the left side is too short
|
||||||
|
- `родство` -> `род-ство`
|
||||||
|
- `чувство` -> `чув-ство`
|
||||||
|
- `предложение` -> `пред-ло-же-ние`
|
||||||
|
|
||||||
|
## Double Consonants
|
||||||
|
|
||||||
|
When two identical consonants stand between vowels, prefer splitting between
|
||||||
|
them.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- `масса` -> `мас-са`
|
||||||
|
- `длинный` -> `длин-ный`
|
||||||
|
- `касса` -> `кас-са`
|
||||||
|
|
||||||
|
Do not force this rule when the double consonant starts a root after a prefix.
|
||||||
|
Without a dictionary, this exception is hard to detect, so implementation may
|
||||||
|
leave such words to the general cluster logic.
|
||||||
|
|
||||||
|
## Prefix-Like Boundaries
|
||||||
|
|
||||||
|
Without a morphology dictionary, treat these as preferred heuristics only.
|
||||||
|
|
||||||
|
If a word starts with a common prefix and the following part is legal, prefer a
|
||||||
|
break after the prefix:
|
||||||
|
|
||||||
|
- `без`, `бес`, `воз`, `вос`, `вз`, `вс`, `из`, `ис`, `низ`, `нис`, `раз`,
|
||||||
|
`рас`, `роз`, `рос`, `от`, `об`, `объ`, `под`, `подъ`, `пред`, `пере`,
|
||||||
|
`при`, `про`, `над`, `сверх`, `меж`
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- `подбить` -> `под-бить`
|
||||||
|
- `размах` -> `раз-мах`
|
||||||
|
- `предложение` -> `пред-ло-же-ние`
|
||||||
|
- `подъезд` -> `подъ-езд`
|
||||||
|
|
||||||
|
Do not create a right side starting with `ы`; prefer later legal breaks.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- `разыскать` -> `ра-зыскать` or `разыс-кать`, not `раз-ыскать`
|
||||||
|
- `розыгрыш` -> `ро-зыгрыш` or `розыг-рыш`, not `роз-ыгрыш`
|
||||||
|
|
||||||
|
## Ranking
|
||||||
|
|
||||||
|
A word may have several legal break points. The plugin should insert all good
|
||||||
|
breaks, but it should avoid noisy low-quality breaks. Use this ranking:
|
||||||
|
|
||||||
|
1. Prefix boundary, if legal.
|
||||||
|
2. Double consonant split between vowels.
|
||||||
|
3. Syllable breaks from adjacent vowel and consonant-cluster rules.
|
||||||
|
4. Longer-cluster fallback break before the last consonant.
|
||||||
|
|
||||||
|
Reject candidates that are legal but awkward when a better candidate is within
|
||||||
|
one character and both candidates divide the same vowel-to-vowel span.
|
||||||
|
|
||||||
|
## Example Expectations
|
||||||
|
|
||||||
|
These strings use `-` where the implementation will insert `SoftHyphen`.
|
||||||
|
|
||||||
|
```text
|
||||||
|
молоко -> мо-ло-ко
|
||||||
|
корова -> ко-ро-ва
|
||||||
|
яблоко -> яб-ло-ко
|
||||||
|
повествование -> по-вест-во-ва-ние
|
||||||
|
предложение -> пред-ло-же-ние
|
||||||
|
компьютер -> компью-тер
|
||||||
|
подъезд -> подъ-езд
|
||||||
|
большой -> боль-шой
|
||||||
|
майор -> май-ор
|
||||||
|
масса -> мас-са
|
||||||
|
длинный -> длин-ный
|
||||||
|
разыскать -> ра-зыс-кать
|
||||||
|
розыгрыш -> ро-зыг-рыш
|
||||||
|
```
|
||||||
|
|
||||||
|
## Non-Goals
|
||||||
|
|
||||||
|
- Full dictionary-level hyphenation.
|
||||||
|
- Stress-aware syllabification.
|
||||||
|
- Exact morpheme detection for every prefix/root boundary.
|
||||||
|
- Hyphenating proper abbreviations and mixed-script technical identifiers.
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
[versions]
|
[versions]
|
||||||
agp = "8.11.2"
|
agp = "8.13.2"
|
||||||
android-compileSdk = "36"
|
android-compileSdk = "36"
|
||||||
android-minSdk = "26"
|
android-minSdk = "26"
|
||||||
android-targetSdk = "36"
|
android-targetSdk = "36"
|
||||||
@@ -19,8 +19,12 @@ ktor = "3.4.3"
|
|||||||
logback = "1.5.32"
|
logback = "1.5.32"
|
||||||
material3 = "1.11.0-alpha07"
|
material3 = "1.11.0-alpha07"
|
||||||
h2 = "2.4.240"
|
h2 = "2.4.240"
|
||||||
|
onnxruntime = "1.23.1"
|
||||||
|
jackson = "2.18.6"
|
||||||
|
|
||||||
[libraries]
|
[libraries]
|
||||||
|
onnxruntime = { module = "com.microsoft.onnxruntime:onnxruntime", version.ref = "onnxruntime" }
|
||||||
|
jackson-databind = { module = "com.fasterxml.jackson.core:jackson-databind", version.ref = "jackson" }
|
||||||
kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" }
|
kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" }
|
||||||
kotlin-testJunit = { module = "org.jetbrains.kotlin:kotlin-test-junit", version.ref = "kotlin" }
|
kotlin-testJunit = { module = "org.jetbrains.kotlin:kotlin-test-junit", version.ref = "kotlin" }
|
||||||
junit = { module = "junit:junit", version.ref = "junit" }
|
junit = { module = "junit:junit", version.ref = "junit" }
|
||||||
@@ -41,6 +45,7 @@ compose-components-resources = { module = "org.jetbrains.compose.components:comp
|
|||||||
compose-uiToolingPreview = { module = "org.jetbrains.compose.ui:ui-tooling-preview", version.ref = "composeMultiplatform" }
|
compose-uiToolingPreview = { module = "org.jetbrains.compose.ui:ui-tooling-preview", version.ref = "composeMultiplatform" }
|
||||||
kotlinx-coroutinesSwing = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-swing", version.ref = "kotlinx-coroutines" }
|
kotlinx-coroutinesSwing = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-swing", version.ref = "kotlinx-coroutines" }
|
||||||
kotlinx-coroutinesCore = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx-coroutines" }
|
kotlinx-coroutinesCore = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx-coroutines" }
|
||||||
|
kotlinx-coroutinesTest = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" }
|
||||||
h2 = { module = "com.h2database:h2", version.ref = "h2" }
|
h2 = { module = "com.h2database:h2", version.ref = "h2" }
|
||||||
logback = { module = "ch.qos.logback:logback-classic", version.ref = "logback" }
|
logback = { module = "ch.qos.logback:logback-classic", version.ref = "logback" }
|
||||||
ktor-serverCore = { module = "io.ktor:ktor-server-core-jvm", version.ref = "ktor" }
|
ktor-serverCore = { module = "io.ktor:ktor-server-core-jvm", version.ref = "ktor" }
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||||
|
<!-- 512x512 app icon - square book mark for launcher use -->
|
||||||
|
<svg width="512" height="512" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<defs>
|
||||||
|
<radialGradient id="bgGrad" cx="45%" cy="35%" r="75%">
|
||||||
|
<stop offset="0%" stop-color="#2e6b8a"/>
|
||||||
|
<stop offset="100%" stop-color="#0d2535"/>
|
||||||
|
</radialGradient>
|
||||||
|
<filter id="shadow" x="-10%" y="-5%" width="130%" height="120%">
|
||||||
|
<feOffset in="SourceAlpha" dx="5" dy="7" result="offset"/>
|
||||||
|
<feGaussianBlur in="offset" stdDeviation="8" result="blur"/>
|
||||||
|
<feColorMatrix in="blur" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.4 0" result="shadowBlur"/>
|
||||||
|
<feMerge>
|
||||||
|
<feMergeNode in="shadowBlur"/>
|
||||||
|
<feMergeNode in="SourceGraphic"/>
|
||||||
|
</feMerge>
|
||||||
|
</filter>
|
||||||
|
<linearGradient id="pageGrad" x1="0%" y1="0%" x2="100%" y2="0%">
|
||||||
|
<stop offset="0%" stop-color="#f0ede3"/>
|
||||||
|
<stop offset="100%" stop-color="#e8e4d8"/>
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="coverGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#3a82a6"/>
|
||||||
|
<stop offset="100%" stop-color="#1a3d52"/>
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="spineGrad" x1="0%" y1="0%" x2="100%" y2="0%">
|
||||||
|
<stop offset="0%" stop-color="#122c3c"/>
|
||||||
|
<stop offset="100%" stop-color="#2e6b8a"/>
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="coverShine" x1="0%" y1="0%" x2="30%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#ffffff" stop-opacity="0.18"/>
|
||||||
|
<stop offset="100%" stop-color="#ffffff" stop-opacity="0"/>
|
||||||
|
</linearGradient>
|
||||||
|
</defs>
|
||||||
|
|
||||||
|
<rect width="512" height="512" fill="url(#bgGrad)"/>
|
||||||
|
<ellipse cx="268" cy="256" rx="200" ry="220" fill="#2e6b8a" opacity="0.25"/>
|
||||||
|
|
||||||
|
<g filter="url(#shadow)">
|
||||||
|
<rect x="112" y="92" width="318" height="318" rx="10" fill="url(#pageGrad)"/>
|
||||||
|
<rect x="104" y="84" width="318" height="318" rx="10" fill="#ece9df"/>
|
||||||
|
<rect x="96" y="76" width="318" height="318" rx="10" fill="#f0ede3"/>
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<rect x="74" y="76" width="54" height="360" rx="10" fill="url(#spineGrad)"/>
|
||||||
|
<rect x="116" y="76" width="324" height="360" rx="10" fill="url(#coverGrad)"/>
|
||||||
|
<rect x="116" y="76" width="324" height="360" rx="10" fill="url(#coverShine)"/>
|
||||||
|
<line x1="128" y1="86" x2="128" y2="426" stroke="#00000030" stroke-width="2"/>
|
||||||
|
<rect x="140" y="100" width="276" height="312" rx="6" fill="none" stroke="#ffffff30" stroke-width="4"/>
|
||||||
|
|
||||||
|
<g transform="translate(139, 116) scale(3.45)">
|
||||||
|
<path d="m 32.120065,25.957965 -15.0296,-9.2912 c -0.3066,-0.187 -0.6532,0.1603 -0.4666,0.4676 l 8.9112,14.4745 c 0.2399,0.3874 0.5665,0.7013 0.9597,0.9284 l 14.0032,8.0555 V 0.34209525 c 0,-0.394094 -0.5532,-0.474248 -0.6665,-0.1002 z" fill="#6197b4"/>
|
||||||
|
<path d="m 25.901665,48.988865 -9.271,15.0556 c -0.1866,0.3073 0.16,0.6546 0.4665,0.4676 l 14.4431,-8.9305 c 0.3866,-0.2405 0.6999,-0.5678 0.9265,-0.9619 l 8.038,-14.0336 H 0.34134532 c -0.393231,0 -0.473212,0.5544 -0.09997,0.6679 z" fill="#bdccd6"/>
|
||||||
|
<path d="m 55.101065,32.189965 9.2711,-15.0623 c 0.1866,-0.3072 -0.16,-0.6546 -0.4666,-0.4675 l -14.4431,8.9371 c -0.3865,0.2405 -0.6998,0.5678 -0.9264,0.9619 l -8.038,14.027 h 40.1634 c 0.3932,0 0.4732,-0.5544 0.1,-0.668 z" fill="#94bfcf"/>
|
||||||
|
<path d="m 54.507965,48.641565 -14.0099,-8.0555 v 40.2507 c 0,0.3941 0.5532,0.4742 0.6665,0.1002 l 7.7181,-25.7094 15.0296,9.2912 c 0.3066,0.187 0.6532,-0.1603 0.4665,-0.4676 l -8.9177,-14.4812 c -0.2333,-0.3807 -0.5666,-0.7013 -0.9531,-0.9284 z" fill="#eee9d9"/>
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<rect x="74" y="390" width="54" height="46" rx="0 0 10 10" fill="#0e2030" opacity="0.75"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 3.6 KiB |
@@ -1,65 +1,264 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||||
<!-- 512x512 app icon — desktop launcher & Android (keep content in inner ~340px safe zone) -->
|
<!-- 512x512 app icon - square book mark for launcher use -->
|
||||||
<svg width="512" height="512" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
||||||
<defs>
|
<svg
|
||||||
<radialGradient id="bgGrad" cx="45%" cy="35%" r="75%">
|
width="512"
|
||||||
<stop offset="0%" stop-color="#2e6b8a"/>
|
height="512"
|
||||||
<stop offset="100%" stop-color="#0d2535"/>
|
viewBox="0 0 512 512"
|
||||||
|
fill="none"
|
||||||
|
version="1.1"
|
||||||
|
id="svg20"
|
||||||
|
sodipodi:docname="icon-app.svg"
|
||||||
|
inkscape:version="1.4.4 (1:1.4.4+202605061436+dcaf3e7d9e)"
|
||||||
|
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||||
|
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
xmlns:svg="http://www.w3.org/2000/svg">
|
||||||
|
<sodipodi:namedview
|
||||||
|
id="namedview20"
|
||||||
|
pagecolor="#ffffff"
|
||||||
|
bordercolor="#000000"
|
||||||
|
borderopacity="0.25"
|
||||||
|
inkscape:showpageshadow="2"
|
||||||
|
inkscape:pageopacity="0.0"
|
||||||
|
inkscape:pagecheckerboard="0"
|
||||||
|
inkscape:deskcolor="#d1d1d1"
|
||||||
|
inkscape:zoom="1.7832031"
|
||||||
|
inkscape:cx="264.13144"
|
||||||
|
inkscape:cy="289.36693"
|
||||||
|
inkscape:window-width="1861"
|
||||||
|
inkscape:window-height="1163"
|
||||||
|
inkscape:window-x="0"
|
||||||
|
inkscape:window-y="0"
|
||||||
|
inkscape:window-maximized="1"
|
||||||
|
inkscape:current-layer="svg20" />
|
||||||
|
<defs
|
||||||
|
id="defs10">
|
||||||
|
<radialGradient
|
||||||
|
id="bgGrad"
|
||||||
|
cx="45%"
|
||||||
|
cy="35%"
|
||||||
|
r="75%">
|
||||||
|
<stop
|
||||||
|
offset="0%"
|
||||||
|
stop-color="#2e6b8a"
|
||||||
|
id="stop1" />
|
||||||
|
<stop
|
||||||
|
offset="100%"
|
||||||
|
stop-color="#0d2535"
|
||||||
|
id="stop2" />
|
||||||
</radialGradient>
|
</radialGradient>
|
||||||
<filter id="shadow" x="-10%" y="-5%" width="130%" height="120%">
|
<filter
|
||||||
<feDropShadow dx="5" dy="7" stdDeviation="8" flood-color="#00000066"/>
|
id="shadow"
|
||||||
|
x="-0.05748503"
|
||||||
|
y="-0.05748503"
|
||||||
|
width="1.1299401"
|
||||||
|
height="1.1359281">
|
||||||
|
<feOffset
|
||||||
|
in="SourceAlpha"
|
||||||
|
dx="5"
|
||||||
|
dy="7"
|
||||||
|
result="offset"
|
||||||
|
id="feOffset2" />
|
||||||
|
<feGaussianBlur
|
||||||
|
in="offset"
|
||||||
|
stdDeviation="8"
|
||||||
|
result="blur"
|
||||||
|
id="feGaussianBlur2" />
|
||||||
|
<feColorMatrix
|
||||||
|
in="blur"
|
||||||
|
type="matrix"
|
||||||
|
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.4 0"
|
||||||
|
result="shadowBlur"
|
||||||
|
id="feColorMatrix2" />
|
||||||
|
<feMerge
|
||||||
|
id="feMerge3">
|
||||||
|
<feMergeNode
|
||||||
|
in="shadowBlur"
|
||||||
|
id="feMergeNode2" />
|
||||||
|
<feMergeNode
|
||||||
|
in="SourceGraphic"
|
||||||
|
id="feMergeNode3" />
|
||||||
|
</feMerge>
|
||||||
</filter>
|
</filter>
|
||||||
<linearGradient id="pageGrad" x1="0%" y1="0%" x2="100%" y2="0%">
|
<linearGradient
|
||||||
<stop offset="0%" stop-color="#f0ede3"/>
|
id="pageGrad"
|
||||||
<stop offset="100%" stop-color="#e8e4d8"/>
|
x1="112"
|
||||||
|
y1="92"
|
||||||
|
x2="430"
|
||||||
|
y2="92"
|
||||||
|
gradientUnits="userSpaceOnUse">
|
||||||
|
<stop
|
||||||
|
offset="0%"
|
||||||
|
stop-color="#f0ede3"
|
||||||
|
id="stop3" />
|
||||||
|
<stop
|
||||||
|
offset="100%"
|
||||||
|
stop-color="#e8e4d8"
|
||||||
|
id="stop4" />
|
||||||
</linearGradient>
|
</linearGradient>
|
||||||
<linearGradient id="coverGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
<linearGradient
|
||||||
<stop offset="0%" stop-color="#3a82a6"/>
|
id="coverGrad"
|
||||||
<stop offset="100%" stop-color="#1a3d52"/>
|
x1="122.27474"
|
||||||
|
y1="72.099931"
|
||||||
|
x2="463.80072"
|
||||||
|
y2="413.62592"
|
||||||
|
gradientTransform="matrix(0.6899326,0,0,0.76659181,67.335419,73.748798)"
|
||||||
|
gradientUnits="userSpaceOnUse">
|
||||||
|
<stop
|
||||||
|
offset="0%"
|
||||||
|
stop-color="#3a82a6"
|
||||||
|
id="stop5" />
|
||||||
|
<stop
|
||||||
|
offset="100%"
|
||||||
|
stop-color="#1a3d52"
|
||||||
|
id="stop6" />
|
||||||
</linearGradient>
|
</linearGradient>
|
||||||
<linearGradient id="spineGrad" x1="0%" y1="0%" x2="100%" y2="0%">
|
<linearGradient
|
||||||
<stop offset="0%" stop-color="#122c3c"/>
|
id="spineGrad"
|
||||||
<stop offset="100%" stop-color="#2e6b8a"/>
|
x1="191.06718"
|
||||||
|
y1="29.434673"
|
||||||
|
x2="330.49458"
|
||||||
|
y2="29.434673"
|
||||||
|
gradientTransform="matrix(0.30396746,0,0,1.8795869,63.07392,73.440088)"
|
||||||
|
gradientUnits="userSpaceOnUse">
|
||||||
|
<stop
|
||||||
|
offset="0%"
|
||||||
|
stop-color="#122c3c"
|
||||||
|
id="stop7" />
|
||||||
|
<stop
|
||||||
|
offset="100%"
|
||||||
|
stop-color="#2e6b8a"
|
||||||
|
id="stop8" />
|
||||||
</linearGradient>
|
</linearGradient>
|
||||||
<linearGradient id="coverShine" x1="0%" y1="0%" x2="30%" y2="100%">
|
<linearGradient
|
||||||
<stop offset="0%" stop-color="#ffffff" stop-opacity="0.18"/>
|
id="coverShine"
|
||||||
<stop offset="100%" stop-color="#ffffff" stop-opacity="0"/>
|
x1="122.27474"
|
||||||
|
y1="72.099931"
|
||||||
|
x2="224.73254"
|
||||||
|
y2="413.62592"
|
||||||
|
gradientTransform="matrix(0.6899326,0,0,0.76659181,67.335419,73.748798)"
|
||||||
|
gradientUnits="userSpaceOnUse">
|
||||||
|
<stop
|
||||||
|
offset="0%"
|
||||||
|
stop-color="#ffffff"
|
||||||
|
stop-opacity="0.18"
|
||||||
|
id="stop9" />
|
||||||
|
<stop
|
||||||
|
offset="100%"
|
||||||
|
stop-color="#ffffff"
|
||||||
|
stop-opacity="0"
|
||||||
|
id="stop10" />
|
||||||
</linearGradient>
|
</linearGradient>
|
||||||
</defs>
|
</defs>
|
||||||
|
<rect
|
||||||
<!-- Full-bleed background -->
|
width="512"
|
||||||
<rect width="512" height="512" fill="url(#bgGrad)"/>
|
height="512"
|
||||||
|
fill="url(#bgGrad)"
|
||||||
<!-- Subtle radial glow behind book -->
|
id="rect10" />
|
||||||
<ellipse cx="268" cy="256" rx="200" ry="220" fill="#2e6b8a" opacity="0.25"/>
|
<ellipse
|
||||||
|
cx="262.23917"
|
||||||
<!-- Book, scaled 1.84x and centered (book canvas 200x260 → 368x478, centered in 512x512) -->
|
cy="259.92554"
|
||||||
<!-- x_offset=(512-368)/2=72, y_offset=(512-478)/2=17 -->
|
rx="145.45056"
|
||||||
<g transform="translate(72, 17) scale(1.84)">
|
ry="159.99562"
|
||||||
<!-- Pages -->
|
fill="#2e6b8a"
|
||||||
<rect x="36" y="18" width="142" height="230" rx="2" fill="url(#pageGrad)" filter="url(#shadow)"/>
|
opacity="0.25"
|
||||||
<rect x="34" y="16" width="142" height="230" rx="2" fill="#ece9df"/>
|
id="ellipse10"
|
||||||
<rect x="32" y="14" width="142" height="230" rx="2" fill="#f0ede3"/>
|
style="stroke-width:0.727253" />
|
||||||
<!-- Spine -->
|
<g
|
||||||
<rect x="18" y="14" width="18" height="230" rx="2" fill="url(#spineGrad)"/>
|
filter="url(#shadow)"
|
||||||
<line x1="35" y1="14" x2="35" y2="244" stroke="#00000030" stroke-width="1"/>
|
id="g13"
|
||||||
<!-- Cover -->
|
transform="matrix(0.72725281,0,0,0.72725281,67.335419,73.748798)">
|
||||||
<rect x="32" y="14" width="142" height="230" rx="2" fill="url(#coverGrad)"/>
|
<rect
|
||||||
<rect x="32" y="14" width="142" height="230" rx="2" fill="url(#coverShine)"/>
|
x="112"
|
||||||
<!-- Cover border -->
|
y="92"
|
||||||
<rect x="40" y="22" width="126" height="214" rx="1" fill="none" stroke="#ffffff30" stroke-width="1.5"/>
|
width="318"
|
||||||
<!-- Star (scale 0.888 within book, translate 67,59) -->
|
height="318"
|
||||||
<g transform="translate(67, 59) scale(0.888)">
|
rx="10"
|
||||||
<path d="m 32.120065,25.957965 -15.0296,-9.2912 c -0.3066,-0.187 -0.6532,0.1603 -0.4666,0.4676 l 8.9112,14.4745 c 0.2399,0.3874 0.5665,0.7013 0.9597,0.9284 l 14.0032,8.0555 V 0.34209525 c 0,-0.394094 -0.5532,-0.474248 -0.6665,-0.1002 z" fill="#6197b4"/>
|
fill="url(#pageGrad)"
|
||||||
<path d="m 25.901665,48.988865 -9.271,15.0556 c -0.1866,0.3073 0.16,0.6546 0.4665,0.4676 l 14.4431,-8.9305 c 0.3866,-0.2405 0.6999,-0.5678 0.9265,-0.9619 l 8.038,-14.0336 H 0.34134532 c -0.393231,0 -0.473212,0.5544 -0.09997,0.6679 z" fill="#bdccd6"/>
|
id="rect11"
|
||||||
<path d="m 55.101065,32.189965 9.2711,-15.0623 c 0.1866,-0.3072 -0.16,-0.6546 -0.4666,-0.4675 l -14.4431,8.9371 c -0.3865,0.2405 -0.6998,0.5678 -0.9264,0.9619 l -8.038,14.027 h 40.1634 c 0.3932,0 0.4732,-0.5544 0.1,-0.668 z" fill="#94bfcf"/>
|
style="fill:url(#pageGrad)" />
|
||||||
<path d="m 54.507965,48.641565 -14.0099,-8.0555 v 40.2507 c 0,0.3941 0.5532,0.4742 0.6665,0.1002 l 7.7181,-25.7094 15.0296,9.2912 c 0.3066,0.187 0.6532,-0.1603 0.4665,-0.4676 l -8.9177,-14.4812 c -0.2333,-0.3807 -0.5666,-0.7013 -0.9531,-0.9284 z" fill="#eee9d9"/>
|
<rect
|
||||||
</g>
|
x="104"
|
||||||
<!-- Title -->
|
y="84"
|
||||||
<text x="103" y="180" text-anchor="middle" font-family="Georgia, serif" font-size="15" font-weight="bold" fill="#ffffff" letter-spacing="1">TOREAD</text>
|
width="318"
|
||||||
<line x1="55" y1="188" x2="151" y2="188" stroke="#ffffff50" stroke-width="0.8"/>
|
height="318"
|
||||||
<text x="103" y="202" text-anchor="middle" font-family="Georgia, serif" font-size="9" fill="#aaccdd" letter-spacing="2">E-READER</text>
|
rx="10"
|
||||||
<!-- Bottom spine detail -->
|
fill="#ece9df"
|
||||||
<rect x="18" y="228" width="18" height="16" fill="#0e2030"/>
|
id="rect12" />
|
||||||
|
<rect
|
||||||
|
x="96"
|
||||||
|
y="76"
|
||||||
|
width="318"
|
||||||
|
height="318"
|
||||||
|
rx="10"
|
||||||
|
fill="#f0ede3"
|
||||||
|
id="rect13" />
|
||||||
|
</g>
|
||||||
|
<rect
|
||||||
|
x="121.15213"
|
||||||
|
y="128.76512"
|
||||||
|
width="42.381393"
|
||||||
|
height="262.06592"
|
||||||
|
rx="7.8484058"
|
||||||
|
fill="url(#spineGrad)"
|
||||||
|
id="rect14"
|
||||||
|
style="fill:url(#spineGrad);stroke:none;stroke-width:0.755863" />
|
||||||
|
<rect
|
||||||
|
x="151.69673"
|
||||||
|
y="129.02002"
|
||||||
|
width="235.62991"
|
||||||
|
height="261.811"
|
||||||
|
rx="7.2725282"
|
||||||
|
fill="url(#coverGrad)"
|
||||||
|
id="rect15"
|
||||||
|
style="fill:url(#coverGrad);stroke-width:0.727253" />
|
||||||
|
<rect
|
||||||
|
x="151.69673"
|
||||||
|
y="129.02002"
|
||||||
|
width="235.62991"
|
||||||
|
height="261.811"
|
||||||
|
rx="7.2725282"
|
||||||
|
fill="url(#coverShine)"
|
||||||
|
id="rect16"
|
||||||
|
style="display:inline;fill:url(#coverShine);stroke-width:0.727253" />
|
||||||
|
<line
|
||||||
|
x1="160.42378"
|
||||||
|
y1="136.29254"
|
||||||
|
x2="160.42378"
|
||||||
|
y2="383.5585"
|
||||||
|
stroke="#00000030"
|
||||||
|
stroke-width="1.45451"
|
||||||
|
id="line16" />
|
||||||
|
<rect
|
||||||
|
x="162.24403"
|
||||||
|
y="141.29759"
|
||||||
|
width="215.68887"
|
||||||
|
height="240.71645"
|
||||||
|
rx="4.6888885"
|
||||||
|
fill="none"
|
||||||
|
stroke="#ffffff30"
|
||||||
|
stroke-width="3.10595"
|
||||||
|
id="rect17"
|
||||||
|
style="fill:none;stroke:#000000;stroke-opacity:0.104098" />
|
||||||
|
<g
|
||||||
|
transform="matrix(2.5090222,0,0,2.5090222,168.42356,158.11013)"
|
||||||
|
id="g20">
|
||||||
|
<path
|
||||||
|
d="m 32.120065,25.957965 -15.0296,-9.2912 c -0.3066,-0.187 -0.6532,0.1603 -0.4666,0.4676 l 8.9112,14.4745 c 0.2399,0.3874 0.5665,0.7013 0.9597,0.9284 l 14.0032,8.0555 V 0.34209525 c 0,-0.394094 -0.5532,-0.474248 -0.6665,-0.1002 z"
|
||||||
|
fill="#6197b4"
|
||||||
|
id="path17" />
|
||||||
|
<path
|
||||||
|
d="m 25.901665,48.988865 -9.271,15.0556 c -0.1866,0.3073 0.16,0.6546 0.4665,0.4676 l 14.4431,-8.9305 c 0.3866,-0.2405 0.6999,-0.5678 0.9265,-0.9619 l 8.038,-14.0336 H 0.34134532 c -0.393231,0 -0.473212,0.5544 -0.09997,0.6679 z"
|
||||||
|
fill="#bdccd6"
|
||||||
|
id="path18" />
|
||||||
|
<path
|
||||||
|
d="m 55.101065,32.189965 9.2711,-15.0623 c 0.1866,-0.3072 -0.16,-0.6546 -0.4666,-0.4675 l -14.4431,8.9371 c -0.3865,0.2405 -0.6998,0.5678 -0.9264,0.9619 l -8.038,14.027 h 40.1634 c 0.3932,0 0.4732,-0.5544 0.1,-0.668 z"
|
||||||
|
fill="#94bfcf"
|
||||||
|
id="path19" />
|
||||||
|
<path
|
||||||
|
d="m 54.507965,48.641565 -14.0099,-8.0555 v 40.2507 c 0,0.3941 0.5532,0.4742 0.6665,0.1002 l 7.7181,-25.7094 15.0296,9.2912 c 0.3066,0.187 0.6532,-0.1603 0.4665,-0.4676 l -8.9177,-14.4812 c -0.2333,-0.3807 -0.5666,-0.7013 -0.9531,-0.9284 z"
|
||||||
|
fill="#eee9d9"
|
||||||
|
id="path20" />
|
||||||
</g>
|
</g>
|
||||||
</svg>
|
</svg>
|
||||||
|
Before Width: | Height: | Size: 4.2 KiB After Width: | Height: | Size: 7.0 KiB |
|
After Width: | Height: | Size: 212 KiB |
|
After Width: | Height: | Size: 208 KiB |
|
After Width: | Height: | Size: 392 KiB |
|
After Width: | Height: | Size: 398 KiB |
|
After Width: | Height: | Size: 212 KiB |
|
After Width: | Height: | Size: 203 KiB |
|
After Width: | Height: | Size: 365 KiB |
|
After Width: | Height: | Size: 262 KiB |
|
After Width: | Height: | Size: 407 KiB |
|
After Width: | Height: | Size: 280 KiB |
|
After Width: | Height: | Size: 136 KiB |
|
After Width: | Height: | Size: 82 KiB |
@@ -0,0 +1,56 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Download the pinned Supertonic 3 CPU model. No packages or credentials required."""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
MANIFEST = json.loads((ROOT / "scripts/supertonic-3-model.json").read_text())
|
||||||
|
|
||||||
|
|
||||||
|
def valid(path, entry):
|
||||||
|
if not path.is_file() or path.stat().st_size != entry["size"]:
|
||||||
|
return False
|
||||||
|
digest = hashlib.sha256() if "sha256" in entry else hashlib.sha1()
|
||||||
|
if "git_blob" in entry:
|
||||||
|
digest.update(f"blob {entry['size']}\0".encode())
|
||||||
|
with path.open("rb") as source:
|
||||||
|
for chunk in iter(lambda: source.read(1024 * 1024), b""):
|
||||||
|
digest.update(chunk)
|
||||||
|
return digest.hexdigest() == entry.get("sha256", entry.get("git_blob"))
|
||||||
|
|
||||||
|
|
||||||
|
def download(manifest, destination):
|
||||||
|
total = sum(entry["size"] for entry in manifest["files"])
|
||||||
|
print(f"{manifest['repository']}: {total / 1e6:.1f} MB; destination: {destination}", flush=True)
|
||||||
|
base = f"https://huggingface.co/{manifest['repository']}/resolve/{manifest['revision']}"
|
||||||
|
for entry in manifest["files"]:
|
||||||
|
target = destination / entry["path"]
|
||||||
|
if valid(target, entry):
|
||||||
|
print(f"Verified {entry['path']}", flush=True)
|
||||||
|
continue
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
temporary = target.with_suffix(target.suffix + ".part")
|
||||||
|
print(f"Downloading {entry['path']} ({entry['size'] / 1e6:.1f} MB)", flush=True)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(f"{base}/{entry['path']}", timeout=60) as source, temporary.open("wb") as output:
|
||||||
|
while chunk := source.read(1024 * 1024):
|
||||||
|
output.write(chunk)
|
||||||
|
if not valid(temporary, entry):
|
||||||
|
raise RuntimeError(f"Checksum mismatch: {entry['path']}")
|
||||||
|
temporary.replace(target)
|
||||||
|
finally:
|
||||||
|
temporary.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
destination = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / ".local/tts/supertonic-3"
|
||||||
|
print("Supertonic model license: OpenRAIL-M (saved as LICENSE alongside the model).", flush=True)
|
||||||
|
download(MANIFEST, destination)
|
||||||
|
print("Ready. Run ./gradlew :composeApp:run and use Read aloud in a book.", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||