Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .github/workflows/windows-portable.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,26 @@ jobs:
- name: Test and package portable Windows app
shell: pwsh
run: ./scripts/build-windows.ps1 -JavaHome $env:JAVA_HOME
- name: Check packaged version file
shell: pwsh
run: |
Add-Type -AssemblyName System.IO.Compression.FileSystem
$zip = Get-ChildItem release/*-Windows-Portable-x64.zip | Select-Object -First 1
$archive = [IO.Compression.ZipFile]::OpenRead($zip.FullName)
try {
function Read-Entry($name) {
$entry = $archive.GetEntry($name)
if (!$entry) { throw "Missing archive entry: $name" }
$reader = [IO.StreamReader]::new($entry.Open())
try { return $reader.ReadToEnd() } finally { $reader.Dispose() }
}
$version = (Read-Entry 'KittyTune/version.txt').Trim()
$config = Read-Entry 'KittyTune/app/KittyTune.cfg'
$match = [regex]::Match($config, '(?m)^java-options=-Djpackage\.app-version=(.+)')
if (!$match.Success -or $version -ne $match.Groups[1].Value.Trim()) {
throw 'version.txt does not match the packaged launcher'
}
} finally { $archive.Dispose() }
- name: Test transparent window renderer fallback
shell: pwsh
run: ./gradlew.bat :test --tests '*TransparentWindowRenderingTest' -PdesktopOnly=true --console=plain
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ kotlin-js-store/
*.py
!scripts/check-linux-dbus.py
*.ps1
!src/main/resources/updater/*.ps1
!scripts/build-smtc-bridge.ps1
!scripts/build-native-windows.ps1
!scripts/build-windows.ps1
Expand Down
22 changes: 19 additions & 3 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -909,8 +909,24 @@ val enableSegmentHeap = tasks.register<EnableSegmentHeapTask>("enableSegmentHeap
mustRunAfter(stripForeignNativesDistributable, stripForeignNativesDistributableMain)
}

tasks.matching { it.name in listOf("createDistributable", "createReleaseDistributable") }.configureEach {
if (desktopIsWindows) finalizedBy(enableSegmentHeap)
tasks.withType<org.jetbrains.compose.desktop.application.tasks.AbstractJPackageTask>().configureEach {
if (desktopIsWindows && name in listOf("createDistributable", "createReleaseDistributable")) {
finalizedBy(enableSegmentHeap)
val packagedVersion = project.version.toString()
inputs.property("readableVersion", packagedVersion)
doLast {
destinationDir.get().asFile.resolve("KittyTune/version.txt").writeText("$packagedVersion\n", Charsets.UTF_8)
}
}
}

tasks.withType<org.jetbrains.compose.desktop.application.tasks.AbstractJPackageTask>().configureEach {
if (desktopIsWindows && name in listOf("packageMsi", "packageReleaseMsi")) {
val imageName = if (name == "packageReleaseMsi") "createReleaseDistributable" else "createDistributable"
val image = tasks.named<org.jetbrains.compose.desktop.application.tasks.AbstractJPackageTask>(imageName)
dependsOn(image)
appImage.set(image.flatMap { it.destinationDir.dir("KittyTune") })
}
}

tasks.matching { it.name == "zipWindowsPortable" || (it.name.startsWith("package") && it.name.endsWith("Msi")) }.configureEach {
Expand Down Expand Up @@ -990,7 +1006,7 @@ tasks.register<Test>("headlessTest") {
"PlayerRemainingTimeTest", "PlaylistTotalDurationTest", "SettingsSearchTest",
"VolumeCurveTest", "TrackTrimTest", "TrimTimeParseTest", "SyncMergeTest", "DownloadJobsTest", "DownloadFilesTest", "LyricsMergePerformanceTest", "*LyricsMatcherTest",
"WindowBoundsRestorationTest", "TextFieldShortcutGuardTest", "PaletteCacheTest", "PeakLimiterTest", "*FadingEdgeRenderTest",
"WindowsNativeDspTest", "AudioLineCloserTest", "PlaybackDrmSessionTest", "*HlsRetirementTest", "*SoundCloudDrmPipelineTest", "DesktopRenderTest", "DesktopDensityTest",
"*WindowsUpdateTest", "WindowsNativeDspTest", "AudioLineCloserTest", "PlaybackDrmSessionTest", "*HlsRetirementTest", "*SoundCloudDrmPipelineTest", "DesktopRenderTest", "DesktopDensityTest",
"ConnectNetworkStateTest", "ConnectRefactorTest", "SyncPlaybackTest", "ConnectWireTest",
"ConnectSocketListenerTest", "ConnectHandoffTest", "ConnectLanServerTest", "ConnectRenderTest", "LocalizationParityTest",
"PlayerButtonRowsTest", "PlayheadClockTest", "WheelSeekTest", "PlayingBarsTest", "*WslSidecarSetupTest", "*WslUninstallRenderTest", "*ProtectedTracksNoticeTest", "*ProtectedTracksCardsRenderTest", "*MixQueuePlannerTest", "*MixRenderTest", "*AudioPathRenderTest", "*LyricsSweepRenderTest", "*ShareCardTest",
Expand Down
105 changes: 66 additions & 39 deletions src/main/kotlin/com/alananasss/kittytune/data/UpdateManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -506,13 +506,13 @@ object UpdateManager {
}

internal fun resolveKittyTuneExe(): File? {
val jpackagePath = System.getProperty("jpackage.app.path")
val possibleExePaths = mutableListOf<File>()
jpackagePath?.let { p ->
val f = File(p)
if (f.isFile) possibleExePaths.add(f)
else if (f.isDirectory) File(f, "KittyTune.exe").let { if (it.exists()) possibleExePaths.add(it) }
val jpackagePath = System.getProperty("jpackage.app-path") ?: System.getProperty("jpackage.app.path")
if (jpackagePath != null) {
val path = File(jpackagePath)
val launcher = if (path.isDirectory) File(path, "KittyTune.exe") else path
return launcher.takeIf { it.isAbsolute && it.isFile && it.name.equals("KittyTune.exe", ignoreCase = true) }
}
val possibleExePaths = mutableListOf<File>()
possibleExePaths.addAll(listOfNotNull(
File(System.getenv("LOCALAPPDATA") ?: "", "KittyTune/KittyTune.exe"),
File(System.getenv("LOCALAPPDATA") ?: "", "Programs/KittyTune/KittyTune.exe"),
Expand All @@ -534,36 +534,40 @@ object UpdateManager {
val escapedLog = logFile.absolutePath.replace("'", "''")
val escapedMsiLog = msiLogFile.absolutePath.replace("'", "''")
val isMsi = installerFile.name.endsWith(".msi", ignoreCase = true)
val expectedVersion = releaseInfo?.versionName.orEmpty().replace("'", "''")
val support = requireNotNull(javaClass.getResourceAsStream("/updater/windows-install-support.ps1")).use {
it.bufferedReader(Charsets.UTF_8).readText()
}

val installCmd = if (isMsi) {
"""
Log "Executing msiexec..."
${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', '/qn', '/norestart', 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru -WindowStyle Hidden
${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', '/qn', 'REINSTALLMODE=amus', ('INSTALLDIR="{0}"' -f ${'$'}installDir), '/norestart', 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru -WindowStyle Hidden
Log "msiexec silent install finished with exit code ${'$'}(${'$'}p.ExitCode)"

# Fallback 1: If exit code 1638 (same version already installed), retry with REINSTALL=ALL
if (${'$'}p.ExitCode -eq 1638) {
Log "Detected exit code 1638 (same version). Retrying silent reinstall..."
${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', 'REINSTALL=ALL', 'REINSTALLMODE=amus', '/qn', '/norestart', 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru -WindowStyle Hidden
${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', 'REINSTALL=ALL', '/qn', 'REINSTALLMODE=amus', ('INSTALLDIR="{0}"' -f ${'$'}installDir), '/norestart', 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru -WindowStyle Hidden
Log "msiexec silent reinstall finished with exit code ${'$'}(${'$'}p.ExitCode)"
}

# Fallback 2: If silent install failed (e.g. 1603 due to UAC elevation required), retry with basic UI (/qb)
if (${'$'}p.ExitCode -ne 0) {
if (${'$'}p.ExitCode -notin @(0, 3010, 1641)) {
Log "Silent install failed (${'$'}(${'$'}p.ExitCode)). Retrying with basic UI (/qb)..."
${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', '/qb', '/norestart', 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru
${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', '/qb', 'REINSTALLMODE=amus', ('INSTALLDIR="{0}"' -f ${'$'}installDir), '/norestart', 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru
Log "msiexec basic UI install finished with exit code ${'$'}(${'$'}p.ExitCode)"
if (${'$'}p.ExitCode -eq 1638) {
Log "Retrying basic UI install with REINSTALL=ALL..."
${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', 'REINSTALL=ALL', 'REINSTALLMODE=amus', '/qb', '/norestart', 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru
${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', 'REINSTALL=ALL', '/qb', 'REINSTALLMODE=amus', ('INSTALLDIR="{0}"' -f ${'$'}installDir), '/norestart', 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru
Log "msiexec basic UI reinstall finished with exit code ${'$'}(${'$'}p.ExitCode)"
}
}

# Fallback 3: Full interactive wizard if basic UI still failed
if (${'$'}p.ExitCode -ne 0) {
if (${'$'}p.ExitCode -notin @(0, 3010, 1641)) {
Log "Basic UI install failed (${'$'}(${'$'}p.ExitCode)). Retrying with interactive installer..."
${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', '/norestart', '/l*v', '"$escapedMsiLog"') -Wait -PassThru
${'$'}p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', '"$escapedInstaller"', '/norestart', 'REINSTALLMODE=amus', ('INSTALLDIR="{0}"' -f ${'$'}installDir), 'MSIINSTALLPERUSER=1', 'ALLUSERS=2', 'REBOOT=ReallySuppress', '/l*v', '"$escapedMsiLog"') -Wait -PassThru
Log "msiexec interactive install finished with exit code ${'$'}(${'$'}p.ExitCode)"
}
""".trimIndent()
Expand All @@ -572,7 +576,7 @@ object UpdateManager {
Log "Executing setup executable..."
${'$'}p = Start-Process -FilePath '$escapedInstaller' -ArgumentList @('/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/SP-') -Wait -PassThru -WindowStyle Hidden
Log "Setup finished with exit code ${'$'}(${'$'}p.ExitCode)"
if (${'$'}p.ExitCode -ne 0) {
if (${'$'}p.ExitCode -notin @(0, 3010, 1641)) {
Log "Silent setup failed (${'$'}(${'$'}p.ExitCode)). Retrying with interactive installer..."
${'$'}p = Start-Process -FilePath '$escapedInstaller' -Wait -PassThru
Log "Interactive setup finished with exit code ${'$'}(${'$'}p.ExitCode)"
Expand All @@ -582,13 +586,31 @@ object UpdateManager {

return """
# KittyTune Windows Auto-Updater Script
${'$'}ErrorActionPreference = 'Stop'
$support
${'$'}exePath = '$escapedTargetExe'
${'$'}logFile = '$escapedLog'
function Log(${'$'}msg) {
${'$'}ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
"[${'$'}ts] ${'$'}msg" | Out-File -FilePath ${'$'}logFile -Append -Encoding utf8
"[${'$'}ts] ${'$'}msg" | Out-File -LiteralPath ${'$'}logFile -Append -Encoding utf8
}

Log "Starting updater for PID $targetPid"
try {
if (![IO.File]::Exists(${'$'}exePath)) { throw 'Cannot determine the running KittyTune installation.' }
${'$'}installDir = [IO.Path]::GetDirectoryName(${'$'}exePath)
${'$'}expectedVersion = '$expectedVersion'
if (![string]::IsNullOrWhiteSpace(${'$'}expectedVersion)) {
${'$'}expectedKey = Get-KittyTuneVersionKey ${'$'}expectedVersion
} else {
${'$'}expectedVersion = Get-KittyTuneMsiVersion '$escapedInstaller'
${'$'}expectedKey = Get-KittyTuneVersionKey ${'$'}expectedVersion
}
${if (isMsi) "Assert-KittyTuneMsiTarget '$escapedInstaller' ${'$'}installDir" else ""}
} catch {
Log "Cannot start update: ${'$'}(${'$'}_.Exception.Message)"
throw
}
${'$'}targetPid = $targetPid
try {
${'$'}proc = Get-Process -Id ${'$'}targetPid -ErrorAction Stop
Expand All @@ -598,8 +620,11 @@ object UpdateManager {
Log "Process ${'$'}targetPid is not running or already exited."
}

Log "Ensuring all KittyTune processes are stopped..."
${'$'}procs = Get-Process -Name "KittyTune", "kittytune", "WindowsSmtcBridge" -ErrorAction SilentlyContinue
Log "Stopping processes for ${'$'}exePath..."
${'$'}procs = Get-Process -Name "KittyTune", "WindowsSmtcBridge" -ErrorAction SilentlyContinue | Where-Object {
try { [IO.Path]::GetFullPath(${'$'}_.Path).Equals(${'$'}exePath,[StringComparison]::OrdinalIgnoreCase) }
catch { ${'$'}false }
}
if (${'$'}procs) {
${'$'}procs | Stop-Process -Force -ErrorAction SilentlyContinue
${'$'}procs | ForEach-Object {
Expand All @@ -608,29 +633,27 @@ object UpdateManager {
}
Start-Sleep -Seconds 2

$installCmd

${'$'}exePath = '$escapedTargetExe'
if (-not (Test-Path -Path ${'$'}exePath)) {
${'$'}candidates = @(
"${'$'}env:LOCALAPPDATA\KittyTune\KittyTune.exe",
"${'$'}env:LOCALAPPDATA\Programs\KittyTune\KittyTune.exe",
"${'$'}env:ProgramFiles\KittyTune\KittyTune.exe",
"${'$'}{env:ProgramFiles(x86)}\KittyTune\KittyTune.exe"
)
foreach (${'$'}c in ${'$'}candidates) {
if (Test-Path -Path ${'$'}c) {
${'$'}exePath = ${'$'}c
break
}
${'$'}shortcuts = @(Save-KittyTuneShortcuts -Executable ${'$'}exePath)
${'$'}installed = ${'$'}false
try {
$installCmd
if (${'$'}p.ExitCode -notin @(0, 3010, 1641)) { throw "Installer failed with exit code ${'$'}(${'$'}p.ExitCode)." }
if (${'$'}p.ExitCode -in @(3010, 1641)) { Log 'Update installed; Windows restart is required before relaunch.'; return }
${'$'}actualVersion = Get-KittyTuneVersion ${'$'}exePath
if ((Get-KittyTuneVersionKey ${'$'}actualVersion) -ne ${'$'}expectedKey) {
throw "Expected version ${'$'}expectedVersion at ${'$'}exePath, found ${'$'}actualVersion."
}
}

if (Test-Path -Path ${'$'}exePath) {
Log "Relaunching KittyTune from ${'$'}exePath"
try {
[IO.File]::WriteAllText((Join-Path ${'$'}installDir 'version.txt'), ${'$'}actualVersion + [Environment]::NewLine)
} catch { Log "Could not refresh version.txt: ${'$'}(${'$'}_.Exception.Message)" }
${'$'}installed = ${'$'}true
} catch {
Log "Update failed: ${'$'}(${'$'}_.Exception.Message)"
throw
} finally { Restore-KittyTuneShortcuts -Snapshot ${'$'}shortcuts }
if (${'$'}installed) {
Log "Relaunching verified version ${'$'}actualVersion from ${'$'}exePath"
Start-Process -FilePath ${'$'}exePath
} else {
Log "Could not find KittyTune.exe to relaunch"
}
Log "Updater script finished."
""".trimIndent()
Expand All @@ -647,6 +670,10 @@ object UpdateManager {
if (installer != null && installer.exists()) {
val currentPid = runCatching { ProcessHandle.current().pid() }.getOrDefault(0L)
val targetExe = resolveKittyTuneExe()
if (targetExe == null) {
_status.value = UpdateStatus.ERROR
return
}
val tmpDir = File(System.getProperty("java.io.tmpdir"), "KittyTuneUpdates")
tmpDir.mkdirs()
val scriptFile = File(tmpDir, "update_install_${System.currentTimeMillis()}.ps1")
Expand All @@ -659,7 +686,7 @@ object UpdateManager {
logFile = logFile,
msiLogFile = msiLogFile
)
scriptFile.writeText(scriptContent, Charsets.UTF_8)
scriptFile.writeBytes(byteArrayOf(0xEF.toByte(), 0xBB.toByte(), 0xBF.toByte()) + scriptContent.toByteArray(Charsets.UTF_8))

ProcessBuilder(
"powershell.exe",
Expand Down
Loading
Loading