diff --git a/.gitignore b/.gitignore index f4fa06fdc7..d42ca9d1ac 100644 --- a/.gitignore +++ b/.gitignore @@ -47,3 +47,6 @@ sentry.properties /desktopApp/generated.conveyor.conf # Conveyor output directory /output/ + +# Local workspace files +MEMORY.md diff --git a/.gitmodules b/.gitmodules index f2e7e9ad69..7565d7e40d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ [submodule "core"] path = core - url = https://github.com/maxrave-dev/core \ No newline at end of file + url = https://github.com/blimjoe/core.git diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index a912548aaf..322baeb0d8 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -57,17 +57,19 @@ kotlin { } } -// listOf( -// iosArm64(), -// iosSimulatorArm64() -// ).forEach { iosTarget -> -// iosTarget.binaries.framework { -// baseName = "ComposeApp" -// isStatic = true -// } -// } + // The iOS port is in progress. Opt in to compile/link diagnostics without + // making the unfinished Native source sets part of normal Android/Desktop builds. + if (providers.gradleProperty("enableIos").map(String::toBoolean).getOrElse(false)) { + listOf(iosArm64(), iosSimulatorArm64()).forEach { iosTarget -> + iosTarget.binaries.framework { + baseName = "ComposeApp" + isStatic = true + } + } + } jvm() + applyDefaultHierarchyTemplate() sourceSets { dependencies { @@ -75,9 +77,10 @@ kotlin { val koinBom = project.dependencies.platform(libs.koin.bom) implementation(composeBom) implementation(koinBom) - implementation(libs.commons.io) } androidMain.dependencies { + implementation(libs.commons.io) + api(libs.coil.network.okhttp) api(project.dependencies.platform(libs.koin.bom)) api(libs.koin.android) implementation(libs.koin.androidx.compose) @@ -123,7 +126,6 @@ kotlin { implementation(libs.compose.material3.adaptive) implementation(libs.compose.material.ripple) - implementation(libs.ui.tooling.preview) // Other module api(projects.common) @@ -149,7 +151,7 @@ kotlin { // Coil api(libs.coil.compose) - api(libs.coil.network.okhttp) + api(libs.coil.network.core) api(libs.kmpalette.core) api(libs.kmpalette.network) implementation(libs.materialkolor) @@ -186,10 +188,16 @@ kotlin { implementation(libs.liquid.glass) implementation(libs.liquid.glass.shape) } + findByName("iosMain")?.dependencies { + implementation("io.coil-kt.coil3:coil-network-ktor3:${libs.versions.coil3.get()}") + implementation(libs.ktor.client.darwin) + } commonTest.dependencies { implementation(libs.kotlin.test) } jvmMain.dependencies { + implementation(libs.commons.io) + api(libs.coil.network.okhttp) // Desktop app entry (main.kt), jpackage/Conveyor // packaging, and tray icon live in :desktopApp per the // JetBrains 2026 KMP default structure. This module keeps the @@ -969,4 +977,4 @@ afterEvaluate { .configureEach { dependsOn("generateBuildKonfig") } -} \ No newline at end of file +} diff --git a/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/Platform.android.kt b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/Platform.android.kt index d8f5d76140..1eeafeb10e 100644 --- a/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/Platform.android.kt +++ b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/Platform.android.kt @@ -1,3 +1,5 @@ package com.maxrave.simpmusic -actual fun getPlatform(): Platform = Platform.Android \ No newline at end of file +actual fun getPlatform(): Platform = Platform.Android + +internal actual fun desktopOsName(): String = System.getProperty("os.name") ?: "jvm" diff --git a/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/extension/JvmFileExt.kt b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/extension/JvmFileExt.kt new file mode 100644 index 0000000000..05f1825613 --- /dev/null +++ b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/extension/JvmFileExt.kt @@ -0,0 +1,24 @@ +package com.maxrave.simpmusic.extension + +import java.io.File +import java.io.InputStream +import java.io.OutputStream +import java.util.zip.ZipInputStream +import java.util.zip.ZipOutputStream + +fun InputStream.zipInputStream(): ZipInputStream = ZipInputStream(this) + +fun OutputStream.zipOutputStream(): ZipOutputStream = ZipOutputStream(this) + +fun getSizeOfFile(dir: File): Long { + var dirSize: Long = 0 + if (!dir.listFiles().isNullOrEmpty()) { + for (f in dir.listFiles()!!) { + dirSize += f.length() + if (f.isDirectory) { + dirSize += getSizeOfFile(f) + } + } + } + return dirSize +} diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt index 1dba3cac8b..cdb021afc5 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt @@ -559,10 +559,10 @@ fun App( ) { // On Android both materials go through the folding bar, which draws the mini // player itself. Desktop keeps the always-open flat bar under its own one. - val useFoldingBar = getPlatform() == Platform.Android || isLiquidGlassEnabled == TRUE + val useFoldingBar = getPlatform() == Platform.Android || (getPlatform() == Platform.Desktop && isLiquidGlassEnabled == TRUE) Column { AnimatedVisibility( - isShowMiniPlayer && !useFoldingBar && isLiquidGlassEnabled == DataStoreManager.FALSE, + isShowMiniPlayer && !useFoldingBar, enter = fadeIn() + slideInHorizontally(), exit = fadeOut(), ) { @@ -634,7 +634,7 @@ fun App( exit = fadeOut(), ) { MiniPlayer( - if (getPlatform() == Platform.Android) { + if (getPlatform() != Platform.Desktop) { Modifier // Glass keeps its 52dp card; the flat one is 56dp. .height(if (isLiquidGlassEnabled == TRUE) 56.dp else 60.dp) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/Platform.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/Platform.kt index 36b353f4ce..9f61641748 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/Platform.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/Platform.kt @@ -8,8 +8,10 @@ sealed class Platform { fun osName(): String = when (this) { Android -> "android" iOS -> "iOS" - Desktop -> System.getProperty("os.name") ?: "jvm" + Desktop -> desktopOsName() } } -expect fun getPlatform(): Platform \ No newline at end of file +expect fun getPlatform(): Platform + +internal expect fun desktopOsName(): String diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/extension/AllExt.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/extension/AllExt.kt index fa82c652b1..628a7e8dc6 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/extension/AllExt.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/extension/AllExt.kt @@ -38,13 +38,6 @@ import simpmusic.composeapp.generated.resources.recently import simpmusic.composeapp.generated.resources.self_promotion import simpmusic.composeapp.generated.resources.sponsor import simpmusic.composeapp.generated.resources.title -import java.io.File -import java.io.InputStream -import java.io.OutputStream -import java.util.Locale -import java.util.concurrent.TimeUnit -import java.util.zip.ZipInputStream -import java.util.zip.ZipOutputStream import kotlin.time.ExperimentalTime fun String?.removeDuplicateWords(): String { @@ -120,12 +113,7 @@ fun TimeLine.lengthLabel(): String = if (isLive) stringResource(Res.string.live_ @Composable fun formatDuration(duration: Long): String { if (duration < 0L) return stringResource(Res.string.na_na) - val minutes: Long = TimeUnit.MINUTES.convert(duration, TimeUnit.MILLISECONDS) - val seconds: Long = ( - TimeUnit.SECONDS.convert(duration, TimeUnit.MILLISECONDS) - - minutes * TimeUnit.SECONDS.convert(1, TimeUnit.MINUTES) - ) - return String.format(Locale.ENGLISH, "%02d:%02d", minutes, seconds) + return formatPlaybackDuration(duration) } fun parseTimestampToMilliseconds(timestamp: String): Double { @@ -165,28 +153,11 @@ fun parseTimestampToMilliseconds(timestamp: String): Double { return totalSeconds * 1000 } -fun InputStream.zipInputStream(): ZipInputStream = ZipInputStream(this) - -fun OutputStream.zipOutputStream(): ZipOutputStream = ZipOutputStream(this) - fun Long?.bytesToMB(): Long { val mbInBytes = 1024 * 1024 return this?.div(mbInBytes) ?: 0L } -fun getSizeOfFile(dir: File): Long { - var dirSize: Long = 0 - if (!dir.listFiles().isNullOrEmpty()) { - for (f in dir.listFiles()!!) { - dirSize += f.length() - if (f.isDirectory) { - dirSize += getSizeOfFile(f) - } - } - } - return dirSize -} - fun ArtistBrowse.toArtistScreenData(): ArtistScreenData = ArtistScreenData( title = this.name, @@ -289,4 +260,4 @@ fun SponsorBlockType.displayRes(): StringResource = SponsorBlockType.PREVIEW -> Res.string.preview SponsorBlockType.SELF_PROMOTION -> Res.string.self_promotion SponsorBlockType.SPONSOR -> Res.string.sponsor - } \ No newline at end of file + } diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/extension/LocalTimestamp.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/extension/LocalTimestamp.kt new file mode 100644 index 0000000000..5b58db2993 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/extension/LocalTimestamp.kt @@ -0,0 +1,12 @@ +package com.maxrave.simpmusic.extension + +import kotlinx.datetime.TimeZone +import kotlinx.datetime.toLocalDateTime +import kotlin.time.Instant + +internal fun formatLocalTimestamp(epochMillis: Long, zone: TimeZone = TimeZone.currentSystemDefault()): String { + val local = Instant.fromEpochMilliseconds(epochMillis).toLocalDateTime(zone) + fun Int.padded(width: Int = 2) = toString().padStart(width, '0') + return "${local.year.padded(4)}-${local.month.ordinal.plus(1).padded()}-${local.day.padded()} " + + "${local.hour.padded()}:${local.minute.padded()}:${local.second.padded()}" +} diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/extension/NumberFormat.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/extension/NumberFormat.kt new file mode 100644 index 0000000000..fcdd2d7ee0 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/extension/NumberFormat.kt @@ -0,0 +1,10 @@ +package com.maxrave.simpmusic.extension + +import kotlin.math.roundToInt + +internal fun formatPlaybackSpeed(speed: Float): String { + val tenths = (speed * 10).roundToInt() + return "${tenths / 10}.${tenths % 10}" +} + +internal fun formatGroupedNumber(value: Int?): String = value?.toString()?.reversed()?.chunked(3)?.joinToString(",")?.reversed() ?: "null" diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/extension/PlaybackDuration.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/extension/PlaybackDuration.kt new file mode 100644 index 0000000000..5f0fd1caa6 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/extension/PlaybackDuration.kt @@ -0,0 +1,10 @@ +package com.maxrave.simpmusic.extension + +/** Locale-independent mm:ss, keeping total minutes for tracks longer than an hour. */ +internal fun formatPlaybackDuration(milliseconds: Long): String { + require(milliseconds >= 0) { "Playback duration must be non-negative" } + val totalSeconds = milliseconds / 1_000 + val minutes = (totalSeconds / 60).toString().padStart(2, '0') + val seconds = (totalSeconds % 60).toString().padStart(2, '0') + return "$minutes:$seconds" +} diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/CollapsingToolbar.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/CollapsingToolbar.kt index 37a19d5430..51f0414348 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/CollapsingToolbar.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/CollapsingToolbar.kt @@ -47,7 +47,6 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap -import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.onGloballyPositioned diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ExpandableText.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ExpandableText.kt index aeca3add45..adac070af9 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ExpandableText.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ExpandableText.kt @@ -73,7 +73,7 @@ fun ExpandableText( text .substring(startIndex = 0, endIndex = lastCharIndex) .dropLast(showMoreText.length) - .dropLastWhile { Character.isWhitespace(it) || it == '.' } + .dropLastWhile { it.isWhitespace() || it == '.' } append(adjustText) withStyle(style = showMoreStyle) { append(showMoreText) } } diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LyricText.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LyricText.kt index a0f383d26b..01ec648497 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LyricText.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LyricText.kt @@ -11,13 +11,20 @@ import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextDirection import androidx.compose.ui.unit.LayoutDirection -import java.text.Bidi +import androidx.compose.ui.text.rememberTextMeasurer +import androidx.compose.ui.text.style.ResolvedTextDirection @Composable -internal fun rememberLyricLayoutDirection(text: String): LayoutDirection = - remember(text) { - if (Bidi(text, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT).baseIsLeftToRight()) LayoutDirection.Ltr else LayoutDirection.Rtl +internal fun rememberLyricLayoutDirection(text: String): LayoutDirection { + val measurer = rememberTextMeasurer() + return remember(text, measurer) { + if (text.isEmpty()) LayoutDirection.Ltr + else { + val layout = measurer.measure(text, style = TextStyle(textDirection = TextDirection.ContentOrLtr)) + if (layout.getParagraphDirection(0) == ResolvedTextDirection.Rtl) LayoutDirection.Rtl else LayoutDirection.Ltr + } } +} /** * A lyric and its subtitles share an edge, while each text keeps its own reading direction. diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LyricsView.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LyricsView.kt index 54eca64968..0c0d43d086 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LyricsView.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LyricsView.kt @@ -90,7 +90,8 @@ import com.maxrave.simpmusic.viewModel.SharedViewModel import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import org.jetbrains.compose.resources.painterResource -import java.text.Bidi +import androidx.compose.ui.text.rememberTextMeasurer +import androidx.compose.ui.text.style.ResolvedTextDirection import kotlin.math.abs import kotlin.math.exp import kotlin.math.sqrt @@ -1078,13 +1079,20 @@ private fun AnimatedWord( // Null keeps Classic's DimRichPendingColor untouched. pendingColorOverride: Color? = null, ) { - val wordBidi = - remember(word, lineDirection) { - val fallback = - if (lineDirection == LayoutDirection.Rtl) Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT else Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT - Bidi(word, fallback) - } - val wordDirection = if (wordBidi.baseIsLeftToRight()) TextDirection.Ltr else TextDirection.Rtl + val bidiMeasurer = rememberTextMeasurer() + val wordBidi = remember(word, lineDirection, bidiMeasurer) { + bidiMeasurer.measure( + word, + style = androidx.compose.ui.text.TextStyle( + textDirection = if (lineDirection == LayoutDirection.Rtl) TextDirection.ContentOrRtl else TextDirection.ContentOrLtr, + ), + ) + } + val wordDirection = if (word.isEmpty()) { + if (lineDirection == LayoutDirection.Rtl) TextDirection.Rtl else TextDirection.Ltr + } else if (wordBidi.getParagraphDirection(0) == ResolvedTextDirection.Rtl) TextDirection.Rtl else TextDirection.Ltr + val isEntirelyLeftToRight = wordDirection == TextDirection.Ltr && + word.indices.all { wordBidi.getBidiRunDirection(it) == ResolvedTextDirection.Ltr } val style = typo().headlineLarge.copy( fontSize = customFontSize ?: typo().headlineLarge.fontSize, @@ -1215,7 +1223,7 @@ private fun AnimatedWord( translationY = -eased * EMP_RISE_EM * amount * fontPx }, ) { - if (!wordBidi.isLeftToRight) { + if (!isEntirelyLeftToRight) { // Keep Arabic shaping and combining marks intact, including RTL words in an LTR line. ShapedLyricsWord( word = word, diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ModalBottomSheet.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ModalBottomSheet.kt index 15449a0d8d..9bf499dd16 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ModalBottomSheet.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ModalBottomSheet.kt @@ -2194,7 +2194,7 @@ fun PlaybackSpeedPitchBottomSheet( ) } Text( - text = "x${String.format("%.1f", playbackSpeed)}", + text = "x${com.maxrave.simpmusic.extension.formatPlaybackSpeed(playbackSpeed)}", style = typo().titleMedium, color = rememberSurfaceDarkColors().subtitle, modifier = Modifier.widthIn(min = 60.dp), diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/MiniPlayer.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/MiniPlayer.kt index 50acc48db2..52da5dc778 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/MiniPlayer.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/MiniPlayer.kt @@ -267,7 +267,7 @@ fun MiniPlayer( job4.join() } - if (getPlatform() == Platform.Android) { + if (getPlatform() != Platform.Desktop) { // One shape for both the Card and the clip below. They must not diverge: the clip wraps // the Card's own background draw, so the larger radius wins and silently becomes the // visible one. diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt index 2c17b7c0cd..3e468fe2ef 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt @@ -466,9 +466,7 @@ import simpmusic.composeapp.generated.resources.youtube_account import simpmusic.composeapp.generated.resources.youtube_subtitle_language import simpmusic.composeapp.generated.resources.youtube_subtitle_language_message import simpmusic.composeapp.generated.resources.youtube_transcript -import java.time.Instant -import java.time.ZoneId -import java.time.format.DateTimeFormatter +import com.maxrave.simpmusic.extension.formatLocalTimestamp @OptIn( ExperimentalMaterial3Api::class, @@ -637,10 +635,7 @@ fun SettingScreen( return@derivedStateOf runBlocking { getString( Res.string.last_checked_at, - DateTimeFormatter - .ofPattern("yyyy-MM-dd HH:mm:ss") - .withZone(ZoneId.systemDefault()) - .format(Instant.ofEpochMilli(lastCheckLong)), + formatLocalTimestamp(lastCheckLong), ) } } @@ -727,7 +722,7 @@ fun SettingScreen( ) // Above every section, and inside item 0 rather than an item of its own, for the // glow reason above. - SettingGroup( + if (getPlatform() != Platform.iOS) SettingGroup( title = stringResource(Res.string.login_sync_section), modifier = Modifier.onSizeChanged { devicesGroupHeightPx = it.height }, ) { @@ -994,7 +989,7 @@ fun SettingScreen( onClick = { showColorPickerDialog = true }, ) } - SettingItem( + if (getPlatform() != Platform.iOS) SettingItem( title = stringResource(Res.string.enable_liquid_glass_effect), subtitle = stringResource(Res.string.enable_liquid_glass_effect_description), smallSubtitle = true, @@ -1527,66 +1522,68 @@ fun SettingScreen( } item(key = "playback") { SettingGroup(title = stringResource(Res.string.playback)) { - // Under Playback rather than Audio because that whole group sits inside an - // Android-only branch — "Open system equalizer" is an Android feature — and this - // one is on both platforms: mpv's `af` chain on Desktop, an AudioProcessor in the - // Media3 sink on Android, driven from the same stored curve. - AnimatedVisibility(visible = getPlatform() != Platform.Android || equalizerType != DataStoreManager.EQUALIZER_TYPE_SYSTEM) { - Column { - SettingItem( - title = stringResource(Res.string.equalizer), - subtitle = stringResource(Res.string.equalizer_description), - smallSubtitle = true, - switch = (equalizerEnabled to { viewModel.setEqualizerEnabled(it) }), - ) - // Only while on. A curve that visibly does nothing is worse than no curve — - // and the stored bands survive the switch, so turning it back on returns to - // the shape the user built rather than to flat. - AnimatedVisibility(visible = equalizerEnabled) { - EqualizerSection() + if (getPlatform() != Platform.iOS) { + // Under Playback rather than Audio because that whole group sits inside an + // Android-only branch — "Open system equalizer" is an Android feature — and this + // one is on both platforms: mpv's `af` chain on Desktop, an AudioProcessor in the + // Media3 sink on Android, driven from the same stored curve. + AnimatedVisibility(visible = getPlatform() != Platform.Android || equalizerType != DataStoreManager.EQUALIZER_TYPE_SYSTEM) { + Column { + SettingItem( + title = stringResource(Res.string.equalizer), + subtitle = stringResource(Res.string.equalizer_description), + smallSubtitle = true, + switch = (equalizerEnabled to { viewModel.setEqualizerEnabled(it) }), + ) + // Only while on. A curve that visibly does nothing is worse than no curve — + // and the stored bands survive the switch, so turning it back on returns to + // the shape the user built rather than to flat. + AnimatedVisibility(visible = equalizerEnabled) { + EqualizerSection() + } } } - } - // Beside the equalizer rather than in its own group: all three are the same kind of - // thing — one stored setting reshaping the audio on both backends — and a user - // hunting for "reverb" looks wherever the sound settings are, not under a heading - // they have to guess. - SettingItem( - title = stringResource(Res.string.audio_delay), - subtitle = stringResource(Res.string.audio_delay_description), - smallSubtitle = true, - switch = (delayEnabled to { viewModel.setDelayEnabled(it) }), - ) - // Only while on, like the curve — and the three values survive the switch, so - // turning it back on returns to the echo the user dialled in. - AnimatedVisibility(visible = delayEnabled) { - DelaySection() - } - SettingItem( - title = stringResource(Res.string.audio_reverb), - subtitle = stringResource(Res.string.audio_reverb_description), - smallSubtitle = true, - switch = (reverbEnabled to { viewModel.setReverbEnabled(it) }), - ) - // Same again: the room and the wet level outlive the switch. - AnimatedVisibility(visible = reverbEnabled) { - ReverbSection() - } - SettingItem( - title = stringResource(Res.string.audio_eight_d), - subtitle = - when { - castState.isRemote -> stringResource(Res.string.not_available_while_casting) - !eightDAvailable -> stringResource(Res.string.eight_d_unavailable) - else -> stringResource(Res.string.audio_eight_d_description) - }, - smallSubtitle = true, - switch = (eightDEnabled to viewModel::setEightDEnabled), - // A saved on-state may still be switched off when the native filter is absent. - isEnable = !castState.isRemote && (eightDAvailable || eightDEnabled), - ) - AnimatedVisibility(visible = eightDEnabled && eightDAvailable && !castState.isRemote) { - EightDSection() + // Beside the equalizer rather than in its own group: all three are the same kind of + // thing — one stored setting reshaping the audio on both backends — and a user + // hunting for "reverb" looks wherever the sound settings are, not under a heading + // they have to guess. + SettingItem( + title = stringResource(Res.string.audio_delay), + subtitle = stringResource(Res.string.audio_delay_description), + smallSubtitle = true, + switch = (delayEnabled to { viewModel.setDelayEnabled(it) }), + ) + // Only while on, like the curve — and the three values survive the switch, so + // turning it back on returns to the echo the user dialled in. + AnimatedVisibility(visible = delayEnabled) { + DelaySection() + } + SettingItem( + title = stringResource(Res.string.audio_reverb), + subtitle = stringResource(Res.string.audio_reverb_description), + smallSubtitle = true, + switch = (reverbEnabled to { viewModel.setReverbEnabled(it) }), + ) + // Same again: the room and the wet level outlive the switch. + AnimatedVisibility(visible = reverbEnabled) { + ReverbSection() + } + SettingItem( + title = stringResource(Res.string.audio_eight_d), + subtitle = + when { + castState.isRemote -> stringResource(Res.string.not_available_while_casting) + !eightDAvailable -> stringResource(Res.string.eight_d_unavailable) + else -> stringResource(Res.string.audio_eight_d_description) + }, + smallSubtitle = true, + switch = (eightDEnabled to viewModel::setEightDEnabled), + // A saved on-state may still be switched off when the native filter is absent. + isEnable = !castState.isRemote && (eightDAvailable || eightDEnabled), + ) + AnimatedVisibility(visible = eightDEnabled && eightDAvailable && !castState.isRemote) { + EightDSection() + } } SettingItem( title = stringResource(Res.string.save_playback_state), @@ -1600,109 +1597,111 @@ fun SettingScreen( switch = (killServiceOnExit to { viewModel.setKillServiceOnExit(it) }), ) } - // Crossfade (all platforms) - SettingItem( - title = stringResource(Res.string.crossfade), - subtitle = - if (castState.isRemote) { - stringResource(Res.string.not_available_while_casting) - } else { - stringResource(Res.string.crossfade_description) - }, - smallSubtitle = true, - switch = (crossfadeEnabled to { viewModel.setCrossfadeEnabled(it) }), - isEnable = !castState.isRemote, - ) - AnimatedVisibility(visible = crossfadeEnabled) { - Column { - SettingItem( - title = stringResource(Res.string.crossfade_duration), - subtitle = - if (castState.isRemote) { - stringResource(Res.string.not_available_while_casting) - } else if (crossfadeDuration == DataStoreManager.CROSSFADE_DURATION_AUTO) { - stringResource(Res.string.crossfade_auto) - } else { - "${crossfadeDuration / 1000}s" - }, - isEnable = !castState.isRemote, - onClick = { - viewModel.setAlertData( - SettingAlertState( - title = runBlocking { getString(Res.string.crossfade_duration) }, - selectOne = - SettingAlertState.SelectData( - listSelect = - listOf( - (crossfadeDuration == DataStoreManager.CROSSFADE_DURATION_AUTO) to - runBlocking { getString(Res.string.crossfade_auto) }, - (crossfadeDuration == 1000) to "1s", - (crossfadeDuration == 2000) to "2s", - (crossfadeDuration == 3000) to "3s", - (crossfadeDuration == 5000) to "5s", - (crossfadeDuration == 8000) to "8s", - (crossfadeDuration == 10000) to "10s", - (crossfadeDuration == 12000) to "12s", - (crossfadeDuration == 15000) to "15s", - (crossfadeDuration == 20000) to "20s", - (crossfadeDuration == 30000) to "30s", - ), - ), - confirm = - runBlocking { getString(Res.string.change) } to { state -> - val duration = - when (state.selectOne?.getSelected()) { - runBlocking { - getString( - Res.string.crossfade_auto, - ) - }, - -> DataStoreManager.CROSSFADE_DURATION_AUTO - "1s" -> 1000 - "2s" -> 2000 - "3s" -> 3000 - "5s" -> 5000 - "8s" -> 8000 - "10s" -> 10000 - "12s" -> 12000 - "15s" -> 15000 - "20s" -> 20000 - "30s" -> 30000 - else -> 5000 - } - viewModel.setCrossfadeDuration(duration) - }, - dismiss = runBlocking { getString(Res.string.cancel) }, - ), - ) + if (getPlatform() != Platform.iOS) { + // Crossfade on backends with two-player mixing. + SettingItem( + title = stringResource(Res.string.crossfade), + subtitle = + if (castState.isRemote) { + stringResource(Res.string.not_available_while_casting) + } else { + stringResource(Res.string.crossfade_description) }, - ) -// if (getPlatform() == Platform.Android) { - SettingItem( - title = stringResource(Res.string.crossfade_dj_mode), - subtitle = - if (castState.isRemote) { - stringResource(Res.string.not_available_while_casting) - } else { - stringResource(Res.string.crossfade_dj_mode_description) - }, - smallSubtitle = true, - switch = ((crossfadeDjMode) to { viewModel.setCrossfadeDjMode(it) }), - isEnable = !castState.isRemote, - ) - SettingItem( - title = stringResource(Res.string.crossfade_skip_album), - subtitle = - if (castState.isRemote) { - stringResource(Res.string.not_available_while_casting) - } else { - stringResource(Res.string.crossfade_skip_album_description) + smallSubtitle = true, + switch = (crossfadeEnabled to { viewModel.setCrossfadeEnabled(it) }), + isEnable = !castState.isRemote, + ) + AnimatedVisibility(visible = crossfadeEnabled) { + Column { + SettingItem( + title = stringResource(Res.string.crossfade_duration), + subtitle = + if (castState.isRemote) { + stringResource(Res.string.not_available_while_casting) + } else if (crossfadeDuration == DataStoreManager.CROSSFADE_DURATION_AUTO) { + stringResource(Res.string.crossfade_auto) + } else { + "${crossfadeDuration / 1000}s" + }, + isEnable = !castState.isRemote, + onClick = { + viewModel.setAlertData( + SettingAlertState( + title = runBlocking { getString(Res.string.crossfade_duration) }, + selectOne = + SettingAlertState.SelectData( + listSelect = + listOf( + (crossfadeDuration == DataStoreManager.CROSSFADE_DURATION_AUTO) to + runBlocking { getString(Res.string.crossfade_auto) }, + (crossfadeDuration == 1000) to "1s", + (crossfadeDuration == 2000) to "2s", + (crossfadeDuration == 3000) to "3s", + (crossfadeDuration == 5000) to "5s", + (crossfadeDuration == 8000) to "8s", + (crossfadeDuration == 10000) to "10s", + (crossfadeDuration == 12000) to "12s", + (crossfadeDuration == 15000) to "15s", + (crossfadeDuration == 20000) to "20s", + (crossfadeDuration == 30000) to "30s", + ), + ), + confirm = + runBlocking { getString(Res.string.change) } to { state -> + val duration = + when (state.selectOne?.getSelected()) { + runBlocking { + getString( + Res.string.crossfade_auto, + ) + }, + -> DataStoreManager.CROSSFADE_DURATION_AUTO + "1s" -> 1000 + "2s" -> 2000 + "3s" -> 3000 + "5s" -> 5000 + "8s" -> 8000 + "10s" -> 10000 + "12s" -> 12000 + "15s" -> 15000 + "20s" -> 20000 + "30s" -> 30000 + else -> 5000 + } + viewModel.setCrossfadeDuration(duration) + }, + dismiss = runBlocking { getString(Res.string.cancel) }, + ), + ) }, - smallSubtitle = true, - switch = ((crossfadeSkipAlbum) to { viewModel.setCrossfadeSkipAlbum(it) }), - isEnable = !castState.isRemote, - ) -// } + ) + // if (getPlatform() == Platform.Android) { + SettingItem( + title = stringResource(Res.string.crossfade_dj_mode), + subtitle = + if (castState.isRemote) { + stringResource(Res.string.not_available_while_casting) + } else { + stringResource(Res.string.crossfade_dj_mode_description) + }, + smallSubtitle = true, + switch = ((crossfadeDjMode) to { viewModel.setCrossfadeDjMode(it) }), + isEnable = !castState.isRemote, + ) + SettingItem( + title = stringResource(Res.string.crossfade_skip_album), + subtitle = + if (castState.isRemote) { + stringResource(Res.string.not_available_while_casting) + } else { + stringResource(Res.string.crossfade_skip_album_description) + }, + smallSubtitle = true, + switch = ((crossfadeSkipAlbum) to { viewModel.setCrossfadeSkipAlbum(it) }), + isEnable = !castState.isRemote, + ) + // } + } } } } @@ -2750,10 +2749,7 @@ fun SettingScreen( if (autoBackupLastTime == 0L) { stringResource(Res.string.never) } else { - DateTimeFormatter - .ofPattern("yyyy-MM-dd HH:mm:ss") - .withZone(ZoneId.systemDefault()) - .format(Instant.ofEpochMilli(autoBackupLastTime)) + formatLocalTimestamp(autoBackupLastTime) }, ) } diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LocalPlaylistScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LocalPlaylistScreen.kt index dc8dd5fee6..3e59d0f32b 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LocalPlaylistScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LocalPlaylistScreen.kt @@ -89,7 +89,6 @@ import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.CompositingStrategy import androidx.compose.ui.graphics.ImageBitmap -import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.lerp diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/AppLogFiles.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/AppLogFiles.kt index 5762a27e94..e66f3192f4 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/AppLogFiles.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/AppLogFiles.kt @@ -1,5 +1,6 @@ package com.maxrave.simpmusic.ui.screen.other +import okio.use import com.maxrave.domain.extension.epochMillisToLocalDateTime import com.maxrave.domain.extension.now import com.maxrave.logger.Logger @@ -7,10 +8,13 @@ import com.maxrave.simpmusic.expect.shareImage import com.maxrave.simpmusic.getPlatform import com.maxrave.simpmusic.utils.VersionManager import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO import kotlinx.coroutines.withContext import kotlinx.datetime.number -import java.io.File -import java.io.RandomAccessFile +import com.maxrave.data.io.fileSystem +import okio.Path +import okio.Path.Companion.toPath +import okio.buffer import kotlin.time.Clock import kotlin.time.Instant @@ -63,9 +67,9 @@ internal class LogTail( /** True when [lines] changed. */ fun poll(): Boolean { - val files = Logger.logFiles(name).map(::File) + val files = Logger.logFiles(name).map { it.toPath() } val live = files.lastOrNull() ?: return false - val size = live.length() + val size = fileSystem().metadataOrNull(live)?.size ?: 0L return when { // First read, or the live file rolled over and started again from empty. liveOffset < 0 || size < liveOffset -> { @@ -85,10 +89,10 @@ internal class LogTail( } } - private fun reload(files: List) { + private fun reload(files: List) { nextId = 0 val text = StringBuilder() - files.dropLast(1).filter(File::exists).forEach { text.append(it.readText()) } + files.dropLast(1).filter { fileSystem().exists(it) }.forEach { text.append(fileSystem().read(it) { readUtf8() }) } val (liveText, end) = readCompleteLines(files.last(), 0) text.append(liveText) liveOffset = end @@ -112,16 +116,15 @@ internal class LogTail( /** Everything from [from] to the last complete line, and the offset just past it. */ private fun readCompleteLines( - file: File, + file: Path, from: Long, ): Pair { - if (!file.exists()) return "" to 0L - RandomAccessFile(file, "r").use { raf -> - val length = raf.length() + val fs = fileSystem() + if (!fs.exists(file)) return "" to 0L + fs.openReadOnly(file).use { handle -> + val length = handle.size() if (length <= from) return "" to from - val bytes = ByteArray((length - from).toInt()) - raf.seek(from) - raf.readFully(bytes) + val bytes = handle.source(from).buffer().use { it.readByteArray(length - from) } val end = bytes.lastIndexOf('\n'.code.toByte()) if (end < 0) return "" to from return bytes.decodeToString(0, end + 1) to from + end + 1 @@ -219,7 +222,7 @@ internal suspend fun exportLog(chooserTitle: String): Boolean { for (name in listOf(Logger.APP_LOG, Logger.ERROR_LOG)) { appendLine() appendLine("===== $name.log =====") - Logger.logFiles(name).map(::File).filter(File::exists).forEach { append(it.readText()) } + Logger.logFiles(name).map { it.toPath() }.filter { fileSystem().exists(it) }.forEach { append(fileSystem().read(it) { readUtf8() }) } } }.let(::redactSecrets).encodeToByteArray() }.getOrNull() diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/AppLogScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/AppLogScreen.kt index 686405bf28..36de7bdb5e 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/AppLogScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/AppLogScreen.kt @@ -84,6 +84,7 @@ import com.maxrave.simpmusic.ui.icon.UnfoldMore import com.maxrave.simpmusic.ui.theme.LocalIsDarkTheme import com.maxrave.simpmusic.ui.theme.typo import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/PlaylistScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/PlaylistScreen.kt index b0f01b5351..4106e66fe9 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/PlaylistScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/PlaylistScreen.kt @@ -66,7 +66,6 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap -import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.lerp import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.onGloballyPositioned diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/PodcastsScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/PodcastsScreen.kt index 314e0fe062..b8b4bc83e0 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/PodcastsScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/PodcastsScreen.kt @@ -50,7 +50,6 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap -import androidx.compose.ui.graphics.asImageBitmap import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.ui.component.rememberHolderPainter diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt index 2bd6572adb..ed5f77afa4 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt @@ -219,7 +219,7 @@ fun SearchScreen( // columns stretch each tile to half the window, and since the tile keeps a 2:1 ratio it grows // absurdly tall with it. val screenInfo = getScreenSizeInfo() - val isMobilePortrait = getPlatform() == Platform.Android && screenInfo.wDP < screenInfo.hDP + val isMobilePortrait = getPlatform() != Platform.Desktop && screenInfo.wDP < screenInfo.hDP val moodGridColumns = if (isMobilePortrait) 2 else 4 val hazeState = rememberHazeState() diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentAppleMusic.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentAppleMusic.kt index 580f61953b..efac185ccc 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentAppleMusic.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentAppleMusic.kt @@ -426,7 +426,7 @@ private fun AppleMusicMainView( // top band held above it, over a stretch as long as the status bar is tall: the bottom edge's // treatment, mirrored. Desktop has no status bar, so there the artwork keeps the panel's top. val statusBarHeight = with(localDensity) { WindowInsets.statusBars.getTop(localDensity).toDp() } - val topInset = if (meshPage && getPlatform() == Platform.Android) statusBarHeight else 0.dp + val topInset = if (meshPage && getPlatform() != Platform.Desktop) statusBarHeight else 0.dp val topFade = topInset val shownHeight = if (showsClip) clipFrameHeight else artworkHeight val meshSeam = topInset + shownHeight diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentM3Expressive.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentM3Expressive.kt index d3b3eb0839..36b1e6253d 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentM3Expressive.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentM3Expressive.kt @@ -527,7 +527,7 @@ private fun NowPlayingM3ExpressiveLayout( }, ) { ExpressiveTrackInfoRow(state = state, actions = actions) - if (getPlatform() == Platform.Android) { + if (getPlatform() != Platform.Desktop) { ExpressivePlaybackControls( state = state, actions = actions, diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt index 9790681f5c..58ce675b04 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt @@ -405,7 +405,7 @@ private fun NowPlayingSoundCloudLayout( .background(colors.surfaceContainer) .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = togglePlayPause), ) { - if (getPlatform() == Platform.Android) { + if (getPlatform() != Platform.Desktop) { LeftToRight { HorizontalPager( state = state.artworkPagerState, diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSpotify.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSpotify.kt index 3207357e61..2fd3472034 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSpotify.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSpotify.kt @@ -1032,7 +1032,7 @@ fun NowPlayingContentSpotify( state = state, actions = actions, ) - if (getPlatform() == Platform.Android) { + if (getPlatform() != Platform.Desktop) { SpotifyPlaybackControls( state = state, actions = actions, @@ -1591,7 +1591,7 @@ fun NowPlayingContentSpotify( text = stringResource( Res.string.view_count, - "%,d".format(state.screenData.songInfoData?.viewCount), + com.maxrave.simpmusic.extension.formatGroupedNumber(state.screenData.songInfoData?.viewCount), ), style = typo().labelMedium, color = Color.White, diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingExpressiveCards.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingExpressiveCards.kt index 18aedacc1c..9dea0b1c04 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingExpressiveCards.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingExpressiveCards.kt @@ -848,7 +848,7 @@ internal fun ExpressiveBelowTheFold( text = stringResource( Res.string.view_count, - "%,d".format(state.screenData.songInfoData?.viewCount), + com.maxrave.simpmusic.extension.formatGroupedNumber(state.screenData.songInfoData?.viewCount), ), style = typo().labelMedium, color = Color.White, diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicOutputSheet.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicOutputSheet.kt index bb71208ecf..42ebf9da97 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicOutputSheet.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicOutputSheet.kt @@ -280,7 +280,7 @@ private fun AudioOutput.kindLabel(): String? = private fun AudioOutput.icon(): ImageVector = when (kind) { // The phone's own speaker on Android; the system default on desktop, which is a computer. - AudioOutputKind.DEVICE_SPEAKER -> if (getPlatform() == Platform.Android) SimpIcons.Smartphone else SimpIcons.Speaker + AudioOutputKind.DEVICE_SPEAKER -> if (getPlatform() != Platform.Desktop) SimpIcons.Smartphone else SimpIcons.Speaker AudioOutputKind.WIRED, AudioOutputKind.BLUETOOTH, AudioOutputKind.USB -> SimpIcons.Headphones AudioOutputKind.HDMI, AudioOutputKind.OTHER -> SimpIcons.Speaker } diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicShared.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicShared.kt index e45d14ff51..b28e2bee97 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicShared.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicShared.kt @@ -1044,7 +1044,7 @@ internal fun AppleMusicBottomCluster( ) { val localDensity = LocalDensity.current Column(modifier = modifier.fillMaxWidth().padding(horizontal = 20.dp).padding(top = topPadding)) { - if (getPlatform() == Platform.Android) { + if (getPlatform() != Platform.Desktop) { AppleMusicPlaybackControls(state = state, actions = actions, typography = typography) Spacer(modifier = Modifier.height(18.dp)) deviceVolumeController?.let { controller -> diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/NetworkFirstInterceptor.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/NetworkFirstInterceptor.kt index 74b2655473..6b0fbcabf1 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/NetworkFirstInterceptor.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/NetworkFirstInterceptor.kt @@ -14,12 +14,15 @@ import coil3.request.SuccessResult import com.maxrave.logger.Logger import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.ensureActive import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext -import java.util.UUID +import kotlin.time.Clock +import kotlin.uuid.ExperimentalUuidApi +import kotlin.uuid.Uuid /** * HTTP(S) images use cache for 24 hours, then try the network with stale-cache fallback. @@ -29,9 +32,10 @@ import java.util.UUID * Stage each response under a temporary key in the SAME disk cache and promote it only after * decoding succeeds. This keeps a 404 or an undecodable 200 from replacing the offline fallback. */ +@OptIn(ExperimentalUuidApi::class) class NetworkFirstInterceptor( private val ttlMillis: Long = 24L * 60 * 60 * 1000, - private val nowMillis: () -> Long = { System.currentTimeMillis() }, + private val nowMillis: () -> Long = { Clock.System.now().toEpochMilliseconds() }, private val imageLoader: () -> ImageLoader, ) : Interceptor { init { @@ -107,7 +111,7 @@ class NetworkFirstInterceptor( // Keep a successfully decoded stale image alive while refreshing. A failed refresh can // return it even if another request evicts its disk entry in the meantime. - val temporaryKey = "coil-network-first:${UUID.randomUUID()}" + val temporaryKey = "coil-network-first:${Uuid.random()}" val networkRequest = request.newBuilder() .memoryCachePolicy(if (request.memoryCachePolicy.writeEnabled) CachePolicy.WRITE_ONLY else CachePolicy.DISABLED) .diskCachePolicy(if (request.diskCachePolicy.writeEnabled) CachePolicy.WRITE_ONLY else CachePolicy.DISABLED) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/BrowserLoginViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/BrowserLoginViewModel.kt index ad2d3b6065..2f1ba9e4e2 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/BrowserLoginViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/BrowserLoginViewModel.kt @@ -47,10 +47,8 @@ class BrowserLoginViewModel( } catch (error: CancellationException) { throw error } catch (error: Exception) { - val site = error.stackTrace.firstOrNull { it.className.startsWith("com.maxrave.data.browserlogin.") } - val location = site?.let { "${it.className}.${it.methodName}:${it.lineNumber}" } ?: "unknown" - // Never pass the throwable/message: native file errors can contain private paths. - log("Browser discovery failed: ${error::class.simpleName} at $location", LogLevel.WARN) + // Exception messages and stack traces can contain private browser paths. + log("Browser discovery failed: ${error::class.simpleName}", LogLevel.WARN) _state.value = _state.value.copy(loading = false, error = BrowserLoginFailure.INVALID_DATA) } } diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/ImportViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/ImportViewModel.kt index bd6c67a252..f3d6e35414 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/ImportViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/ImportViewModel.kt @@ -7,6 +7,7 @@ import com.maxrave.domain.repository.ImportRepository import com.maxrave.logger.LogLevel import com.maxrave.simpmusic.viewModel.base.BaseViewModel import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryDynamicPlaylistViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryDynamicPlaylistViewModel.kt index 5fc77ecf2e..4482ffc5a4 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryDynamicPlaylistViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryDynamicPlaylistViewModel.kt @@ -20,6 +20,7 @@ import com.maxrave.simpmusic.ui.screen.home.analytics.monthFullNameResource import com.maxrave.simpmusic.ui.screen.library.LibraryDynamicPlaylistType import com.maxrave.simpmusic.viewModel.base.BaseViewModel import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryViewModel.kt index b41e19287c..ef1de16da2 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryViewModel.kt @@ -201,9 +201,9 @@ class LibraryViewModel( }.let { temp.remove(it) } - temp.removeIf { it is SongEntity && it.inLibrary == Config.REMOVED_SONG_DATE_TIME } + temp.removeAll { it is SongEntity && it.inLibrary == Config.REMOVED_SONG_DATE_TIME } if (dataStoreManager.loggedIn.first() == DataStoreManager.TRUE) { - temp.removeIf { it is PlaylistEntity && it.id == "LM" } + temp.removeAll { it is PlaylistEntity && it.id == "LM" } temp.add( PlaylistEntity( title = getString(Res.string.youtube_liked_music), diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LocalPlaylistViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LocalPlaylistViewModel.kt index abd3fc16f1..bcae3799e1 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LocalPlaylistViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LocalPlaylistViewModel.kt @@ -41,6 +41,7 @@ import com.maxrave.logger.Logger import com.maxrave.simpmusic.pagination.PagingActions import com.maxrave.simpmusic.viewModel.base.BaseViewModel import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.ExperimentalCoroutinesApi diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/PlaylistViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/PlaylistViewModel.kt index 8875be11a2..f6bb5d5474 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/PlaylistViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/PlaylistViewModel.kt @@ -32,6 +32,7 @@ import com.maxrave.simpmusic.viewModel.PlaylistUIState.Loading import com.maxrave.simpmusic.viewModel.PlaylistUIState.Success import com.maxrave.simpmusic.viewModel.base.BaseViewModel import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/PodcastViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/PodcastViewModel.kt index fdaf9ff767..9d04e67768 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/PodcastViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/PodcastViewModel.kt @@ -1,5 +1,6 @@ package com.maxrave.simpmusic.viewModel +import kotlin.time.Clock import androidx.lifecycle.viewModelScope import com.maxrave.common.Config import com.maxrave.domain.data.entities.EpisodeEntity @@ -256,7 +257,7 @@ class PodcastViewModel( viewModelScope.launch { podcastRepository.updatePodcastInLibraryNow(id).collectLatest { // Podcast đã được cập nhật trong thư viện - log("Podcast $id updated in library at ${System.currentTimeMillis()}") + log("Podcast $id updated in library at ${Clock.System.now().toEpochMilliseconds()}") } } } diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SharedViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SharedViewModel.kt index 4dd5884e5c..bc8ae2ad5f 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SharedViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SharedViewModel.kt @@ -84,6 +84,7 @@ import com.maxrave.simpmusic.utils.shownPromoIds import com.maxrave.simpmusic.utils.withShownPromo import com.maxrave.simpmusic.viewModel.base.BaseViewModel import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.flow.Flow @@ -126,7 +127,8 @@ import simpmusic.composeapp.generated.resources.removed_from_youtube_liked import simpmusic.composeapp.generated.resources.shared import simpmusic.composeapp.generated.resources.updated import simpmusic.composeapp.generated.resources.vote_submitted -import java.io.FileOutputStream +import com.maxrave.data.io.fileSystem +import okio.Path.Companion.toPath import kotlin.math.abs import kotlin.reflect.KClass import kotlin.time.Clock @@ -1253,7 +1255,7 @@ class SharedViewModel( val updateChannel = dataStoreManager.updateChannel.first() dataStoreManager.putString( "CheckForUpdateAt", - System.currentTimeMillis().toString(), + Clock.System.now().toEpochMilliseconds().toString(), ) if (updateChannel == DataStoreManager.GITHUB) { updateRepository.checkForGithubReleaseUpdate().collectLatest { response -> @@ -2179,9 +2181,10 @@ class SharedViewModel( nowPlayingState.value?.track?.let { track -> val bytesArray = bitmap.toByteArray() try { - val fileOutputStream = FileOutputStream("$path.jpg") - fileOutputStream.write(bytesArray) - fileOutputStream.close() + val imageBytes = requireNotNull(bytesArray) { "Cannot encode the track artwork" } + withContext(Dispatchers.IO) { + fileSystem().write("$path.jpg".toPath()) { write(imageBytes) } + } Logger.d(tag, "Thumbnail saved to $path.jpg") } catch (e: Exception) { throw RuntimeException(e) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SoundCloudPlayerViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SoundCloudPlayerViewModel.kt index d0ce71f789..b7dc743cc7 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SoundCloudPlayerViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SoundCloudPlayerViewModel.kt @@ -8,6 +8,7 @@ import com.maxrave.logger.Logger import com.maxrave.simpmusic.viewModel.base.BaseViewModel import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO import kotlinx.coroutines.Job import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay diff --git a/composeApp/src/commonTest/kotlin/com/maxrave/simpmusic/extension/PlaybackDurationTest.kt b/composeApp/src/commonTest/kotlin/com/maxrave/simpmusic/extension/PlaybackDurationTest.kt new file mode 100644 index 0000000000..ac96cfd98d --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/maxrave/simpmusic/extension/PlaybackDurationTest.kt @@ -0,0 +1,28 @@ +package com.maxrave.simpmusic.extension + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith + +class PlaybackDurationTest { + @Test + fun truncatesSubsecondPrecision() { + assertEquals("00:00", formatPlaybackDuration(0)) + assertEquals("00:00", formatPlaybackDuration(999)) + assertEquals("00:01", formatPlaybackDuration(1_999)) + assertEquals("00:59", formatPlaybackDuration(59_999)) + assertEquals("01:00", formatPlaybackDuration(60_000)) + } + + @Test + fun preservesTotalMinutesForLongTracksWithoutOverflow() { + assertEquals("60:00", formatPlaybackDuration(3_600_000)) + assertEquals("100:01", formatPlaybackDuration(6_001_000)) + assertEquals("153722867280912:55", formatPlaybackDuration(Long.MAX_VALUE)) + } + + @Test + fun rejectsUnknownDurationWhichTheUiLocalizesSeparately() { + assertFailsWith { formatPlaybackDuration(-1) } + } +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/IosDeepLinks.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/IosDeepLinks.kt new file mode 100644 index 0000000000..0fc2dbe452 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/IosDeepLinks.kt @@ -0,0 +1,10 @@ +package com.maxrave.simpmusic + +import com.eygraber.uri.Uri +import com.maxrave.domain.data.model.intent.GenericIntent +import com.maxrave.simpmusic.viewModel.SharedViewModel +import org.koin.mp.KoinPlatform.getKoin + +fun handleIosUrl(url: String) { + getKoin().get().setIntent(GenericIntent(data = Uri.parse(url))) +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/IosPlaybackSmokeTest.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/IosPlaybackSmokeTest.kt new file mode 100644 index 0000000000..bb8050c604 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/IosPlaybackSmokeTest.kt @@ -0,0 +1,88 @@ +package com.maxrave.simpmusic + +import platform.AVFoundation.* +import platform.MediaPlayer.* + +import com.maxrave.data.mediaservice.SharedMediaPlayerHandler +import com.maxrave.domain.mediaservice.player.MediaPlayerListener +import com.maxrave.domain.mediaservice.handler.MediaPlayerHandler +import com.maxrave.data.io.fileDir +import com.maxrave.data.player.AvPlayerAdapter +import com.maxrave.domain.data.player.GenericMediaItem +import com.maxrave.domain.data.player.GenericMediaMetadata +import com.maxrave.domain.data.player.PlayerConstants +import kotlinx.coroutines.* +import okio.FileSystem +import okio.Path.Companion.toPath +import org.koin.mp.KoinPlatform.getKoin + +/** Invoked only by the Debug host's explicit --playback-smoke-test launch argument. */ +fun startIosPlaybackSmokeTest(url: String) { + CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate).launch { + val report = StringBuilder() + val player = getKoin().get() + var selected: GenericMediaItem? = null + val listener = object : MediaPlayerListener { + override fun onMediaItemTransition(mediaItem: GenericMediaItem?, reason: Int) { selected = mediaItem } + } + player.addListener(listener) + suspend fun await(description: String, condition: () -> Boolean) { + withTimeout(30_000) { while (!condition()) delay(100) } + report.appendLine("PASS $description") + } + try { + withTimeout(30_000) { + (getKoin().get() as SharedMediaPlayerHandler).awaitStartup() + } + val first = GenericMediaItem("ios-smoke-1", url, GenericMediaMetadata(title = "Playback verification")) + val second = first.copy(mediaId = "ios-smoke-2") + player.clearMediaItems() + player.addMediaItem(first) + check(selected == first) + report.appendLine("PASS first queue item publishes metadata") + player.addMediaItem(first) + player.addMediaItem(second) + player.seekTo(1, 0) + player.play() + await("AVPlayer ready") { player.playbackState == PlayerConstants.STATE_READY } + await("playback clock advances") { player.isPlaying && player.currentPosition > 1_000 } + await("Now Playing metadata published") { + MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo?.get(MPMediaItemPropertyTitle) == first.metadata.title + } + player.pause() + delay(400) + val pausedAt = player.currentPosition + delay(700) + check(!player.isPlaying && kotlin.math.abs(player.currentPosition - pausedAt) < 200) + report.appendLine("PASS pause holds position") + player.seekTo(6_000) + await("seek reaches target") { kotlin.math.abs(player.currentPosition - 6_000) < 750 } + player.moveMediaItem(1, 2) + check(player.currentMediaItemIndex == 2) + report.appendLine("PASS duplicate track move preserves identity") + player.removeMediaItem(0) + check(player.currentMediaItemIndex == 1) + report.appendLine("PASS duplicate removal preserves current index") + player.seekToPreviousMediaItem() + await("previous selects adjacent track") { player.currentMediaItem?.mediaId == second.mediaId } + player.seekToNext() + await("next selects adjacent track") { player.currentMediaItemIndex == 1 } + player.play() + await("resumes playback after track change") { player.isPlaying && player.currentPosition > 500 } + player.clearMediaItems() + check(player.mediaItemCount == 0 && !player.hasNextMediaItem()) + report.appendLine("PASS empty queue has no next item") + check(selected == null) + report.appendLine("PASS empty queue clears metadata") + report.appendLine("RESULT PASS") + } catch (error: Throwable) { + report.appendLine("RESULT FAIL ${error.message}") + report.appendLine("state=${player.playbackState} intent=${player.playWhenReady} playing=${player.isPlaying} position=${player.currentPosition} rate=${player.nativePlayer.rate}") + } finally { + player.removeListener(listener) + FileSystem.SYSTEM.createDirectories(fileDir().toPath()) + FileSystem.SYSTEM.write((fileDir() + "/ios-playback-smoke.txt").toPath()) { writeUtf8(report.toString()) } + println(report.toString()) + } + } +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/MainViewController.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/MainViewController.kt index 933603c917..ae2965c178 100644 --- a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/MainViewController.kt +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/MainViewController.kt @@ -1,5 +1,70 @@ package com.maxrave.simpmusic import androidx.compose.ui.window.ComposeUIViewController +import androidx.compose.runtime.* +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import com.maxrave.domain.manager.DataStoreManager +import com.maxrave.kotlinytmusicscraper.YouTube +import com.maxrave.kotlinytmusicscraper.models.YouTubeLocale +import kotlinx.coroutines.flow.first +import org.koin.mp.KoinPlatform.getKoin +import coil3.ImageLoader +import coil3.compose.setSingletonImageLoaderFactory +import coil3.network.ktor3.KtorNetworkFetcherFactory +import com.maxrave.common.AppIdentity +import com.maxrave.data.di.loader.loadAllModules +import com.maxrave.data.io.fileDir +import com.maxrave.logger.Logger +import com.maxrave.simpmusic.di.viewModelModule +import com.maxrave.simpmusic.utils.VersionManager +import io.ktor.client.HttpClient +import io.ktor.client.engine.darwin.Darwin +import org.koin.core.context.startKoin +import org.koin.core.context.loadKoinModules +import platform.UIKit.UIDevice -fun MainViewController() = ComposeUIViewController { App() } \ No newline at end of file +private var initialized = false + +private fun initializeIosApp() { + if (initialized) return + com.maxrave.simpmusic.viewModel.applyPendingIosRestore() + Logger.enableFileLogging(fileDir() + "/logs") + startKoin { + loadAllModules(AppIdentity( + applicationId = "com.maxrave.simpmusic", + versionName = BuildKonfig.versionName, + platform = "iOS " + UIDevice.currentDevice.systemVersion, + isDevBuild = false, + )) + loadKoinModules(viewModelModule) + } + VersionManager.initialize() + initialized = true +} + +fun MainViewController(): platform.UIKit.UIViewController { + initializeIosApp() + return ComposeUIViewController { + setSingletonImageLoaderFactory { context -> + ImageLoader.Builder(context) + .components { add(KtorNetworkFetcherFactory(HttpClient(Darwin))) } + .build() + } + var preferencesReady by remember { mutableStateOf(false) } + LaunchedEffect(Unit) { + // Music is unavailable in some system regions. Apply the app's supported region + // and language before Home launches requests, without blocking the main thread. + val settings = getKoin().get() + getKoin().get().locale = YouTubeLocale( + settings.location.first(), settings.language.first().take(2), + ) + preferencesReady = true + } + if (preferencesReady) App() + else Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() } + } +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/Platform.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/Platform.ios.kt index a47ec8b069..3655cd24b4 100644 --- a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/Platform.ios.kt +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/Platform.ios.kt @@ -1,4 +1,5 @@ package com.maxrave.simpmusic -import platform.UIKit.UIDevice -actual fun getPlatform(): Platform = Platform.iOS \ No newline at end of file +actual fun getPlatform(): Platform = Platform.iOS + +internal actual fun desktopOsName(): String = "jvm" diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/CopyToClipboard.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/CopyToClipboard.ios.kt new file mode 100644 index 0000000000..29c2d59bb5 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/CopyToClipboard.ios.kt @@ -0,0 +1,19 @@ +package com.maxrave.simpmusic.expect + +import kotlinx.cinterop.ExperimentalForeignApi +import platform.Foundation.NSThread +import platform.UIKit.UIPasteboard +import platform.darwin.dispatch_async +import platform.darwin.dispatch_get_main_queue + +@OptIn(ExperimentalForeignApi::class) +actual fun copyToClipboard(label: String, text: String) { + // UIPasteboard has no Android-style clip label. UIKit access stays on the main thread. + if (NSThread.isMainThread) { + UIPasteboard.generalPasteboard.string = text + } else { + dispatch_async(dispatch_get_main_queue()) { + UIPasteboard.generalPasteboard.string = text + } + } +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/FolderPath.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/FolderPath.ios.kt new file mode 100644 index 0000000000..a7a6c08768 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/FolderPath.ios.kt @@ -0,0 +1,22 @@ +package com.maxrave.simpmusic.expect + +import kotlinx.cinterop.ExperimentalForeignApi +import platform.Foundation.NSDocumentDirectory +import platform.Foundation.NSFileManager +import platform.Foundation.NSSearchPathForDirectoriesInDomains +import platform.Foundation.NSUserDomainMask + +@OptIn(ExperimentalForeignApi::class) +actual fun getDownloadFolderPath(): String { + // iOS has no writable public Downloads directory. Keep music inside the app sandbox. + val documents = NSSearchPathForDirectoriesInDomains( + NSDocumentDirectory, + NSUserDomainMask, + true, + ).firstOrNull() as? String ?: error("The app's Documents directory is unavailable") + val downloads = "$documents/Downloads" + check(NSFileManager.defaultManager.createDirectoryAtPath(downloads, true, null, null)) { + "Cannot create the app's Downloads directory" + } + return downloads +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/IosPresentation.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/IosPresentation.kt new file mode 100644 index 0000000000..c32d806c2a --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/IosPresentation.kt @@ -0,0 +1,36 @@ +@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) +package com.maxrave.simpmusic.expect + +import platform.CoreGraphics.CGRectMake +import platform.UIKit.* + +internal fun activeWindow(): UIWindow? = UIApplication.sharedApplication.connectedScenes + .filterIsInstance() + .filter { it.activationState == UISceneActivationStateForegroundActive } + .flatMap { it.windows.filterIsInstance() } + .firstOrNull { it.isKeyWindow() } + +internal fun topViewController(): UIViewController? { + var controller = activeWindow()?.rootViewController ?: return null + while (true) { + controller = when { + controller.presentedViewController != null -> controller.presentedViewController!! + controller is UINavigationController -> controller.visibleViewController ?: return controller + controller is UITabBarController -> controller.selectedViewController ?: return controller + else -> return controller + } + } +} + +internal fun presentShare(items: List, title: String): Boolean { + val presenter = topViewController() ?: return false + val sheet = UIActivityViewController(items, null) + sheet.title = title + sheet.popoverPresentationController?.let { + it.sourceView = presenter.view + it.sourceRect = CGRectMake(0.0, 0.0, 1.0, 1.0) + it.permittedArrowDirections = 0uL + } + presenter.presentViewController(sheet, true, null) + return true +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/OpenUrl.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/OpenUrl.ios.kt new file mode 100644 index 0000000000..cd795360a3 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/OpenUrl.ios.kt @@ -0,0 +1,18 @@ +package com.maxrave.simpmusic.expect + +import platform.Foundation.NSURL +import platform.UIKit.UIApplication +import platform.darwin.dispatch_async +import platform.darwin.dispatch_get_main_queue + +actual fun openUrl(url: String) { + val target = NSURL.URLWithString(url) ?: return + dispatch_async(dispatch_get_main_queue()) { + UIApplication.sharedApplication.openURL(target, emptyMap(), null) + } +} + +actual fun shareUrl(title: String, url: String) { + val target = NSURL.URLWithString(url) ?: return + dispatch_async(dispatch_get_main_queue()) { presentShare(listOf(title, target), title) } +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/Orientation.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/Orientation.ios.kt new file mode 100644 index 0000000000..cdf71e8019 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/Orientation.ios.kt @@ -0,0 +1,7 @@ +package com.maxrave.simpmusic.expect +import platform.UIKit.* +actual fun currentOrientation(): Orientation = when (activeWindow()?.windowScene?.interfaceOrientation) { + UIInterfaceOrientationLandscapeLeft, UIInterfaceOrientationLandscapeRight -> Orientation.LANDSCAPE + UIInterfaceOrientationPortrait, UIInterfaceOrientationPortraitUpsideDown -> Orientation.PORTRAIT + else -> Orientation.UNSPECIFIED +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ShareImage.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ShareImage.ios.kt new file mode 100644 index 0000000000..cf15dbd6c3 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ShareImage.ios.kt @@ -0,0 +1,44 @@ +@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) +package com.maxrave.simpmusic.expect + +import com.maxrave.data.io.fileSystem +import kotlinx.cinterop.* +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withContext +import okio.Path.Companion.toPath +import platform.Foundation.* +import platform.Photos.* +import kotlin.coroutines.resume + +internal suspend fun photoWritePermission(): Boolean = suspendCancellableCoroutine { continuation -> + PHPhotoLibrary.requestAuthorizationForAccessLevel(PHAccessLevelAddOnly) { status -> + if (continuation.isActive) continuation.resume(status == PHAuthorizationStatusAuthorized || status == PHAuthorizationStatusLimited) + } +} + +actual suspend fun saveImageToDevice(bytes: ByteArray, fileName: String): Boolean { + if (bytes.isEmpty() || !photoWritePermission()) return false + val data = bytes.usePinned { NSData.create(bytes = it.addressOf(0), length = bytes.size.toULong()) } + return suspendCancellableCoroutine { continuation -> + PHPhotoLibrary.sharedPhotoLibrary().performChanges({ + PHAssetCreationRequest.creationRequestForAsset().addResourceWithType(PHAssetResourceTypePhoto, data, null) + }) { success, _ -> if (continuation.isActive) continuation.resume(success) } + } +} + +actual suspend fun shareImage(bytes: ByteArray, fileName: String, chooserTitle: String, mimeType: String): Boolean { + val path = withContext(Dispatchers.IO) { + runCatching { + val directory = (NSTemporaryDirectory() + "sharing/" + NSUUID().UUIDString).toPath() + fileSystem().createDirectories(directory) + val name = fileName.substringAfterLast('/').substringAfterLast('\\') + require(name.isNotBlank() && name != "." && name != "..") + (directory / name).also { fileSystem().write(it) { write(bytes) } } + }.getOrNull() + } ?: return false + return withContext(Dispatchers.Main) { + presentShare(listOf(NSURL.fileURLWithPath(path.toString())), chooserTitle) + } +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/UnmeteredNetwork.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/UnmeteredNetwork.ios.kt new file mode 100644 index 0000000000..a8b6f1f5bc --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/UnmeteredNetwork.ios.kt @@ -0,0 +1,20 @@ +@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) +package com.maxrave.simpmusic.expect + +import platform.Network.* +import platform.darwin.dispatch_get_main_queue + +private object Connectivity { + var unmetered = false + private val monitor = nw_path_monitor_create() + init { + nw_path_monitor_set_update_handler(monitor) { path -> + unmetered = path != null && nw_path_get_status(path) == nw_path_status_satisfied && + !nw_path_is_expensive(path) && !nw_path_is_constrained(path) + } + nw_path_monitor_set_queue(monitor, dispatch_get_main_queue()) + nw_path_monitor_start(monitor) + } +} + +actual fun isOnUnmeteredNetwork(): Boolean = Connectivity.unmetered diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/Bitmap.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/Bitmap.ios.kt new file mode 100644 index 0000000000..3e64055127 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/Bitmap.ios.kt @@ -0,0 +1,30 @@ +package com.maxrave.simpmusic.expect.ui + +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asComposeImageBitmap +import androidx.compose.ui.graphics.asSkiaBitmap +import coil3.toBitmap +import com.maxrave.simpmusic.extension.toResizedBitmap +import org.jetbrains.skia.EncodedImageFormat +import org.jetbrains.skia.Image + +actual fun ImageBitmap.toByteArray(): ByteArray? { + val image = Image.makeFromBitmap(this.asSkiaBitmap()) + val bytesArray = + image.encodeToData(EncodedImageFormat.JPEG, 100)?.bytes + return bytesArray +} + +actual fun ImageBitmap.toPngByteArray(): ByteArray? { + val image = Image.makeFromBitmap(this.asSkiaBitmap()) + return image.encodeToData(EncodedImageFormat.PNG)?.bytes +} + +actual fun coil3.Image.toImageBitmap(): ImageBitmap = + this.toBitmap().asComposeImageBitmap() + +// Skia bitmaps live in memory and can always be read, so a plain resize is enough here. +actual fun ImageBitmap.toReadableBitmap( + width: Int, + height: Int, +): ImageBitmap = toResizedBitmap(width, height) diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/Cookies.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/Cookies.ios.kt new file mode 100644 index 0000000000..7451f5c1db --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/Cookies.ios.kt @@ -0,0 +1,112 @@ +@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) +package com.maxrave.simpmusic.expect.ui + +import androidx.compose.foundation.layout.* +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.interop.UIKitView +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import platform.Foundation.* +import platform.WebKit.* +import platform.darwin.NSObject + +private object IosCookies : WebViewCookieManager { + private var cookies: List = emptyList() + fun refresh(onDone: () -> Unit = {}) { + WKWebsiteDataStore.defaultDataStore().httpCookieStore.getAllCookies { values -> + cookies = values.orEmpty().filterIsInstance() + onDone() + } + } + override fun getCookie(url: String): String { + val host = NSURL.URLWithString(url)?.host.orEmpty() + return cookies.filter { host == it.domain.trimStart('.') || host.endsWith("." + it.domain.trimStart('.')) } + .joinToString("; ") { "${it.name}=${it.value}" } + } + override fun removeAllCookies() { + cookies = emptyList() + val store = WKWebsiteDataStore.defaultDataStore().httpCookieStore + store.getAllCookies { values -> values.orEmpty().filterIsInstance().forEach { store.deleteCookie(it, null) } } + } +} +actual fun createWebViewCookieManager(): WebViewCookieManager = IosCookies + +@Composable +actual fun PlatformWebView(state: MutableState, initUrl: String, + aboveContent: @Composable BoxScope.() -> Unit, clearCookies: Boolean, onPageFinished: (String) -> Unit) { + val callback by rememberUpdatedState(onPageFinished) + val delegate = remember { object : NSObject(), WKNavigationDelegateProtocol { + @kotlinx.cinterop.ObjCSignatureOverride + override fun webView(webView: WKWebView, didStartProvisionalNavigation: WKNavigation?) { + state.value = WebViewState.Loading(0) + } + @kotlinx.cinterop.ObjCSignatureOverride + override fun webView(webView: WKWebView, didFinishNavigation: WKNavigation?) { + IosCookies.refresh { + state.value = WebViewState.Finished + callback(webView.URL?.absoluteString.orEmpty()) + } + } + } } + Box(Modifier.fillMaxSize()) { + UIKitView(factory = { + WKWebView(frame = kotlinx.cinterop.cValue { }, configuration = WKWebViewConfiguration()).apply { + navigationDelegate = delegate + customUserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Version/18.0 Mobile/15E148 Safari/604.1" + val request = NSURLRequest(NSURL.URLWithString(initUrl)!!) + if (clearCookies) { + val store = WKWebsiteDataStore.defaultDataStore() + store.removeDataOfTypes(WKWebsiteDataStore.allWebsiteDataTypes(), NSDate.distantPast) { loadRequest(request) } + } else loadRequest(request) + } + }, modifier = Modifier.fillMaxSize(), onRelease = { it.stopLoading(); it.navigationDelegate = null }) + aboveContent() + } +} + +@Composable +actual fun DiscordWebView(state: MutableState, aboveContent: @Composable BoxScope.() -> Unit, + onLoginDone: (String) -> Unit) { + val callback by rememberUpdatedState(onLoginDone) + var webView by remember { mutableStateOf(null) } + val delegate = remember { object : NSObject(), WKNavigationDelegateProtocol { + override fun webView(webView: WKWebView, didFinishNavigation: WKNavigation?) { + state.value = WebViewState.Finished + } + } } + // Discord navigates inside a single page after sign-in, without a navigation callback. + LaunchedEffect(webView) { + val view = webView ?: return@LaunchedEffect + var delivered = false + while (isActive && !delivered) { + if (view.URL?.host == "discord.com") { + view.evaluateJavaScript(""" + (function() { + var frame = document.createElement('iframe'); + document.body.appendChild(frame); + var token = frame.contentWindow.localStorage.getItem('token'); + frame.remove(); + return token; + })() + """.trimIndent()) { token, _ -> + (token as? String)?.trim('"')?.takeIf { it.isNotBlank() }?.let { + delivered = true + callback(it) + } + } + } + delay(1000) + } + } + Box(Modifier.fillMaxSize()) { + UIKitView(factory = { + WKWebView(frame = kotlinx.cinterop.cValue { }, configuration = WKWebViewConfiguration()).apply { + navigationDelegate = delegate + webView = this + loadRequest(NSURLRequest(NSURL.URLWithString("https://discord.com/login")!!)) + } + }, modifier = Modifier.fillMaxSize(), onRelease = { it.stopLoading(); it.navigationDelegate = null; webView = null }) + aboveContent() + } +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/DeviceSync.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/DeviceSync.ios.kt new file mode 100644 index 0000000000..c97b229451 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/DeviceSync.ios.kt @@ -0,0 +1,21 @@ +package com.maxrave.simpmusic.expect.ui + +import androidx.compose.runtime.Composable +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton + +@Composable +private fun UnsupportedDialog(onDismiss: () -> Unit) { + AlertDialog(onDismissRequest = onDismiss, + text = { Text("Device pairing is unavailable on iOS.") }, + confirmButton = { TextButton(onClick = onDismiss) { Text("OK") } }) +} +@Composable actual fun LoginSyncDialog(onDismiss: () -> Unit) = UnsupportedDialog(onDismiss) +@Composable actual fun LibrarySyncDialog(onDismiss: () -> Unit) = UnsupportedDialog(onDismiss) +actual fun restartAfterSyncedSettings() = Unit +@Composable actual fun SongRecognitionSheet(onFind: (String) -> Unit, onDismiss: () -> Unit) { + AlertDialog(onDismissRequest = onDismiss, + text = { Text("Song recognition is unavailable on iOS.") }, + confirmButton = { TextButton(onClick = onDismiss) { Text("OK") } }) +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/FilePicker.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/FilePicker.ios.kt new file mode 100644 index 0000000000..fc57af2fa1 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/FilePicker.ios.kt @@ -0,0 +1,41 @@ +@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) +package com.maxrave.simpmusic.expect.ui + +import androidx.compose.runtime.* +import com.maxrave.simpmusic.expect.topViewController +import platform.Foundation.* +import platform.UIKit.* +import platform.darwin.NSObject + +@Composable +actual fun filePickerResult(onResultUri: (String?) -> Unit): FilePickerLauncher { + val callback by rememberUpdatedState(onResultUri) + val delegate = remember { object : NSObject(), UIDocumentPickerDelegateProtocol { + override fun documentPicker(controller: UIDocumentPickerViewController, didPickDocumentsAtURLs: List<*>) { + callback((didPickDocumentsAtURLs.firstOrNull() as? NSURL)?.absoluteString) + } + override fun documentPickerWasCancelled(controller: UIDocumentPickerViewController) { callback(null) } + } } + return remember(delegate) { object : FilePickerLauncher { + override fun launch() { + val presenter = topViewController() ?: return callback(null) + val picker = UIDocumentPickerViewController(documentTypes = listOf("public.data"), inMode = UIDocumentPickerMode.UIDocumentPickerModeImport) + picker.delegate = delegate + presenter.presentViewController(picker, true, null) + } + } } +} + +@Composable +actual fun fileSaverResult(fileName: String, mimeType: String, onResultUri: (String?) -> Unit): FilePickerLauncher { + val callback by rememberUpdatedState(onResultUri) + return remember(fileName) { object : FilePickerLauncher { + override fun launch() { + // backupNative writes the archive here, then presents the system export sheet. + val directory = NSTemporaryDirectory() + NSUUID().UUIDString + if (!NSFileManager.defaultManager.createDirectoryAtPath(directory, true, null, null)) return callback(null) + val name = fileName.substringAfterLast('/').substringAfterLast('\\') + callback(NSURL.fileURLWithPath("$directory/$name").absoluteString) + } + } } +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/ImageIo.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/ImageIo.ios.kt new file mode 100644 index 0000000000..f0788f9fe4 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/ImageIo.ios.kt @@ -0,0 +1,28 @@ +package com.maxrave.simpmusic.expect.ui + +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.toComposeImageBitmap +import com.maxrave.data.io.fileDir +import com.maxrave.data.io.fileSystem +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.withContext +import okio.Path.Companion.toPath +import org.jetbrains.skia.Image +import platform.Foundation.NSURL + +actual fun decodeImageBitmap(bytes: ByteArray): ImageBitmap? = runCatching { + Image.makeFromEncoded(bytes).toComposeImageBitmap() +}.getOrNull() + +actual suspend fun persistPickedImage(bytes: ByteArray, fileName: String): String? = withContext(Dispatchers.IO) { + runCatching { + val directory = "${fileDir()}/playlist_covers".toPath() + val name = fileName.substringAfterLast('/').substringAfterLast('\\') + require(name.isNotBlank() && name != "." && name != "..") + fileSystem().createDirectories(directory) + val file = directory / name + fileSystem().write(file) { write(bytes) } + NSURL.fileURLWithPath(file.toString()).absoluteString + }.getOrNull() +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/MediaPlayerView.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/MediaPlayerView.ios.kt new file mode 100644 index 0000000000..464dc3db18 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/MediaPlayerView.ios.kt @@ -0,0 +1,88 @@ +@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) +package com.maxrave.simpmusic.expect.ui + +import kotlinx.cinterop.useContents +import androidx.compose.foundation.layout.* +import androidx.compose.ui.layout.ContentScale +import coil3.compose.AsyncImage +import com.maxrave.domain.mediaservice.handler.MediaPlayerHandler +import androidx.compose.material3.Text +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.interop.UIKitViewController +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.unit.dp +import com.maxrave.data.player.AvPlayerAdapter +import com.maxrave.domain.data.model.metadata.Lyrics +import com.maxrave.domain.data.model.streams.TimeLine +import com.maxrave.domain.manager.DataStoreManager +import kotlinx.coroutines.delay +import org.koin.compose.koinInject +import platform.AVFoundation.* +import platform.AVKit.AVPlayerViewController +import platform.Foundation.NSURL + +@Composable +actual fun MediaPlayerView(url: String, modifier: Modifier, cropToBounds: Boolean, onFirstFrame: () -> Unit) { + val player = remember(url) { AVPlayer(NSURL.URLWithString(url)!!) } + val controller = remember(player) { AVPlayerViewController().apply { + this.player = player + showsPlaybackControls = false + videoGravity = if (cropToBounds) AVLayerVideoGravityResizeAspectFill else AVLayerVideoGravityResizeAspect + } } + val callback by rememberUpdatedState(onFirstFrame) + LaunchedEffect(controller) { + player.play() + while (!controller.readyForDisplay) delay(50) + callback() + } + DisposableEffect(player) { onDispose { player.pause(); player.replaceCurrentItemWithPlayerItem(null) } } + UIKitViewController(factory = { controller }, modifier = modifier) +} + +@Composable +actual fun rememberVideoAspectRatio(playerName: String): Float? { + val player = koinInject().nativePlayer + var ratio by remember { mutableStateOf(null) } + LaunchedEffect(player) { + while (true) { + ratio = player.currentItem?.presentationSize?.let { + it.useContents { if (height > 0) (width / height).toFloat() else null } + } + delay(500) + } + } + return ratio +} + +@Composable +actual fun MediaPlayerViewWithSubtitle(modifier: Modifier, playerName: String, shouldPip: Boolean, + shouldShowSubtitle: Boolean, shouldScaleDownSubtitle: Boolean, isInPipMode: Boolean, + timelineState: TimeLine, lyricsData: Lyrics?, translatedLyricsData: Lyrics?, + mainTextStyle: TextStyle, translatedTextStyle: TextStyle) { + val player = koinInject().nativePlayer + val offset by koinInject().lyricsOffsetMs.collectAsState(0) + val controller = remember(player) { AVPlayerViewController().apply { + this.player = player + showsPlaybackControls = false + allowsPictureInPicturePlayback = shouldPip + } } + val ratio = rememberVideoAspectRatio(playerName) + val nowPlaying by koinInject().nowPlayingState.collectAsState() + Box(modifier) { + if (ratio != null) UIKitViewController(factory = { controller }, modifier = Modifier.fillMaxSize()) + else AsyncImage(model = nowPlaying.songEntity?.thumbnails, contentDescription = null, + contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) + if (shouldShowSubtitle) { + val time = timelineState.current - offset + val line = lyricsData?.lines?.lastOrNull { (it.startTimeMs.toLongOrNull() ?: Long.MAX_VALUE) <= time } + val translation = translatedLyricsData?.lines?.lastOrNull { (it.startTimeMs.toLongOrNull() ?: Long.MAX_VALUE) <= time } + Column(Modifier.align(Alignment.BottomCenter).padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) { + line?.let { Text(it.words, style = mainTextStyle, color = Color.White) } + translation?.let { Text(it.words, style = translatedTextStyle, color = Color.White) } + } + } + } +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/NativeCapabilities.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/NativeCapabilities.ios.kt new file mode 100644 index 0000000000..752902805e --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/NativeCapabilities.ios.kt @@ -0,0 +1,39 @@ +package com.maxrave.simpmusic.expect.ui + +import androidx.compose.runtime.* +import androidx.compose.material3.ColorScheme +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import com.maxrave.simpmusic.expect.photoWritePermission +import kotlinx.coroutines.launch + +actual fun isLyricsBlurSupported(): Boolean = true +actual fun isWallpaperDynamicColorSupported(): Boolean = false +@Composable actual fun platformDynamicColorScheme(isDark: Boolean): ColorScheme? = null +@Composable actual fun SystemBarAppearanceEffect(isDark: Boolean) { + SideEffect { + com.maxrave.simpmusic.expect.activeWindow()?.overrideUserInterfaceStyle = + if (isDark) platform.UIKit.UIUserInterfaceStyle.UIUserInterfaceStyleDark + else platform.UIKit.UIUserInterfaceStyle.UIUserInterfaceStyleLight + } +} +// Google Cast is optional, as on FOSS Android. AVPlayer provides AirPlay through iOS. +actual fun isPlatformCastAvailable(): Boolean = false +@Composable actual fun PlatformCastButton(modifier: Modifier, tint: Color) { } +@Composable actual fun rememberCastReceivers(discover: Boolean): CastReceivers = remember { CastReceivers(emptyList(), {}, {}) } +@Composable actual fun rememberDeviceVolumeController(): DeviceVolumeController? = null +@Composable actual fun rememberLocalNetworkPermission(): LocalNetworkPermissionRequester = remember { + // iOS shows its own permission prompt on the first local-network connection. + object : LocalNetworkPermissionRequester { override fun requestIfNeeded(url: String) {} } +} +@Composable actual fun rememberSaveImagePermission(onResult: (Boolean) -> Unit): SaveImagePermissionRequester { + val callback by rememberUpdatedState(onResult) + val scope = rememberCoroutineScope() + return remember(scope) { object : SaveImagePermissionRequester { + override fun requestIfNeeded() { scope.launch { callback(photoWritePermission()) } } + } } +} +@Composable actual fun openEqResult(audioSessionId: Int): OpenEqLauncher = remember { + // iOS has no external system equalizer activity. The app's own audio settings remain separate. + object : OpenEqLauncher { override fun launch() {} } +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/PhotoPicker.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/PhotoPicker.ios.kt new file mode 100644 index 0000000000..2214cadbe0 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/PhotoPicker.ios.kt @@ -0,0 +1,38 @@ +@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) +package com.maxrave.simpmusic.expect.ui + +import androidx.compose.runtime.* +import com.maxrave.simpmusic.expect.topViewController +import platform.Foundation.* +import platform.PhotosUI.* +import platform.darwin.NSObject +import platform.darwin.dispatch_async +import platform.darwin.dispatch_get_main_queue + +@Composable +actual fun photoPickerResult(onResultUri: (String?) -> Unit): PhotoPickerLauncher { + val callback by rememberUpdatedState(onResultUri) + val delegate = remember { object : NSObject(), PHPickerViewControllerDelegateProtocol { + override fun picker(picker: PHPickerViewController, didFinishPicking: List<*>) { + picker.dismissViewControllerAnimated(true, null) + val result = didFinishPicking.firstOrNull() as? PHPickerResult + if (result == null) { callback(null); return } + result.itemProvider.loadFileRepresentationForTypeIdentifier("public.image") { source, _ -> + val output = source?.let { + val target = NSURL.fileURLWithPath(NSTemporaryDirectory() + NSUUID().UUIDString + "-" + (it.lastPathComponent ?: "image")) + if (NSFileManager.defaultManager.copyItemAtURL(it, target, null)) target.absoluteString else null + } + dispatch_async(dispatch_get_main_queue()) { callback(output) } + } + } + } } + return remember(delegate) { object : PhotoPickerLauncher { + override fun launch() { + val presenter = topViewController() ?: return callback(null) + val configuration = PHPickerConfiguration().apply { selectionLimit = 1; filter = PHPickerFilter.imagesFilter } + val picker = PHPickerViewController(configuration) + picker.delegate = delegate + presenter.presentViewController(picker, true, null) + } + } } +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/PlatformBackHandler.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/PlatformBackHandler.ios.kt new file mode 100644 index 0000000000..1cf498e275 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/PlatformBackHandler.ios.kt @@ -0,0 +1,8 @@ +package com.maxrave.simpmusic.expect.ui + +import androidx.compose.runtime.Composable + +@Composable +internal actual fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit) { + // Navigation uses the visible back buttons and Compose's iOS back gesture. +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/Scrollbar.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/Scrollbar.ios.kt new file mode 100644 index 0000000000..93868ec103 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/expect/ui/Scrollbar.ios.kt @@ -0,0 +1,56 @@ +package com.maxrave.simpmusic.expect.ui + +import androidx.compose.foundation.ScrollState +import androidx.compose.foundation.gestures.FlingBehavior +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.grid.LazyGridState +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.carousel.CarouselState +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier + +@Composable +actual fun HorizontalScrollBar( + modifier: Modifier, + scrollState: LazyListState, + flingBehavior: FlingBehavior?, +) { +} + +@Composable +actual fun HorizontalScrollBar( + modifier: Modifier, + scrollState: LazyGridState, + flingBehavior: FlingBehavior?, +) { +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +actual fun HorizontalScrollBar( + modifier: Modifier, + scrollState: CarouselState, + itemCount: Int, +) { +} + +@Composable +actual fun VerticalScrollBar( + scrollState: LazyListState, + modifier: Modifier, +) { +} + +@Composable +actual fun VerticalScrollBar( + scrollState: LazyGridState, + modifier: Modifier, +) { +} + +@Composable +actual fun VerticalScrollBar( + scrollState: ScrollState, + modifier: Modifier, +) { +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/extension/UIExt.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/extension/UIExt.ios.kt new file mode 100644 index 0000000000..dca9edf18d --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/extension/UIExt.ios.kt @@ -0,0 +1,29 @@ +package com.maxrave.simpmusic.extension + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalWindowInfo +import com.maxrave.domain.data.model.ui.ScreenSizeInfo +import platform.UIKit.UIApplication +import kotlin.math.roundToInt + +@Composable +actual fun getScreenSizeInfo(): ScreenSizeInfo { + val size = LocalWindowInfo.current.containerSize + val density = LocalDensity.current + return ScreenSizeInfo(with(density) { size.height.toDp().value.roundToInt() }, + with(density) { size.width.toDp().value.roundToInt() }, size.height, size.width) +} + +@Composable +actual fun KeepScreenOn() { + DisposableEffect(Unit) { + val previous = UIApplication.sharedApplication.idleTimerDisabled + UIApplication.sharedApplication.idleTimerDisabled = true + onDispose { UIApplication.sharedApplication.idleTimerDisabled = previous } + } +} + +@Composable +actual fun rememberIsInPipMode(): Boolean = false diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/ui/component/LiquidGlassAppBottomNavigationBar.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/ui/component/LiquidGlassAppBottomNavigationBar.ios.kt new file mode 100644 index 0000000000..8ff396acef --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/ui/component/LiquidGlassAppBottomNavigationBar.ios.kt @@ -0,0 +1,23 @@ +package com.maxrave.simpmusic.ui.component + +import androidx.compose.runtime.Composable +import androidx.navigation.NavController +import com.maxrave.simpmusic.expect.ui.PlatformBackdrop +import com.maxrave.simpmusic.viewModel.SharedViewModel +import kotlin.reflect.KClass + +@Composable +actual fun LiquidGlassAppBottomNavigationBar( + startDestination: Any, + navController: NavController, + backdrop: PlatformBackdrop, + viewModel: SharedViewModel, + isScrolledToTop: Boolean, + showAnalyticsTab: Boolean, + showMixForYouTab: Boolean, + onOpenNowPlaying: () -> Unit, + liquidGlass: Boolean, + reloadDestinationIfNeeded: (KClass<*>) -> Unit +) { + AppBottomNavigationBar(startDestination, navController, showAnalyticsTab, showMixForYouTab, reloadDestinationIfNeeded) +} \ No newline at end of file diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/ui/screen/player/FullscreenPlayer.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/ui/screen/player/FullscreenPlayer.ios.kt new file mode 100644 index 0000000000..7ade1071d7 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/ui/screen/player/FullscreenPlayer.ios.kt @@ -0,0 +1,12 @@ +package com.maxrave.simpmusic.ui.screen.player + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect + +@Composable +actual fun FullScreenRotationImmersive(onLaunch: () -> Unit, onDispose: () -> Unit) { + DisposableEffect(Unit) { + onLaunch() + onDispose { onDispose() } + } +} diff --git a/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/viewModel/SettingsViewModel.ios.kt b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/viewModel/SettingsViewModel.ios.kt new file mode 100644 index 0000000000..cba6162e99 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/maxrave/simpmusic/viewModel/SettingsViewModel.ios.kt @@ -0,0 +1,140 @@ +@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) +package com.maxrave.simpmusic.viewModel + +import com.eygraber.uri.Uri +import com.maxrave.common.DB_NAME +import com.maxrave.common.SETTINGS_FILENAME +import com.maxrave.data.db.documentDirectory +import com.maxrave.data.io.fileDir +import com.maxrave.domain.repository.CacheRepository +import com.maxrave.domain.repository.CommonRepository +import com.maxrave.simpmusic.expect.topViewController +import kotlinx.coroutines.IO +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okio.* +import okio.Path.Companion.toPath +import platform.Foundation.* +import platform.UIKit.* + +private val fs = FileSystem.SYSTEM +private val settingsName = "$SETTINGS_FILENAME.preferences_pb" +private val pendingRoot get() = (fileDir() + "/pending-restore").toPath() +private fun path(uri: Uri) = (NSURL.URLWithString(uri.toString())?.path ?: uri.toString()).toPath() + +actual suspend fun calculateDataFraction(cacheRepository: CacheRepository): SettingsStorageSectionFraction? = null +actual suspend fun readPickedFile(uri: Uri): ByteArray = withContext(Dispatchers.IO) { fs.read(path(uri)) { readByteArray() } } +actual fun getPackageName(): String = "com.maxrave.simpmusic" +actual fun getFileDir(): String = fileDir() +actual fun changeLanguageNative(code: String) { + NSUserDefaults.standardUserDefaults.setObject(listOf(code), forKey = "AppleLanguages") +} + +/** Applied before Koin opens Room/DataStore, so no live database or preferences are overwritten. */ +internal fun applyPendingIosRestore() { + val root = pendingRoot + if (!fs.exists(root / "ready")) return + for (name in listOf(DB_NAME, settingsName)) { + val source = root / name + if (fs.exists(source)) { + val target = documentDirectory().toPath() / name + if (name == DB_NAME) { + fs.delete((target.toString() + "-wal").toPath(), mustExist = false) + fs.delete((target.toString() + "-shm").toPath(), mustExist = false) + } + fs.atomicMove(source, target) + } + } + val downloads = root / "downloads" + if (fs.exists(downloads)) { + val target = (fileDir() + "/downloads").toPath() + fs.createDirectories(target) + fs.list(downloads).forEach { fs.atomicMove(it, target / it.name) } + } + fs.deleteRecursively(root) +} + +actual suspend fun restoreNative(commonRepository: CommonRepository, uri: Uri, getData: () -> Unit) { + val root = pendingRoot + fs.deleteRecursively(root, mustExist = false) + fs.createDirectories(root) + try { + fs.openZip(path(uri)).use { zip -> + val archiveRoot = "/".toPath() + require(zip.exists(archiveRoot / DB_NAME)) { "Backup contains no music database" } + for (name in listOf(DB_NAME, settingsName)) { + val source = archiveRoot / name + if (zip.exists(source)) zip.source(source).use { input -> fs.sink(root / name).buffer().use { it.writeAll(input) } } + } + val downloads = archiveRoot / "downloads" + if (zip.exists(downloads)) { + fs.createDirectories(root / "downloads") + zip.list(downloads).filter { it.name.endsWith(".m4a") && zip.metadata(it).isRegularFile }.forEach { source -> + zip.source(source).use { input -> fs.sink(root / "downloads" / source.name).buffer().use { it.writeAll(input) } } + } + } + } + fs.write(root / "ready") { writeUtf8("ready") } + } catch (error: Throwable) { + fs.deleteRecursively(root, mustExist = false) + throw error + } + withContext(Dispatchers.Main) { + val alert = UIAlertController.alertControllerWithTitle("Backup ready", "Close SimpMusic from the app switcher and reopen it to apply the restored library.", UIAlertControllerStyleAlert) + alert.addAction(UIAlertAction.actionWithTitle("OK", UIAlertActionStyleDefault, null)) + topViewController()?.presentViewController(alert, true, null) + } +} + +private data class ZipEntry(val name: ByteArray, val crc: Int, val size: Long, val offset: Long) +private fun crc32(path: Path): Int { + var crc = -1 + fs.source(path).buffer().use { input -> + while (!input.exhausted()) { + crc = crc xor (input.readByte().toInt() and 255) + repeat(8) { crc = (crc ushr 1) xor (if (crc and 1 != 0) 0xedb88320.toInt() else 0) } + } + } + return crc.inv() +} + +actual suspend fun backupNative(commonRepository: CommonRepository, uri: Uri, backupDownloaded: Boolean) { + commonRepository.databaseDaoCheckpoint() + val entries = mutableListOf(DB_NAME to requireNotNull(commonRepository.getDatabasePath()).toPath(), settingsName to (documentDirectory().toPath() / settingsName)) + val downloadRoot = (fileDir() + "/downloads").toPath() + if (backupDownloaded) fs.listOrNull(downloadRoot).orEmpty().filter { it.name.endsWith(".m4a") }.forEach { entries += "downloads/${it.name}" to it } + // Stored ZIP entries keep exports compatible with desktop/Android without a Native ZIP dependency. + fs.sink(path(uri)).buffer().use { out -> + val index = mutableListOf() + var written = 0L + for ((name, file) in entries) { + if (!fs.exists(file)) continue + val bytes = name.encodeToByteArray() + val size = fs.metadata(file).size ?: 0L + require(size <= 0xffffffffL) { "Backup entry is too large" } + val crc = crc32(file) + index += ZipEntry(bytes, crc, size, written) + out.writeIntLe(0x04034b50).writeShortLe(20).writeShortLe(0x800).writeShortLe(0) + .writeShortLe(0).writeShortLe(0).writeIntLe(crc).writeIntLe(size.toInt()).writeIntLe(size.toInt()) + .writeShortLe(bytes.size).writeShortLe(0).write(bytes) + fs.source(file).use { out.writeAll(it) } + written += 30 + bytes.size + size + } + val centralStart = written + for (entry in index) { + with(entry) { + out.writeIntLe(0x02014b50).writeShortLe(20).writeShortLe(20).writeShortLe(0x800).writeShortLe(0) + .writeShortLe(0).writeShortLe(0).writeIntLe(crc).writeIntLe(size.toInt()).writeIntLe(size.toInt()) + .writeShortLe(name.size).writeShortLe(0).writeShortLe(0).writeShortLe(0).writeShortLe(0) + .writeIntLe(0).writeIntLe(offset.toInt()).write(name) + written += 46 + entry.name.size + } + } + out.writeIntLe(0x06054b50).writeShortLe(0).writeShortLe(0).writeShortLe(index.size).writeShortLe(index.size) + .writeIntLe((written - centralStart).toInt()).writeIntLe(centralStart.toInt()).writeShortLe(0) + } + withContext(Dispatchers.Main) { + val picker = UIDocumentPickerViewController(uRLs = listOf(NSURL.fileURLWithPath(path(uri).toString())), inMode = UIDocumentPickerMode.UIDocumentPickerModeExportToService) + topViewController()?.presentViewController(picker, true, null) + } +} diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/Platform.jvm.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/Platform.jvm.kt index b1fb40edfe..a056f996dc 100644 --- a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/Platform.jvm.kt +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/Platform.jvm.kt @@ -1,4 +1,6 @@ package com.maxrave.simpmusic -actual fun getPlatform(): Platform = Platform.Desktop \ No newline at end of file +actual fun getPlatform(): Platform = Platform.Desktop + +internal actual fun desktopOsName(): String = System.getProperty("os.name") ?: "jvm" diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/extension/JvmFileExt.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/extension/JvmFileExt.kt new file mode 100644 index 0000000000..05f1825613 --- /dev/null +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/extension/JvmFileExt.kt @@ -0,0 +1,24 @@ +package com.maxrave.simpmusic.extension + +import java.io.File +import java.io.InputStream +import java.io.OutputStream +import java.util.zip.ZipInputStream +import java.util.zip.ZipOutputStream + +fun InputStream.zipInputStream(): ZipInputStream = ZipInputStream(this) + +fun OutputStream.zipOutputStream(): ZipOutputStream = ZipOutputStream(this) + +fun getSizeOfFile(dir: File): Long { + var dirSize: Long = 0 + if (!dir.listFiles().isNullOrEmpty()) { + for (f in dir.listFiles()!!) { + dirSize += f.length() + if (f.isDirectory) { + dirSize += getSizeOfFile(f) + } + } + } + return dirSize +} diff --git a/core b/core index 8413a257cb..b0bfb60cfb 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit 8413a257cbe45d102a9f101f2760e35b549e4d9e +Subproject commit b0bfb60cfb50e10748dad0d1b2772bcf2a13cefd diff --git a/docs/ios-port.md b/docs/ios-port.md new file mode 100644 index 0000000000..84f888450a --- /dev/null +++ b/docs/ios-port.md @@ -0,0 +1,148 @@ +# iOS port + +The `ios-support` branches in this repository and `core` contain the Apple Silicon +simulator port. Android and Desktop retain their existing playback engines. iOS +uses AVFoundation with the shared queue and playback handler. + +## Build and run + +Requirements: macOS, Xcode with an iOS simulator runtime, Python 3, and JDK 21. +Initialize `core` with `git submodule update --init --recursive` on a fresh clone. + +```sh +python3 scripts/build-ios-framework.py +xcodebuild -project iosApp/SimpMusic.xcodeproj -scheme SimpMusic \ + -configuration Debug -sdk iphonesimulator \ + -destination 'platform=iOS Simulator,name=iPhone 17 Pro' \ + -derivedDataPath /tmp/SimpMusicIosBuild \ + SKIP_KOTLIN_BUILD=YES CODE_SIGNING_ALLOWED=NO build +xcrun simctl install booted /tmp/SimpMusicIosBuild/Build/Products/Debug-iphonesimulator/SimpMusic.app +xcrun simctl launch booted com.maxrave.simpmusic +``` + +Alternatively open `iosApp/SimpMusic.xcodeproj` and run the shared `SimpMusic` +scheme. Its build phase builds the appropriate Kotlin framework and copies the +Compose resources. `SKIP_KOTLIN_BUILD=YES` is for a framework already built for +the matching configuration and platform. Device builds need a signing team; +device signing and App Store distribution have not been validated. + +`build-ios-framework.py` uses `JAVA_HOME`, or Android Studio's bundled JDK when +none is set. It temporarily removes the repository's daemon vendor restriction +and restores the original criteria in `finally`. Its lock serializes builds +started through that script. Do not run a separate wrapper script that changes +the same criteria concurrently. + +The application Native targets remain opt-in with `-PenableIos=true`. Useful +standalone checks, passed as arguments to `build-ios-framework.py`, include: + +```text +:data:compileKotlinIosSimulatorArm64 +:composeApp:compileKotlinIosSimulatorArm64 +:composeApp:linkDebugFrameworkIosSimulatorArm64 +:data:compileKotlinJvm +:composeApp:jvmTest +:data:compileAndroidMain +:composeApp:compileAndroidMain +:ktorExt:iosSimulatorArm64Test +:spotify:iosSimulatorArm64Test +:kotlinYtmusicScraper:iosSimulatorArm64Test +``` + +## Platform implementation + +- Startup initializes Koin, Room, DataStore, logging, view models, Coil's Darwin + image loader, and Compose resources before rendering the shared application. +- AVPlayer handles AAC/HLS, seek, queue edits, shuffle/repeat, audio sessions, + interruptions, and route changes. Now Playing metadata and remote commands use + MediaPlayer. Startup reads settings without blocking the main thread, and a + queue selected during startup takes precedence over the saved queue. +- The iOS stream request uses an Apple client returning direct AAC and HLS. Its + parameters are documented in [yt-dlp's client definitions](https://github.com/yt-dlp/yt-dlp/blob/master/yt_dlp/extractor/youtube/_base.py). + Android/Desktop retain their NewPipe extraction path. Service-side changes, + region restrictions, private tracks, and account requirements can still affect + which tracks are playable; the Native playback request is anonymous. +- Foreground NSURLSession downloads save AAC atomically in the application + sandbox. Playback prefers a completed offline file. Clearing transient player + cache does not remove downloaded tracks. +- WebKit provides login pages and cookie reads; platform file/photo pickers, + artwork persistence, Photos export, sharing, clipboard, and external links use + native APIs. Deep links are forwarded into shared navigation. +- Backup exports a standard ZIP containing the database and preferences, with + optional downloaded AAC files. Restore stages an archive and applies it on the + next full app launch before Room/DataStore open. It does not overwrite an open + database. Close the app through the app switcher and reopen after staging. +- Shared file/log access uses Okio. Date, number, and bidirectional lyric layout + no longer depend on JVM APIs. iOS HMAC and Spotify TOTP use CommonCrypto, with + known-vector simulator tests. + +## Deliberate limits + +Device pairing/library sync, Cast, microphone song recognition, system EQ, +wallpaper colors, and the Android/Desktop audio effects are unavailable on iOS; +their normal settings entry points are hidden. The player supports normal speed, +volume, sleep fade, queue, and repeat controls, without the two-player crossfade +or DSP chain of the other engines. Downloads are foreground tasks, without a +background NSURLSession implementation. iOS cannot merge or tag separate video +and audio downloads with the JVM FFmpeg path. + +Account sign-in completion, physical-device interruptions/AirPlay, App Store +packaging, and long-running background downloads require separate validation. + +## Verified on 2026-11-14 + +- `data` Native and JVM compilation, Compose Native framework linking, Android + compilation of data/Compose, and all 70 Compose JVM tests passed. +- Simulator tests passed: HMAC (2), Spotify TOTP (1), and scraper/locale (14). +- Xcode built and installed the app on iOS 26 simulators (iPhone 17 Pro and + iPhone 16e). Home browsing, artwork, Settings, and the Google login page loaded. + No account credentials were entered or sign-in completion claimed. +- The Debug host's real AVPlayer smoke test passed 13 checks: readiness, + advancing playback clock, system Now Playing metadata, pause, seek, next and + previous, duplicate-track identity, empty queues, and track metadata events. +- An online YouTube track played for over a minute. Its position also advanced + from 07:56 to 12:10 while the app was backgrounded and the simulator locked. + The simulator did not display the lock-screen media panel, so interactive + lock-screen controls remain unverified despite successful metadata publication. + +To repeat the player check with a booted simulator and the Debug app installed: + +```sh +python3 scripts/verify-ios-playback.py --device SIMULATOR_UDID +``` + +It generates a quiet local WAV in the app's sandbox, drives the actual AVPlayer, +prints a PASS/FAIL report, and leaves normal launches unaffected. `--url` accepts +an optional remote audio URL. The report lives at +`Documents/SimpMusic/ios-playback-smoke.txt` inside that simulator app container. +The backup/restore round trip, Photos permission flow, video-mode visuals, and +physical-device audio interruptions have not received end-to-end validation. + +## Unsigned device archive (2026-11-14) + +An arm64 Release archive passed Xcode archiving and was packaged as +`output/SimpMusic-ios-arm64-unsigned-4e36a279.ipa` (31,010,209 bytes). +The package was checked for the iOS device Mach-O platform, arm64 architecture, +ZIP integrity, and bundled Compose resources. Its adjacent JSON records source +commits and SHA-256. The minimum deployment target is iOS 16. + +No signing identity or provisioning profile was available. This IPA requires +signing before installation on a standard iPhone; physical-device installation +and playback remain unverified. + +The initial Release link exhausted the default 5 GB JVM heap. This command +successfully linked with a temporary 12 GB heap (about 13 minutes): + +```sh +JAVA_HOME='/Applications/Android Studio.app/Contents/jbr/Contents/Home' \ + python3 scripts/build-ios-framework.py :composeApp:linkReleaseFrameworkIosArm64 \ + '-Dorg.gradle.jvmargs=-Xmx12g -XX:+UseG1GC' --max-workers=2 +xcodebuild -project iosApp/SimpMusic.xcodeproj -scheme SimpMusic \ + -configuration Release -sdk iphoneos -destination 'generic/platform=iOS' \ + -archivePath /tmp/SimpMusicDevice.xcarchive \ + -derivedDataPath /tmp/SimpMusicDeviceBuild \ + SKIP_KOTLIN_BUILD=YES CODE_SIGNING_ALLOWED=NO archive +``` + +The repository's default heap configuration is unchanged. Package the archived +application under `Payload/SimpMusic.app` in a ZIP with an `.ipa` extension; +do not use the simulator application for device packaging. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index acc58e9c26..41b033cd95 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -166,6 +166,7 @@ car-app-projected = { group = "androidx.car.app", name = "app-projected", versio androidx-media = { group = "androidx.media", name = "media", version.ref = "androidx-media" } coil-compose = { group = "io.coil-kt.coil3", name = "coil-compose", version.ref = "coil3" } coil-network-okhttp = { group = "io.coil-kt.coil3", name = "coil-network-okhttp", version.ref = "coil3" } +coil-network-core = { group = "io.coil-kt.coil3", name = "coil-network-core", version.ref = "coil3" } kmpalette-core = { module = "com.kmpalette:kmpalette-core", version.ref = "kmpalette" } kmpalette-network = { module = "com.kmpalette:extensions-network", version.ref = "kmpalette" } materialkolor = { module = "com.materialkolor:material-kolor", version.ref = "materialkolor" } diff --git a/iosApp/SimpMusic.xcodeproj/project.pbxproj b/iosApp/SimpMusic.xcodeproj/project.pbxproj new file mode 100644 index 0000000000..9ea313e62a --- /dev/null +++ b/iosApp/SimpMusic.xcodeproj/project.pbxproj @@ -0,0 +1,26 @@ +// !$*UTF8*$! +{ archiveVersion = 1; classes = {}; objectVersion = 56; objects = { +000000000000000000000016 = { isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; +000000000000000000000017 = { isa = PBXBuildFile; fileRef = 000000000000000000000016; }; +000000000000000000000007 = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimpMusicApp.swift; sourceTree = ""; }; +000000000000000000000006 = { isa = PBXFileReference; explicitFileType = wrapper.application; path = SimpMusic.app; sourceTree = BUILT_PRODUCTS_DIR; }; +000000000000000000000009 = { isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ComposeApp.framework; path = "../composeApp/build/bin/$(KOTLIN_TARGET)/$(KOTLIN_FRAMEWORK_VARIANT)/ComposeApp.framework"; sourceTree = SOURCE_ROOT; }; +000000000000000000000008 = { isa = PBXBuildFile; fileRef = 000000000000000000000007; }; +00000000000000000000000A = { isa = PBXBuildFile; fileRef = 000000000000000000000009; }; +000000000000000000000003 = { isa = PBXGroup; path = SimpMusic; sourceTree = ""; children = (000000000000000000000007, 000000000000000000000016,); }; +000000000000000000000004 = { isa = PBXGroup; name = Products; sourceTree = ""; children = (000000000000000000000006,); }; +000000000000000000000002 = { isa = PBXGroup; sourceTree = ""; children = (000000000000000000000003, 000000000000000000000009, 000000000000000000000004,); }; +00000000000000000000000B = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (000000000000000000000008,); runOnlyForDeploymentPostprocessing = 0; }; +00000000000000000000000C = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (00000000000000000000000A,); runOnlyForDeploymentPostprocessing = 0; }; +00000000000000000000000D = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = (000000000000000000000017,); runOnlyForDeploymentPostprocessing = 0; }; +00000000000000000000000E = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; buildActionMask = 2147483647; files = (); inputPaths = (); outputPaths = (); name = "Build Kotlin framework"; runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "set -eu\nif [ \"${SKIP_KOTLIN_BUILD:-NO}\" = \"YES\" ]; then exit 0; fi\ncd \"$SRCROOT/..\"\nif [ \"$PLATFORM_NAME\" = \"iphonesimulator\" ]; then target=IosSimulatorArm64; else target=IosArm64; fi\npython3 scripts/build-ios-framework.py \":composeApp:link${CONFIGURATION}Framework${target}\"\n"; }; +00000000000000000000000F = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; buildActionMask = 2147483647; files = (); inputPaths = (); outputPaths = (); name = "Copy Compose resources"; runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "set -eu\nsource=\"$SRCROOT/../composeApp/build/generated/compose/resourceGenerator/preparedResources/commonMain/composeResources\"\ntarget=\"$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/compose-resources/composeResources/simpmusic.composeapp.generated.resources\"\nmkdir -p \"$target\"\ncp -R \"$source\"/. \"$target\"/\n"; }; +000000000000000000000005 = { isa = PBXNativeTarget; buildConfigurationList = 000000000000000000000011; buildPhases = (00000000000000000000000E, 00000000000000000000000B, 00000000000000000000000C, 00000000000000000000000D, 00000000000000000000000F,); buildRules = (); dependencies = (); name = SimpMusic; productName = SimpMusic; productReference = 000000000000000000000006; productType = "com.apple.product-type.application"; }; +000000000000000000000001 = { isa = PBXProject; attributes = { LastUpgradeCheck = 2600; }; buildConfigurationList = 000000000000000000000010; compatibilityVersion = "Xcode 14.0"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = (en, Base); mainGroup = 000000000000000000000002; productRefGroup = 000000000000000000000004; projectDirPath = ""; projectRoot = ""; targets = (000000000000000000000005,); }; +000000000000000000000010 = { isa = XCConfigurationList; buildConfigurations = (000000000000000000000012, 000000000000000000000013,); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; +000000000000000000000012 = { isa = XCBuildConfiguration; name = Debug; buildSettings = { KOTLIN_FRAMEWORK_VARIANT = debugFramework; CLANG_ENABLE_MODULES = YES; SDKROOT = iphoneos; IPHONEOS_DEPLOYMENT_TARGET = 16.0; SWIFT_VERSION = 5.0; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; DEBUG_INFORMATION_FORMAT = dwarf; }; }; +000000000000000000000013 = { isa = XCBuildConfiguration; name = Release; buildSettings = { KOTLIN_FRAMEWORK_VARIANT = releaseFramework; CLANG_ENABLE_MODULES = YES; SDKROOT = iphoneos; IPHONEOS_DEPLOYMENT_TARGET = 16.0; SWIFT_VERSION = 5.0; }; }; +000000000000000000000011 = { isa = XCConfigurationList; buildConfigurations = (000000000000000000000014, 000000000000000000000015,); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; +000000000000000000000014 = { isa = XCBuildConfiguration; name = Debug; buildSettings = { KOTLIN_FRAMEWORK_VARIANT = debugFramework; CLANG_ENABLE_MODULES = YES; SDKROOT = iphoneos; IPHONEOS_DEPLOYMENT_TARGET = 16.0; SWIFT_VERSION = 5.0; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; PRODUCT_BUNDLE_IDENTIFIER = com.maxrave.simpmusic; PRODUCT_NAME = "$(TARGET_NAME)"; INFOPLIST_FILE = SimpMusic/Info.plist; TARGETED_DEVICE_FAMILY = "1,2"; ENABLE_USER_SCRIPT_SANDBOXING = NO; CODE_SIGN_STYLE = Automatic; ARCHS = arm64; FRAMEWORK_SEARCH_PATHS = ("$(inherited)", "$(SRCROOT)/../composeApp/build/bin/$(KOTLIN_TARGET)/debugFramework"); "KOTLIN_TARGET[sdk=iphonesimulator*]" = iosSimulatorArm64; "KOTLIN_TARGET[sdk=iphoneos*]" = iosArm64; OTHER_LDFLAGS = ("$(inherited)", "-lsqlite3", "-lc++"); SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; DEBUG_INFORMATION_FORMAT = dwarf; }; }; +000000000000000000000015 = { isa = XCBuildConfiguration; name = Release; buildSettings = { KOTLIN_FRAMEWORK_VARIANT = releaseFramework; CLANG_ENABLE_MODULES = YES; SDKROOT = iphoneos; IPHONEOS_DEPLOYMENT_TARGET = 16.0; SWIFT_VERSION = 5.0; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; PRODUCT_BUNDLE_IDENTIFIER = com.maxrave.simpmusic; PRODUCT_NAME = "$(TARGET_NAME)"; INFOPLIST_FILE = SimpMusic/Info.plist; TARGETED_DEVICE_FAMILY = "1,2"; ENABLE_USER_SCRIPT_SANDBOXING = NO; CODE_SIGN_STYLE = Automatic; ARCHS = arm64; FRAMEWORK_SEARCH_PATHS = ("$(inherited)", "$(SRCROOT)/../composeApp/build/bin/$(KOTLIN_TARGET)/releaseFramework"); "KOTLIN_TARGET[sdk=iphonesimulator*]" = iosSimulatorArm64; "KOTLIN_TARGET[sdk=iphoneos*]" = iosArm64; OTHER_LDFLAGS = ("$(inherited)", "-lsqlite3", "-lc++"); }; }; +}; rootObject = 000000000000000000000001; } diff --git a/iosApp/SimpMusic.xcodeproj/xcshareddata/xcschemes/SimpMusic.xcscheme b/iosApp/SimpMusic.xcodeproj/xcshareddata/xcschemes/SimpMusic.xcscheme new file mode 100644 index 0000000000..a9b0cbd50a --- /dev/null +++ b/iosApp/SimpMusic.xcodeproj/xcshareddata/xcschemes/SimpMusic.xcscheme @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/iosApp/SimpMusic/Assets.xcassets/AppIcon.appiconset/AppIcon.png b/iosApp/SimpMusic/Assets.xcassets/AppIcon.appiconset/AppIcon.png new file mode 100644 index 0000000000..b9c6728f36 Binary files /dev/null and b/iosApp/SimpMusic/Assets.xcassets/AppIcon.appiconset/AppIcon.png differ diff --git a/iosApp/SimpMusic/Assets.xcassets/AppIcon.appiconset/Contents.json b/iosApp/SimpMusic/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000000..0a42994e64 --- /dev/null +++ b/iosApp/SimpMusic/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1 @@ +{"images":[{"filename":"AppIcon.png","idiom":"universal","platform":"ios","size":"1024x1024"}],"info":{"author":"xcode","version":1}} diff --git a/iosApp/SimpMusic/Assets.xcassets/Contents.json b/iosApp/SimpMusic/Assets.xcassets/Contents.json new file mode 100644 index 0000000000..f223229d3b --- /dev/null +++ b/iosApp/SimpMusic/Assets.xcassets/Contents.json @@ -0,0 +1 @@ +{"info":{"author":"xcode","version":1}} diff --git a/iosApp/SimpMusic/Info.plist b/iosApp/SimpMusic/Info.plist new file mode 100644 index 0000000000..0f40ace5ae --- /dev/null +++ b/iosApp/SimpMusic/Info.plist @@ -0,0 +1,22 @@ + + + +CFBundleDisplayNameSimpMusic +CFBundleExecutable$(EXECUTABLE_NAME) +CFBundleIdentifier$(PRODUCT_BUNDLE_IDENTIFIER) +CFBundleName$(PRODUCT_NAME) +CFBundlePackageTypeAPPL +CFBundleShortVersionString1.0 +CFBundleVersion1 +CFBundleURLTypesCFBundleURLSchemessimpmusicwordbyword +LSRequiresIPhoneOS +UIApplicationSceneManifestUIApplicationSupportsMultipleScenes +CADisableMinimumFrameDurationOnPhone +UILaunchScreen +UIBackgroundModesaudio +NSPhotoLibraryAddUsageDescriptionSave track artwork and lyric images to your photo library. +NSPhotoLibraryUsageDescriptionChoose artwork for your playlists. +NSLocalNetworkUsageDescriptionConnect to music services on your local network. +UISupportedInterfaceOrientationsUIInterfaceOrientationPortraitUIInterfaceOrientationLandscapeLeftUIInterfaceOrientationLandscapeRight +UISupportedInterfaceOrientations~ipadUIInterfaceOrientationPortraitUIInterfaceOrientationPortraitUpsideDownUIInterfaceOrientationLandscapeLeftUIInterfaceOrientationLandscapeRight + diff --git a/iosApp/SimpMusic/SimpMusicApp.swift b/iosApp/SimpMusic/SimpMusicApp.swift new file mode 100644 index 0000000000..b4b3ee951d --- /dev/null +++ b/iosApp/SimpMusic/SimpMusicApp.swift @@ -0,0 +1,26 @@ +import SwiftUI +import ComposeApp + +@main +struct SimpMusicApp: App { + var body: some Scene { + WindowGroup { + ComposeRoot().ignoresSafeArea() + .onOpenURL { IosDeepLinksKt.handleIosUrl(url: $0.absoluteString) } + } + } +} + +struct ComposeRoot: UIViewControllerRepresentable { + func makeUIViewController(context: Context) -> UIViewController { + let controller = MainViewControllerKt.MainViewController() + #if DEBUG + let arguments = ProcessInfo.processInfo.arguments + if let index = arguments.firstIndex(of: "--playback-smoke-test"), index + 1 < arguments.count { + IosPlaybackSmokeTestKt.startIosPlaybackSmokeTest(url: arguments[index + 1]) + } + #endif + return controller + } + func updateUIViewController(_ controller: UIViewController, context: Context) {} +} diff --git a/scripts/build-ios-framework.py b/scripts/build-ios-framework.py new file mode 100644 index 0000000000..002f304061 --- /dev/null +++ b/scripts/build-ios-framework.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""Build the opt-in iOS framework using the installed JDK 21, restoring daemon criteria.""" +import os +import fcntl +from pathlib import Path +import subprocess +import sys + +root = Path(__file__).resolve().parents[1] +criteria = root / "gradle/gradle-daemon-jvm.properties" +# Xcode and CLI builds share the daemon criteria; serialize this temporary override. +lock_path = root / ".gradle/ios-build.lock" +lock_path.parent.mkdir(parents=True, exist_ok=True) +lock = lock_path.open("w") +fcntl.flock(lock, fcntl.LOCK_EX) +original = criteria.read_bytes() +env = os.environ.copy() +if not env.get("JAVA_HOME"): + bundled = Path("/Applications/Android Studio.app/Contents/jbr/Contents/Home") + if bundled.exists(): + env["JAVA_HOME"] = str(bundled) +tasks = sys.argv[1:] or [":composeApp:linkDebugFrameworkIosSimulatorArm64"] +try: + # The repository pins a vendor that may not be installed; use any local JDK 21. + criteria.write_text("toolchainVersion=21\n") + result = subprocess.run( + [str(root / "gradlew"), "-PenableIos=true", *tasks, + "--no-configuration-cache", "--console=plain"], cwd=root, env=env, + ) +finally: + criteria.write_bytes(original) +sys.exit(result.returncode) diff --git a/scripts/verify-ios-playback.py b/scripts/verify-ios-playback.py new file mode 100644 index 0000000000..332a779060 --- /dev/null +++ b/scripts/verify-ios-playback.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""Exercise the Debug iOS application's real AVPlayer and queue on a booted simulator.""" +import argparse +import json +import math +from pathlib import Path +import struct +import subprocess +import sys +import time +import wave + +parser = argparse.ArgumentParser() +parser.add_argument("--device", help="Simulator UDID; defaults to the first booted device") +parser.add_argument("--url", help="Optional remote audio URL; otherwise generate a quiet WAV fixture") +args = parser.parse_args() + +def simctl(*arguments): + return subprocess.check_output(["xcrun", "simctl", *arguments], text=True).strip() + +if not args.device: + inventory = json.loads(simctl("list", "devices", "booted", "--json")) + args.device = next((device["udid"] for devices in inventory["devices"].values() + for device in devices if device["state"] == "Booted"), None) +if not args.device: + parser.error("Boot an iOS simulator first") +container = Path(simctl("get_app_container", args.device, "com.maxrave.simpmusic", "data")) +report = container / "Documents/SimpMusic/ios-playback-smoke.txt" +report.unlink(missing_ok=True) +url = args.url +if not url: + fixture = container / "Documents/ios-playback-fixture.wav" + with wave.open(str(fixture), "wb") as audio: + audio.setparams((1, 2, 22050, 0, "NONE", "not compressed")) + audio.writeframes(b"".join(struct.pack("