Skip to content

Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.

C

feat: prompt to download missing languages with native sheet and Translate settings fallback (#105)

anna8eebc71cb6c6
diff --git a/docs/tweaks.md b/docs/tweaks.md
index 8e0da2ec..580cafd7 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -161,10 +161,11 @@ Shared:
shown at once and kept in memory until Spotify quits, and Automatic putting back what the order chose
LyricsTranslation/ a song's lines translated from the lyrics' corner menu, for the lines no source translated, three
ways, each its own item: on the iPhone by Apple's Translate (iOS 26, the song's language told by
- NaturalLanguage, both languages downloaded in the Translate app or the item says where to) and by Apple
+ NaturalLanguage, both languages downloaded: a missing pair brings up Apple's download sheet, and if they are
+ still missing the alert offers Open Settings) and by Apple
Intelligence's model (iOS 26 where it is on and speaks the language; permissive guardrails for changing
the user's own text, 12 lines a session, greedy and capped at 60 tokens a line, exactly one string a line by a generation schema; Translate retried once, as its first ask can fail while it loads), both in
- OnDeviceTranslation.swift, the frameworks weak linked; and by an AI translator on the user's own key, picked on the Lyrics page (SGKeyAITranslator): Gemini, an OpenAI-compatible server (chat completions; OpenAI's unless a server URL is given, such as OpenRouter's or an Ollama on the network, which Spotify's ATS allows for local addresses) or Anthropic (the Messages API). Each provider is one entry of LyricsTranslation.m's table: its Keychain slot (one key each, never in the settings, so an export never has one), its model presets (the cheapest first; OpenAI-compatible has none and needs a model), its request and its reply's reader. The answer's shape is forced where the API can (Gemini a bare array, the others {"lines": [...]} by a strict schema), the reader takes either, and a 400 that names an optional field (Gemini's thinking level, OpenAI's schema or reasoning effort, Anthropic's output_config) is asked once more without them. The prompt is shared (Vitrine's with {language} and {count}, editable in a sheet, SGKeyAIPrompt) and the provider adds its sentence on the answer's shape; the model (spotifyglass.lyrics.<id>.model), the server, Gemini's thinking level (SGKeyAIThinking: Low, Medium or High, unset low, as 3.8 Flash refuses minimal) and the request timeout (SGKeyAITimeout: 30 to 300 s, unset 120, the request's timeoutInterval) are read at each ask and checked as they are read, a new thinking level asks again, and the log names the provider, the model, the host and the prompt's SHA-256 prefix, never the key. Temperature is not offered: Anthropic's API turns it down and OpenAI's reasoning models take only the default. The menu item says where the lyrics go. Translate on iPhone and Apple Intelligence each have a switch that leaves them out of the menu (SGKeyLyricsTranslateOnDevice, SGKeyLyricsAppleIntelligence, both on). A translation that reads the same as its line (SGLyricsBareText) is not drawn under it, and the line still counts as translated. The translate items show for every song with Translate any song on (SGKeyLyricsTranslateEverySong, off), else only for a song NaturalLanguage finds in another language than the Lyrics page's (or the iPhone's): one distinct line in five it is at least 80% sure of, or two in another script (a verse in Hangul among English), not the whole song's guess (short lines sway that: Havana reads as Dutch), so songs half in English count and a repeated chorus weighs as one line; Translate on iPhone translates from the language most of those lines are in and leaves lines already in the target as they are. Apple Intelligence's lines show and are saved a batch at a time, only lines without a translation are sent, and a batch it turns down is skipped (asking again sends only those lines). Every finished translation is kept by SavedTranslations.m in Caches/Vitrine/Translations, one JSON file a song and language with each line's text to its translation under "lines" and who made it and when ("by", "model", "made"; a file from before has the lines alone and reads as Unknown), the newest 200, synced when the song's lines are shown: each line knows whether its translation was made here (SGKaraokeLine.translationMade), and a made one with nothing saved is taken off, so the Lyrics page's Saved translations row deletes them at once, posting SGLyricsTranslationsDidChangeNotification as Translate any song does for the open lyrics to sync and redraw. The translate menu names who made a saved translation and when, and for one an AI made (or no one known) offers Delete This Translation, which removes the song's file and the launch's answer for it, so asking again sends the song. Gemini's reply read and checked on the Mac
+ OnDeviceTranslation.swift (prepareLanguageDownload, openTranslateSettings), the frameworks weak linked; and by an AI translator on the user's own key, picked on the Lyrics page (SGKeyAITranslator): Gemini, an OpenAI-compatible server (chat completions; OpenAI's unless a server URL is given, such as OpenRouter's or an Ollama on the network, which Spotify's ATS allows for local addresses) or Anthropic (the Messages API). Each provider is one entry of LyricsTranslation.m's table: its Keychain slot (one key each, never in the settings, so an export never has one), its model presets (the cheapest first; OpenAI-compatible has none and needs a model), its request and its reply's reader. The answer's shape is forced where the API can (Gemini a bare array, the others {"lines": [...]} by a strict schema), the reader takes either, and a 400 that names an optional field (Gemini's thinking level, OpenAI's schema or reasoning effort, Anthropic's output_config) is asked once more without them. The prompt is shared (Vitrine's with {language} and {count}, editable in a sheet, SGKeyAIPrompt) and the provider adds its sentence on the answer's shape; the model (spotifyglass.lyrics.<id>.model), the server, Gemini's thinking level (SGKeyAIThinking: Low, Medium or High, unset low, as 3.8 Flash refuses minimal) and the request timeout (SGKeyAITimeout: 30 to 300 s, unset 120, the request's timeoutInterval) are read at each ask and checked as they are read, a new thinking level asks again, and the log names the provider, the model, the host and the prompt's SHA-256 prefix, never the key. Temperature is not offered: Anthropic's API turns it down and OpenAI's reasoning models take only the default. The menu item says where the lyrics go. Translate on iPhone and Apple Intelligence each have a switch that leaves them out of the menu (SGKeyLyricsTranslateOnDevice, SGKeyLyricsAppleIntelligence, both on). A translation that reads the same as its line (SGLyricsBareText) is not drawn under it, and the line still counts as translated. The translate items show for every song with Translate any song on (SGKeyLyricsTranslateEverySong, off), else only for a song NaturalLanguage finds in another language than the Lyrics page's (or the iPhone's): one distinct line in five it is at least 80% sure of, or two in another script (a verse in Hangul among English), not the whole song's guess (short lines sway that: Havana reads as Dutch), so songs half in English count and a repeated chorus weighs as one line; Translate on iPhone translates from the language most of those lines are in and leaves lines already in the target as they are. Apple Intelligence's lines show and are saved a batch at a time, only lines without a translation are sent, and a batch it turns down is skipped (asking again sends only those lines). Every finished translation is kept by SavedTranslations.m in Caches/Vitrine/Translations, one JSON file a song and language with each line's text to its translation under "lines" and who made it and when ("by", "model", "made"; a file from before has the lines alone and reads as Unknown), the newest 200, synced when the song's lines are shown: each line knows whether its translation was made here (SGKaraokeLine.translationMade), and a made one with nothing saved is taken off, so the Lyrics page's Saved translations row deletes them at once, posting SGLyricsTranslationsDidChangeNotification as Translate any song does for the open lyrics to sync and redraw. The translate menu names who made a saved translation and when, and for one an AI made (or no one known) offers Delete This Translation, which removes the song's file and the launch's answer for it, so asking again sends the song. Gemini's reply read and checked on the Mac
against harness/lyrics-translation/
LockScreenLyrics/ the line being sung in the system's now playing (Lock screen translation, SGKeyLockScreenTranslation,
off: a translation the line has in its place, its words timed over the line's and cut in pieces
diff --git a/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m b/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m
index 158b06d9..af5e3d48 100644
--- a/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m
+++ b/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m
@@ -2066,7 +2066,7 @@ static BOOL anyUntranslated(NSArray<SGKaraokeLine *> *lines) {
offer(@"Translate on iPhone", @"translate", @"Apple's Translate, on this iPhone",
^{ return [SGTranslationSource by:SGTranslatedOnDevice model:nil made:nil]; },
^(NSArray<SGKaraokeLine *> *lines, NSString *track, NSString *to, SGRTranslated progress, SGRTranslated done) {
- [SGOnDeviceTranslation translate:textsOf(lines) to:to done:done];
+ [SGOnDeviceTranslation translate:textsOf(lines) to:to from:weakSelf done:done];
});
}
if (intelligence) {
@@ -2112,11 +2112,22 @@ static BOOL anyUntranslated(NSArray<SGKaraokeLine *> *lines) {
}
[self offerExtras];
if (error) {
- UIAlertController *alert = [UIAlertController alertControllerWithTitle:translations ? @"Partly translated" : @"No translation"
+ BOOL needsDownload = [source.by isEqualToString:SGTranslatedOnDevice] && [error hasPrefix:@"Download "];
+ NSString *title = needsDownload ? @"Language not downloaded" : (translations ? @"Partly translated" : @"No translation");
+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:title
message:error preferredStyle:UIAlertControllerStyleAlert];
// Over the player, which is dark whatever the system's appearance.
alert.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
- [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]];
+ if (needsDownload) {
+ [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];
+ UIAlertAction *open = [UIAlertAction actionWithTitle:@"Open Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
+ [SGOnDeviceTranslation openTranslateSettings];
+ }];
+ [alert addAction:open];
+ alert.preferredAction = open;
+ } else {
+ [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]];
+ }
[SGTopController() presentViewController:alert animated:YES completion:nil];
}
});
diff --git a/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.h b/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.h
index 9c8f73dd..0371457c 100644
--- a/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.h
+++ b/tweak/Sources/Shared/LyricsTranslation/LyricsTranslation.h
@@ -81,7 +81,8 @@ NSArray<SGModRow *> *SGAITranslatorRows(void);
@interface SGOnDeviceTranslation : NSObject
@property (class, readonly) BOOL translationAvailable;
+ (BOOL)appleIntelligenceAvailable:(NSString *)languageTag;
-+ (void)translate:(NSArray<NSString *> *)lines to:(NSString *)languageTag done:(void (^)(NSArray<NSString *> *lines, NSString *error))done;
++ (void)openTranslateSettings;
++ (void)translate:(NSArray<NSString *> *)lines to:(NSString *)languageTag from:(UIView *)view done:(void (^)(NSArray<NSString *> *lines, NSString *error))done;
// Apple Intelligence works through the song a batch at a time: `progress` gets the lines so far, "" for the rest.
+ (void)translateWithAppleIntelligence:(NSArray<NSString *> *)lines to:(NSString *)languageTag song:(NSString *)song
progress:(void (^)(NSArray<NSString *> *lines))progress
diff --git a/tweak/Sources/Shared/LyricsTranslation/OnDeviceTranslation.swift b/tweak/Sources/Shared/LyricsTranslation/OnDeviceTranslation.swift
index 19afe177..c2da4763 100644
--- a/tweak/Sources/Shared/LyricsTranslation/OnDeviceTranslation.swift
+++ b/tweak/Sources/Shared/LyricsTranslation/OnDeviceTranslation.swift
@@ -4,9 +4,27 @@
import Foundation
import FoundationModels
import NaturalLanguage
+import SwiftUI
import Translation
+import UIKit
import os
+// Apple's sheet that downloads the song's languages: Translation shows it only from a SwiftUI view.
+@available(iOS 26.0, *)
+private struct SGPrepareTranslationView: View {
+ let configuration: TranslationSession.Configuration
+ let onComplete: () -> Void
+
+ var body: some View {
+ Color.clear
+ .translationTask(configuration) { session in
+ try? await session.prepareTranslation()
+ onComplete()
+ }
+ .onDisappear { onComplete() }
+ }
+}
+
@objc(SGOnDeviceTranslation)
public final class SGOnDeviceTranslation: NSObject {
private static let log = Logger(subsystem: "spotifyglass", category: "translation")
@@ -53,13 +71,67 @@ public final class SGOnDeviceTranslation: NSObject {
// MARK: Translation framework
+ // Over the player, a clear full-screen pane that the sheet is presented from, dark as SGPresentDark makes the
+ // mod's: a sheet's glass is its presentation's, which a child controller's override does not reach. The pane
+ // goes when prepareTranslation() returns or throws, or when the pane is taken away.
+ @available(iOS 26.0, *)
+ @MainActor
+ private static func prepareLanguageDownload(source: Locale.Language, target: Locale.Language, from view: UIView) async {
+ await withCheckedContinuation { continuation in
+ var finished = false
+ var controller: UIViewController?
+ // Run now, or after the transition under way: UIKit drops a present or dismiss made during one.
+ let afterTransition = { (of: UIViewController, run: @escaping () -> Void) in
+ if let transition = of.transitionCoordinator ?? of.presentedViewController?.transitionCoordinator,
+ transition.animate(alongsideTransition: nil, completion: { _ in run() }) {} else { run() }
+ }
+ let finish = {
+ guard !finished else { return }
+ finished = true
+ if let host = controller { afterTransition(host) { host.presentingViewController?.dismiss(animated: false) } }
+ controller = nil
+ continuation.resume()
+ }
+ // Chosen now, not at the tap: the menu the item was in may have gone since. Not a controller on its way out.
+ guard var top = view.window?.rootViewController else { return finish() }
+ while let next = top.presentedViewController, !next.isBeingDismissed { top = next }
+ afterTransition(top) {
+ guard top.viewIfLoaded?.window != nil, top.presentedViewController == nil else { return finish() }
+ let host = UIHostingController(rootView: SGPrepareTranslationView(configuration: .init(source: source, target: target), onComplete: finish))
+ controller = host
+ host.view.backgroundColor = .clear
+ host.modalPresentationStyle = .overFullScreen
+ host.overrideUserInterfaceStyle = .dark
+ host.presentationController?.overrideTraitCollection = UITraitCollection(userInterfaceStyle: .dark)
+ top.present(host, animated: false)
+ }
+ }
+ }
+
+ @objc public static func openTranslateSettings() {
+ DispatchQueue.main.async {
+ let app = UIApplication.shared
+ // Translate's page in Settings; private schemes, so it may open only Settings' top level.
+ let candidates = ["App-Prefs:TRANSLATE", "prefs:root=TRANSLATE"]
+ func tryOpen(index: Int) {
+ guard index < candidates.count, let url = URL(string: candidates[index]) else { return }
+ app.open(url, options: [:]) { success in
+ if !success {
+ tryOpen(index: index + 1)
+ }
+ }
+ }
+ tryOpen(index: 0)
+ }
+ }
+
@objc public static var translationAvailable: Bool {
if #available(iOS 26.0, *) { return true }
return false
}
// One translation per line, "" for a line with no words; or nil and why not.
- @objc public static func translate(_ lines: [String], to languageTag: String, done: @escaping ([String]?, String?) -> Void) {
+ @objc public static func translate(_ lines: [String], to languageTag: String, from view: UIView, done: @escaping ([String]?, String?) -> Void) {
guard #available(iOS 26.0, *) else { return finish(done, nil, "Translating on this iPhone needs iOS 26.") }
let target = Locale.Language(identifier: languageTag)
guard let source = sourceLanguage(lines, target: target) else { return finish(done, nil, "The song's language could not be told from its words.") }
@@ -69,7 +141,11 @@ public final class SGOnDeviceTranslation: NSObject {
case .unsupported:
return finish(done, nil, "Apple's Translate does not translate \(name(source)) into \(name(target)).")
case .supported:
- return finish(done, nil, "Download \(name(source)) and \(name(target)) in Settings > Apps > Translate > Languages, then try again.")
+ await prepareLanguageDownload(source: source, target: target, from: view)
+ if await LanguageAvailability().status(from: source, to: target) != .installed {
+ // SGRKaraokeView offers Open Settings for the message that starts "Download ".
+ return finish(done, nil, "Download \(name(source)) and \(name(target)) in Settings > Apps > Translate > Languages, then try again.")
+ }
case .installed:
break
@unknown default: