Skip to content

VoiceStudio is the open-source, fully-local ElevenLabs alternative — voice cloning, voice design, video dubbing, dictation, transcription & audiobook creation in 646 languages.

feat(mobile): UI polish from the emulator review

debpalash08d9bcdd957f
diff --git a/mobile/android/README.md b/mobile/android/README.md
index 4216cdf2a..61d074a08 100644
--- a/mobile/android/README.md
+++ b/mobile/android/README.md
@@ -38,6 +38,11 @@ AGP 8.12.0, Kotlin 2.2.21 and direct dependencies are pinned in the wrapper and
sandbox writable directories; parallel workers are capped for this shared host.
The version name/code are derived at configuration time from root `package.json`.
+The adaptive launcher icon (including its themed monochrome layer) and launch
+screen are generated during Gradle preBuild from `docs/logo.svg` and the default
+canvas token by `scripts/generate_brand_resources.py`. Generated resources stay
+in `app/build/`; no copied logo binaries are checked in.
+
## Layout
- `app`: launcher, Navigation Compose, consent, generated asset packaging, JVM UI
@@ -61,20 +66,24 @@ The version name/code are derived at configuration time from root `package.json`
All five tabs are reachable without pairing. Consent dismissal means No.
Speak, Clone, Dictate and Dub remember their own Run on choice. An installed
-phone model is preferred; otherwise the paired computer is used or a model
-card offers Download. Dub requires ASR, translation and cloning models. Run on
-is a compact This phone / Computer control visible only when paired. Phone and
+phone model is preferred; otherwise the paired computer is used or a
+compact card offers Get with the total download size. Dub groups its ASR,
+translation and cloning dependencies in one card; each gated model has its own
+licence confirmation. The card also opens Models. Run on is a compact This phone / Computer control visible only when paired. Phone and
computer voices remain separate, with a location badge in the combined list.
-Settings opens optional Connect and Models.
+Settings opens optional Connect and Models. Model choices use product names and
+localized capabilities; licence details stay inside the acceptance sheet.
Speak has a large editor with placeholder-only copy, three compact picker chips,
-Generate, a player and compact recent rows. Dictate has one central microphone
-control: tap starts/stops; hold records until release. Connect keeps URL/PIN
+Generate, a player and compact recent rows. Dictate keeps the microphone and
+copy/share controls above the tab bar while the transcript scrolls: tap
+starts/stops; hold records until release. Connect keeps URL/PIN
under Enter address and the optional API key under More. Model licences open in
a sheet with complete inert terms, a rights confirmation and Accept / Decline.
Screens use short labels and icons; hints live behind one info action. Settings
-uses rows without explanatory paragraphs. Errors use short messages and a
-recovery action; the original structured error keys remain available to workers.
+uses distinct row icons without explanatory paragraphs. Pickers mark the current
+selection, use normal text colors, and show palette color swatches. Errors use
+short messages and a recovery action; the original structured error keys remain available to workers.
Connect supports CameraX/ZXing QR scanning, manual URL/PIN/API-key entry, saved
hosts and editable labels; last-seen timestamps are retained locally. Public `/health` must carry the backend
@@ -251,7 +260,7 @@ available offline in About.
tasks. The separate computer model-licences link opens the paired host UI.
Computer model setup remains on the host; no admin endpoint is exposed.
- No blur or custom motion is used. Compose follows the system animation scale;
- all content scrolls, text scales, touch targets are at least 48 dp. Large font
+ long content scrolls, text scales, touch targets are at least 48 dp. Large font
scales show labelled navigation icons without squeezed tab text. A visible
text field or backend-provided name is used for each interactive choice.
@@ -259,9 +268,9 @@ available offline in About.
Gradle bundles the generated `mobile/contract/models.json` with the locale
catalogues. Unknown fields are ignored; invalid revisions, checksums, file
-paths, sizes, runtime/capability pairs and schema versions fail closed. No
-catalogue or model is fetched when a tab is opened. Model IDs and declared
-metadata are displayed from that bundle.
+paths, sizes, product names, runtime/capability pairs and schema versions fail
+closed. No catalogue or model is fetched when a tab is opened. Screens use
+product names and localized capability labels from that bundle.
Models cards show name, size, capability and one Download / Cancel / Delete
action. Their licence action opens languages, declared terms and actual storage;
@@ -365,12 +374,14 @@ export HF_HUB_CACHE="$PWD/build/hf-empty"
./gradlew assembleDebugAndroidTest
```
-The current host run passed all four Gradle tasks: 119 JVM tests, zero failures
+The current host run passed all four Gradle tasks: 123 JVM tests, zero failures
or skips, and zero lint errors. Debug app and instrumentation APKs build for
arm64-v8a and x86_64; instrumentation is not executed here.
JVM checks cover existing M1 API/security, storage, worker, picker, protocol and
-Compose smoke regressions, plus local catalogue/routing, licence persistence and
+Compose smoke regressions, plus generated logo/adaptive/splash resources, compact download prompts,
+separate queued licence sheets, picker marks/colors/swatches, Dictate control
+spacing, local catalogue/routing, licence persistence and
withdrawal, HTTP resume and restart, checksum rejection, mirror fallback,
Wi-Fi/mobile-data policy, low storage, cancellation, deletion, synthetic WAV
metadata, native cancellation control and microphone lifecycle cleanup. Phone
diff --git a/mobile/android/app/build.gradle.kts b/mobile/android/app/build.gradle.kts
index 631e7b954..067c826d4 100644
--- a/mobile/android/app/build.gradle.kts
+++ b/mobile/android/app/build.gradle.kts
@@ -26,6 +26,7 @@ android {
sourceSets["main"].jniLibs.srcDir(rootDir.resolve("../native/android/build/jniLibs"))
sourceSets["main"].assets.srcDir(layout.buildDirectory.dir("generated/catalogs"))
sourceSets["main"].res.srcDir(layout.buildDirectory.dir("generated/catalogResources"))
+ sourceSets["main"].res.srcDir(layout.buildDirectory.dir("generated/brandResources"))
}
kotlin { jvmToolchain(21); compilerOptions { jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17) } }
val bundleCatalogs by tasks.registering {
@@ -110,3 +111,11 @@ val buildNativeRuntimes by tasks.registering(Exec::class) {
commandLine("bash", nativeRoot.resolve("build.sh"))
}
tasks.named("preBuild") { dependsOn(buildNativeRuntimes) }
+
+val generateBrandResources by tasks.registering(Exec::class) {
+ val generator = rootDir.resolve("scripts/generate_brand_resources.py")
+ inputs.files(generator, repository.resolve("docs/logo.svg"), repository.resolve("mobile/contract/tokens.json"))
+ outputs.dir(layout.buildDirectory.dir("generated/brandResources"))
+ commandLine("python3", generator, "--output", layout.buildDirectory.dir("generated/brandResources").get().asFile)
+}
+tasks.named("preBuild") { dependsOn(generateBrandResources) }
diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xml
index 874fd3186..d152c18de 100644
--- a/mobile/android/app/src/main/AndroidManifest.xml
+++ b/mobile/android/app/src/main/AndroidManifest.xml
@@ -9,7 +9,8 @@
<uses-feature android:name="android.hardware.camera.any" android:required="false" />
<uses-feature android:name="android.hardware.microphone" android:required="false" />
<application android:name=".VoiceStudioApplication" android:label="@string/app_name"
- android:allowBackup="false" android:supportsRtl="true" android:theme="@style/AppTheme"
+ android:allowBackup="false" android:supportsRtl="true" android:theme="@style/AppTheme.Launch"
+ android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher"
android:networkSecurityConfig="@xml/network_security_config">
<activity android:name=".MainActivity" android:exported="true" android:windowSoftInputMode="adjustResize">
<intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter>
diff --git a/mobile/android/app/src/main/kotlin/com/voicestudio/mobile/MainActivity.kt b/mobile/android/app/src/main/kotlin/com/voicestudio/mobile/MainActivity.kt
index fe353901b..f882d92ce 100644
--- a/mobile/android/app/src/main/kotlin/com/voicestudio/mobile/MainActivity.kt
+++ b/mobile/android/app/src/main/kotlin/com/voicestudio/mobile/MainActivity.kt
@@ -39,6 +39,7 @@ import java.util.Locale
class VoiceStudioApplication:Application()
class MainActivity:ComponentActivity() {
override fun onCreate(savedInstanceState:Bundle?) {
+ setTheme(R.style.AppTheme)
super.onCreate(savedInstanceState);enableEdgeToEdge()
setContent {StudioApp()}
}
@@ -124,7 +125,7 @@ class MainActivity:ComponentActivity() {
}
}
if(!state.loading&&prefs.consent==null) AlertDialog(shape=MaterialTheme.shapes.large,onDismissRequest={vm.consent(false)},title={Text(tr("consent.title"))},
- text={Column(Modifier.verticalScroll(rememberScrollState()),verticalArrangement=Arrangement.spacedBy(VSTheme.gap)) {Text(tr("consent.body"));Text(tr("mobile.android.analytics_local"))}},
+ text={Column(Modifier.verticalScroll(rememberScrollState()),verticalArrangement=Arrangement.spacedBy(VSTheme.gap)) {Text(tr("consent.body"));Text(tr("mobile.consent.phone_note"))}},
confirmButton={TextButton(shape=MaterialTheme.shapes.small,onClick={vm.consent(true)}) {Text(tr("consent.yes"))}},
dismissButton={TextButton(shape=MaterialTheme.shapes.small,onClick={vm.consent(false)}) {Text(tr("consent.no"))}})
}
diff --git a/mobile/android/app/src/main/res/values-v31/styles.xml b/mobile/android/app/src/main/res/values-v31/styles.xml
new file mode 100644
index 000000000..c3803003f
--- /dev/null
+++ b/mobile/android/app/src/main/res/values-v31/styles.xml
@@ -0,0 +1,7 @@
+<resources>
+ <style name="AppTheme.Launch" parent="AppTheme">
+ <item name="android:windowBackground">@drawable/vs_splash</item>
+ <item name="android:windowSplashScreenBackground">@color/vs_canvas</item>
+ <item name="android:windowSplashScreenAnimatedIcon">@drawable/vs_launcher_foreground</item>
+ </style>
+</resources>
diff --git a/mobile/android/app/src/main/res/values/styles.xml b/mobile/android/app/src/main/res/values/styles.xml
index 1e84c3c70..6c9a6c8b5 100644
--- a/mobile/android/app/src/main/res/values/styles.xml
+++ b/mobile/android/app/src/main/res/values/styles.xml
@@ -1 +1,10 @@
-<resources><style name="AppTheme" parent="android:style/Theme.Material.NoActionBar"><item name="android:windowLightStatusBar">false</item><item name="android:fontFamily">sans</item></style></resources>
+<resources>
+ <style name="AppTheme" parent="android:style/Theme.Material.NoActionBar">
+ <item name="android:windowLightStatusBar">false</item>
+ <item name="android:fontFamily">sans</item>
+ <item name="android:windowBackground">@color/vs_canvas</item>
+ </style>
+ <style name="AppTheme.Launch" parent="AppTheme">
+ <item name="android:windowBackground">@drawable/vs_splash</item>
+ </style>
+</resources>
diff --git a/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/BrandResourcesTest.kt b/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/BrandResourcesTest.kt
new file mode 100644
index 000000000..afe3ca4a5
--- /dev/null
+++ b/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/BrandResourcesTest.kt
@@ -0,0 +1,34 @@
+package com.voicestudio.mobile
+
+import org.junit.Assert.*
+import org.junit.Test
+import java.io.File
+import javax.xml.parsers.DocumentBuilderFactory
+
+class BrandResourcesTest {
+ @Test fun adaptiveAndLaunchArtworkUseCanonicalLogoPathsAndCanvas() {
+ val root=File(requireNotNull(System.getProperty("androidRoot")))
+ val factory=DocumentBuilderFactory.newInstance().apply {isNamespaceAware=true}
+ fun paths(file:File)=factory.newDocumentBuilder().parse(file).getElementsByTagName("path").let {nodes ->
+ (0 until nodes.length).map {index ->
+ val item=nodes.item(index) as org.w3c.dom.Element
+ item.getAttribute("d").ifBlank {item.getAttributeNS("http://schemas.android.com/apk/res/android","pathData")}
+ }
+ }
+ val canonical=paths(root.resolve("../../docs/logo.svg"))
+ assertEquals(2,canonical.size)
+ val generated=root.resolve("app/build/generated/brandResources")
+ for(name in listOf("vs_logo","vs_launcher_foreground","vs_launcher_monochrome")) {
+ assertEquals(canonical,paths(generated.resolve("drawable/$name.xml")))
+ }
+ val adaptive=generated.resolve("mipmap-anydpi/ic_launcher.xml").readText()
+ assertTrue(adaptive.contains("<monochrome"))
+ assertTrue(adaptive.contains("@color/vs_canvas"))
+ val colors=generated.resolve("values/brand_colors.xml").readText()
+ val tokens=root.resolve("../contract/tokens.json").readText()
+ val rgba=Regex("\\\"dark\\\"\\s*:\\s*\\{\\s*\\\"canvas\\\"\\s*:\\s*\\\"(#[a-fA-F0-9]{8})").find(tokens)!!.groupValues[1]
+ assertTrue(colors.contains("#"+rgba.substring(7)+rgba.substring(1,7)))
+ assertTrue(root.resolve("app/src/main/AndroidManifest.xml").readText().contains("@mipmap/ic_launcher"))
+ assertTrue(root.resolve("app/src/main/res/values-v31/styles.xml").readText().contains("@drawable/vs_launcher_foreground"))
+ }
+}
diff --git a/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/PhoneNavigationTest.kt b/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/PhoneNavigationTest.kt
index 8508a9005..8fe3e189e 100644
--- a/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/PhoneNavigationTest.kt
+++ b/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/PhoneNavigationTest.kt
@@ -23,6 +23,7 @@ class PhoneNavigationTest {
@get:Rule val compose=createComposeRule()
@Test fun allTabsAndModelManagementWorkWithoutPairing() = runBlocking {
val app=ApplicationProvider.getApplicationContext<Application>()
+ androidx.work.testing.WorkManagerTestInitHelper.initializeTestWorkManager(app)
val vault=object: CredentialVault {
override fun read(host: String): Secret? = null
override fun write(host: String,secret: Secret?) = Unit
diff --git a/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/PhoneVoiceUiTest.kt b/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/PhoneVoiceUiTest.kt
index 70f293341..eaddcfa1a 100644
--- a/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/PhoneVoiceUiTest.kt
+++ b/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/PhoneVoiceUiTest.kt
@@ -46,7 +46,8 @@ class PhoneVoiceUiTest {
compose.onNodeWithText("Save").performClick()
await {vm.phone.state.value.voices.any {it.name=="New name"}}
compose.onNode(hasText("Speak") and hasClickAction()).performClick()
- compose.onNodeWithContentDescription("Voice, currently Preset voice 1").performScrollTo().performClick()
+ compose.onNodeWithContentDescription(com.voicestudio.mobile.l10n.L10n.load(ApplicationProvider.getApplicationContext<Application>(),"en").let {l ->
+ l.t("mobile.android.selection",mapOf("label" to l.t("mobile.speak.voice"),"value" to l.t("mobile.local.preset_voice",mapOf("number" to 1))))}).performScrollTo().performClick()
compose.onNodeWithText("Search").performTextInput("New name")
compose.onNode(hasText("New name") and !hasSetTextAction()).performClick()
compose.onNodeWithText("New name").assertExists()
diff --git a/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/StudioSmokeTest.kt b/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/StudioSmokeTest.kt
index eb7611301..dd98e0ee7 100644
--- a/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/StudioSmokeTest.kt
+++ b/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/StudioSmokeTest.kt
@@ -59,6 +59,7 @@ class StudioSmokeTest {
try {
compose.setContent {CompositionLocalProvider(LocalHostPlayerFactory provides {_,_->player}) {StudioApp(vm)}}
awaitCondition {!vm.state.value.loading}
+ compose.onNodeWithText("Saved on this phone. Nothing is sent.").assertExists()
compose.onNodeWithText("No thanks").assertExists().performClick()
awaitCondition {vm.preferences.value.consent==false}
compose.onNodeWithText("Settings").performClick()
diff --git a/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/UiPolishRegressionTest.kt b/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/UiPolishRegressionTest.kt
new file mode 100644
index 000000000..a8dbb9473
--- /dev/null
+++ b/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/UiPolishRegressionTest.kt
@@ -0,0 +1,121 @@
+package com.voicestudio.mobile
+
+import android.app.Application
+import android.os.Looper
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createComposeRule
+import androidx.lifecycle.viewModelScope
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import androidx.test.core.app.ApplicationProvider
+import com.voicestudio.mobile.data.*
+import com.voicestudio.mobile.features.*
+import com.voicestudio.mobile.designsystem.VoiceStudioTheme
+import com.voicestudio.mobile.l10n.L10n
+import kotlinx.coroutines.*
+import org.junit.*
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.Shadows.shadowOf
+import org.robolectric.annotation.Config
+
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk=[34])
+class UiPolishRegressionTest {
+ @get:Rule val compose=createComposeRule()
+ @Test fun tabsHaveOneDownloadCardAndNoRawModelLabelsOrToolbarGear()=runBlocking {
+ val app=ApplicationProvider.getApplicationContext<Application>()
+ androidx.work.testing.WorkManagerTestInitHelper.initializeTestWorkManager(app)
+ val store=SessionStore(app,object:CredentialVault {
+ override fun read(host:String):Secret?=null
+ override fun write(host:String,secret:Secret?)=Unit
+ })
+ store.update {Preferences(consent=false)}
+ val vm=StudioViewModel(app,store)
+ try {
+ compose.setContent {StudioApp(vm)}
+ compose.waitUntil(15000) {shadowOf(Looper.getMainLooper()).idle();!vm.state.value.loading&&!vm.phone.state.value.loading}
+ fun tab(name:String)=compose.onNode(hasText(name) and hasClickAction()).performClick()
+ fun noIdentifiers() {
+ vm.phone.state.value.models.forEach {model ->
+ compose.onNodeWithText(model.id).assertDoesNotExist()
+ compose.onNodeWithText(model.repo).assertDoesNotExist()
+ compose.onNodeWithText(model.licence.id).assertDoesNotExist()
+ }
+ compose.onNodeWithContentDescription("Models").assertDoesNotExist()
+ }
+ noIdentifiers()
+ compose.onAllNodesWithText("Get").assertCountEquals(1)
+ tab("Voices");noIdentifiers()
+ compose.onNodeWithText("Clone a voice").performClick()
+ compose.onAllNodesWithText("Get").assertCountEquals(1)
+ tab("Dub");noIdentifiers()
+ compose.onAllNodesWithText("Get").assertCountEquals(1)
+ compose.onNodeWithText("Dub needs 3 downloads",substring=true).assertExists()
+ tab("Dictate");noIdentifiers()
+ compose.onAllNodesWithText("Get").assertCountEquals(1)
+ compose.onNodeWithContentDescription("Copy").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Share").assertIsDisplayed()
+ val copy=compose.onNodeWithContentDescription("Copy").fetchSemanticsNode().boundsInRoot
+ val tabBar=compose.onNode(hasText("Settings") and hasClickAction()).fetchSemanticsNode().boundsInRoot
+ Assert.assertTrue("Copy must clear the tab bar",copy.bottom<tabBar.top)
+ tab("Settings")
+ compose.onNodeWithText("Light palette").performScrollTo().performClick()
+ Assert.assertTrue(compose.onAllNodesWithTag("palette-swatch",useUnmergedTree=true).fetchSemanticsNodes().isNotEmpty())
+ compose.onAllNodesWithTag("choice-check",useUnmergedTree=true).assertCountEquals(1)
+ Assert.assertFalse(vm.phone.downloads.progress.value.values.any {it.running})
+ } finally {vm.viewModelScope.cancel()}
+ }
+ @Test fun dubGetRequiresSeparateConsentAndDeclineStopsTheQueue()=runBlocking {
+ val app=ApplicationProvider.getApplicationContext<Application>()
+ shadowOf(app.getSystemService(android.app.ActivityManager::class.java)).setMemoryInfo(
+ android.app.ActivityManager.MemoryInfo().apply {totalMem=16_000_000_000})
+ // The test cannot contact model hosts, even after acceptance.
+ shadowOf(app.getSystemService(android.net.ConnectivityManager::class.java)).apply {
+ clearAllNetworks();setActiveNetworkInfo(null)
+ }
+ val store=SessionStore(app,object:CredentialVault {
+ override fun read(host:String):Secret?=null
+ override fun write(host:String,secret:Secret?)=Unit
+ })
+ store.update {Preferences(consent=false)}
+ val vm=StudioViewModel(app,store)
+ try {
+ compose.setContent {androidx.compose.runtime.CompositionLocalProvider(LocalL10n provides L10n.load(app,"en")) {
+ VoiceStudioTheme {
+ val phone=vm.phone.state.collectAsStateWithLifecycle().value
+ com.voicestudio.mobile.features.models.MissingModelsCard(vm,"mobile.tabs.dub",
+ listOf("asr","translate","clone").mapNotNull {cap ->phone.models.firstOrNull {it.capability==cap}})
+ }
+ }}
+ compose.waitUntil(15000) {shadowOf(Looper.getMainLooper()).idle();!vm.phone.state.value.loading}
+ compose.onNodeWithText("Get").performClick()
+ compose.onNodeWithText("Whisper Tiny").assertExists()
+ compose.onNodeWithText("Accept").assertIsNotEnabled()
+ Assert.assertTrue(vm.phone.downloads.progress.value.isEmpty())
+ compose.onNodeWithContentDescription("I have the rights this licence requires for my use.").performScrollTo().performClick()
+ compose.onNodeWithText("Accept").performClick()
+ compose.waitUntil(15000) {shadowOf(Looper.getMainLooper()).idle();vm.phone.state.value.receipts.values.any {it.lastOrNull()?.accepted==true}}
+ compose.waitForIdle()
+ compose.onNodeWithText("OmniVoice").assertExists()
+ compose.onNodeWithText("Accept").assertIsNotEnabled()
+ compose.onNodeWithText("Decline").performClick()
+ compose.onNodeWithText("Accept").assertDoesNotExist()
+ val clone=vm.phone.state.value.models.first {it.capability=="clone"}
+ Assert.assertFalse(vm.phone.licence.accepted(clone))
+ Assert.assertFalse(vm.phone.downloads.progress.value.values.any {it.running})
+ } finally {vm.viewModelScope.cancel()}
+ }
+ @Test fun pickerShowsVisibleSelectedMark() {
+ val app=ApplicationProvider.getApplicationContext<Application>()
+ compose.setContent {androidx.compose.runtime.CompositionLocalProvider(LocalL10n provides L10n.load(app,"en")) {
+ VoiceStudioTheme {Picker("mobile.settings.mode","dark",listOf("dark" to "Dark","light" to "Light")) {}}
+ }}
+ compose.onNodeWithText("Mode").performClick()
+ compose.onNode(hasText("Dark") and isSelected()).assertExists()
+ compose.onAllNodesWithTag("choice-check",useUnmergedTree=true).assertCountEquals(1)
+ val layouts=mutableListOf<androidx.compose.ui.text.TextLayoutResult>()
+ compose.onNode(hasText("Dark") and hasAnyAncestor(isDialog()),useUnmergedTree=true)
+ .performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.GetTextLayoutResult) {it(layouts)}
+ Assert.assertEquals(androidx.compose.ui.graphics.Color(com.voicestudio.mobile.designsystem.VSTheme.roles("default",true).getValue("text")),layouts.single().layoutInput.style.color)
+ }
+}
diff --git a/mobile/android/core/local/src/main/kotlin/com/voicestudio/mobile/local/ModelCatalog.kt b/mobile/android/core/local/src/main/kotlin/com/voicestudio/mobile/local/ModelCatalog.kt
index a3219025a..0eb7efb19 100644
--- a/mobile/android/core/local/src/main/kotlin/com/voicestudio/mobile/local/ModelCatalog.kt
+++ b/mobile/android/core/local/src/main/kotlin/com/voicestudio/mobile/local/ModelCatalog.kt
@@ -12,7 +12,7 @@ import java.io.File
@SerialName("terms_fingerprint") val termsFingerprint: String, val terms: JsonObject = JsonObject(emptyMap()))
@Serializable data class PhoneModel(val id: String, val capability: String, val runtime: String, val repo: String, val revision: String,
val files: List<ModelFile>, @SerialName("total_bytes") val totalBytes: Long, val languages: List<String>,
- @SerialName("min_ram_gb") val minRamGb: Double, val licence: ModelLicence, val config: JsonObject = JsonObject(emptyMap())) {
+ @SerialName("min_ram_gb") val minRamGb: Double, val licence: ModelLicence, val config: JsonObject = JsonObject(emptyMap()), val name: String = "") {
val gated: Boolean get() = licence.category != "commercial-ok" || licence.requiresAcceptance
fun fits(ramBytes: Long): Boolean = ramBytes.toDouble() >= minRamGb * 1_000_000_000
fun option(name: String, fallback: String = ""): String = config[name]?.jsonPrimitive?.contentOrNull ?: fallback
@@ -25,6 +25,7 @@ import java.io.File
require(catalog.schemaVersion == 1)
require(catalog.models.map {it.id}.distinct().size == catalog.models.size)
catalog.models.forEach { m ->
+ require(m.name.isNotBlank())
require(Regex("[a-zA-Z0-9_-]+").matches(m.id))
require(Regex("[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+").matches(m.repo))
require(Regex("[0-9a-f]{40}").matches(m.revision))
diff --git a/mobile/android/core/local/src/test/kotlin/com/voicestudio/mobile/local/LocalPolicyTest.kt b/mobile/android/core/local/src/test/kotlin/com/voicestudio/mobile/local/LocalPolicyTest.kt
index 064ebe39f..f62d42cd0 100644
--- a/mobile/android/core/local/src/test/kotlin/com/voicestudio/mobile/local/LocalPolicyTest.kt
+++ b/mobile/android/core/local/src/test/kotlin/com/voicestudio/mobile/local/LocalPolicyTest.kt
@@ -18,7 +18,7 @@ class LocalPolicyTest {
@get:Rule val temporary=TemporaryFolder()
private val payload="pinned model data".toByteArray()
private fun model(gated: Boolean=false, digest: String=hash(payload)): PhoneModel = ModelCatalog.decode("""
- {"schema_version":1,"unknown":"ignored","models":[{"id":"fixture","capability":"tts","runtime":"sherpa-onnx",
+ {"schema_version":1,"unknown":"ignored","models":[{"id":"fixture","name":"Fixture","capability":"tts","runtime":"sherpa-onnx",
"repo":"org/model","revision":"${"a".repeat(40)}","files":[{"path":"weights.bin","size":${payload.size},"sha256":"$digest","role":"model"}],
"total_bytes":${payload.size},"languages":["en"],"min_ram_gb":2,
"licence":{"id":"example","category":"${if(gated) "non-commercial" else "commercial-ok"}","requires_acceptance":$gated,"credit":"Credit","rights_holder":"Holder","terms_fingerprint":"${"b".repeat(64)}"},"config":{}}]}
@@ -42,7 +42,7 @@ class LocalPolicyTest {
@Test fun invalidCatalogueCannotChooseAnUnpinnedOrEscapingFile() {
val json=kotlinx.serialization.json.Json
val valid=json.encodeToString(ModelCatalog.serializer(),ModelCatalog(1,listOf(model())))
- for(invalid in listOf(valid.replace("weights.bin","../escape"),valid.replace("weights.bin",".verified"),valid.replace(hash(payload),"missing-checksum"),valid.replace("\"schema_version\":1","\"schema_version\":2"))) {
+ for(invalid in listOf(valid.replace("\"name\":\"Fixture\"","\"name\":\"\""),valid.replace("weights.bin","../escape"),valid.replace("weights.bin",".verified"),valid.replace(hash(payload),"missing-checksum"),valid.replace("\"schema_version\":1","\"schema_version\":2"))) {
try {ModelCatalog.decode(invalid);fail("Invalid catalogue accepted")} catch(_:IllegalArgumentException) {}
}
}
diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/Components.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/Components.kt
index 83335a072..0981f2454 100644
--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/Components.kt
+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/Components.kt
@@ -1,6 +1,10 @@
package com.voicestudio.mobile.features
import androidx.compose.foundation.BorderStroke
+import androidx.compose.foundation.background
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.testTag
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
@@ -104,7 +108,7 @@ fun Modifier.dismissKeyboardOnTap(): Modifier = composed {
val description=tr("mobile.android.selection",mapOf("label" to tr(label),"value" to value))
Surface(onClick={dismiss();onClick()},enabled=enabled,color=role("surface"),shape=MaterialTheme.shapes.small,modifier=Modifier.fillMaxWidth().heightIn(min=VSTheme.touchTarget).semantics {contentDescription=description}) {
Row(Modifier.padding(VSTheme.inset),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(VSTheme.gap)) {
- Icon(Icons.Default.Settings,contentDescription=null,tint=role("textMuted"))
+ Icon(rowIcon(label),contentDescription=null,tint=role("textMuted"))
Text(tr(label),style=MaterialTheme.typography.labelLarge,maxLines=1,overflow=TextOverflow.Ellipsis)
Text(value,Modifier.weight(1f),color=role("textMuted"),style=MaterialTheme.typography.labelLarge,textAlign=TextAlign.End,maxLines=1,overflow=TextOverflow.Ellipsis)
Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight,contentDescription=null,tint=role("textMuted"))
@@ -120,7 +124,7 @@ fun Modifier.dismissKeyboardOnTap(): Modifier = composed {
if(compact) {
val valueLabel=choices.firstOrNull {it.id==value}?.title ?: tr(label)
val description=tr("mobile.android.selection",mapOf("label" to tr(label),"value" to valueLabel))
- AssistChip(onClick={open=true},enabled=choices.isNotEmpty(),label={Text(valueLabel,maxLines=1,overflow=TextOverflow.Ellipsis)},modifier=Modifier.heightIn(min=VSTheme.touchTarget).semantics {contentDescription=description})
+ AssistChip(onClick={open=true},enabled=choices.isNotEmpty(),label={Text(valueLabel,Modifier.fillMaxWidth(),textAlign=androidx.compose.ui.text.style.TextAlign.Center,maxLines=1,overflow=TextOverflow.Ellipsis)},modifier=Modifier.fillMaxWidth().heightIn(min=VSTheme.touchTarget).semantics {contentDescription=description})
} else PickerRow(label,choices.firstOrNull {it.id==value}?.title ?: tr("mobile.android.choose"),choices.isNotEmpty()) {open=true}
if(open) AlertDialog(modifier=Modifier.dismissKeyboardOnTap(),shape=MaterialTheme.shapes.large,onDismissRequest={open=false}, title={Text(tr(label))}, containerColor=role("surfaceOverlay"),
text={ Column(verticalArrangement=Arrangement.spacedBy(VSTheme.gap)) {
@@ -130,11 +134,16 @@ fun Modifier.dismissKeyboardOnTap(): Modifier = composed {
LazyColumn(Modifier.heightIn(max=(VSTokens.SPACING_GAP*20).dp)) {
items(matches,key={it.id}) { choice ->
TextButton(shape=MaterialTheme.shapes.small,onClick={change(choice.id);open=false;query=""},enabled=choice.enabled,
+ colors=ButtonDefaults.textButtonColors(contentColor=role("text"),disabledContentColor=role("textMuted")),
modifier=Modifier.fillMaxWidth().heightIn(min=VSTheme.touchTarget).semantics { selected = choice.id==value }) {
- Column(Modifier.fillMaxWidth()) {
+ choice.swatch?.let {color ->
+ Box(Modifier.padding(end=VSTheme.gap).size(24.dp).background(Color(color),CircleShape).testTag("palette-swatch"))
+ }
+ Column(Modifier.weight(1f)) {
Text(choice.title,maxLines=2,overflow=TextOverflow.Ellipsis)
choice.supporting?.let {Text(it,style=MaterialTheme.typography.bodySmall,color=role("textMuted"))}
}
+ if(choice.id==value) Icon(Icons.Default.Check,contentDescription=null,modifier=Modifier.padding(start=VSTheme.gap).testTag("choice-check"))
}
}
}
@@ -177,7 +186,7 @@ fun Modifier.dismissKeyboardOnTap(): Modifier = composed {
val label = tr(key)
val dismiss=rememberKeyboardDismiss()
Row(Modifier.fillMaxWidth().heightIn(min=VSTheme.touchTarget).padding(horizontal=VSTheme.inset),verticalAlignment=Alignment.CenterVertically, horizontalArrangement=Arrangement.spacedBy(VSTheme.gap)) {
- Icon(Icons.Default.Settings,contentDescription=null,tint=role("textMuted"))
+ Icon(rowIcon(key),contentDescription=null,tint=role("textMuted"))
Text(label, Modifier.weight(1f))
Switch(checked=value, onCheckedChange={dismiss();change(it)}, modifier=Modifier.semantics { contentDescription=label })
}
@@ -209,7 +218,7 @@ fun languageName(code: String, locale: String): String = Locale.forLanguageTag(c
@Composable fun SettingsLink(label: String, value: String = "", onClick: ()->Unit) {
Surface(onClick=onClick,color=role("surface"),shape=MaterialTheme.shapes.small,modifier=Modifier.fillMaxWidth().heightIn(min=VSTheme.touchTarget)) {
Row(Modifier.padding(VSTheme.inset),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(VSTheme.gap)) {
- Icon(Icons.Default.Settings,contentDescription=null)
+ Icon(rowIcon(label),contentDescription=null)
Text(tr(label),Modifier.weight(1f));if(value.isNotBlank()) Text(value,Modifier.weight(1f),color=role("textMuted"),maxLines=1,overflow=TextOverflow.Ellipsis,textAlign=TextAlign.End)
Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight,contentDescription=null)
}
@@ -273,3 +282,26 @@ fun shortErrorKey(key: String): String = when {
color=role("textMuted"),modifier=Modifier.padding(horizontal=VSTheme.gap/2,vertical=VSTheme.gap/4))
}
}
+
+/** Semantic icons shared by settings and full-width picker rows. */
+fun rowIcon(key: String): ImageVector = when {
+ key.contains("connect") || key.contains("host") -> VSIcons.Link
+ key.contains("model") -> VSIcons.Download
+ key.endsWith("mode") -> VSIcons.Contrast
+ key.contains("palette") -> VSIcons.Palette
+ key.contains("language") -> VSIcons.Globe
+ key.contains("notification") -> VSIcons.Bell
+ key.contains("privacy") || key.contains("analytics") -> VSIcons.Shield
+ key.contains("voice") -> Icons.Default.Person
+ else -> Icons.Default.Info
+}
+
+/** Transcript scrolls independently; recording and sharing stay clear of the tab bar. */
+@Composable fun DictationLayout(content: @Composable ColumnScope.()->Unit, controls: @Composable ColumnScope.()->Unit) {
+ Column(Modifier.fillMaxSize().imePadding().dismissKeyboardOnTap()) {
+ Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(VSTheme.inset),
+ verticalArrangement=Arrangement.spacedBy(VSTheme.gap),content=content)
+ Column(Modifier.fillMaxWidth().padding(horizontal=VSTheme.inset).padding(bottom=VSTheme.inset),
+ verticalArrangement=Arrangement.spacedBy(VSTheme.gap),content=controls)
+ }
+}
diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/PhoneStudio.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/PhoneStudio.kt
index 1664cb052..69fe838d6 100644
--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/PhoneStudio.kt
+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/PhoneStudio.kt
@@ -58,11 +58,11 @@ class PhoneStudio(context: Context, private val scope: CoroutineScope, private v
try {jobs[model.id]?.cancelAndJoin();cancelInference();downloads.delete(model);refresh()}
catch(e:CancellationException) {throw e} catch(e:Exception) {failure(e)}
}}
- fun accept(model: PhoneModel, accepted: Boolean, fingerprint: String) {scope.launch {
+ fun accept(model: PhoneModel, accepted: Boolean, fingerprint: String, completed: (Boolean)->Unit = {}) {scope.launch {
try {
if(!accepted) {jobs[model.id]?.cancelAndJoin();cancelInference()}
- withContext(Dispatchers.IO) {licence.record(model,accepted,fingerprint)};refresh()
- } catch(e:CancellationException) {throw e} catch(e:Exception) {failure(e)}
+ withContext(Dispatchers.IO) {licence.record(model,accepted,fingerprint)};refresh();completed(true)
+ } catch(e:CancellationException) {throw e} catch(e:Exception) {failure(e);completed(false)}
}}
fun speak(model: PhoneModel, text: String, speaker: Int, voice: PhoneVoice? = null, language: String? = null) {
if(inference?.isActive==true) return
diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/Selections.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/Selections.kt
index ed79024c6..f5343d029 100644
--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/Selections.kt
+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/Selections.kt
@@ -35,7 +35,7 @@ class LanguageCatalog(val names: List<String>) {
}
}
-data class Choice(val id: String, val title: String, val enabled: Boolean = true, val supporting: String? = null)
+data class Choice(val id: String, val title: String, val enabled: Boolean = true, val supporting: String? = null, val swatch: Long? = null)
fun engineChoices(family: EngineFamily, profile: Profile?, text: (String) -> String): List<Choice> = family.backends.map { engine ->
val incompatible = profile?.hasReferenceAudio == true && engine.supportsCloning != true
val explanation=listOfNotNull(
diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/VSIcons.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/VSIcons.kt
index 7ef3946fd..9e0db4730 100644
--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/VSIcons.kt
+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/VSIcons.kt
@@ -8,6 +8,17 @@ import androidx.compose.ui.unit.dp
import com.voicestudio.mobile.designsystem.*
object VSIcons {
+ private fun symbol(name: String, data: String): ImageVector = ImageVector.Builder(name,24.dp,24.dp,24f,24f)
+ .addPath(pathData=androidx.compose.ui.graphics.vector.PathParser().parsePathString(data).toNodes(),
+ fill=SolidColor(Color(VSTheme.roles("default",true).getValue("text"))),pathFillType=androidx.compose.ui.graphics.PathFillType.EvenOdd).build()
+ val Link by lazy {symbol("Link","M3.9 12a4 4 0 0 1 4-4h3V6h-3a6 6 0 0 0 0 12h3v-2h-3a4 4 0 0 1-4-4z M8 11h8v2H8z M13 6h3a6 6 0 0 1 0 12h-3v-2h3a4 4 0 0 0 0-8h-3z")}
+ val Globe by lazy {symbol("Globe","M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z M4.3 10h3a17 17 0 0 0 0 4h-3a8 8 0 0 1 0-4z M5.1 8a8 8 0 0 1 4-3.5A15 15 0 0 0 7.7 8z M5.1 16h2.6a15 15 0 0 0 1.4 3.5A8 8 0 0 1 5.1 16z M9.4 10h5.2a15 15 0 0 1 0 4H9.4a15 15 0 0 1 0-4z M9.8 8A13 13 0 0 1 12 4a13 13 0 0 1 2.2 4z M9.8 16h4.4A13 13 0 0 1 12 20a13 13 0 0 1-2.2-4z M16.3 8a15 15 0 0 0-1.4-3.5 8 8 0 0 1 4 3.5z M16.7 10h3a8 8 0 0 1 0 4h-3a17 17 0 0 0 0-4z M16.3 16h2.6a8 8 0 0 1-4 3.5 15 15 0 0 0 1.4-3.5z")}
+ val Contrast by lazy {symbol("Contrast","M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z M12 4v16a8 8 0 0 1 0-16z")}
+ val Palette by lazy {symbol("Palette","M12 2a10 10 0 0 0 0 20h1a3 3 0 0 0 2-5c-.5-.5-.1-1 .5-1H17a5 5 0 0 0 5-5c0-5-5-9-10-9z M7 7a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0z M12 5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0z M17 7a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0z M7 13a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0z")}
+ val Bell by lazy {symbol("Bell","M12 2a2 2 0 0 0-2 2v.3C7.6 5.1 6 7.3 6 10v6l-2 2v1h16v-1l-2-2v-6c0-2.7-1.6-4.9-4-5.7V4a2 2 0 0 0-2-2z M10 20a2 2 0 0 0 4 0z")}
+ val Shield by lazy {symbol("Shield","M12 2 3 6v6c0 5.5 4 9 9 11 5-2 9-5.5 9-11V6z M12 4.2 19 7v5c0 4-3 7-7 8.8z")}
+ val Video by lazy {symbol("Video","M3 4h14a2 2 0 0 1 2 2v3l4-3v12l-4-3v3a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z M8 8v8l6-4z")}
+
private fun glyph(name: String, draw: androidx.compose.ui.graphics.vector.PathBuilder.()->Unit): ImageVector =
ImageVector.Builder(name,24.dp,24.dp,24f,24f).path(fill=SolidColor(Color(VSTheme.roles("default",true).getValue("text"))),pathBuilder=draw).build()
val Qr by lazy {glyph("QR") {
diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dictate/DictateScreen.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dictate/DictateScreen.kt
index 0760a8eb1..ccb4110ac 100644
--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dictate/DictateScreen.kt
+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dictate/DictateScreen.kt
@@ -49,7 +49,7 @@ import kotlinx.coroutines.CancellationException
var holding by remember {mutableStateOf(false)}
val holdStart=permissionAction(Manifest.permission.RECORD_AUDIO,"mobile.permissions.microphone",vm::fail) {if(holding) controller.start()}
val start=permissionAction(Manifest.permission.RECORD_AUDIO,"mobile.permissions.microphone",vm::fail,controller::start)
- Screen {
+ DictationLayout(content={
ScreenTitle("mobile.tabs.dictate")
if(checking) {Text(tr("common.loading"));LinearProgressIndicator()}
readinessError?.let {error ->
@@ -64,12 +64,13 @@ import kotlinx.coroutines.CancellationException
}
Secondary("mobile.simple.retry",!checking) {scope.launch {check()}}
Text(transcript,modifier=Modifier.fillMaxWidth().heightIn(min=VSTheme.touchTarget*3).semantics {liveRegion=LiveRegionMode.Polite})
+ }, controls={
MicControl(active,ready,tap={holding=false;if(active) controller.finish() else start()},hold={holding=true;holdStart()},release={if(holding) {holding=false;controller.finish()}})
- Row(Modifier.fillMaxWidth(),horizontalArrangement=Arrangement.Center) {
+ Row(Modifier.fillMaxWidth(),horizontalArrangement=Arrangement.spacedBy(VSTheme.gap,androidx.compose.ui.Alignment.CenterHorizontally)) {
IconAction("mobile.dictate.copy",VSIcons.Copy,transcript.isNotBlank()) {context.getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText(null,transcript))}
IconAction("mobile.speak.share",androidx.compose.material.icons.Icons.Default.Share,transcript.isNotBlank()) {shareText(context,transcript)}
}
- }
+ })
}
@Composable fun DictateScreen(vm: StudioViewModel) {
diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dictate/PhoneDictateScreen.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dictate/PhoneDictateScreen.kt
index e1c98d00a..18a08b532 100644
--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dictate/PhoneDictateScreen.kt
+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dictate/PhoneDictateScreen.kt
@@ -17,7 +17,7 @@ import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import com.voicestudio.mobile.designsystem.*
import com.voicestudio.mobile.features.*
-import com.voicestudio.mobile.features.models.ModelCard
+import com.voicestudio.mobile.features.models.MissingModelsCard
import com.voicestudio.mobile.local.*
import com.voicestudio.mobile.network.ClientFailure
import kotlinx.coroutines.*
@@ -70,14 +70,15 @@ internal class PhoneDictation(private val engine: LocalEngine, private val scope
var holding by remember {mutableStateOf(false)}
val start=permissionAction(Manifest.permission.RECORD_AUDIO,"mobile.permissions.microphone",vm::fail) {if(ready&&model!=null) controller.start(model)}
val holdStart=permissionAction(Manifest.permission.RECORD_AUDIO,"mobile.permissions.microphone",vm::fail) {if(holding&&ready&&model!=null) controller.start(model)}
- Screen {
+ DictationLayout(content={
ScreenTitle("mobile.tabs.dictate")
- if(!ready) model?.let {ModelCard(vm,it)}
+ if(!ready) model?.let {MissingModelsCard(vm,"mobile.tabs.dictate",listOf(it))}
Text(text,modifier=Modifier.fillMaxWidth().heightIn(min=VSTheme.touchTarget*3).semantics {liveRegion=LiveRegionMode.Polite})
+ }, controls={
MicControl(active,ready,tap={holding=false;if(active) controller.finish() else start()},hold={holding=true;holdStart()},release={if(holding) {holding=false;controller.finish()}})
- Row(Modifier.fillMaxWidth(),horizontalArrangement=Arrangement.Center) {
+ Row(Modifier.fillMaxWidth(),horizontalArrangement=Arrangement.spacedBy(VSTheme.gap,androidx.compose.ui.Alignment.CenterHorizontally)) {
IconAction("mobile.dictate.copy",VSIcons.Copy,text.isNotBlank()) {context.getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText(null,text))}
IconAction("mobile.speak.share",androidx.compose.material.icons.Icons.Default.Share,text.isNotBlank()) {shareText(context,text)}
}
- }
+ })
}
diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dub/DubScreen.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dub/DubScreen.kt
index c86655188..c585ae269 100644
--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dub/DubScreen.kt
+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dub/DubScreen.kt
@@ -107,14 +107,14 @@ import java.io.File
}
Screen {
ScreenTitle("mobile.tabs.dub")
- StepHeading("mobile.simple.source",VSIcons.Download)
+ StepHeading("mobile.simple.source",VSIcons.Video)
if(copying || catalog==null) InlineLoading()
Secondary("mobile.dub.pick_media",!copying) {picker.launch(arrayOf("video/*","audio/*"))}
if(filePath!=null) {
SelectedDubSource(sourceName ?: File(filePath!!).name) {File(filePath!!).delete();filePath=null;sourceName=null}
}
Field("mobile.dub.paste_url",link,{link=it})
- StepHeading("mobile.simple.languages",Icons.Default.Edit)
+ StepHeading("mobile.simple.languages",VSIcons.Globe)
MultiPicker("mobile.dub.target_languages",targets,languages) {targets=it}
StepHeading("mobile.simple.voice",Icons.Default.Person)
Group {Picker("mobile.speak.voice",voice,dubVoiceChoices(state.profiles,tr("mobile.simple.default_voice")),{voice=it})}
diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dub/PhoneDubScreen.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dub/PhoneDubScreen.kt
index d4614c6a6..aabf3d5dc 100644
--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dub/PhoneDubScreen.kt
+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dub/PhoneDubScreen.kt
@@ -68,11 +68,11 @@ import java.io.File
}
Screen {
ScreenTitle("mobile.tabs.dub")
- StepHeading("mobile.simple.source",VSIcons.Download)
+ StepHeading("mobile.simple.source",VSIcons.Video)
Secondary("mobile.dub.pick_media",!copying&&!state.busy) {picker.launch(arrayOf("audio/*","video/*"))}
path?.let {source ->SelectedDubSource(sourceName ?: File(source).name) {File(source).delete();path=null;sourceName=null}}
if(copying||catalog==null) InlineLoading()
- StepHeading("mobile.simple.languages",Icons.Default.Edit)
+ StepHeading("mobile.simple.languages",VSIcons.Globe)
MultiPicker("mobile.dub.target_languages",targets,languages) {targets=it}
StepHeading("mobile.simple.voice",Icons.Default.Person)
ChoicePicker("mobile.speak.voice",voice,listOf(Choice("",tr("mobile.simple.reference")))+phone.voices.map {Choice(it.id,it.name)},compact=true) {voice=it}
@@ -87,7 +87,7 @@ import java.io.File
TaskModelPicker(vm,"dub-translate",setOf("translate"),translator)
TaskModelPicker(vm,"dub",setOf("clone"),clone)
}
- missing.forEach {ModelCard(vm,it)}
+ MissingModelsCard(vm,"mobile.tabs.dub",missing)
Action("mobile.simple.dub",ready&&consent&&path!=null&&targets.isNotEmpty()&&!copying&&!state.busy) {
val source=path?.let(::File) ?: return@Action
val title=sourceName ?: source.name
diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/models/ModelsScreen.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/models/ModelsScreen.kt
index 844c09ef0..1513e7720 100644
--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/models/ModelsScreen.kt
+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/models/ModelsScreen.kt
@@ -11,6 +11,7 @@ import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
+import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalConfiguration
@@ -37,17 +38,17 @@ import com.voicestudio.mobile.local.*
val preferences by vm.preferences.collectAsState()
val context=LocalContext.current
var terms by remember(model.id,model.licence.termsFingerprint) {mutableStateOf(false)}
- var checked by remember(terms) {mutableStateOf(false)}
+ var downloadAfterAccept by remember(model.id) {mutableStateOf(false)}
val installed=model.id in state.installed
val fits=model.fits(vm.phone.ramBytes)
val downloading=progress[model.id]?.running==true
Group {
Column(Modifier.fillMaxWidth().padding(VSTheme.inset),verticalArrangement=Arrangement.spacedBy(VSTheme.gap)) {
- Text(model.id,style=MaterialTheme.typography.titleMedium)
+ Text(model.name,style=MaterialTheme.typography.titleMedium)
Text(Formatter.formatFileSize(context,model.totalBytes))
Row(Modifier.fillMaxWidth(),verticalAlignment=Alignment.CenterVertically) {
Text(tr("mobile.simple.${model.capability}"),Modifier.weight(1f),style=MaterialTheme.typography.labelSmall)
- TextButton(onClick={terms=true}) {Text(model.licence.id)}
+ IconAction("mobile.local.review_licence",Icons.Default.Info) {downloadAfterAccept=false;terms=true}
}
if(!fits) Text(tr("mobile.simple.ram",mapOf("ram" to model.minRamGb)),color=role("textMuted"))
progress[model.id]?.let {p ->
@@ -59,13 +60,28 @@ import com.voicestudio.mobile.local.*
}
if(downloading) Secondary("common.cancel") {vm.phone.cancelDownload(model)}
else if(!installed) Secondary("mobile.local.download",fits) {
- try {if(!vm.phone.licence.accepted(model)) terms=true else vm.phone.download(model,preferences.allowMobileModels)} catch(e:Exception) {vm.fail(e)}
+ try {if(!vm.phone.licence.accepted(model)) {downloadAfterAccept=true;terms=true} else vm.phone.download(model,preferences.allowMobileModels)} catch(e:Exception) {vm.fail(e)}
} else Secondary("common.delete") {vm.phone.delete(model)}
}
}
- if(terms) ModalBottomSheet(containerColor=role("surfaceOverlay"),onDismissRequest={terms=false}) {
+ if(terms) ModelLicenceSheet(vm,model,onDismiss={terms=false}) {
+ terms=false
+ if(downloadAfterAccept) vm.phone.download(model,preferences.allowMobileModels)
+ }
+}
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable private fun ModelLicenceSheet(vm: StudioViewModel, model: PhoneModel, onDismiss: ()->Unit, accepted: ()->Unit) {
+ val state by vm.phone.state.collectAsState()
+ val progress by vm.phone.downloads.progress.collectAsState()
+ val context=LocalContext.current
+ val installed=model.id in state.installed
+ val downloading=progress[model.id]?.running==true
+ var checked by remember(model.id,model.licence.termsFingerprint) {mutableStateOf(false)}
+ var saving by remember(model.id) {mutableStateOf(false)}
+ ModalBottomSheet(containerColor=role("surfaceOverlay"),onDismissRequest={if(!saving) onDismiss()}) {
Column(Modifier.fillMaxWidth().heightIn(max=(LocalConfiguration.current.screenHeightDp*.65f).dp).padding(VSTheme.inset).verticalScroll(rememberScrollState()),verticalArrangement=Arrangement.spacedBy(VSTheme.gap)) {
- Text(model.id)
+ Text(model.name)
Text(model.languages.joinToString(", "))
Text(tr("mobile.local.storage_used",mapOf("size" to Formatter.formatFileSize(context,state.storage[model.id] ?: 0))))
Text(tr("mobile.local.licence_label",mapOf("licence" to model.licence.id,"category" to model.licence.category)))
@@ -79,13 +95,13 @@ import com.voicestudio.mobile.local.*
Text(tr("mobile.local.receipt",mapOf("action" to tr(if(receipt.accepted) "mobile.local.accepted" else "mobile.local.not_accepted"),"time" to java.text.DateFormat.getDateTimeInstance().format(java.util.Date(receipt.time)),"version" to receipt.appVersion,"fingerprint" to receipt.fingerprint)))
}
Text(tr("mobile.local.licensor_notice"))
- if(!installed&&!downloading&&(state.storage[model.id] ?: 0)>0) Secondary("common.delete") {vm.phone.delete(model);terms=false}
+ if(!installed&&!downloading&&(state.storage[model.id] ?: 0)>0) Secondary("common.delete") {vm.phone.delete(model);onDismiss()}
ConsentCheck("mobile.local.licence_confirm",checked) {checked=it}
- Secondary("mobile.local.withdraw") {vm.phone.accept(model,false,model.licence.termsFingerprint);terms=false}
+ Secondary("mobile.local.withdraw",!saving) {vm.phone.accept(model,false,model.licence.termsFingerprint);onDismiss()}
}
Row(Modifier.fillMaxWidth(),horizontalArrangement=Arrangement.SpaceEvenly) {
- TextButton(onClick={terms=false}) {Text(tr("mobile.simple.decline"))}
- TextButton(enabled=checked,onClick={vm.phone.accept(model,true,model.licence.termsFingerprint);terms=false}) {Text(tr("mobile.simple.accept"))}
+ TextButton(enabled=!saving,onClick=onDismiss) {Text(tr("mobile.simple.decline"))}
+ TextButton(enabled=checked&&!saving,onClick={saving=true;vm.phone.accept(model,true,model.licence.termsFingerprint) {saved -> saving=false;if(saved) accepted()}}) {Text(tr("mobile.simple.accept"))}
}
}
}
@@ -94,31 +110,79 @@ import com.voicestudio.mobile.local.*
val host by vm.state.collectAsState()
val phone by vm.phone.state.collectAsState()
val preferences by vm.preferences.collectAsState()
- var models by remember {mutableStateOf(false)}
val choices=phone.models.filter {it.capability in capabilities}
val selected=choices.firstOrNull {it.id==preferences.phoneModels[task]} ?: choices.firstOrNull {it.id in phone.installed&&it.fits(vm.phone.ramBytes)} ?: choices.firstOrNull()
val ready=selected?.let {it.id in phone.installed&&it.fits(vm.phone.ramBytes)}==true&&dependencies.all {cap -> phone.models.any {it.capability==cap&&it.id in phone.installed&&it.fits(vm.phone.ramBytes)}}
val location=routeTask(preferences.runLocations[task],ready,host.connected)
Column(Modifier.fillMaxSize()) {
- Row(Modifier.fillMaxWidth().padding(horizontal=VSTheme.inset),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(VSTheme.gap)) {
- if(host.connected) {
+ if(host.connected) Row(Modifier.fillMaxWidth().padding(horizontal=VSTheme.inset),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(VSTheme.gap)) {
if(LocalDensity.current.fontScale<=1.5f) Text(tr("mobile.local.run_on"),style=MaterialTheme.typography.labelSmall)
SingleChoiceSegmentedButtonRow(Modifier.weight(1f)) {
listOf("phone" to "mobile.local.this_phone","computer" to "mobile.simple.computer").forEachIndexed {index,(id,key) ->
SegmentedButton(selected=(location==RunLocation.COMPUTER)==(id=="computer"),onClick={vm.phone.cancelInference();vm.preference {it.copy(runLocations=it.runLocations+(task to id))}},shape=SegmentedButtonDefaults.itemShape(index,2)) {Text(tr(key),maxLines=1,overflow=TextOverflow.Ellipsis)}
}
}
- } else Spacer(Modifier.weight(1f))
- IconAction("mobile.local.models",Icons.Default.Settings) {models=!models}
}
- if(location!=RunLocation.COMPUTER&&task !in setOf("speak","dub")) TaskModelPicker(vm,task,capabilities,selected,compact=true)
- Box(Modifier.weight(1f)) {if(models) ModelsScreen(vm) else content(location,selected)}
+ Box(Modifier.weight(1f)) {content(location,selected)}
}
}
@Composable fun TaskModelPicker(vm: StudioViewModel, task: String, capabilities: Set<String>, selected: PhoneModel?, compact: Boolean = false) {
val phone by vm.phone.state.collectAsState()
ChoicePicker("mobile.local.model",selected?.id.orEmpty(),phone.models.filter {it.capability in capabilities}.map {
- Choice(it.id,it.id,enabled=it.fits(vm.phone.ramBytes),supporting=if(it.fits(vm.phone.ramBytes)) null else tr("mobile.local.ram_required",mapOf("ram" to it.minRamGb)))
+ Choice(it.id,it.name,enabled=it.fits(vm.phone.ramBytes),supporting=if(it.fits(vm.phone.ramBytes)) tr("mobile.simple.${it.capability}") else tr("mobile.local.ram_required",mapOf("ram" to it.minRamGb)))
},compact=compact) {id -> vm.phone.cancelInference();vm.preference {it.copy(phoneModels=it.phoneModels+(task to id))}}
}
+
+/** One explicit Get action starts the dependency list; each gated model keeps its own sheet. */
+@Composable fun MissingModelsCard(vm: StudioViewModel, feature: String, models: List<PhoneModel>) {
+ val state by vm.phone.state.collectAsState()
+ val progress by vm.phone.downloads.progress.collectAsState()
+ val preferences by vm.preferences.collectAsState()
+ val context=LocalContext.current
+ val needed=models.distinctBy {it.id}.filterNot {state.canRun(it,vm.phone.ramBytes)}
+ var queue by rememberSaveable {mutableStateOf(emptyList<String>())}
+ var showModels by rememberSaveable {mutableStateOf(false)}
+ if(needed.isEmpty()) return
+ val pending=state.models.firstOrNull {it.id==queue.firstOrNull()}
+ LaunchedEffect(queue,state.receipts) {
+ if(pending!=null && state.accepted(pending)) {
+ vm.phone.download(pending,preferences.allowMobileModels)
+ queue=queue.drop(1)
+ }
+ }
+ val size=Formatter.formatFileSize(context,needed.sumOf {it.totalBytes})
+ val label=if(needed.size==1) tr("mobile.simple.download_one",mapOf("name" to needed.single().name,"size" to size))
+ else tr("mobile.simple.downloads",mapOf("feature" to tr(feature),"count" to needed.size,"size" to size))
+ val running=needed.any {progress[it.id]?.running==true}
+ Group {
+ Column(Modifier.padding(VSTheme.inset),verticalArrangement=Arrangement.spacedBy(VSTheme.gap)) {
+ Row(verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(VSTheme.gap)) {
+ IconAction("mobile.simple.download_models",VSIcons.Download) {showModels=true}
+ Column(Modifier.weight(1f)) {
+ Text(label,style=MaterialTheme.typography.labelLarge)
+ if(needed.size==1) Text(tr("mobile.simple.${needed.single().capability}"),style=MaterialTheme.typography.labelSmall,color=role("textMuted"))
+ }
+ if(running) IconAction("common.cancel",Icons.Default.Close) {queue=emptyList();needed.forEach(vm.phone::cancelDownload)}
+ else TextButton(enabled=queue.isEmpty()&&needed.all {it.fits(vm.phone.ramBytes)},onClick={queue=needed.map {it.id}}) {Text(tr("mobile.simple.get"))}
+ }
+ needed.firstOrNull {!it.fits(vm.phone.ramBytes)}?.let {Text(tr("mobile.simple.ram",mapOf("ram" to it.minRamGb)),color=role("textMuted"))}
+ if(running) {
+ val total=needed.sumOf {progress[it.id]?.total ?: it.totalBytes}
+ val received=needed.sumOf {progress[it.id]?.received ?: 0L}
+ LinearProgressIndicator(progress={(received.toFloat()/total.coerceAtLeast(1)).coerceIn(0f,1f)},modifier=Modifier.fillMaxWidth())
+ }
+ }
+ }
+ if(pending!=null&&!state.accepted(pending)) ModelLicenceSheet(vm,pending,onDismiss={queue=emptyList()}) {
+ // Receipt refresh advances the queue only after the exact terms have been saved.
+ }
+ if(showModels) ModelsDialog(vm) {showModels=false}
+}
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable private fun ModelsDialog(vm: StudioViewModel, dismiss: ()->Unit) {
+ ModalBottomSheet(onDismissRequest=dismiss,containerColor=role("surfaceOverlay")) {
+ Box(Modifier.fillMaxWidth().fillMaxHeight(.9f)) {ModelsScreen(vm)}
+ }
+}
diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/settings/SettingsScreen.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/settings/SettingsScreen.kt
index 79d779fb0..5437736c5 100644
--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/settings/SettingsScreen.kt
+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/settings/SettingsScreen.kt
@@ -44,8 +44,8 @@ import com.voicestudio.mobile.l10n.L10n
val palettes=paletteChoices(l)
Group {
Picker("mobile.settings.mode",prefs.mode,listOf("dark","light","system").map {it to l.t("mobile.settings.mode_$it")}) {value -> vm.preference {it.copy(mode=value)}}
- Picker("mobile.settings.light_palette",prefs.lightPalette,palettes) {value -> vm.preference {it.copy(lightPalette=value)}}
- Picker("mobile.settings.dark_palette",prefs.darkPalette,palettes) {value -> vm.preference {it.copy(darkPalette=value)}}
+ ChoicePicker("mobile.settings.light_palette",prefs.lightPalette,palettes.map {Choice(it.first,it.second,swatch=VSTheme.roles(it.first,false).getValue("messageAction"))}) {value -> vm.preference {it.copy(lightPalette=value)}}
+ ChoicePicker("mobile.settings.dark_palette",prefs.darkPalette,palettes.map {Choice(it.first,it.second,swatch=VSTheme.roles(it.first,true).getValue("messageAction"))}) {value -> vm.preference {it.copy(darkPalette=value)}}
}
Heading("mobile.settings.language")
diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/speak/SpeakScreen.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/speak/SpeakScreen.kt
index f8eea754a..3305373b9 100644
--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/speak/SpeakScreen.kt
+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/speak/SpeakScreen.kt
@@ -112,7 +112,7 @@ import kotlinx.coroutines.*
Box(Modifier.weight(1f)) {com.voicestudio.mobile.features.models.TaskModelPicker(vm,"speak",setOf(capability),selected,compact=true)}
Box(Modifier.weight(1f)) {ChoicePicker("mobile.speak.language",language,languageChoices,compact=true) {language=it}}
}
- if(selected?.let {!phone.canRun(it,vm.phone.ramBytes)}!=false) selected?.let {com.voicestudio.mobile.features.models.ModelCard(vm,it)}
+ if(selected?.let {!phone.canRun(it,vm.phone.ramBytes)}!=false) selected?.let {com.voicestudio.mobile.features.models.MissingModelsCard(vm,"mobile.tabs.speak",listOf(it))}
else Action("mobile.speak.generate",text.isNotBlank()&&selected!=null&&phone.progress==null) {vm.phone.speak(selected!!,text,speaker.toIntOrNull() ?: 0,voice,language.takeUnless {it=="auto"})}
phone.progress?.let {p ->
LinearProgressIndicator(progress={p},modifier=Modifier.fillMaxWidth())
diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/voices/VoicesScreen.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/voices/VoicesScreen.kt
index a04defee2..96d92849f 100644
--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/voices/VoicesScreen.kt
+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/voices/VoicesScreen.kt
@@ -35,6 +35,7 @@ import java.io.File
val scope=rememberCoroutineScope()
val lifecycle=LocalLifecycleOwner.current
var cloning by rememberSaveable {mutableStateOf(false)}
+ var more by rememberSaveable {mutableStateOf(false)}
var query by rememberSaveable {mutableStateOf("")}
var name by rememberSaveable {mutableStateOf("")}
var sample by rememberSaveable {mutableStateOf<String?>(null)}
@@ -66,7 +67,11 @@ import java.io.File
ScreenTitle("mobile.tabs.voices")
if(!cloning) Action("mobile.voices.new_clone",!state.busy&&phone.progress==null) {cloning=true}
if(cloning) {
- if(location!=RunLocation.COMPUTER&&model!=null&&!phone.canRun(model,vm.phone.ramBytes)) ModelCard(vm,model)
+ if(location!=RunLocation.COMPUTER) {
+ if(model!=null&&!phone.canRun(model,vm.phone.ramBytes)) MissingModelsCard(vm,"mobile.tabs.voices",listOf(model))
+ Secondary("mobile.simple.more") {more=!more}
+ if(more) TaskModelPicker(vm,"clone",setOf("asr"),model)
+ }
Field("mobile.voices.name_label",name,{name=it.take(200)})
Info("mobile.voices.consent_title","mobile.voices.consent_body")
ConsentCheck("mobile.simple.voice_consent",permission,{permission=it})
diff --git a/mobile/android/scripts/generate_brand_resources.py b/mobile/android/scripts/generate_brand_resources.py
new file mode 100644
index 000000000..eba777fad
--- /dev/null
+++ b/mobile/android/scripts/generate_brand_resources.py
@@ -0,0 +1,86 @@
+#!/usr/bin/env python3
+"""Generate Android vectors/adaptive icons from the canonical SVG and theme tokens."""
+import argparse
+import json
+from pathlib import Path
+import xml.etree.ElementTree as ET
+
+ANDROID = 'http://schemas.android.com/apk/res/android'
+AAPT = 'http://schemas.android.com/aapt'
+SVG = 'http://www.w3.org/2000/svg'
+ET.register_namespace('android', ANDROID)
+ET.register_namespace('aapt', AAPT)
+
+def android(**attrs):
+ return {f'{{{ANDROID}}}{key}': str(value) for key, value in attrs.items()}
+
+def generate(repository, output):
+ logo = ET.parse(repository / 'docs/logo.svg').getroot()
+ tokens = json.loads((repository / 'mobile/contract/tokens.json').read_text())
+ canvas = next(p for p in tokens['palettes'] if p['id'] == 'default')['colors'][tokens['defaultMode']]['canvas']
+ # Contract colors are RGBA; Android resources use ARGB.
+ canvas = '#' + canvas[7:9] + canvas[1:7]
+ gradients = {node.attrib['id']: node for node in logo.findall(f'.//{{{SVG}}}linearGradient')}
+
+ def write(name, node):
+ target = output / name
+ target.parent.mkdir(parents=True, exist_ok=True)
+ ET.indent(node)
+ ET.ElementTree(node).write(target, encoding='utf-8', xml_declaration=True)
+
+ def vector(adaptive=False, monochrome=False):
+ size = 108 if adaptive else 64
+ root = ET.Element('vector', android(width=f'{size}dp', height=f'{size}dp', viewportWidth=size, viewportHeight=size))
+ # The complete waveform + spark fit inside the adaptive icon safe zone.
+ parent = ET.SubElement(root, 'group', android(scaleX='.9', scaleY='.9', translateX='25.2', translateY='25.2')) if adaptive else root
+ for path in logo.findall(f'{{{SVG}}}path'):
+ attrs = android(pathData=path.attrib['d'])
+ for source, target in [('stroke-width', 'strokeWidth'), ('stroke-linecap', 'strokeLineCap'), ('stroke-linejoin', 'strokeLineJoin')]:
+ if source in path.attrib:
+ attrs.update(android(**{target: path.attrib[source]}))
+ node = ET.SubElement(parent, 'path', attrs)
+ for source, target in [('stroke', 'strokeColor'), ('fill', 'fillColor')]:
+ value = path.attrib.get(source)
+ if not value:
+ continue
+ if monochrome:
+ node.attrib.update(android(**{target: '#FFFFFFFF'}))
+ elif value.startswith('url(#'):
+ gradient = gradients[value[5:-1]]
+ attr = ET.SubElement(node, f'{{{AAPT}}}attr', {'name': f'android:{target}'})
+ converted = ET.SubElement(attr, 'gradient', android(type='linear', startX=gradient.attrib['x1'], startY=gradient.attrib['y1'], endX=gradient.attrib['x2'], endY=gradient.attrib['y2']))
+ for stop in gradient:
+ ET.SubElement(converted, 'item', android(offset=stop.attrib.get('offset', '0'), color=stop.attrib['stop-color']))
+ else:
+ node.attrib.update(android(**{target: value}))
+ return root
+
+ write('drawable/vs_logo.xml', vector())
+ write('drawable/vs_launcher_foreground.xml', vector(adaptive=True))
+ write('drawable/vs_launcher_monochrome.xml', vector(adaptive=True, monochrome=True))
+ colors = ET.Element('resources')
+ ET.SubElement(colors, 'color', {'name': 'vs_canvas'}).text = canvas
+ write('values/brand_colors.xml', colors)
+ # Adaptive icons are available on every supported Android version. Older
+ # Android versions ignore the monochrome child; API 33+ uses it for theming.
+ icon = ET.Element('adaptive-icon')
+ ET.SubElement(icon, 'background', android(drawable='@color/vs_canvas'))
+ ET.SubElement(icon, 'foreground', android(drawable='@drawable/vs_launcher_foreground'))
+ ET.SubElement(icon, 'monochrome', android(drawable='@drawable/vs_launcher_monochrome'))
+ write('mipmap-anydpi/ic_launcher.xml', icon)
+ for legacy in ['mipmap-anydpi-v26', 'mipmap-anydpi-v33']:
+ stale = output / legacy / 'ic_launcher.xml'
+ if stale.exists():
+ stale.unlink()
+ if not any(stale.parent.iterdir()):
+ stale.parent.rmdir()
+ splash = ET.Element('layer-list')
+ ET.SubElement(splash, 'item', android(drawable='@color/vs_canvas'))
+ ET.SubElement(splash, 'item', android(drawable='@drawable/vs_logo', gravity='center', width='96dp', height='96dp'))
+ write('drawable/vs_splash.xml', splash)
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--output', type=Path, required=True)
+ args = parser.parse_args()
+ generate(Path(__file__).resolve().parents[3], args.output)
diff --git a/mobile/contract/strings.android-additions.en.json b/mobile/contract/strings.android-additions.en.json
index cc846e895..504317415 100644
--- a/mobile/contract/strings.android-additions.en.json
+++ b/mobile/contract/strings.android-additions.en.json
@@ -33,7 +33,7 @@
"inference_failed": "On-device inference failed. Free memory or choose a smaller model and try again.",
"catalogue_failed": "The bundled model catalogue could not be read. Update or reinstall the app.",
"capture_slow": "This phone could not process microphone audio fast enough. Stop other apps or use your computer.",
- "preset_voice": "Preset voice {{number}}",
+ "preset_voice": "Voice {{number}}",
"transfer": "{{received}} of {{total}}",
"privacy": "On-device tasks send nothing anywhere. Only model downloads you start and requests to your paired computer use the network.",
"computer_feature": "This feature currently runs on your computer. You can use Speak and Dictate on this phone without pairing.",
@@ -91,7 +91,14 @@
"analytics": "Analytics",
"language": "Language",
"default_voice": "Default voice",
- "licence_error": "Licence required"
+ "licence_error": "Licence required",
+ "get": "Get",
+ "downloads_one": "{{feature}} needs {{count}} download \u00b7 {{size}}",
+ "downloads_other": "{{feature}} needs {{count}} downloads \u00b7 {{size}}",
+ "download_one": "{{name}} \u00b7 {{size}}"
+ },
+ "consent": {
+ "phone_note": "Saved on this phone. Nothing is sent."
}
}
}
diff --git a/mobile/contract/strings.ios-additions.en.json b/mobile/contract/strings.ios-additions.en.json
index 023956ec6..c1bfe9cfc 100644
--- a/mobile/contract/strings.ios-additions.en.json
+++ b/mobile/contract/strings.ios-additions.en.json
@@ -33,7 +33,7 @@
"this_phone": "This phone",
"my_computer": "My computer",
"download_prompt": "Download {{model}} ({{size}}) to run on this phone.",
- "preset_voice": "Preset voice {{number}}",
+ "preset_voice": "Voice {{number}}",
"model_details": "{{size}} \u00b7 {{languages}} \u00b7 Licence: {{licence}}",
"privacy": "On-device tasks send nothing anywhere. The app only downloads models you start and sends requests to your paired computer. Models stay in private storage and are excluded from backups.",
"computer_required": "Pair your computer in Settings to use this task.",
@@ -91,10 +91,17 @@
"analytics": "Analytics",
"language": "Language",
"default_voice": "Default voice",
- "licence_error": "Licence required"
+ "licence_error": "Licence required",
+ "get": "Get",
+ "downloads_one": "{{feature}} needs {{count}} download \u00b7 {{size}}",
+ "downloads_other": "{{feature}} needs {{count}} downloads \u00b7 {{size}}",
+ "download_one": "{{name}} \u00b7 {{size}}"
},
"permissions": {
"microphone_phone": "VoiceStudio uses the microphone for on-device dictation and voice references. Computer tasks send audio only to your paired computer."
+ },
+ "consent": {
+ "phone_note": "Saved on this phone. Nothing is sent."
}
}
}
diff --git a/mobile/ios/README.md b/mobile/ios/README.md
index 7c3098099..315b21514 100644
--- a/mobile/ios/README.md
+++ b/mobile/ios/README.md
@@ -14,6 +14,7 @@ mobile/ios/scripts/check-platform.sh
python3 mobile/ios/scripts/prepare_resources.py \
--output mobile/ios/.generated/bundle \
--info-output mobile/ios/.generated/Info.plist
+python3 mobile/ios/scripts/test_resources.py
swiftc -frontend -parse mobile/ios/VoiceStudio/App/*.swift \
mobile/ios/VoiceStudio/Features/*.swift mobile/ios/VoiceStudio/Platform/*.swift \
mobile/ios/VoiceStudioUITests/*.swift
@@ -53,9 +54,9 @@ Choose an installed simulator name. The native build verifies pinned artifacts,
`VoiceStudioKit/LocalEngine` is the single feature-facing interface: synthesize, clone, transcribe, streamTranscribe and translate. C runtime handles remain on detached workers; an atomic cancellation token crosses tasks. TTS uses sherpa Kitten/Kokoro, offline ASR uses Whisper, and streaming ASR uses the catalogue's Zipformer family. Streaming preserves endpoint finals, produces a final session transcript and rejects sample-rate changes. Whisper handles long input in 20-second windows while reusing the recognizer. Its native decode has no abort callback: cancellation is checked between windows and the current decode must return before cleanup. TTS and OmniVoice cancel through their native callbacks; llama checks between tokens and through its CPU abort callback. Progress reports loading/running/finished; native APIs without fractional callbacks remain indeterminate during the current step. Every locally generated WAV passes `markSynthetic`, which adds a synthetic-audio INFO comment.
-Speak, clone, Dictate and Dub remember independent This phone / Computer choices. Without a choice, a compatible installed and accepted phone model wins; otherwise a paired computer wins; otherwise an inline model/size prompt links to Models. A remembered computer choice falls back to the phone or Models prompt while unpaired, matching Android, and applies again after pairing. Speak offers three compact pickers (voice, model, language), a text box, Generate and the existing playback, waveform, seeking, sharing and saving controls. Its phone voice picker includes presets and saved references; reference voices select OmniVoice rather than preset TTS. Phone generations persist locally and can be played or deleted in Recent. Dictate captures mono PCM16 at 16 kHz and sends it directly to `LocalEngine` on the phone route. Neither phone path requires a computer or makes a network request.
+Speak, clone, Dictate and Dub remember independent This phone / Computer choices. Without a choice, a compatible installed and accepted phone model wins; otherwise a paired computer wins; otherwise a compact download card offers Get and links to Models. A remembered computer choice falls back to the phone or Models prompt while unpaired, matching Android, and applies again after pairing. Speak offers three compact pickers (voice, model, language), a text box, Generate and the existing playback, waveform, seeking, sharing and saving controls. Its phone voice picker includes presets and saved references; reference voices select OmniVoice rather than preset TTS. Phone generations persist locally and can be played or deleted in Recent. Dictate captures mono PCM16 at 16 kHz and sends it directly to `LocalEngine` on the phone route. Neither phone path requires a computer or makes a network request.
-Models decodes the generated `mobile/contract/models.json`, bundled at build time alongside the locale catalogs. Unknown fields are ignored. Invalid revisions, hashes, unsafe file paths, sizes, duplicate IDs and runtime/capability mismatches are rejected. Cards show name, size, capability and one Download/Cancel/Delete action. Languages, licence terms and per-model storage are in the licence sheet. Unsupported RAM requirements stay visible with an explanation and cannot download or load. Models has Download, Cancel, Delete, a total storage counter and an explicit mobile-data toggle.
+Models decodes the generated `mobile/contract/models.json`, bundled at build time alongside the locale catalogs. Unknown fields are ignored. Missing or blank product names, invalid revisions, hashes, unsafe file paths, sizes, duplicate IDs and runtime/capability mismatches are rejected. Cards show product name, size, localized capability and one Download/Cancel/Delete action. Feature screens and model cards hide IDs, repository names and licence codes; licence details are in the acceptance sheet. Languages, licence terms and per-model storage are in the licence sheet. Unsupported RAM requirements stay visible with an explanation and cannot download or load. Models has Download, Cancel, Delete, a total storage counter and an explicit mobile-data toggle.
Downloads start only from a user action. Four-MiB HTTP ranges persist across cancellation and relaunch; servers ignoring ranges can return a complete file. Hugging Face is attempted first, then hf-mirror.com. A dedicated cookie/credential-free session permits only HTTPS HF/mirror delivery domains (including signed HF CDN redirects); host credentials and referrers are never forwarded. Wi-Fi-only is enforced by both the local path check and URLSession's cellular/expensive-network policy unless mobile data was allowed. Files stay under private Application Support, excluded from backup. Each file is size/SHA-256 verified before installation and hashed again before native loading. Active leases prevent delete/replacement during inference. Downloads interrupted by suspension resume from persisted ranges when the user starts them again; continuous background model downloading is not promised.
@@ -73,7 +74,9 @@ Extraction uses AVAssetReader with 24-kHz mono PCM, preserving gaps and soundtra
Progress cards show stage, percent and Cancel. Backgrounding cancels ongoing work; Whisper's current native decode must finish before cancellation returns. Sources, exact model identities (including terms/configuration), original PCM, segment translations, reference transcripts, render hashes and outputs are checkpointed atomically under private storage. Resume on a pending card continues after interruption/relaunch without translating or mixing completed segments twice. Corrupt cached renders are rebuilt; corrupt completed outputs and changed catalogue identities are blocked. Licence permission is rechecked between stages and by each native load. Multiple target outputs commit separately. Phone history plays video/audio, shares, saves via the system document picker and deletes completed jobs. Completed phone dubs use the same opt-in local notifications setting as computer dubs. Pending jobs can also be deleted when idle. Deleting a job removes its source, checkpoints and outputs; files are retained until explicit deletion. Media is bounded to four hours, references to 30 seconds, and ASR state to 10,000 segments.
-The screen layout uses short labels and icons with one primary action, compact history rows, a round dictation microphone, expandable manual pairing and grouped Settings rows. Explanations and privacy details are in info sheets; full legal terms remain visible in licence sheets. Licence acceptance starts unchecked with Accept/Decline actions.
+The screen layout uses short labels and semantic icons with one primary action, compact history rows, a round dictation microphone, expandable manual pairing and grouped Settings rows. Each feature has one compact missing-model card: product name and size for one model, or feature, count and combined size for several. Get starts the required downloads and presents separate unchecked acceptance sheets for every gated model; declining or dismissing stops the remaining queue. Already installed models are not downloaded again after acceptance. Tap the card label or Settings → Models to manage models. Clone model selection is under More. Pickers mark their current selection; palettes show token-based color swatches and normal text colors. Dictate copy/share controls sit above the tab bar in a bottom safe-area inset. Explanations and privacy details are in info sheets; full legal terms remain visible in licence sheets.
+
+The app icon and launch logo are generated from `docs/logo.png` by `scripts/generate-brand-assets.swift` through `prepare_resources.py`. The icon is opaque; its canvas and the light/dark launch background come from shared tokens. XcodeGen prepares the ignored asset catalog before discovering resources, and each app build refreshes it. No generated artwork is committed. First-run consent says the choice is saved on this phone and sends nothing.
## Computer workflows
@@ -91,8 +94,8 @@ Settings, appearance and language work without pairing. Permissions are requeste
## Verification limits and interpretations
-Verified with CLT: the strict Swift 6 package suite, macOS platform-wrapper type-checks, resource generation, XcodeGen generation and app/UI-test syntax parsing. Separate opt-in runs verify all three actual native libraries, Kitten/Whisper/Zipformer inference, phone reference creation and cloned Speak, and the complete audio dub workflow with native translation/cloning and checkpoint reuse. The tiny Zipformer recognizes the ending phrase of the synthetic smoke sentence; this is an inference check, not a transcription-accuracy claim.
+Verified with CLT: the strict Swift 6 package suite, macOS platform-wrapper type-checks, resource generation, XcodeGen generation and app/UI-test syntax parsing. Separate opt-in runs exercise all three actual native libraries, Kitten/Whisper/Zipformer inference, phone reference creation and cloned Speak, and the complete audio dub workflow with native translation/cloning and checkpoint reuse. The complete native dub smoke currently fails its French-output assertion on a misrecognized tiny Whisper transcript; audio export and checkpoint reuse pass. Clean English translation, voice creation and cloned Speak pass. The tiny Zipformer recognizes the ending phrase of the synthetic smoke sentence; this is an inference check, not a transcription-accuracy claim.
-`VoiceStudioUITests/PhoneScreens.swift` covers unpaired screens, licence consent and collapsed details; `ScreenshotTour` captures phone and computer screens as retained Xcode test attachments. These tests are authored, not run on this CLT-only host. The iOS xcframework build/link, SwiftUI compilation, simulator UI tests, physical-device model RAM/thermal behavior, download/cellular transitions, microphone/local-network/QR permissions, VoiceOver/largest Dynamic Type, signing, background uploads and real-host end-to-end workflows require full Xcode/device validation. macOS inference does not prove iOS execution.
+`VoiceStudioUITests/PhoneScreens.swift` covers unpaired screens, compact download cards, product names, licence consent, picker selection, dictation action placement and collapsed details; `ScreenshotTour` captures phone and computer screens plus palette/language pickers as retained Xcode test attachments. These tests are authored, not run on this CLT-only host. The iOS xcframework build/link, SwiftUI compilation, simulator UI tests, physical-device model RAM/thermal behavior, download/cellular transitions, microphone/local-network/QR permissions, VoiceOver/largest Dynamic Type, signing, background uploads and real-host end-to-end workflows require full Xcode/device validation. macOS inference does not prove iOS execution.
-Contract interpretations: the optional catalogue `licence.terms` contains the full disclosure and is displayed when supplied; the fingerprint remains catalogue-authoritative. HF's signed delivery CDNs are allowed only within its HF-owned delivery domains, because normal model resolve URLs redirect there. Downloads resume at verified range boundaries rather than URLSession opaque resume blobs. The pinned llama prebuilt lacks a simulator slice, so that slice is built from the same pinned source. Missing transitive SHA-256 fields in shared pins are documented in the native README. For dubbing, “segments + timestamps” means one timed speech envelope per bounded Whisper window, matching Android; it does not imply diarization. A remembered computer route falls back while unpaired because its segmented control is hidden. A cancelled dub stays resumable; deletion is explicit. iOS background resume is a user-started Resume after foregrounding, not guaranteed background compute. Video mux and compressed-source extraction need full Xcode/device validation; macOS audio tests exercise the real uncompressed-file conversion and export paths.
+Contract interpretations: Get starts a queue with separate per-model acceptance; declining or dismissing stops the unstarted remainder while already authorized transfers continue. The compact card links to Models through its label. The optional catalogue `licence.terms` contains the full disclosure and is displayed when supplied; the fingerprint remains catalogue-authoritative. HF's signed delivery CDNs are allowed only within its HF-owned delivery domains, because normal model resolve URLs redirect there. Downloads resume at verified range boundaries rather than URLSession opaque resume blobs. The pinned llama prebuilt lacks a simulator slice, so that slice is built from the same pinned source. Missing transitive SHA-256 fields in shared pins are documented in the native README. For dubbing, “segments + timestamps” means one timed speech envelope per bounded Whisper window, matching Android; it does not imply diarization. A remembered computer route falls back while unpaired because its segmented control is hidden. A cancelled dub stays resumable; deletion is explicit. iOS background resume is a user-started Resume after foregrounding, not guaranteed background compute. Video mux and compressed-source extraction need full Xcode/device validation; macOS audio tests exercise the real uncompressed-file conversion and export paths.
diff --git a/mobile/ios/VoiceStudio/App/AppModel.swift b/mobile/ios/VoiceStudio/App/AppModel.swift
index 2136ab04a..7a8689af6 100644
--- a/mobile/ios/VoiceStudio/App/AppModel.swift
+++ b/mobile/ios/VoiceStudio/App/AppModel.swift
@@ -34,6 +34,7 @@ import BackgroundTasks
if mockMode {
for task in ["speak", "dictate", "clone", "dub"] { d.removeObject(forKey: "run-on."+task) }
d.removeObject(forKey: "consentAnswered"); d.removeObject(forKey: "activeHost")
+ d.removeObject(forKey: "theme"); d.removeObject(forKey: "language")
connection = ConnectionStore(defaults: d, vault: SmokeVault(), transport: SmokeTransport())
} else { connection = ConnectionStore() }
hostState = HostState(dub: DubWorkflow())
diff --git a/mobile/ios/VoiceStudio/App/SelectionControls.swift b/mobile/ios/VoiceStudio/App/SelectionControls.swift
index 825b6d3ee..0168ccbb4 100644
--- a/mobile/ios/VoiceStudio/App/SelectionControls.swift
+++ b/mobile/ios/VoiceStudio/App/SelectionControls.swift
@@ -6,6 +6,7 @@ struct SelectionOption: Identifiable {
let title: String
var subtitle: String? = nil
var enabled = true
+ var swatch: Theme? = nil
}
struct SelectionRow: View {
@@ -83,16 +84,27 @@ struct ChoicePicker: View {
selection = option.id; presenting = false
} label: {
HStack(spacing: VSTokens.spacingGap) {
+ if let swatch = option.swatch {
+ HStack(spacing: 0) {
+ swatch.color("canvas")
+ swatch.color("surface")
+ swatch.color("messageAction")
+ }.frame(width: 36, height: 24).clipShape(RoundedRectangle(cornerRadius: 4))
+ .overlay(RoundedRectangle(cornerRadius: 4).strokeBorder(theme.color("border")))
+ .accessibilityHidden(true).accessibilityIdentifier("choice.swatch." + option.id)
+ }
VStack(alignment: .leading, spacing: VSTokens.spacingGap) {
Text(option.title).foregroundStyle(theme.color(option.enabled ? "text" : "textMuted"))
.lineLimit(2).truncationMode(.tail)
if let subtitle = option.subtitle { Text(subtitle).font(.custom("InterVariable", size: VSTokens.textLabel.size, relativeTo: .caption)).foregroundStyle(theme.color("textMuted")) }
}
Spacer(minLength: 0)
- if selection == option.id { Image(systemName: "checkmark").foregroundStyle(theme.color("messageAction")) }
+ if selection == option.id { Image(systemName: "checkmark").foregroundStyle(theme.color("text")).accessibilityIdentifier("choice.selected") }
}.frame(minHeight: 44).contentShape(Rectangle())
}.buttonStyle(VSButtonStyle(kind: .tertiary)).disabled(!option.enabled)
- .accessibilityLabel(option.title).accessibilityValue(option.subtitle ?? "")
+ .accessibilityLabel(option.title)
+ .accessibilityValue(ListFormatter.localizedString(byJoining: [model.t(selection == option.id ? "mobile.ios.selected" : "mobile.ios.not_selected")] + (option.subtitle.map { [$0] } ?? [])))
+ .accessibilityAddTraits(selection == option.id ? .isSelected : [])
.accessibilityIdentifier("choice.option." + option.id).listRowBackground(theme.color("surface"))
}
}
@@ -179,11 +191,12 @@ struct InfoButton: View {
let title: String
let detail: String
var row = false
+ var icon = "info.circle"
@State private var showing = false
var body: some View {
Button { showing = true } label: {
- if row { Label(title, systemImage: "info.circle") }
- else { Image(systemName: "info.circle").accessibilityLabel(title) }
+ if row { Label(title, systemImage: icon) }
+ else { Image(systemName: icon).accessibilityLabel(title) }
}.labelStyle(.titleAndIcon)
.buttonStyle(VSButtonStyle(kind: .tertiary))
.sheet(isPresented: $showing) {
diff --git a/mobile/ios/VoiceStudio/App/ThemeUI.swift b/mobile/ios/VoiceStudio/App/ThemeUI.swift
index 08c308dfd..98ccbeaa3 100644
--- a/mobile/ios/VoiceStudio/App/ThemeUI.swift
+++ b/mobile/ios/VoiceStudio/App/ThemeUI.swift
@@ -150,6 +150,7 @@ struct ConsentView: View {
var body: some View {
Page {
Text(model.t("privacy.analytics_title")).font(.custom("InterVariable", size: VSTokens.textEditor.size, relativeTo: .title))
+ Text(model.t("mobile.consent.phone_note"))
InfoButton(title: model.t("mobile.simple.info"), detail: model.t("privacy.analytics_subtitle"))
ViewThatFits(in: .horizontal) {
HStack(spacing: VSTokens.spacingGap) { choice(true); choice(false) }
diff --git a/mobile/ios/VoiceStudio/Features/DictateView.swift b/mobile/ios/VoiceStudio/Features/DictateView.swift
index f0283ad30..8530a8ad5 100644
--- a/mobile/ios/VoiceStudio/Features/DictateView.swift
+++ b/mobile/ios/VoiceStudio/Features/DictateView.swift
@@ -25,7 +25,7 @@ struct DictateView: View {
var body: some View {
Page {
RunOnPicker(preference: $preference, task: "dictate", installed: localReady).disabled(listening || finalizing)
- if route == .download { LocalDownloadPrompt(item: phoneModel) }
+ if route == .download { LocalDownloadPrompt(items: phoneModel.map { [$0] } ?? [], feature: "mobile.tabs.dictate") }
if route == .connect { NavigationLink(model.t("mobile.settings.connection")) { ConnectView() } }
if checking { ProgressView(model.t("common.loading")) }
else if !ready && route == .computer {
@@ -52,12 +52,16 @@ struct DictateView: View {
Task { try? await Task.sleep(for: .milliseconds(150)); suppressTap = false }
}
}, perform: { holding = true; suppressTap = true; if !listening && ready { start() } })
- HStack {
+ }.navigationTitle(model.t("mobile.tabs.dictate"))
+ .safeAreaInset(edge: .bottom, spacing: 0) {
+ HStack(spacing: VSTokens.spacingGap) {
Button(model.t("mobile.dictate.copy"), systemImage: "doc.on.doc") { UIPasteboard.general.string = text }
+ .accessibilityIdentifier("dictate.copy")
ShareLink(item: text) { Label(model.t("mobile.speak.share"), systemImage: "square.and.arrow.up") }
+ .accessibilityIdentifier("dictate.share")
}.labelStyle(.iconOnly).buttonStyle(VSButtonStyle(kind: .tertiary)).disabled(text.isEmpty)
-
- }.navigationTitle(model.t("mobile.tabs.dictate"))
+ .frame(maxWidth: .infinity).padding(Theme.compactInset).background(theme.color("canvas"))
+ }
.task { preference = model.phone.preference("dictate"); await model.phone.refresh(); await readiness() }
.onChange(of: preference) { _, _ in Task { await readiness() } }
.onChange(of: route) { _, _ in Task { await readiness() } }
diff --git a/mobile/ios/VoiceStudio/Features/DubView.swift b/mobile/ios/VoiceStudio/Features/DubView.swift
index 317242f00..46d2e18f8 100644
--- a/mobile/ios/VoiceStudio/Features/DubView.swift
+++ b/mobile/ios/VoiceStudio/Features/DubView.swift
@@ -44,7 +44,10 @@ struct ComputerDubView: View {
TextField(model.t("mobile.dub.paste_url"), text: $sourceURL).keyboardType(.URL).textInputAutocapitalization(.never).autocorrectionDisabled().accessibilityIdentifier("dub.source_url")
Label(model.t("mobile.simple.languages"), systemImage: "globe")
Button { selectingLanguages = true } label: {
- SelectionRow(label: model.t("mobile.dub.target_languages"), value: ListFormatter.localizedString(byJoining: languages.filter { selected.contains($0.code) }.map(\.name)))
+ HStack(spacing: VSTokens.spacingGap) {
+ Image(systemName: "globe").accessibilityHidden(true)
+ SelectionRow(label: model.t("mobile.dub.target_languages"), value: ListFormatter.localizedString(byJoining: languages.filter { selected.contains($0.code) }.map(\.name)))
+ }
}.buttonStyle(VSButtonStyle(kind: .tertiary)).accessibilityIdentifier("dub.languages")
ScrollView(.horizontal) {
HStack(spacing: VSTokens.spacingGap) {
diff --git a/mobile/ios/VoiceStudio/Features/ModelsView.swift b/mobile/ios/VoiceStudio/Features/ModelsView.swift
index 9a069f1bd..4d8bab539 100644
--- a/mobile/ios/VoiceStudio/Features/ModelsView.swift
+++ b/mobile/ios/VoiceStudio/Features/ModelsView.swift
@@ -5,7 +5,6 @@ struct ModelsView: View {
@Environment(AppModel.self) private var model
@Environment(\.vsTheme) private var theme
@State private var reviewing: PhoneModel?
- @State private var checked = false
var body: some View {
@Bindable var phone = model.phone
Page {
@@ -17,12 +16,12 @@ struct ModelsView: View {
}
ForEach(phone.models) { item in
Card {
- Text(item.id).font(.headline)
+ Text(item.name).font(.headline)
Text(ByteCountFormatter.string(fromByteCount: item.total_bytes, countStyle: .file))
HStack {
Text(model.t("mobile.simple." + item.capability.rawValue)).font(.caption)
Spacer()
- Button(item.licence.id) { reviewing = item }.accessibilityIdentifier("model.licence."+item.id).buttonStyle(VSButtonStyle(kind: .tertiary))
+ Button(model.t("mobile.simple.info"), systemImage: "info.circle") { reviewing = item }.accessibilityIdentifier("model.licence."+item.id).buttonStyle(VSButtonStyle(kind: .tertiary))
}
if !item.fits() { Text(model.t("mobile.simple.ram", ["ram": String(item.min_ram_gb)])) }
if let value = phone.progress[item.id] {
@@ -31,45 +30,99 @@ struct ModelsView: View {
} else if phone.installed.contains(item.id) {
Button(model.t("common.delete"), role: .destructive) { Task { await phone.delete(item) } }
} else {
- Button(model.t("mobile.local.download")) {
- if item.licence.gated && !phone.accepted.contains(item.id) { reviewing = item }
- else { phone.download(item) }
- }.disabled(!item.fits())
+ ModelDownloadButton(items: [item], titleKey: "mobile.local.download")
}
}
}
}.navigationTitle(model.t("mobile.local.models"))
.task { await phone.refresh() }
- .sheet(item: $reviewing, onDismiss: { checked = false }) { item in
- NavigationStack {
- Page(backgroundRole: "surfaceOverlay") {
- Text(item.id).font(.headline)
- Text(model.t("mobile.local.licence_terms", ["licence": item.licence.id, "category": model.t("mobile.local.category_" + item.licence.category), "holder": item.licence.rights_holder, "credit": item.licence.credit]))
- if let terms = item.licence.disclosure { Text(terms).textSelection(.enabled) }
- Text(model.t("mobile.local.fingerprint", ["fingerprint": item.licence.terms_fingerprint])).textSelection(.enabled)
- Text(item.languages.joined(separator: ", "))
- Text(model.t("mobile.local.storage_used", ["size": ByteCountFormatter.string(fromByteCount: phone.modelBytes[item.id] ?? 0, countStyle: .file)]))
- if phone.progress[item.id] == nil && (phone.modelBytes[item.id] ?? 0) > 0 && !phone.installed.contains(item.id) {
- Button(model.t("common.delete"), role: .destructive) { Task { await phone.delete(item); reviewing = nil } }
- }
- if item.licence.gated {
- Text(model.t("mobile.local.acceptance_help"))
- Toggle(model.t("mobile.local.licence_confirm"), isOn: $checked).accessibilityIdentifier("models.consent").frame(minHeight: 44)
- if phone.accepted.contains(item.id) {
- Button(model.t("mobile.local.withdraw"), role: .destructive) { Task { await phone.accept(item, accepted: false); reviewing = nil } }
- }
- HStack {
- Button(model.t("mobile.simple.accept")) { Task { await phone.accept(item, accepted: true); reviewing = nil } }.disabled(!checked).accessibilityIdentifier("models.accept")
- Button(model.t("mobile.simple.decline")) { reviewing = nil }
+ .sheet(item: $reviewing) { item in
+ ModelLicenceSheet(item: item)
+ }
+ }
+}
+
+struct ModelLicenceSheet: View {
+ @Environment(AppModel.self) private var model
+ @Environment(\.vsTheme) private var theme
+ @Environment(\.dismiss) private var dismiss
+ let item: PhoneModel
+ var onAccepted: () -> Void = {}
+ @State private var checked = false
+ @State private var saving = false
+ var body: some View {
+ NavigationStack {
+ Page(backgroundRole: "surfaceOverlay") {
+ Text(item.name).font(.headline)
+ Text(model.t("mobile.local.licence_terms", ["licence": item.licence.id, "category": model.t("mobile.local.category_" + item.licence.category), "holder": item.licence.rights_holder, "credit": item.licence.credit]))
+ if let terms = item.licence.disclosure { Text(terms).textSelection(.enabled) }
+ Text(model.t("mobile.local.fingerprint", ["fingerprint": item.licence.terms_fingerprint])).textSelection(.enabled)
+ Text(item.languages.joined(separator: ", "))
+ Text(model.t("mobile.local.storage_used", ["size": ByteCountFormatter.string(fromByteCount: model.phone.modelBytes[item.id] ?? 0, countStyle: .file)]))
+ if model.phone.progress[item.id] == nil && (model.phone.modelBytes[item.id] ?? 0) > 0 && !model.phone.installed.contains(item.id) {
+ Button(model.t("common.delete"), role: .destructive) { Task { await model.phone.delete(item); dismiss() } }
+ }
+ if item.licence.gated {
+ Text(model.t("mobile.local.acceptance_help"))
+ Toggle(model.t("mobile.local.licence_confirm"), isOn: $checked).accessibilityIdentifier("models.consent").frame(minHeight: 44)
+ if model.phone.accepted.contains(item.id) {
+ Button(model.t("mobile.local.withdraw"), role: .destructive) {
+ Task { saving = true; defer { saving = false }; if await model.phone.accept(item, accepted: false) { dismiss() } }
}
}
- }.navigationTitle(model.t("mobile.local.licence"))
- .toolbar { Button(model.t("common.close")) { reviewing = nil } }
- }.environment(model).presentationBackground(theme.color("surfaceOverlay"))
+ HStack {
+ Button(model.t("mobile.simple.accept")) {
+ Task {
+ saving = true; defer { saving = false }
+ if await model.phone.accept(item, accepted: true) { onAccepted(); dismiss() }
+ }
+ }.disabled(!checked || saving).accessibilityIdentifier("models.accept")
+ Button(model.t("mobile.simple.decline")) { dismiss() }.disabled(saving)
+ }
+ }
+ }.navigationTitle(model.t("mobile.local.licence"))
+ .toolbar { Button(model.t("common.close")) { dismiss() }.disabled(saving) }
+ }.interactiveDismissDisabled(saving).presentationBackground(theme.color("surfaceOverlay"))
+ }
+}
+
+/// Reused by Models and every compact feature prompt; starting a batch never bypasses terms.
+struct ModelDownloadButton: View {
+ @Environment(AppModel.self) private var model
+ let items: [PhoneModel]
+ var titleKey = "mobile.simple.get"
+ @State private var queue = ModelDownloadQueue([])
+ @State private var reviewing: PhoneModel?
+ @State private var continueDownloads = false
+ private var downloading: Bool { items.contains { model.phone.progress[$0.id] != nil } }
+ var body: some View {
+ Button(model.t(downloading ? "common.cancel" : titleKey)) {
+ if downloading {
+ queue = ModelDownloadQueue([])
+ for item in items { model.phone.cancel(item) }
+ } else {
+ queue = ModelDownloadQueue(items); advance()
+ }
+ }.disabled(items.isEmpty || !items.allSatisfy { $0.fits() })
+ .accessibilityIdentifier("models.get")
+ .sheet(item: $reviewing, onDismiss: {
+ if continueDownloads { continueDownloads = false; advance() }
+ else { queue = ModelDownloadQueue([]) }
+ }) { item in
+ ModelLicenceSheet(item: item, onAccepted: { continueDownloads = true }).id(item.id)
+ }
+ }
+ private func advance() {
+ while let step = queue.next(installed: model.phone.installed, accepted: model.phone.accepted) {
+ switch step {
+ case .licence(let item): reviewing = item; return
+ case .download(let item): model.phone.download(item)
+ }
}
}
}
+
struct RunOnPicker: View {
@Environment(AppModel.self) private var model
@Binding var preference: TaskLocation?
@@ -91,13 +144,43 @@ struct RunOnPicker: View {
}
struct LocalDownloadPrompt: View {
@Environment(AppModel.self) private var model
- let item: PhoneModel?
+ let items: [PhoneModel]
+ let feature: String
+ private var needed: [PhoneModel] { items.filter { !model.phone.ready($0) } }
+ private var progress: Double? {
+ guard needed.contains(where: { model.phone.progress[$0.id] != nil }) else { return nil }
+ let total = needed.reduce(0.0) { $0 + Double($1.total_bytes) }
+ return needed.reduce(0.0) { $0 + Double($1.total_bytes) * (model.phone.progress[$1.id] ?? 0) } / max(1, total)
+ }
+ private var size: String { ByteCountFormatter.string(fromByteCount: needed.reduce(0) { $0 + $1.total_bytes }, countStyle: .file) }
+ private var title: String {
+ if let item = needed.first, needed.count == 1 {
+ return model.t("mobile.simple.download_one", ["name": item.name, "size": size])
+ }
+ return model.l10n.t("mobile.simple.downloads", ["feature": model.t(feature), "count": String(needed.count), "size": size], count: needed.count)
+ }
var body: some View {
- Card {
- Label(model.t("mobile.simple.models_error"), systemImage: "arrow.down.circle")
- if let item { Text(ByteCountFormatter.string(fromByteCount: item.total_bytes, countStyle: .file)).font(.caption) }
- NavigationLink(model.t("mobile.simple.download_models")) { ModelsView() }
-
+ if !needed.isEmpty {
+ Card {
+ HStack(spacing: VSTokens.spacingGap) {
+ NavigationLink { ModelsView() } label: {
+ HStack(spacing: VSTokens.spacingGap) {
+ Image(systemName: "arrow.down.circle").accessibilityHidden(true)
+ VStack(alignment: .leading, spacing: 4) {
+ Text(title)
+ if let item = needed.first, needed.count == 1 {
+ Text(model.t("mobile.simple." + item.capability.rawValue)).font(.caption)
+ }
+ }.frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }.buttonStyle(VSButtonStyle(kind: .tertiary)).accessibilityIdentifier("models.open")
+ ModelDownloadButton(items: needed)
+ }
+ if let progress { ProgressView(value: progress).accessibilityLabel(model.t("mobile.local.downloading")) }
+ if let item = needed.first(where: { !$0.fits() }) {
+ Text(model.t("mobile.simple.ram", ["ram": String(item.min_ram_gb)])).font(.caption)
+ }
+ }.accessibilityIdentifier("models.prompt")
}
}
}
diff --git a/mobile/ios/VoiceStudio/Features/PhoneDubView.swift b/mobile/ios/VoiceStudio/Features/PhoneDubView.swift
index e0da3793e..db961ae0b 100644
--- a/mobile/ios/VoiceStudio/Features/PhoneDubView.swift
+++ b/mobile/ios/VoiceStudio/Features/PhoneDubView.swift
@@ -30,7 +30,10 @@ struct PhoneDubView: View {
if let source { SelectedFileRow(name: source.name) { self.source = nil } }
Label(model.t("mobile.simple.languages"),systemImage: "globe")
Button { languages = true } label: {
- SelectionRow(label: model.t("mobile.dub.target_languages"),value: ListFormatter.localizedString(byJoining: choices.filter { targets.contains($0.code) }.map(\.name)))
+ HStack(spacing: VSTokens.spacingGap) {
+ Image(systemName: "globe").accessibilityHidden(true)
+ SelectionRow(label: model.t("mobile.dub.target_languages"),value: ListFormatter.localizedString(byJoining: choices.filter { targets.contains($0.code) }.map(\.name)))
+ }
}.buttonStyle(VSButtonStyle(kind: .tertiary)).accessibilityIdentifier("dub.languages")
ScrollView(.horizontal) {
HStack { ForEach(choices.filter { targets.contains($0.code) }) { language in
@@ -49,7 +52,7 @@ struct PhoneDubView: View {
phoneModel("dub-translate",.translate)
phoneModel("dub",.clone)
}.disabled(copying || model.phone.activeDub != nil)
- ForEach(model.phone.dubModels.filter { !model.phone.ready($0) }) { LocalDownloadPrompt(item: $0) }
+ LocalDownloadPrompt(items: model.phone.dubModels, feature: "mobile.tabs.dub")
Button(model.t("mobile.simple.dub"),systemImage: "film") { start() }.buttonStyle(VSButtonStyle(kind: .primary))
.disabled(!ready || !consent || source == nil || targets.isEmpty || model.busy || copying || model.phone.activeDub != nil)
.accessibilityIdentifier("dub.start")
@@ -102,7 +105,10 @@ struct PhoneDubView: View {
if let code = language.code { if targets.contains(code) { targets.remove(code) } else { targets.insert(code) } }
} label: {
HStack { Text(language.name); Spacer(); Image(systemName: targets.contains(language.code ?? "") ? "checkmark.circle.fill" : "circle") }.frame(minHeight: 44)
- }.accessibilityValue(model.t(targets.contains(language.code ?? "") ? "mobile.ios.selected" : "mobile.ios.not_selected"))
+ }.buttonStyle(VSButtonStyle(kind: .tertiary))
+ .accessibilityValue(model.t(targets.contains(language.code ?? "") ? "mobile.ios.selected" : "mobile.ios.not_selected"))
+ .accessibilityAddTraits(targets.contains(language.code ?? "") ? .isSelected : [])
+ .listRowBackground(theme.color("surface"))
}
}.scrollContentBackground(.hidden).background(theme.color("surfaceOverlay")).keyboardAccessible()
.navigationTitle(model.t("mobile.dub.target_languages"))
@@ -117,7 +123,7 @@ struct PhoneDubView: View {
.onDisappear { creating?.cancel() }
}
private func phoneModel(_ task: String,_ capability: ModelCapability) -> some View {
- ChoicePicker(label: model.t("mobile.simple."+capability.rawValue),selection: Binding(get: { model.phone.selectedModel(task,capability)?.id ?? "" },set: { model.phone.chooseModel(task,$0) }),options: model.phone.candidates(capability).map { SelectionOption(id: $0.id,title: $0.id,enabled: $0.fits()) })
+ ChoicePicker(label: model.t("mobile.simple."+capability.rawValue),selection: Binding(get: { model.phone.selectedModel(task,capability)?.id ?? "" },set: { model.phone.chooseModel(task,$0) }),options: model.phone.candidates(capability).map { SelectionOption(id: $0.id,title: $0.name,subtitle: model.t("mobile.simple." + $0.capability.rawValue),enabled: $0.fits()) })
}
private func start() {
guard let source else { return }
diff --git a/mobile/ios/VoiceStudio/Features/SettingsView.swift b/mobile/ios/VoiceStudio/Features/SettingsView.swift
index 4eae0e328..52448cc11 100644
--- a/mobile/ios/VoiceStudio/Features/SettingsView.swift
+++ b/mobile/ios/VoiceStudio/Features/SettingsView.swift
@@ -7,8 +7,8 @@ struct SettingsView: View {
@Bindable var model = model
Page {
Card {
- NavigationLink { ModelsView() } label: { Label(model.t("mobile.local.models"),systemImage: "square.stack.3d.up") }
NavigationLink { ConnectView() } label: { HStack { Image(systemName: "link").accessibilityHidden(true); SelectionRow(label: model.t("mobile.settings.connection"),value: model.connection.active?.label ?? "") } }.accessibilityIdentifier("settings.connect")
+ NavigationLink { ModelsView() } label: { Label(model.t("mobile.local.models"),systemImage: "arrow.down.circle") }
}
if model.connection.client != nil {
Card {
@@ -28,7 +28,7 @@ struct SettingsView: View {
Toggle(isOn: Binding(get: { model.notifications }, set: { value in Task { await model.enableNotifications(value) } })) { Label(model.t("mobile.settings.notifications"),systemImage: "bell") }.frame(minHeight: 44)
}
Card {
- InfoButton(title: model.t("mobile.simple.privacy"), detail: model.t("mobile.local.privacy"), row: true)
+ InfoButton(title: model.t("mobile.simple.privacy"), detail: model.t("mobile.local.privacy"), row: true, icon: "shield")
Toggle(isOn: $model.analytics) { Label(model.t("mobile.simple.analytics"),systemImage: "chart.bar") }.frame(minHeight: 44)
}
Card {
@@ -41,7 +41,7 @@ struct SettingsView: View {
}.navigationTitle(model.t("mobile.tabs.settings")).navigationBarTitleDisplayMode(.large)
}
private func palette(key: String, selection: Binding<String>) -> some View {
- ChoicePicker(label: model.t(key), selection: selection, options: VSTokens.palettes.map { SelectionOption(id: $0.id, title: Theme.paletteLabel($0, l10n: model.l10n)) }, icon: "paintpalette")
+ ChoicePicker(label: model.t(key), selection: selection, options: VSTokens.palettes.map { SelectionOption(id: $0.id, title: Theme.paletteLabel($0, l10n: model.l10n), swatch: Theme(palette: $0.id, appearance: key == "mobile.settings.light_palette" ? .light : .dark)) }, icon: "paintpalette").accessibilityIdentifier(key)
}
}
struct LicensesView: View {
diff --git a/mobile/ios/VoiceStudio/Features/SpeakView.swift b/mobile/ios/VoiceStudio/Features/SpeakView.swift
index f0d6536b5..5266797bd 100644
--- a/mobile/ios/VoiceStudio/Features/SpeakView.swift
+++ b/mobile/ios/VoiceStudio/Features/SpeakView.swift
@@ -43,7 +43,7 @@ struct SpeakView: View {
var body: some View {
Page {
RunOnPicker(preference: $preference, task: "speak", installed: localReady).disabled(generating)
- if route == .download { LocalDownloadPrompt(item: phoneModel) }
+ if route == .download { LocalDownloadPrompt(items: phoneModel.map { [$0] } ?? [], feature: "mobile.tabs.speak") }
if route == .connect { NavigationLink(model.t("mobile.settings.connection")) { ConnectView() } }
ZStack(alignment: .topLeading) {
if text.isEmpty { Text(model.t("mobile.speak.placeholder")).foregroundStyle(theme.color("textMuted")).padding(Theme.compactInset).allowsHitTesting(false) }
@@ -55,7 +55,7 @@ struct SpeakView: View {
if route != .computer {
HStack(spacing: VSTokens.spacingGap) {
ChoicePicker(label: model.t("mobile.speak.voice"), selection: $speakerID, options: (0..<min(128,Int(phoneModel?.config["num_speakers"]?.number ?? 1))).map { SelectionOption(id: String($0), title: model.t("mobile.local.preset_voice", ["number": String($0 + 1)])) } + model.phone.voices.map { SelectionOption(id: "phone:"+$0.id.uuidString,title: $0.name) }, compact: true)
- ChoicePicker(label: model.t("mobile.local.models"), selection: Binding(get: { phoneModel?.id ?? "" }, set: { phoneModelID = $0; model.phone.chooseModel("speak-"+capability.rawValue,$0) }), options: model.phone.candidates(capability).map { SelectionOption(id: $0.id, title: $0.id, enabled: $0.fits()) }, compact: true)
+ ChoicePicker(label: model.t("mobile.local.models"), selection: Binding(get: { phoneModel?.id ?? "" }, set: { phoneModelID = $0; model.phone.chooseModel("speak-"+capability.rawValue,$0) }), options: model.phone.candidates(capability).map { SelectionOption(id: $0.id, title: $0.name, subtitle: model.t("mobile.simple." + $0.capability.rawValue), enabled: $0.fits()) }, compact: true)
ChoicePicker(label: model.t("mobile.speak.language"), selection: $phoneLanguage, options: phoneVoice == nil ? (phoneModel?.languages ?? []).map { SelectionOption(id: $0, title: Locale(identifier: model.l10n.locale).localizedString(forLanguageCode: $0) ?? $0) } : [SelectionOption(id: "auto",title: model.t("mobile.ios.language_auto"))], compact: true)
}.disabled(generating)
diff --git a/mobile/ios/VoiceStudio/Features/VoicesView.swift b/mobile/ios/VoiceStudio/Features/VoicesView.swift
index 23aa240d8..2f8610a8d 100644
--- a/mobile/ios/VoiceStudio/Features/VoicesView.swift
+++ b/mobile/ios/VoiceStudio/Features/VoicesView.swift
@@ -27,9 +27,7 @@ struct VoicesView: View {
var body: some View {
Page {
RunOnPicker(preference: $preference, task: "clone", installed: localReady)
- if route != .computer {
- ChoicePicker(label: model.t("mobile.local.models"),selection: Binding(get: { model.phone.selectedModel("clone",.asr)?.id ?? "" },set: { model.phone.chooseModel("clone",$0) }),options: model.phone.candidates(.asr).map { SelectionOption(id: $0.id,title: $0.id,enabled: $0.fits()) },compact: true)
- }
+ if route == .download { LocalDownloadPrompt(items: model.phone.selectedModel("clone",.asr).map { [$0] } ?? [], feature: "mobile.tabs.voices") }
SearchField(prompt: model.t("mobile.voices.search"), text: $query)
if entries.isEmpty && !model.loading {
EmptyState(key: "mobile.simple.empty_voices", icon: "person")
@@ -113,8 +111,13 @@ struct CloneView: View {
private var route: TaskRoute { LocalRouting.route(preference: preference,installed: ready,paired: model.connection.client != nil) }
var body: some View {
Page(backgroundRole: "surfaceOverlay") {
- if route == .download { LocalDownloadPrompt(item: asr) }
+ if route == .download { LocalDownloadPrompt(items: asr.map { [$0] } ?? [], feature: "mobile.tabs.voices") }
if route == .connect { NavigationLink(model.t("mobile.simple.reconnect")) { ConnectView() } }
+ if route != .computer {
+ DisclosureGroup(model.t("mobile.simple.more")) {
+ ChoicePicker(label: model.t("mobile.local.models"), selection: Binding(get: { asr?.id ?? "" }, set: { model.phone.chooseModel("clone",$0) }), options: model.phone.candidates(.asr).map { SelectionOption(id: $0.id, title: $0.name, subtitle: model.t("mobile.simple." + $0.capability.rawValue), enabled: $0.fits()) })
+ }
+ }
TextField(model.t("mobile.voices.name_label"),text: $name).accessibilityIdentifier("voices.clone.name")
HStack {
Toggle(model.t("mobile.simple.voice_consent"),isOn: $consent).frame(minHeight: 44)
diff --git a/mobile/ios/VoiceStudio/Info.plist b/mobile/ios/VoiceStudio/Info.plist
index 4629006e5..7d62e2cce 100644
--- a/mobile/ios/VoiceStudio/Info.plist
+++ b/mobile/ios/VoiceStudio/Info.plist
@@ -9,7 +9,11 @@
<key>CFBundleDevelopmentRegion</key><string>en</string>
<key>LSRequiresIPhoneOS</key><true/>
<key>UIApplicationSupportsIndirectInputEvents</key><true/>
-<key>UILaunchScreen</key><dict/>
+<key>UILaunchScreen</key><dict>
+<key>UIColorName</key><string>LaunchCanvas</string>
+<key>UIImageName</key><string>LaunchLogo</string>
+<key>UIImageRespectsSafeAreaInsets</key><true/>
+</dict>
<key>UISupportedInterfaceOrientations</key><array><string>UIInterfaceOrientationPortrait</string><string>UIInterfaceOrientationLandscapeLeft</string><string>UIInterfaceOrientationLandscapeRight</string></array>
<key>UIAppFonts</key><array><string>InterVariable.ttf</string></array>
<key>UIBackgroundModes</key><array><string>processing</string></array>
diff --git a/mobile/ios/VoiceStudio/Platform/PhoneModels.swift b/mobile/ios/VoiceStudio/Platform/PhoneModels.swift
index a9bc2a765..dfb88ad28 100644
--- a/mobile/ios/VoiceStudio/Platform/PhoneModels.swift
+++ b/mobile/ios/VoiceStudio/Platform/PhoneModels.swift
@@ -101,14 +101,15 @@ final class WifiState: @unchecked Sendable {
do { try await store.delete(model); await refresh() }
catch { self.error = error as? ClientError ?? ClientError("mobile.errors.file") }
}
- func accept(_ model: PhoneModel, accepted: Bool) async {
- guard let store else { return }
+ @discardableResult func accept(_ model: PhoneModel, accepted: Bool) async -> Bool {
+ guard let store else { return false }
if !accepted { downloads[model.id]?.cancel() }
do {
guard let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String else { throw ClientError("mobile.local.configuration") }
try await store.accept(model, fingerprint: model.licence.terms_fingerprint, appVersion: version, accepted: accepted)
await refresh()
- } catch { self.error = error as? ClientError ?? ClientError("mobile.errors.file") }
+ return true
+ } catch { self.error = error as? ClientError ?? ClientError("mobile.errors.file"); return false }
}
var dubModels: [PhoneModel] { [selectedModel("dub-asr",.asr), selectedModel("dub-translate",.translate), selectedModel("dub",.clone)].compactMap { $0 } }
var dubReady: Bool { dubModels.count == 3 && dubModels.allSatisfy(ready) }
diff --git a/mobile/ios/VoiceStudio/project.yml b/mobile/ios/VoiceStudio/project.yml
index 3c8817662..744b4a487 100644
--- a/mobile/ios/VoiceStudio/project.yml
+++ b/mobile/ios/VoiceStudio/project.yml
@@ -4,6 +4,7 @@ options:
deploymentTarget:
iOS: '17.0'
developmentLanguage: en
+ preGenCommand: python3 ../scripts/prepare_resources.py --output ../.generated/bundle --info-output ../.generated/Info.plist
packages:
VoiceStudioKit:
path: ../VoiceStudioKit
@@ -24,11 +25,13 @@ targets:
- path: Features
- path: Platform
- path: Resources
+ - path: ../.generated/Brand.xcassets
settings:
base:
PRODUCT_BUNDLE_IDENTIFIER: com.voicestudio.mobile
GENERATE_INFOPLIST_FILE: 'NO'
INFOPLIST_FILE: $(DERIVED_FILE_DIR)/VoiceStudio-Info.plist
+ ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
dependencies:
- package: VoiceStudioKit
- framework: ../../native/ios/build/xcframeworks/sherpa-onnx.xcframework
@@ -52,8 +55,12 @@ targets:
inputFiles:
- $(SRCROOT)/../../../package.json
- $(SRCROOT)/Info.plist
+ - $(SRCROOT)/../../../docs/logo.png
+ - $(SRCROOT)/../../contract/tokens.json
+ - $(SRCROOT)/../scripts/generate-brand-assets.swift
outputFiles:
- $(DERIVED_FILE_DIR)/VoiceStudio-Info.plist
+ - $(SRCROOT)/../.generated/Brand.xcassets
VoiceStudioUITests:
type: bundle.ui-testing
platform: iOS
diff --git a/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Local/ModelCatalogue.swift b/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Local/ModelCatalogue.swift
index 54808e830..a0aaa1ddb 100644
--- a/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Local/ModelCatalogue.swift
+++ b/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Local/ModelCatalogue.swift
@@ -51,6 +51,7 @@ public struct PhoneModel: Codable, Identifiable, Sendable {
public var gated: Bool { category != "commercial-ok" || requires_acceptance }
}
public let id: String
+ public let name: String
public let capability: ModelCapability
public let runtime: ModelRuntime
public let repo: String
@@ -65,7 +66,7 @@ public struct PhoneModel: Codable, Identifiable, Sendable {
public func selectingLanguage(_ language: String) throws -> PhoneModel {
guard capability == .tts, languages.contains(language) else { throw ClientError("mobile.local.configuration") }
var options = config; options["lang"] = .string(language)
- return PhoneModel(id: id,capability: capability,runtime: runtime,repo: repo,revision: revision,files: files,total_bytes: total_bytes,languages: languages,min_ram_gb: min_ram_gb,licence: licence,config: options)
+ return PhoneModel(id: id,name: name,capability: capability,runtime: runtime,repo: repo,revision: revision,files: files,total_bytes: total_bytes,languages: languages,min_ram_gb: min_ram_gb,licence: licence,config: options)
}
public func path(role: String, root: URL) -> String { files.first { $0.role == role }.map { root.appendingPathComponent($0.path).path } ?? "" }
public func option(_ key: String, fallback: String = "") -> String { config[key]?.string ?? fallback }
@@ -77,7 +78,8 @@ public struct ModelCatalogue: Codable, Sendable {
let value = try JSONDecoder().decode(Self.self, from: data)
guard value.schema_version == 1, Set(value.models.map(\.id)).count == value.models.count else { throw ClientError("mobile.local.catalogue_error") }
for m in value.models {
- guard safe(m.id), m.repo.split(separator: "/").count == 2, m.repo.split(separator: "/").allSatisfy({ safe(String($0)) }),
+ guard safe(m.id), !m.name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
+ m.repo.split(separator: "/").count == 2, m.repo.split(separator: "/").allSatisfy({ safe(String($0)) }),
hex(m.revision, count: 40), !m.files.isEmpty, m.min_ram_gb.isFinite, m.min_ram_gb > 0,
hex(m.licence.terms_fingerprint, count: 64), ["commercial-ok", "non-commercial", "conditional", "unidentified"].contains(m.licence.category),
Set(m.files.map(\.path)).count == m.files.count,
diff --git a/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Local/ModelDownloadQueue.swift b/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Local/ModelDownloadQueue.swift
new file mode 100644
index 000000000..9895ac345
--- /dev/null
+++ b/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Local/ModelDownloadQueue.swift
@@ -0,0 +1,20 @@
+import Foundation
+
+/// One explicit Get action, with a separate acceptance boundary for every model.
+public struct ModelDownloadQueue: Sendable {
+ public enum Step: Sendable { case licence(PhoneModel), download(PhoneModel) }
+ private var pending: [PhoneModel]
+ public init(_ models: [PhoneModel]) {
+ var seen = Set<String>()
+ pending = models.filter { seen.insert($0.id).inserted }
+ }
+ public mutating func next(installed: Set<String>, accepted: Set<String>) -> Step? {
+ while let model = pending.first {
+ // Never consume this entry until the receipt has actually been saved.
+ if model.licence.gated && !accepted.contains(model.id) { return .licence(model) }
+ pending.removeFirst()
+ if !installed.contains(model.id) { return .download(model) }
+ }
+ return nil
+ }
+}
diff --git a/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/ContractTests.swift b/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/ContractTests.swift
index 24738287c..57899b092 100644
--- a/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/ContractTests.swift
+++ b/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/ContractTests.swift
@@ -75,7 +75,10 @@ func catalogs() throws -> [String: Data] {
for match in regex.matches(in: source, range: NSRange(source.startIndex..., in: source)) {
let key = String(source[Range(match.range(at: 1), in: source)!])
if let suffixes = dynamic[key] { for suffix in suffixes { #expect(l10n.contains(key + suffix), "Missing \(key + suffix)") } }
- else { #expect(l10n.contains(key), "Missing \(key) in \(file.lastPathComponent)") }
+ else {
+ let exists = l10n.contains(key) || (l10n.contains(key + "_one") && l10n.contains(key + "_other"))
+ #expect(exists, "Missing \(key) in \(file.lastPathComponent)")
+ }
}
}
let mobile = L10n.flatten(try JSONSerialization.jsonObject(with: Data(contentsOf: repository.appendingPathComponent("mobile/contract/strings.mobile.en.json"))))
diff --git a/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/LocalInferenceTests.swift b/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/LocalInferenceTests.swift
index e161af463..0106637b3 100644
--- a/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/LocalInferenceTests.swift
+++ b/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/LocalInferenceTests.swift
@@ -12,7 +12,7 @@ private func localDirectory() throws -> URL {
private func localFixture(bytes: Data = Data("model".utf8), gated: Bool = false, capability: String = "tts", fingerprint: String = String(repeating: "a", count: 64)) throws -> PhoneModel {
let runtime = capability == "clone" ? "omnivoice.cpp" : capability == "translate" ? "llama.cpp" : "sherpa-onnx"
let object: [String: Any] = ["schema_version": 1, "models": [[
- "id": "fixture", "capability": capability, "runtime": runtime, "repo": "owner/model", "revision": String(repeating: "b", count: 40),
+ "id": "fixture", "name": "Fixture", "capability": capability, "runtime": runtime, "repo": "owner/model", "revision": String(repeating: "b", count: 40),
"files": [["path": "model.bin", "size": bytes.count, "sha256": SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined(), "role": "model"]],
"total_bytes": bytes.count, "languages": ["en"], "min_ram_gb": 1,
"licence": ["id": "test", "category": gated ? "non-commercial" : "commercial-ok", "requires_acceptance": false, "credit": "Fixture", "rights_holder": "Fixture", "terms_fingerprint": fingerprint],
@@ -312,3 +312,38 @@ private struct LoopbackRangeTransport: HTTPTransport {
#expect(try Data(contentsOf: path.appendingPathComponent("model.bin")) == bytes)
}
#endif
+
+@Test func modelProductNameIsRequiredAndSurvivesLanguageSelection() throws {
+ let fixture = try localFixture()
+ #expect(fixture.name == "Fixture")
+ #expect(try fixture.selectingLanguage("en").name == fixture.name)
+ let encoded = try JSONEncoder().encode(fixture)
+ var object = try JSONSerialization.jsonObject(with: encoded) as! [String: Any]
+ for invalid: String? in [nil, "", " \n "] {
+ object["name"] = invalid
+ let data = try JSONSerialization.data(withJSONObject: ["schema_version": 1, "models": [object]])
+ #expect(throws: (any Error).self) { try ModelCatalogue.decode(data) }
+ }
+}
+
+@Test func downloadBatchRequiresEveryReceiptAndSkipsInstalledModels() throws {
+ let first = try localFixture(gated: true)
+ var object = try JSONSerialization.jsonObject(with: JSONEncoder().encode(first)) as! [String: Any]
+ object["id"] = "second"; object["name"] = "Second"
+ let second = try ModelCatalogue.decode(JSONSerialization.data(withJSONObject: ["schema_version": 1, "models": [object]])).models[0]
+ var queue = ModelDownloadQueue([first, second, first])
+ // Repeated calls cannot skip an unaccepted model (including persistence failure).
+ for _ in 0..<2 {
+ guard case .licence(let item) = queue.next(installed: [], accepted: []) else { Issue.record("Missing first licence gate"); return }
+ #expect(item.id == first.id)
+ }
+ guard case .download(let item) = queue.next(installed: [], accepted: [first.id]) else { Issue.record("Missing first download"); return }
+ #expect(item.id == first.id)
+ guard case .licence(let item) = queue.next(installed: [], accepted: [first.id]) else { Issue.record("Missing second licence gate"); return }
+ #expect(item.id == second.id)
+ // Accepting an installed model authorizes use without downloading it again.
+ #expect(queue.next(installed: [second.id], accepted: [first.id, second.id]) == nil)
+ var permissive = ModelDownloadQueue([try localFixture()])
+ guard case .download = permissive.next(installed: [], accepted: []) else { Issue.record("Permissive model was gated"); return }
+ #expect(permissive.next(installed: [], accepted: []) == nil)
+}
diff --git a/mobile/ios/VoiceStudioUITests/PhoneScreens.swift b/mobile/ios/VoiceStudioUITests/PhoneScreens.swift
index ed9846b3a..3edc00b2d 100644
--- a/mobile/ios/VoiceStudioUITests/PhoneScreens.swift
+++ b/mobile/ios/VoiceStudioUITests/PhoneScreens.swift
@@ -8,9 +8,9 @@ final class PhoneScreens: XCTestCase {
}
@MainActor func testRememberedComputerChoiceFallsBackWhileUnpaired() {
let app = launch(extra: ["-run-on.speak","computer","-run-on.clone","computer","-run-on.dub","computer"])
- XCTAssertTrue(app.buttons["Open Models"].exists)
+ XCTAssertTrue(app.buttons["models.get"].exists)
app.tabBars.buttons["Voices"].tap(); app.buttons["voices.create"].tap()
- XCTAssertTrue(app.buttons["Open Models"].waitForExistence(timeout: 5)); app.buttons["Cancel"].tap()
+ XCTAssertTrue(app.buttons["models.get"].waitForExistence(timeout: 5)); app.buttons["Cancel"].tap()
app.tabBars.buttons["Dub"].tap()
XCTAssertTrue(app.staticTexts["1 Source"].waitForExistence(timeout: 5))
XCTAssertFalse(app.textFields["dub.source_url"].exists)
@@ -18,7 +18,7 @@ final class PhoneScreens: XCTestCase {
@MainActor func testUnpairedCloneShowsModelGateAndConsent() {
let app = launch(); app.tabBars.buttons["Voices"].tap(); app.buttons["voices.create"].tap()
XCTAssertTrue(app.textFields["voices.clone.name"].waitForExistence(timeout: 5))
- XCTAssertTrue(app.buttons["Open Models"].exists)
+ XCTAssertTrue(app.buttons["models.get"].exists)
XCTAssertTrue(app.switches["I have permission"].exists)
XCTAssertFalse(app.buttons["Create clone"].isEnabled)
XCTAssertFalse(app.staticTexts["This task currently runs on your paired computer."].exists)
@@ -43,6 +43,40 @@ final class PhoneScreens: XCTestCase {
XCTAssertTrue(consent.exists); consent.tap(); XCTAssertTrue(accept.isEnabled)
app.buttons["Decline"].tap()
}
+ @MainActor func testCompactDownloadsUseProductNamesAndOneDubAction() {
+ let app = launch()
+ XCTAssertEqual(app.buttons.matching(identifier: "models.get").count, 1)
+ XCTAssertFalse(app.staticTexts["kitten-mini-en-fp16"].exists)
+ XCTAssertTrue(app.buttons["models.open"].label.contains("Kitten"))
+ app.buttons["models.get"].tap()
+ XCTAssertTrue(app.buttons["models.accept"].waitForExistence(timeout: 5))
+ XCTAssertFalse(app.buttons["models.accept"].isEnabled)
+ for _ in 0..<15 { if app.buttons["Decline"].isHittable { break }; app.swipeUp() }
+ app.buttons["Decline"].tap()
+ app.tabBars.buttons["Voices"].tap()
+ XCTAssertFalse(app.buttons["whisper-tiny-int8"].exists)
+ app.tabBars.buttons["Dub"].tap()
+ XCTAssertEqual(app.buttons.matching(identifier: "models.get").count, 1)
+ XCTAssertTrue(app.buttons["models.open"].label.contains("3 downloads"))
+ XCTAssertFalse(app.staticTexts["NOASSERTION"].exists)
+ XCTAssertFalse(app.navigationBars.buttons["Settings"].exists)
+ }
+ @MainActor func testPaletteSelectionAndDictationActionsClearTheTabBar() {
+ let app = launch(); app.tabBars.buttons["Dictate"].tap()
+ let bar = app.tabBars.firstMatch
+ for identifier in ["dictate.copy", "dictate.share"] {
+ let action = app.buttons[identifier]
+ XCTAssertTrue(action.exists)
+ XCTAssertLessThanOrEqual(action.frame.maxY, bar.frame.minY)
+ }
+ app.tabBars.buttons["Settings"].tap()
+ app.buttons["mobile.settings.light_palette"].tap()
+ let studio = app.buttons["choice.option.default"]
+ XCTAssertTrue(studio.waitForExistence(timeout: 5)); XCTAssertEqual(studio.value as? String, "Selected")
+ app.buttons["choice.option.canopy"].tap()
+ app.buttons["mobile.settings.light_palette"].tap()
+ XCTAssertEqual(app.buttons["choice.option.canopy"].value as? String, "Selected")
+ }
@MainActor func testConnectAndPrivacyKeepDetailsCollapsed() {
let app = launch(); app.tabBars.buttons["Settings"].tap()
XCTAssertFalse(app.staticTexts.containing(NSPredicate(format: "label BEGINSWITH %@","On-device tasks send nothing")).firstMatch.exists)
@@ -62,13 +96,16 @@ final class ScreenshotTour: XCTestCase {
}
@MainActor func testPhoneFirstScreens() {
let app = XCUIApplication(); app.launchArguments = ["--ui-smoke","-AppleLanguages","(en)"]
- app.launch(); XCTAssertTrue(app.buttons["consent.no"].waitForExistence(timeout: 10)); capture("Consent",app); app.buttons["consent.no"].tap()
+ app.launch(); XCTAssertTrue(app.buttons["consent.no"].waitForExistence(timeout: 10)); XCTAssertTrue(app.staticTexts["Saved on this phone. Nothing is sent."].exists); capture("Consent",app); app.buttons["consent.no"].tap()
XCTAssertTrue(app.textViews["speak.text"].waitForExistence(timeout: 5)); capture("Speak-phone",app)
app.tabBars.buttons["Voices"].tap(); capture("Voices-phone",app)
app.buttons["voices.create"].tap(); XCTAssertTrue(app.textFields["voices.clone.name"].waitForExistence(timeout: 5)); capture("Clone-phone",app); app.buttons["Cancel"].tap()
- app.tabBars.buttons["Dub"].tap(); capture("Dub-phone",app)
+ app.tabBars.buttons["Dub"].tap(); XCTAssertEqual(app.buttons.matching(identifier: "models.get").count, 1); capture("Dub-phone",app)
app.tabBars.buttons["Dictate"].tap(); capture("Dictate-phone",app)
app.tabBars.buttons["Settings"].tap(); capture("Settings",app)
+ app.buttons["mobile.settings.light_palette"].tap()
+ XCTAssertTrue(app.buttons["choice.option.default"].waitForExistence(timeout: 5)); capture("Palette-picker",app); app.buttons["Close"].tap()
+ app.buttons["Language"].tap(); capture("Language-picker",app); app.buttons["Close"].tap()
app.buttons["Models"].tap(); capture("Models",app)
app.buttons["model.licence.kitten-mini-en-fp16"].tap(); capture("Model-terms",app); app.buttons["Close"].tap()
app.navigationBars.buttons.firstMatch.tap(); app.buttons["settings.connect"].tap(); capture("Connect",app)
diff --git a/mobile/ios/scripts/generate-brand-assets.swift b/mobile/ios/scripts/generate-brand-assets.swift
new file mode 100644
index 000000000..9d6d365b7
--- /dev/null
+++ b/mobile/ios/scripts/generate-brand-assets.swift
@@ -0,0 +1,60 @@
+// Build-time rendering of the repository logo. No binary artwork is maintained in iOS.
+import CoreGraphics
+import Foundation
+import ImageIO
+
+let arguments = CommandLine.arguments
+guard arguments.count == 4 else { fatalError("Expected logo, tokens and asset-catalog paths") }
+let output = URL(fileURLWithPath: arguments[3], isDirectory: true)
+let logoURL = URL(fileURLWithPath: arguments[1])
+guard let source = CGImageSourceCreateWithURL(logoURL as CFURL, nil),
+ let logo = CGImageSourceCreateImageAtIndex(source, 0, nil) else { fatalError("Cannot read repository logo") }
+let tokens = try JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: arguments[2]))) as! [String: Any]
+let palettes = tokens["palettes"] as! [[String: Any]]
+let colors = palettes.first { $0["id"] as? String == "default" }!["colors"] as! [String: [String: String]]
+
+func components(_ hex: String) -> [Double] {
+ let digits = Array(hex.dropFirst())
+ return stride(from: 0, to: 8, by: 2).map { Double(UInt8(String(digits[$0..<($0 + 2)]), radix: 16)!) / 255 }
+}
+func json(_ value: [String: Any], at directory: URL) throws {
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ try JSONSerialization.data(withJSONObject: value, options: [.prettyPrinted, .sortedKeys]).write(to: directory.appendingPathComponent("Contents.json"))
+}
+func png(_ size: Int, at url: URL, background: String? = nil) throws {
+ let space = CGColorSpace(name: CGColorSpace.sRGB)!
+ let alpha = background == nil ? CGImageAlphaInfo.premultipliedLast : CGImageAlphaInfo.noneSkipLast
+ let context = CGContext(data: nil, width: size, height: size, bitsPerComponent: 8, bytesPerRow: size * 4, space: space, bitmapInfo: alpha.rawValue)!
+ let bounds = CGRect(x: 0, y: 0, width: size, height: size)
+ if let background {
+ let c = components(background)
+ context.setFillColor(CGColor(colorSpace: space, components: [c[0], c[1], c[2], 1])!)
+ context.fill(bounds)
+ }
+ context.interpolationQuality = .high
+ context.draw(logo, in: bounds)
+ let image = context.makeImage()!
+ // Catch empty/flat renders before they can become a launcher icon.
+ let pixels = context.data!.assumingMemoryBound(to: UInt8.self)
+ guard stride(from: 0, to: size * size * 4, by: 4).contains(where: { offset in
+ pixels[offset] != pixels[0] || pixels[offset + 1] != pixels[1] || pixels[offset + 2] != pixels[2]
+ }) else { fatalError("Logo render is blank") }
+ let destination = CGImageDestinationCreateWithURL(url as CFURL, "public.png" as CFString, 1, nil)!
+ CGImageDestinationAddImage(destination, image, nil)
+ guard CGImageDestinationFinalize(destination) else { throw CocoaError(.fileWriteUnknown) }
+}
+let info: [String: Any] = ["author": "xcode", "version": 1]
+try json(["info": info], at: output)
+let icons = output.appendingPathComponent("AppIcon.appiconset")
+try json(["info": info, "images": [["filename": "AppIcon.png", "idiom": "universal", "platform": "ios", "size": "1024x1024"]]], at: icons)
+try png(1024, at: icons.appendingPathComponent("AppIcon.png"), background: colors["dark"]!["canvas"]!)
+let launch = output.appendingPathComponent("LaunchLogo.imageset")
+try json(["info": info, "images": (1...3).map { ["filename": "logo-\($0)x.png", "idiom": "universal", "scale": "\($0)x"] }], at: launch)
+for scale in 1...3 { try png(128 * scale, at: launch.appendingPathComponent("logo-\(scale)x.png")) }
+let canvas: [[String: Any]] = ["light", "dark"].map { appearance in
+ let c = components(colors[appearance]!["canvas"]!)
+ var value: [String: Any] = ["idiom": "universal", "color": ["color-space": "srgb", "components": ["red": String(c[0]), "green": String(c[1]), "blue": String(c[2]), "alpha": String(c[3])]]]
+ if appearance == "dark" { value["appearances"] = [["appearance": "luminosity", "value": "dark"]] }
+ return value
+}
+try json(["info": info, "colors": canvas], at: output.appendingPathComponent("LaunchCanvas.colorset"))
diff --git a/mobile/ios/scripts/prepare_resources.py b/mobile/ios/scripts/prepare_resources.py
index 19c4a02c9..ad4bf382f 100644
--- a/mobile/ios/scripts/prepare_resources.py
+++ b/mobile/ios/scripts/prepare_resources.py
@@ -6,11 +6,23 @@ import pathlib
import plistlib
import re
import shutil
+import subprocess
ROOT = pathlib.Path(__file__).resolve().parents[3]
IOS = ROOT / "mobile/ios"
+def prepare_brand_assets(output):
+ """Use macOS CoreGraphics, available with CLT, without an image dependency."""
+ source = IOS / "scripts/generate-brand-assets.swift"
+ cache = IOS / ".cache/brand-assets"
+ cache.mkdir(parents=True, exist_ok=True)
+ renderer = cache / "generate-brand-assets"
+ if not renderer.exists() or renderer.stat().st_mtime < source.stat().st_mtime:
+ subprocess.run(["xcrun", "swiftc", "-module-cache-path", str(cache / "modules"), str(source), "-o", str(renderer)], check=True)
+ subprocess.run([str(renderer), str(ROOT / "docs/logo.png"), str(ROOT / "mobile/contract/tokens.json"), str(output)], check=True)
+
+
def merge(base, addition):
for key, value in addition.items():
if isinstance(value, dict) and isinstance(base.get(key), dict):
@@ -78,5 +90,7 @@ if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--output", required=True, type=pathlib.Path)
parser.add_argument("--info-output", required=True, type=pathlib.Path)
+ parser.add_argument("--assets-output", type=pathlib.Path, default=IOS / ".generated/Brand.xcassets")
args = parser.parse_args()
prepare(args.output, args.info_output)
+ prepare_brand_assets(args.assets_output)
diff --git a/mobile/ios/scripts/test_resources.py b/mobile/ios/scripts/test_resources.py
new file mode 100644
index 000000000..e060b5918
--- /dev/null
+++ b/mobile/ios/scripts/test_resources.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python3
+"""Resource regressions runnable with CLT; no iOS SDK or image dependency."""
+import json
+import pathlib
+import plistlib
+import struct
+import tempfile
+import unittest
+
+import prepare_resources as resources
+
+
+class BrandResources(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ parent = resources.IOS / ".generated"
+ parent.mkdir(exist_ok=True)
+ cls.directory = tempfile.TemporaryDirectory(dir=parent)
+ cls.root = pathlib.Path(cls.directory.name)
+ cls.assets = cls.root / "Brand.xcassets"
+ resources.prepare(cls.root / "bundle", cls.root / "Info.plist")
+ resources.prepare_brand_assets(cls.assets)
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.directory.cleanup()
+
+ def test_icon_is_opaque_1024_and_registered(self):
+ icon = self.assets / "AppIcon.appiconset"
+ entry = json.loads((icon / "Contents.json").read_text())["images"][0]
+ data = (icon / entry["filename"]).read_bytes()
+ self.assertEqual(data[:8], b"\x89PNG\r\n\x1a\n")
+ self.assertEqual(struct.unpack(">II", data[16:24]), (1024, 1024))
+ self.assertEqual(data[25], 2) # RGB, no alpha channel (App Store requirement).
+ self.assertEqual(entry["platform"], "ios")
+ self.assertEqual(entry["size"], "1024x1024")
+
+ def test_launch_uses_repo_logo_and_generated_canvas(self):
+ info = plistlib.loads((self.root / "Info.plist").read_bytes())["UILaunchScreen"]
+ self.assertEqual(info["UIImageName"], "LaunchLogo")
+ self.assertEqual(info["UIColorName"], "LaunchCanvas")
+ images = json.loads((self.assets / "LaunchLogo.imageset/Contents.json").read_text())["images"]
+ self.assertEqual(len(images), 3)
+ for scale, image in enumerate(images, start=1):
+ png = (self.assets / "LaunchLogo.imageset" / image["filename"]).read_bytes()
+ self.assertEqual(struct.unpack(">II", png[16:24]), (128 * scale, 128 * scale))
+ colors = json.loads((self.assets / "LaunchCanvas.colorset/Contents.json").read_text())["colors"]
+ tokens = json.loads((resources.ROOT / "mobile/contract/tokens.json").read_text())
+ palette = next(p for p in tokens["palettes"] if p["id"] == "default")["colors"]
+ for value, appearance in zip(colors, ["light", "dark"]):
+ actual = value["color"]["components"]
+ expected = palette[appearance]["canvas"].lstrip("#")
+ for index, channel in enumerate(["red", "green", "blue", "alpha"]):
+ self.assertAlmostEqual(float(actual[channel]), int(expected[2 * index:2 * index + 2], 16) / 255)
+
+ def test_catalogue_bundles_names_and_phone_consent_note(self):
+ catalogue = json.loads((self.root / "bundle/Catalogs/models.json").read_text())
+ self.assertTrue(all(model["name"].strip() for model in catalogue["models"]))
+ additions = json.loads((self.root / "bundle/Catalogs/strings.ios-additions.en.json").read_text())
+ self.assertEqual(additions["mobile"]["consent"]["phone_note"], "Saved on this phone. Nothing is sent.")
+
+
+if __name__ == "__main__":
+ unittest.main()