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

fix: cut the work hooks do on every frame, layout pass and player report (#96)

My-Name-Is-Jeff10212e451685
diff --git a/harness/album/build.sh b/harness/album/build.sh
index 79e59b70..02ba604a 100755
--- a/harness/album/build.sh
+++ b/harness/album/build.sh
@@ -21,7 +21,7 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar
"$SRC"/Redesigned/Kit/SGRGlass.m "$SRC"/Redesigned/Kit/SGRGlyph.m "$SRC"/Redesigned/Kit/SGRRestyle.m \
"$SRC"/Redesigned/Kit/SGRActionRow.m "$SRC"/Redesigned/Kit/SGRDownload.m "$SRC"/Redesigned/Kit/SGRHeaderInfo.m \
"$SRC"/Redesigned/Kit/SGRedesign.m "$SRC"/Redesigned/Album/AlbumCredits.m \
- -framework UIKit -framework QuartzCore -framework CoreGraphics -framework CoreImage -framework Foundation -framework Symbols -framework AVFoundation -framework CoreMedia \
+ -framework UIKit -framework QuartzCore -framework CoreGraphics -framework CoreImage -framework Foundation -framework Symbols -framework AVFoundation -framework CoreMedia -framework CoreText \
-o "$OUT/AlbumHarness.app/AlbumHarness"
cat > "$OUT/AlbumHarness.app/Info.plist" <<'PLIST'
diff --git a/harness/album/stubs.m b/harness/album/stubs.m
index f521c9f3..053176d2 100644
--- a/harness/album/stubs.m
+++ b/harness/album/stubs.m
@@ -17,3 +17,6 @@ NSString *SGRegisterCustomFont(void) { return nil; }
// MotionSources.m: Apple Music is on, as it is by default.
BOOL SGMotionAppleMusicOn(void) { return YES; }
+
+// Shared/AlbumQueue/AlbumQueueMenu.x: a tapped album header ⋯ records its album for the menu; no menu here.
+void SGAlbumQueueMarkSource(UIView *view) {}
diff --git a/harness/appearance-page/build.sh b/harness/appearance-page/build.sh
index 9d51a3c1..d60a15a2 100755
--- a/harness/appearance-page/build.sh
+++ b/harness/appearance-page/build.sh
@@ -12,7 +12,7 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar
"$(dirname "$0")/main.m" "$(dirname "$0")/../scene.m" "$(dirname "$0")/stubs.m" \
"$SRC"/Native/Appearance/AppearanceSettings.m "$SRC"/Redesigned/Kit/SGRAppearanceSettings.m "$SRC"/Shared/Fonts/FontImport.m \
"$SRC"/Settings/SGPage.m "$SRC"/Settings/SGPageStyle.m "$SRC"/Settings/SGModPage.m "$SRC"/Settings/SGGlowSwitch.m \
- "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
+ "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGGlass.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
-framework UIKit -framework QuartzCore -framework CoreGraphics -framework Foundation -framework CoreText -framework UniformTypeIdentifiers \
-o "$OUT/AppearancePageHarness.app/AppearancePageHarness"
diff --git a/harness/artist/stubs.m b/harness/artist/stubs.m
index 6a47b5c2..47d15556 100644
--- a/harness/artist/stubs.m
+++ b/harness/artist/stubs.m
@@ -12,3 +12,6 @@ __weak UIView *sgr_artistRoot = nil;
// Redesigned/Kit/SGRBridges.x: SGRField.m asks whether the player is opening or closing for its moving field.
BOOL SGRPlayerIsTransitioning(void) { return NO; }
void SGRObservePlayerTransition(id owner, void (^began)(id owner), void (^ended)(id owner)) {}
+
+// Shared/AlbumQueue/AlbumQueueMenu.x: a tapped album header ⋯ records its album for the menu; no menu here.
+void SGAlbumQueueMarkSource(UIView *view) {}
diff --git a/harness/audio-effects-page/build.sh b/harness/audio-effects-page/build.sh
index 563093ef..412f3fe4 100755
--- a/harness/audio-effects-page/build.sh
+++ b/harness/audio-effects-page/build.sh
@@ -15,7 +15,7 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar
"$FX"/AudioEffectsSettings.m "$FX"/AudioEffectsPage.m "$FX"/SGDSPCurveView.m "$FX"/AudioEffectsLibraryPage.m "$FX"/SGDSPFilters.m \
"$FX"/AudioEffectsPresets.m "$FX"/AudioEffectsPresetsPage.m "$FX"/AutoEq.m \
"$SRC"/Settings/SGPage.m "$SRC"/Settings/SGPageStyle.m "$SRC"/Settings/SGModPage.m "$SRC"/Settings/SGGlowSwitch.m \
- "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
+ "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGGlass.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
-framework UIKit -framework QuartzCore -framework CoreGraphics -framework UniformTypeIdentifiers -framework Accelerate -framework Foundation \
-o "$OUT/AudioEffectsPageHarness.app/AudioEffectsPageHarness"
diff --git a/harness/audio-effects/sim/main.m b/harness/audio-effects/sim/main.m
index 13ff80e7..2722091a 100644
--- a/harness/audio-effects/sim/main.m
+++ b/harness/audio-effects/sim/main.m
@@ -27,6 +27,8 @@ static const float kAmplitude = 0.25f;
return 1;
}
@end
+// Shared/Player/PlayerState.x: no state for SGSetPlayerSpeed to start the mod's clock from.
+SPTPlayerState *SGPlayerState(void) { return nil; }
static atomic_bool sg_mute;
static atomic_uint_fast64_t sg_phase;
diff --git a/harness/driver/main.m b/harness/driver/main.m
index 6eb9e772..97c1af48 100644
--- a/harness/driver/main.m
+++ b/harness/driver/main.m
@@ -59,6 +59,15 @@
static HarnessPlayer *sg_player;
id SGDiagnosticsPlayer(void) { return sg_player; }
+// The driver's speed, lossless, automix, sing and landscape commands, each saying it ran.
+static double sg_speed = 1;
+double SGPlayerSpeed(void) { return sg_speed; }
+void SGSetPlayerSpeed(double speed) { sg_speed = speed; SGLog(@"harness: speed %.2f", speed); }
+NSDictionary *SGLosslessProbe(NSString *verb, NSDictionary *p, NSString **error) { *error = @"no lossless in the harness"; return nil; }
+NSDictionary *SGAutoMixProbeCommand(NSDictionary *p, NSString **error) { *error = @"no Automix in the harness"; return nil; }
+void SGSetSingOn(BOOL on) { SGLog(@"harness: sing %d", on); }
+void SGRPlayerShowLandscape(BOOL show) { SGLog(@"harness: landscape %d", show); }
+
#pragma mark - Mod Settings
@interface HarnessSettings : UITableViewController
diff --git a/harness/haptics-page/build.sh b/harness/haptics-page/build.sh
index b1f9e8b1..a14e1097 100755
--- a/harness/haptics-page/build.sh
+++ b/harness/haptics-page/build.sh
@@ -12,7 +12,7 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar
"$(dirname "$0")/main.m" "$(dirname "$0")/stubs.m" "$(dirname "$0")/../scene.m" \
"$SRC"/Shared/Haptics/HapticsSettings.m "$SRC"/Shared/Haptics/SGVibrationsPreview.m "$SRC"/Shared/Haptics/SGFeedback.m \
"$SRC"/Settings/SGPage.m "$SRC"/Settings/SGPageStyle.m "$SRC"/Settings/SGModPage.m "$SRC"/Settings/SGGlowSwitch.m \
- "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
+ "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGGlass.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
-framework UIKit -framework QuartzCore -framework CoreGraphics -framework Foundation \
-o "$OUT/HapticsPageHarness.app/HapticsPageHarness"
diff --git a/harness/haptics/build-sim.sh b/harness/haptics/build-sim.sh
index d5781d28..26710d0a 100755
--- a/harness/haptics/build-sim.sh
+++ b/harness/haptics/build-sim.sh
@@ -28,7 +28,7 @@ SDK=$(xcrun --sdk iphonesimulator --show-sdk-path)
xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-arc -g -O1 -isysroot "$SDK" -Wno-deprecated-declarations \
$EXTRA -I"$SRC" -I"$SRC/Shared/Haptics" -I"$SRC/Shared/Player" -Isim \
sim/main.m sim/fakehaptics.m ../scene.m "$OUT/gen/MusicHaptics.m" "$OUT/gen/SpeedPitch.m" "$SRC/Shared/Player/SGTimePitch.m" "$HAPTICS/SGMusicAnalyzer.m" $SETTINGS \
- "$SRC/Core/SGRebind.m" "$SRC/Core/SGLog.m" "$SRC/Core/SGPrefs.m" "$SRC/Core/SGUIMode.m" "$SRC/Core/SGViewTree.m" "$SRC/Core/SGFlagForce.m" \
+ "$SRC/Core/SGRebind.m" "$SRC/Core/SGLog.m" "$SRC/Core/SGPrefs.m" "$SRC/Core/SGUIMode.m" "$SRC/Core/SGViewTree.m" "$SRC/Core/SGGlass.m" "$SRC/Core/SGFlagForce.m" \
-framework UIKit -framework QuartzCore -framework CoreGraphics -framework AudioToolbox -framework AVFoundation -framework Foundation \
-o "$OUT/HapticsHarness.app/HapticsHarness"
cat > "$OUT/HapticsHarness.app/Info.plist" <<'PLIST'
diff --git a/harness/haptics/sim/main.m b/harness/haptics/sim/main.m
index abe2e747..6ba5deee 100644
--- a/harness/haptics/sim/main.m
+++ b/harness/haptics/sim/main.m
@@ -27,6 +27,10 @@
#import "Shared/Haptics/Haptics.h"
#import "fakehaptics.h"
+// Shared/Player/PlayerState.x, for SpeedPitch.x's SGSetPlayerSpeed: no player state here.
+@class SPTPlayerState;
+SPTPlayerState *SGPlayerState(void) { return nil; }
+
static atomic_uint_fast64_t sg_frame;
static double sg_generatorRate;
diff --git a/harness/head-gestures/sim/build.sh b/harness/head-gestures/sim/build.sh
index 9c2a30dc..a2dca298 100755
--- a/harness/head-gestures/sim/build.sh
+++ b/harness/head-gestures/sim/build.sh
@@ -14,7 +14,7 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar
"$SRC"/Shared/HeadGestures/HeadGesturesSettings.m "$SRC"/Shared/HeadGestures/HeadGesturesTeach.m \
"$SRC"/Shared/HeadGestures/SGHeadDetector.m \
"$SRC"/Settings/SGPage.m "$SRC"/Settings/SGPageStyle.m "$SRC"/Settings/SGModPage.m "$SRC"/Settings/SGGlowSwitch.m \
- "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
+ "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGGlass.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
-framework UIKit -framework QuartzCore -framework CoreGraphics -framework Foundation -framework CoreMotion -framework AudioToolbox -framework AVFoundation \
-o "$OUT/HeadGesturesSim.app/HeadGesturesSim"
diff --git a/harness/library/build.sh b/harness/library/build.sh
index 9e4c3c31..2fda5957 100755
--- a/harness/library/build.sh
+++ b/harness/library/build.sh
@@ -18,7 +18,7 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar
"$OUT"/gen/*.m \
"$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGGlass.m \
"$SRC"/Core/SGBackdrop.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
- "$SRC"/Redesigned/Kit/SGRTokens.m "$SRC"/Redesigned/Kit/SGRPalette.m "$SRC"/Redesigned/Kit/SGRField.m "$SRC"/Redesigned/Kit/SGRFlow.m \
+ "$SRC"/Redesigned/Kit/SGRTokens.m "$SRC"/Redesigned/Kit/SGRPalette.m "$SRC"/Redesigned/Kit/SGRField.m "$SRC"/Redesigned/Kit/SGRFlow.m "$SRC"/Redesigned/Kit/SGRFluid.m \
"$SRC"/Redesigned/Kit/SGRGlass.m "$SRC"/Redesigned/Kit/SGRGlyph.m "$SRC"/Redesigned/Kit/SGRRestyle.m \
"$SRC"/Redesigned/Kit/SGRActionRow.m "$SRC"/Redesigned/Kit/SGRDownload.m "$SRC"/Redesigned/Kit/SGRHeaderInfo.m \
"$SRC"/Redesigned/Kit/SGRedesign.m \
diff --git a/harness/library/stubs.m b/harness/library/stubs.m
index 6a47b5c2..47d15556 100644
--- a/harness/library/stubs.m
+++ b/harness/library/stubs.m
@@ -12,3 +12,6 @@ __weak UIView *sgr_artistRoot = nil;
// Redesigned/Kit/SGRBridges.x: SGRField.m asks whether the player is opening or closing for its moving field.
BOOL SGRPlayerIsTransitioning(void) { return NO; }
void SGRObservePlayerTransition(id owner, void (^began)(id owner), void (^ended)(id owner)) {}
+
+// Shared/AlbumQueue/AlbumQueueMenu.x: a tapped album header ⋯ records its album for the menu; no menu here.
+void SGAlbumQueueMarkSource(UIView *view) {}
diff --git a/harness/listening-stats/build-sim.sh b/harness/listening-stats/build-sim.sh
index 196fe7af..45a67291 100755
--- a/harness/listening-stats/build-sim.sh
+++ b/harness/listening-stats/build-sim.sh
@@ -13,7 +13,7 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar
"$(dirname "$0")/sim/main.m" "$(dirname "$0")/sim/stubs.m" "$(dirname "$0")/../scene.m" "$OUT/gen/ListeningStats.m" \
"$SRC"/Shared/ListeningStats/ListeningStatsPage.m "$SRC"/Shared/ListeningStats/SGPlayLog.m \
"$SRC"/Settings/SGPage.m "$SRC"/Settings/SGPageStyle.m "$SRC"/Settings/SGModPage.m "$SRC"/Settings/SGGlowSwitch.m \
- "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
+ "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGGlass.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
-framework UIKit -framework QuartzCore -framework CoreGraphics -framework Foundation -framework UniformTypeIdentifiers \
-o "$OUT/ListeningStatsHarness.app/ListeningStatsHarness"
diff --git a/harness/live-activity-page/build.sh b/harness/live-activity-page/build.sh
index 0ab2ac13..4800f026 100755
--- a/harness/live-activity-page/build.sh
+++ b/harness/live-activity-page/build.sh
@@ -12,7 +12,7 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar
"$(dirname "$0")/main.m" "$(dirname "$0")/stubs.m" "$(dirname "$0")/../scene.m" \
"$SRC"/Shared/LiveActivity/LiveActivitySettings.m "$SRC"/Shared/LiveActivity/SGLiveActivityPreview.m \
"$SRC"/Settings/SGPage.m "$SRC"/Settings/SGPageStyle.m "$SRC"/Settings/SGModPage.m "$SRC"/Settings/SGGlowSwitch.m \
- "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
+ "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGGlass.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
-framework UIKit -framework QuartzCore -framework CoreGraphics -framework Foundation \
-o "$OUT/LiveActivityPageHarness.app/LiveActivityPageHarness"
diff --git a/harness/lyrics-page/build.sh b/harness/lyrics-page/build.sh
index f0dcf0cf..7792b161 100755
--- a/harness/lyrics-page/build.sh
+++ b/harness/lyrics-page/build.sh
@@ -14,7 +14,7 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar
"$HERE/main.m" "$HERE/../scene.m" "$HERE/../lyrics/stubs.m" "$HERE/../sing/button/sing-stubs.m" \
"$SRC"/Redesigned/Lyrics/LyricsLookSettings.m "$SRC"/Redesigned/Lyrics/LyricsLook.m \
"$SRC"/Redesigned/Lyrics/SGRKaraokeView.m "$SRC"/Redesigned/Lyrics/LyricsText.m "$SRC"/Redesigned/Lyrics/SGRSingButton.m \
- "$SRC"/Redesigned/Lyrics/MeaningSheet.m "$SRC"/Shared/LyricsMeanings/Meanings.m "$SRC"/Shared/LyricsSources/SongMatch.m \
+ "$SRC"/Redesigned/Lyrics/MeaningSheet.m "$SRC"/Shared/LyricsMeanings/Meanings.m "$SRC"/Shared/LyricsSources/SongMatch.m "$SRC"/Shared/LyricsSources/SGTTML.m \
"$SRC"/Shared/Lyrics/KaraokeTiming.m "$SRC"/Shared/Lyrics/Romanise.m "$SRC"/Shared/AdBlock/Protobuf.m \
"$SRC"/Redesigned/Kit/SGRTokens.m "$SRC"/Redesigned/Kit/SGRGlass.m \
"$SRC"/Settings/SGPage.m "$SRC"/Settings/SGPageStyle.m "$SRC"/Settings/SGModPage.m "$SRC"/Settings/SGGlowSwitch.m \
diff --git a/harness/lyrics/stubs.m b/harness/lyrics/stubs.m
index cb78fc3e..51e29fb1 100644
--- a/harness/lyrics/stubs.m
+++ b/harness/lyrics/stubs.m
@@ -149,6 +149,7 @@ NSString *SGKaraokePlayingTrack(void) { return @"harness"; }
NSArray<SGKaraokeLine *> *SGKaraokeLinesForTrack(NSString *trackID) { return sg_lines; }
void SGKaraokeKeepLines(NSString *trackID, NSArray<SGKaraokeLine *> *lines) { sg_lines = lines; }
+void SGAddPlayerStateObserver(id observer) {}
NSInteger SGKaraokeDelayMs(void) { return [NSUserDefaults.standardUserDefaults integerForKey:SGKeyLyricsDelay]; }
NSInteger SGKaraokePositionMs(void) {
diff --git a/harness/menu/build.sh b/harness/menu/build.sh
index e35733e8..0f55e5a8 100755
--- a/harness/menu/build.sh
+++ b/harness/menu/build.sh
@@ -13,7 +13,7 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar
-I"$SRC" -I"$SRC/Shared/Player" -isysroot "$SDK" -Wno-deprecated-declarations \
"$(dirname "$0")/main.m" "$OUT"/gen/*.m \
"$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGGlass.m \
- "$SRC"/Core/SGBackdrop.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
+ "$SRC"/Core/SGBackdrop.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m "$SRC"/Settings/SGPageStyle.m \
-framework UIKit -framework QuartzCore -framework CoreGraphics -framework CoreImage -framework Foundation \
-o "$OUT/MenuHarness.app/MenuHarness"
diff --git a/harness/mod-settings/build.sh b/harness/mod-settings/build.sh
index 7da28c50..456af5c7 100755
--- a/harness/mod-settings/build.sh
+++ b/harness/mod-settings/build.sh
@@ -13,7 +13,7 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar
"$(dirname "$0")/main.m" "$(dirname "$0")/../scene.m" "$(dirname "$0")/stubs.m" \
"$OUT"/gen/ModSettings.m "$SRC"/App/Pages.m "$SRC"/App/About/Signing.m "$SRC"/Shared/AnimatedArtwork/AnimatedArtworkSettings.m \
"$SRC"/Settings/SGPage.m "$SRC"/Settings/SGPageStyle.m "$SRC"/Settings/SGModPage.m "$SRC"/Settings/SGGlowSwitch.m \
- "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
+ "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGGlass.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
-framework UIKit -framework QuartzCore -framework CoreGraphics -framework Foundation \
-o "$OUT/ModSettingsHarness.app/ModSettingsHarness"
diff --git a/harness/mod-settings/stubs.m b/harness/mod-settings/stubs.m
index 2e7213e2..12c0805c 100644
--- a/harness/mod-settings/stubs.m
+++ b/harness/mod-settings/stubs.m
@@ -15,7 +15,7 @@ PAGE(SGAboutPage) PAGE(SGAdsSettingsPage) PAGE(SGAllFlagsPage) PAGE(SGArtistBloc
PAGE(SGGesturesSettingsPage) PAGE(SGHeadGesturesSettingsPage) PAGE(SGHomeSettingsPage) PAGE(SGLabsPage)
PAGE(SGListeningStatsPage) PAGE(SGLiveActivitySettingsPage) PAGE(SGLockScreenWidgetPage) PAGE(SGNavbarSettingsPage)
PAGE(SGNowPlayingBarSettingsPage) PAGE(SGQueueSettingsPage) PAGE(SGRAlbumSettingsPage) PAGE(SGRArtistSettingsPage)
-PAGE(SGRNavbarSettingsPage)
+PAGE(SGRNavbarSettingsPage) PAGE(SGRHomeSettingsPage)
PAGE(SGSingSettingsPage) PAGE(SGSpatialVoiceSettingsPage) PAGE(SGVibrationsSettingsPage)
UIViewController *SGRPlayerSettingsPage(NSArray *more) { return blank(@"SGRPlayerSettingsPage"); }
UIViewController *SGRLyricsSettingsPage(NSString *title, NSString *intro, NSArray<SGModSection *> *sections) { return blank(title); }
@@ -24,6 +24,8 @@ UIViewController *SGRLyricsSettingsPage(NSString *title, NSString *intro, NSArra
NSArray<SGModRow *> *SGAITranslatorRows(void) { return @[SGPageRow(@"SGAITranslatorRows", ^UIViewController *{ return nil; })]; }
ROW(SGAppIconRow) ROW(SGGlassLyricsRow) ROW(SGLockScreenLyricsRow) ROW(SGLyricsMeaningsRow)
ROW(SGLyricsTranslationLanguageRow) ROW(SGLyricsWordTimingRow) ROW(SGRLyricsTextSizesRow) ROW(SGLyricsDelayRow)
+ROW(SGSavedTranslationsRow) ROW(SGTranslateEverySongRow)
+NSArray<SGModRow *> *SGOnDeviceTranslatorRows(void) { return @[SGPageRow(@"SGOnDeviceTranslatorRows", ^UIViewController *{ return nil; })]; }
NSArray<SGModRow *> *SGAppFontRows(void) { return @[]; }
NSArray<SGModRow *> *SGNativeAppearanceRows(void) { return @[]; }
NSArray<SGModRow *> *SGRAppearanceRows(void) { return @[]; }
diff --git a/harness/morph/build.sh b/harness/morph/build.sh
index 438a52c8..2c9b0aa7 100755
--- a/harness/morph/build.sh
+++ b/harness/morph/build.sh
@@ -1,6 +1,6 @@
#!/bin/sh
set -e
-SRC=/Users/vojta/Documents/quick/custom_spotify/custom_spotify/tweak/Sources
+SRC=$(cd "$(dirname "$0")/../../tweak/Sources" && pwd)
OUT=$(dirname "$0")/build
rm -rf "$OUT"; mkdir -p "$OUT/gen" "$OUT/MorphHarness.app"
"$THEOS/bin/logos.pl" -c generator=internal "$SRC/Redesigned/Player/PlayerMorph.x" > "$OUT/gen/PlayerMorph.m"
diff --git a/harness/morph/main.m b/harness/morph/main.m
index 2ff7ae2d..ce4b15c0 100644
--- a/harness/morph/main.m
+++ b/harness/morph/main.m
@@ -26,6 +26,9 @@ CGRect SGRPlayerCoverFrameIn(UIView *host) {
return sg_cover.window ? [host convertRect:sg_cover.bounds fromView:sg_cover] : CGRectNull;
}
void SGRPlayerSetCoverHidden(BOOL hidden) { sg_cover.alpha = hidden ? 0 : 1; }
+// A playing cover at full size, and no animated artwork over it (PlayerMotion.x).
+CGFloat SGRPlayerCoverScale(void) { return 1; }
+BOOL SGRPlayerMotionShowing(void) { return NO; }
id SGRPlayerField(void) { return nil; }
UIImage *SGRNowPlayingArtwork(NSString **uri, NSString **identity) { return sg_art; }
const CGFloat SGRRadiusArtwork = 12;
diff --git a/harness/now-playing/main.m b/harness/now-playing/main.m
index 899a82b8..662f7675 100644
--- a/harness/now-playing/main.m
+++ b/harness/now-playing/main.m
@@ -61,6 +61,8 @@ id SGKaraokePlayer(void) { return sg_player; }
NSString *SGKaraokePlayingTrack(void) { return @"track"; }
NSArray<SGKaraokeLine *> *SGKaraokeLinesForTrack(NSString *trackID) { return sg_lines; }
void SGKaraokeRequestLyrics(NSString *trackID) {}
+// The lines are there from the start, so nothing is posted under it.
+NSNotificationName const SGKaraokeLinesKeptNotification = @"harness.karaokeLinesKept";
NSInteger SGKaraokeDelayMs(void) { return [NSUserDefaults.standardUserDefaults integerForKey:SGKeyLyricsDelay]; }
static SGKaraokeLine *lineOf(NSString *text, NSInteger start, NSInteger end) {
diff --git a/harness/onboarding/main.m b/harness/onboarding/main.m
index 8bef4a43..86baf71e 100644
--- a/harness/onboarding/main.m
+++ b/harness/onboarding/main.m
@@ -9,7 +9,9 @@
// version, 1.0, is not Spotify's either), whose alert follows about 5 s in
#import <UIKit/UIKit.h>
#import <dlfcn.h>
+#import <mach-o/dyld.h>
#import "App/Onboarding/Onboarding.h"
+#import "Shared/Lyrics/Lyrics.h"
#import "Core/SGPrefs.h"
static BOOL sg_old;
@@ -29,6 +31,17 @@ NSString *SGRedesignUntestedWarning(void) {
void SGShowSigningFixIfPending(void) {}
// Settings/SGModPage.m, for the Mod Settings rows, which the harness does not show.
SGModRow *SGWarningRow(NSString *title, NSString *subtitle, void (^action)(void)) { return nil; }
+// Shared/Lyrics/KaraokeSource.x's look for EeveeSpotify, by the loaded image's name alone.
+BOOL SGEeveeSpotifyInjected(void) {
+ for (uint32_t i = 0; i < _dyld_image_count(); i++) {
+ const char *image = _dyld_get_image_name(i);
+ if (image && [@(image).lastPathComponent caseInsensitiveCompare:@"EeveeSpotify.dylib"] == NSOrderedSame) return YES;
+ }
+ return NO;
+}
+// LiveActivitySettings.m and HapticsSettings.m: what the install's Info.plist says.
+BOOL SGLiveActivityAllowedByInstall(void) { return [[NSBundle.mainBundle objectForInfoDictionaryKey:@"NSSupportsLiveActivities"] boolValue]; }
+BOOL SGMusicHapticsListedByInstall(void) { return [[NSBundle.mainBundle objectForInfoDictionaryKey:@"MusicHapticsSupported"] boolValue]; }
@interface Delegate : UIResponder <UIApplicationDelegate>
@end
diff --git a/harness/player/build.sh b/harness/player/build.sh
index 86a3311d..b83be06f 100755
--- a/harness/player/build.sh
+++ b/harness/player/build.sh
@@ -6,7 +6,7 @@ OUT=${OUT:-$(dirname "$0")/build}
rm -rf "$OUT"; mkdir -p "$OUT/gen" "$OUT/PlayerHarness.app"
for f in Redesigned/Player/PlayerLyrics.x Redesigned/Player/PlayerArtwork.x Redesigned/Player/PlayerFooter.x \
- Redesigned/Player/PlayerScroll.x Redesigned/Player/PlayerField.x Redesigned/Player/PlayerMotion.x Redesigned/Player/PlayerLandscape.x Redesigned/Player/PlayerControls.x Redesigned/Player/PlayerHeader.x Redesigned/Kit/SGRBridges.x; do
+ Redesigned/Player/PlayerScroll.x Redesigned/Player/PlayerField.x Redesigned/Player/PlayerMotion.x Redesigned/Player/PlayerLandscape.x Redesigned/Player/PlayerControls.x Redesigned/Player/PlayerHeader.x Redesigned/Player/PlayerCoverAccent.x Redesigned/Kit/SGRBridges.x; do
name=$(basename "$f" .x)
"$THEOS/bin/logos.pl" -c generator=internal "$SRC/$f" > "$OUT/gen/$name.m"
done
@@ -23,10 +23,11 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar
"$SRC"/Shared/AnimatedArtwork/SGMotionFollower.m "$SRC"/Shared/AnimatedArtwork/SGMotionClip.m "$SRC"/Shared/Player/SGLastTrack.m \
"$SRC"/Redesigned/Kit/SGRGlass.m "$SRC"/Settings/SGMarquee.m "$SRC"/Redesigned/Kit/SGRGlyph.m "$SRC"/Redesigned/Kit/SGRRestyle.m \
"$SRC"/Redesigned/Kit/SGRedesign.m \
- "$SRC"/Redesigned/Player/PlayerSettings.m "$SRC"/Redesigned/Player/PlayerVisualiser.m "$SRC"/Redesigned/Player/SGRSpectrum.m "$SRC"/Redesigned/NowPlayingBar/NowPlayingBarSettings.m \
+ "$SRC"/Redesigned/Player/PlayerSettings.m "$SRC"/Redesigned/Player/PlayerVisualiser.m "$SRC"/Redesigned/Player/SGRSpectrum.m "$SRC"/Redesigned/Player/PlayerVolume.m "$SRC"/Redesigned/NowPlayingBar/NowPlayingBarSettings.m \
"$SRC"/Settings/SGPage.m "$SRC"/Settings/SGPageStyle.m "$SRC"/Settings/SGModPage.m "$SRC"/Settings/SGGlowSwitch.m \
"$SRC"/Redesigned/Lyrics/SGRKaraokeView.m "$SRC"/Redesigned/Lyrics/LyricsLook.m "$SRC"/Redesigned/Lyrics/SGRSingButton.m "$SRC"/Redesigned/Lyrics/MeaningSheet.m "$SRC"/Redesigned/Lyrics/LyricsText.m "$SRC"/Shared/Lyrics/KaraokeTiming.m "$SRC"/Shared/Lyrics/Romanise.m "$SRC"/Shared/AdBlock/Protobuf.m \
- -framework UIKit -framework IOKit -framework QuartzCore -framework CoreGraphics -framework CoreImage -framework Foundation -framework Symbols -framework AVFoundation -framework CoreMedia -framework CoreVideo -framework Accelerate \
+ "$SRC"/Shared/LyricsSources/SGTTML.m \
+ -framework UIKit -framework IOKit -framework QuartzCore -framework CoreGraphics -framework CoreImage -framework Foundation -framework Symbols -framework AVFoundation -framework CoreMedia -framework CoreVideo -framework Accelerate -framework MediaPlayer -framework NaturalLanguage \
-o "$OUT/PlayerHarness.app/PlayerHarness"
cat > "$OUT/PlayerHarness.app/Info.plist" <<'PLIST'
diff --git a/harness/player/stubs.m b/harness/player/stubs.m
index 6b70587e..8230c5ef 100644
--- a/harness/player/stubs.m
+++ b/harness/player/stubs.m
@@ -11,6 +11,9 @@
#pragma mark - SGRAccent.x, SGRRepaint.x
UIColor *SGRAccentColor(void) { return nil; }
+// Spotify's own green is kept, so no color is swapped (PlayerCoverAccent.x asks).
+NSInteger SGRAccentRGB(void) { return 0x1ED760; }
+BOOL SGRAccentSwap(CGFloat *r, CGFloat *g, CGFloat *b) { return NO; }
__weak UIView *sgr_nowPlayingRoot = nil;
NSHashTable<UIView *> *sgr_nowPlayingPainted = nil;
__weak UIView *sgr_lyricsPageRoot = nil;
@@ -106,7 +109,7 @@ NSNotificationName const SGKaraokeLinesKeptNotification = @"harness.karaokeLines
BOOL SGKaraokeLooking(NSString *trackID) { return NO; }
id SGKaraokePlayer(void) { return nil; }
SPTPlayerTrack *SGKaraokeTrackFor(NSString *trackID) { return nil; }
-void SGKaraokeRememberTrack(SPTPlayerTrack *track) {}
+void SGKaraokeRememberTrack(SPTPlayerTrack *track, NSString *trackID) {}
// The song runs on from the moment the harness started it, so the sweep is alive in a screenshot.
NSInteger SGKaraokeDelayMs(void) { return [NSUserDefaults.standardUserDefaults integerForKey:SGKeyLyricsDelay]; }
@@ -134,6 +137,30 @@ BOOL SGAITranslatorReady(void) { return NO; }
NSString *SGLyricsTranslationTarget(void) { return @"en"; }
void SGLyricsTranslateWithAI(NSString *trackID, NSArray<SGKaraokeLine *> *lines, NSString *languageTag,
void (^done)(NSArray<NSString *> *translations, NSString *error)) { done(nil, @"harness"); }
+// No translation language is asked for, so none of these is reached past its name.
+NSString *SGLyricsTranslationLanguage(void) { return nil; }
+NSString *SGAITranslatorName(void) { return @"Gemini"; }
+NSString *SGAITranslatorRecipient(void) { return @"Google"; }
+NSString *SGLyricsSongName(NSString *trackID) { return @"the harness's song"; }
+@implementation SGTranslationSource
++ (instancetype)by:(NSString *)by model:(NSString *)model made:(NSDate *)made { return [self new]; }
+- (NSString *)name { return @"Unknown"; }
+- (BOOL)deletable { return NO; }
+@end
+SGTranslationSource *SGAITranslatorSource(void) { return [SGTranslationSource by:@"gemini" model:nil made:nil]; }
+@implementation SGOnDeviceTranslation
++ (BOOL)translationAvailable { return NO; }
++ (BOOL)appleIntelligenceAvailable:(NSString *)languageTag { return NO; }
++ (void)translate:(NSArray<NSString *> *)lines to:(NSString *)languageTag done:(void (^)(NSArray<NSString *> *, NSString *))done { done(nil, @"harness"); }
++ (void)translateWithAppleIntelligence:(NSArray<NSString *> *)lines to:(NSString *)languageTag song:(NSString *)song
+ progress:(void (^)(NSArray<NSString *> *))progress done:(void (^)(NSArray<NSString *> *, NSString *))done { done(nil, @"harness"); }
+@end
+NSNotificationName const SGLyricsTranslationsDidChangeNotification = @"harness.lyricsTranslationsDidChange";
+SGTranslationSource *SGLyricsSyncSavedTranslation(NSString *track, NSString *language, NSArray<SGKaraokeLine *> *lines) { return nil; }
+SGTranslationSource *SGLyricsSaveTranslation(NSString *track, NSString *language, NSArray<SGKaraokeLine *> *lines, SGTranslationSource *source) { return source; }
+void SGLyricsDeleteSavedTranslation(NSString *track, NSString *language) {}
+// LyricsPick.m: no source is picked by hand in the harness.
+NSNotificationName const SGLyricsSourceChosenNotification = @"harness.lyricsSourceChosen";
// Local files: no edits in the harness, so the name is all PlayerLyrics.x needs to watch for one.
#import "Shared/LocalFiles/LocalFiles.h"
@@ -207,6 +234,7 @@ NSString *SGSingModelError(void) { return nil; }
NSString *SGSingModelSizeText(void) { return @""; }
void SGSingDownloadModel(void) {}
void SGSingCancelModelDownload(void) {}
+NSNotificationName const SGSingButtonDidChangeNotification = @"harness.singButtonDidChange";
// MotionSources.m: the default order, Canvas then Apple Music, over the catalog the harness builds. No
// Canvas service: a track whose metadata names no Canvas goes to Apple Music.
diff --git a/harness/playlist/stubs.m b/harness/playlist/stubs.m
index df532177..dc3df900 100644
--- a/harness/playlist/stubs.m
+++ b/harness/playlist/stubs.m
@@ -10,3 +10,6 @@ __weak UIView *sgr_playlistRoot = nil;
// Redesigned/Kit/SGRBridges.x: SGRField.m asks whether the player is opening or closing for its moving field.
BOOL SGRPlayerIsTransitioning(void) { return NO; }
void SGRObservePlayerTransition(id owner, void (^began)(id owner), void (^ended)(id owner)) {}
+
+// Shared/AlbumQueue/AlbumQueueMenu.x: a tapped album header ⋯ records its album for the menu; no menu here.
+void SGAlbumQueueMarkSource(UIView *view) {}
diff --git a/harness/prefs/check.m b/harness/prefs/check.m
new file mode 100644
index 00000000..e83e3f64
--- /dev/null
+++ b/harness/prefs/check.m
@@ -0,0 +1,39 @@
+// Host check for Core/SGPrefs.m's memo: a write applies to the next read, through the accessors or straight
+// to NSUserDefaults, from this thread or another, and an unset key reads as its fallback.
+#import <Foundation/Foundation.h>
+#import "Core/SGPrefs.h"
+
+#define CHECK(cond) do { if (!(cond)) { fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #cond); exit(1); } } while (0)
+
+int main(void) {
+ @autoreleasepool {
+ NSUserDefaults *store = NSUserDefaults.standardUserDefaults;
+ NSString *flag = @"spotifyglass.test.flag", *choice = @"spotifyglass.test.int";
+ for (NSString *key in @[flag, choice, SGKeyStock]) [store removeObjectForKey:key];
+
+ CHECK(SGEnabled(flag) && !SGHidden(flag));
+ CHECK(SGInt(choice, 7) == 7);
+ SGSetEnabled(flag, NO);
+ CHECK(!SGEnabled(flag));
+ SGSetInt(choice, 3);
+ CHECK(SGInt(choice, 7) == 3);
+
+ [store setBool:YES forKey:flag];
+ CHECK(SGHidden(flag));
+ [store removeObjectForKey:flag];
+ CHECK(SGEnabled(flag));
+ [store setBool:YES forKey:SGKeyStock];
+ CHECK(!SGEnabled(flag) && !SGFlag(flag, YES));
+ [store removeObjectForKey:SGKeyStock];
+ CHECK(SGEnabled(flag));
+
+ dispatch_sync(dispatch_get_global_queue(0, 0), ^{ [store setInteger:9 forKey:choice]; });
+ CHECK(SGInt(choice, 7) == 9);
+ [store removeObjectForKey:choice];
+ CHECK(SGInt(choice, 7) == 7);
+
+ for (NSString *key in @[flag, choice]) [store removeObjectForKey:key];
+ puts("prefs: ok");
+ }
+ return 0;
+}
diff --git a/harness/prefs/check.sh b/harness/prefs/check.sh
new file mode 100755
index 00000000..c45d693b
--- /dev/null
+++ b/harness/prefs/check.sh
@@ -0,0 +1,7 @@
+#!/bin/sh
+set -eu
+cd "$(dirname "$0")"
+mkdir -p build
+xcrun clang -fobjc-arc -O2 -Wall -Wextra -Werror -Wno-unused-parameter -I ../../tweak/Sources -I ../../tweak/Sources/Core \
+ -framework Foundation check.m ../../tweak/Sources/Core/SGPrefs.m -o build/check
+build/check
diff --git a/harness/radio-modes/check.m b/harness/radio-modes/check.m
index 2d96e99f..0873a96a 100644
--- a/harness/radio-modes/check.m
+++ b/harness/radio-modes/check.m
@@ -125,7 +125,14 @@ static void (^nested)(void);
return r;
}
@end
-static int failures, checks;
+static int failures, checks, setCounts;
+@interface CountingSet : NSSet
+@end
+@implementation CountingSet
+- (NSUInteger)count { setCounts++; return 0; }
+- (id)member:(id)object { return nil; }
+- (NSEnumerator *)objectEnumerator { return @[].objectEnumerator; }
+@end
#define CHECK(c) do { checks++; if (!(c)) { fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #c); failures++; } } while (0)
static void setReasons(SPTPlayerRestrictions *r, NSSet *v) {
r.disallowTogglingShuffleReasons = v;
@@ -244,6 +251,14 @@ int main(void) { @autoreleasepool {
CHECK(((ESPSetShufflingContextRequest *)[player setShufflingContext:YES]).options == originalOptions);
setReasons(r, [NSSet setWithObject:@"radio"]); player.state.playbackId = nil;
CHECK(((ESPSetShufflingContextRequest *)[player setShufflingContext:YES]).options == originalOptions);
+ // A repeated read of the same state records nothing new.
+ player.state.playbackId = @"playback-123"; player.state.contextURI = @"context-A";
+ r.disallowTogglingShuffleReasons = [CountingSet new];
+ (void)player.state;
+ int counted = setCounts;
+ CHECK(counted == (active ? 1 : 0));
+ (void)player.state; (void)player.state;
+ CHECK(setCounts == counted);
// Missing state leaves the request alone.
player.state = nil;
CHECK(((ESPSetShufflingContextRequest *)[player setShufflingContext:YES]).options == originalOptions);
diff --git a/harness/sleep-timer/main.m b/harness/sleep-timer/main.m
index 0867f659..83e68d4c 100644
--- a/harness/sleep-timer/main.m
+++ b/harness/sleep-timer/main.m
@@ -83,7 +83,9 @@ static float SGSleepTimerGainAt(NSTimeInterval left) {
}
NSInteger SGKaraokePositionMs(void) { return sg_positionMs; }
-id SGKaraokePlayer(void) { return sg_player; }
+// How often the player's state was asked for: SpotifySleepTimer.m's check asks it four times a second.
+static NSInteger sg_playerAsks;
+id SGKaraokePlayer(void) { sg_playerAsks++; return sg_player; }
void SGPlayerSetGain(float gain) { sg_gain = gain; }
NSString *SGURIString(id uri) {
if ([uri isKindOfClass:NSString.class]) return uri;
@@ -127,7 +129,9 @@ static SPTSleepTimer *spotifyTimer(NSUInteger type, NSTimeInterval seconds) {
return timer;
}
+// The core reports a new state with every change, the timer's too: told to the observer before the wait.
static void runFor(NSTimeInterval seconds) {
+ [sg_observer playerStateDidReport:sg_player.state];
[NSRunLoop.currentRunLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:seconds]];
}
@@ -311,8 +315,10 @@ int main(void) {
sg_player.state = state(a, @[b, c], @[], NO);
sg_player.state.isPlaying = YES;
[sg_observer playerStateDidChange:sg_player.state];
- runFor(0.4);
+ NSInteger asks = sg_playerAsks;
+ runFor(0.6);
CHECK(sg_gain == 1, "Spotify's: playing with no timer, full volume");
+ CHECK(sg_playerAsks == asks, "Spotify's: playing with no timer, no check runs");
sg_player.state.sleepTimer = spotifyTimer(1, 20);
runFor(0.4);
CHECK(sg_gain < SGSleepTimerGain(20.5, 30) && sg_gain > SGSleepTimerGain(19, 30), "Spotify's, at a time 20 s on: faded as 20 s into a 30 s fade");
diff --git a/harness/sleep-timer/stub/Shared/Player/PlayerState.h b/harness/sleep-timer/stub/Shared/Player/PlayerState.h
index 8f5f7ff1..c7db1640 100644
--- a/harness/sleep-timer/stub/Shared/Player/PlayerState.h
+++ b/harness/sleep-timer/stub/Shared/Player/PlayerState.h
@@ -4,5 +4,7 @@
NSString *SGURIString(id uri);
@protocol SGPlayerStateObserver <NSObject>
- (void)playerStateDidChange:(SPTPlayerState *)state;
+@optional
+- (void)playerStateDidReport:(SPTPlayerState *)state;
@end
void SGAddPlayerStateObserver(id<SGPlayerStateObserver> observer);
diff --git a/harness/spatial-page/stubs.m b/harness/spatial-page/stubs.m
index 866c2778..52dbfa0f 100644
--- a/harness/spatial-page/stubs.m
+++ b/harness/spatial-page/stubs.m
@@ -40,6 +40,24 @@ void SGSetSingSpatial(BOOL on) {
SGSetEnabled(SGKeySingSpatial, on);
NSLog(@"[harness] spatial voice %@", on ? @"on" : @"off");
}
+// Sing.x's stored sound, with its defaults and ranges; no engine to hand it to.
+static double storedNumber(NSString *key, double fallback, double low, double high) {
+ id value = [NSUserDefaults.standardUserDefaults objectForKey:key];
+ double number = [value isKindOfClass:NSNumber.class] ? [value doubleValue] : fallback;
+ return isfinite(number) ? fmin(high, fmax(low, number)) : fallback;
+}
+double SGSingSpatialDistance(void) { return storedNumber(SGKeySingSpatialDistance, 1.5, 1, 6.5); }
+double SGSingSpatialRoom(void) { return storedNumber(SGKeySingSpatialRoom, 25, 0, 100); }
+double SGSingSpatialFront(void) { return storedNumber(SGKeySingSpatialFront, 5, 5, 60); }
+double SGSingSpatialWidth(void) { return storedNumber(SGKeySingSpatialWidth, 110, 0, 200); }
+void SGSetSingSpatialSound(double meters, double roomPercent, double frontSeconds, double widthPercent) {
+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
+ [defaults setDouble:meters forKey:SGKeySingSpatialDistance];
+ [defaults setDouble:roomPercent forKey:SGKeySingSpatialRoom];
+ [defaults setDouble:frontSeconds forKey:SGKeySingSpatialFront];
+ [defaults setDouble:widthPercent forKey:SGKeySingSpatialWidth];
+ NSLog(@"[harness] spatial sound %.1f m, room %.0f%%, front %.0f s, width %.0f%%", meters, roomPercent, frontSeconds, widthPercent);
+}
// From main.m's launch line (chunk=<ms>): what plays moves on in renders this long, as the engine's clock does, a
// part of a tenth out of step with the wall clock; 0 for a clock that moves smoothly.
double sg_renderChunk;
diff --git a/harness/speed/main.m b/harness/speed/main.m
index 3d8939dd..1ec3c72b 100644
--- a/harness/speed/main.m
+++ b/harness/speed/main.m
@@ -70,6 +70,13 @@ typedef struct {
@end
@implementation SPTPlayerState
+// The hooked -position (SpeedPitch.x) also reads which track and whether paused: one track, playing.
+- (id)track {
+ return nil;
+}
+- (BOOL)isPaused {
+ return NO;
+}
- (double)playbackSpeed {
return 1;
}
@@ -78,6 +85,10 @@ typedef struct {
}
@end
+// Shared/Player/PlayerState.x: no player state for SGSetPlayerSpeed to start the mod's clock from (the mock has
+// no track), so the speed checks see the units alone.
+SPTPlayerState *SGPlayerState(void) { return nil; }
+
static OSStatus decoder(void *refCon, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *timestamp, UInt32 bus,
UInt32 frames, AudioBufferList *data) {
uint64_t start = atomic_fetch_add(&sg_decoded, frames);
diff --git a/harness/system-menu/main.m b/harness/system-menu/main.m
index b746d7a2..b5b4a157 100644
--- a/harness/system-menu/main.m
+++ b/harness/system-menu/main.m
@@ -15,6 +15,7 @@
#import <objc/message.h>
#import <objc/runtime.h>
#import "Redesigned/ContextMenu/ContextMenu.h"
+#import "Shared/LyricsSources/LyricsSources.h"
// The album footer is exercised by harness/album-queue and the Spotify simulator test. These
// player-menu fixtures do not provide an album page or the shared album footer.
@@ -72,6 +73,17 @@ BOOL SGPlayerMenuAnimatedArtwork(void) { return sg_animated; }
void SGPlayerMenuSetAnimatedArtwork(BOOL on) { sg_animated = on; NSLog(@"[harness] animated artwork %d", on); }
static NSUInteger sg_marked;
void SGPlayerMenuMarkPlayers(void) { sg_marked++; }
+// Lyrics Source (LyricsSources.m, LyricsPick.m): every source off, so the menu offers no Lyrics Source, and the
+// rest is never asked.
+NSString *SGKaraokePlayingTrack(void) { return @"harness"; }
+BOOL SGLyricsEnabled(void) { return NO; }
+NSArray<NSString *> *SGLyricsOrder(void) { return @[]; }
+SGLyricsProvider *SGLyricsProviderFor(NSString *key) { return nil; }
+NSString *SGLyricsCreditFor(NSString *trackID) { return nil; }
+NSString *SGLyricsChosenSource(NSString *trackID) { return nil; }
+NSDictionary<NSString *, SGLyricsResult *> *SGLyricsOffersSoFar(NSString *trackID, NSArray<NSString *> **asking) { return @{}; }
+void SGLyricsChooseSource(NSString *trackID, NSString *key) {}
+void SGLyricsChooseAutomatic(NSString *trackID) {}
// The player's background (Redesigned/Player/Player.h's SGRPlayerBackgroundKind): Fluid, so the menu offers
// Animated and the Visualizer; Show Animated Artwork switches it on.
NSInteger SGRPlayerBackground(void) { return sg_background; }
diff --git a/harness/tabbar/build.sh b/harness/tabbar/build.sh
index 65f82498..e89de390 100755
--- a/harness/tabbar/build.sh
+++ b/harness/tabbar/build.sh
@@ -19,7 +19,7 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar
"$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGGlass.m \
"$SRC"/Core/SGBackdrop.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
"$SRC"/Redesigned/Kit/SGRTokens.m "$SRC"/Redesigned/Kit/SGRGlass.m \
- "$SRC"/Redesigned/Navbar/NavbarLayout.m "$SRC"/Shared/Navigation/TabIcons.m \
+ "$SRC"/Redesigned/Navbar/NavbarLayout.m "$SRC"/Shared/Navigation/TabIcons.m "$SRC"/Settings/SGMarquee.m \
-framework UIKit -framework IOKit -framework QuartzCore -framework CoreGraphics -framework Foundation \
-o "$OUT/TabBarHarness.app/TabBarHarness"
diff --git a/tweak/Sources/Core/SGPrefs.h b/tweak/Sources/Core/SGPrefs.h
index c63f3e01..57969c6a 100644
--- a/tweak/Sources/Core/SGPrefs.h
+++ b/tweak/Sources/Core/SGPrefs.h
@@ -18,6 +18,10 @@ void SGSetEnabled(NSString *key, BOOL on);
NSInteger SGInt(NSString *key, NSInteger fallback);
void SGSetInt(NSString *key, NSInteger value);
+// The accessors keep what they read until the defaults change. An observer of NSUserDefaultsDidChangeNotification
+// that reads them calls this first, as observers are not called in a set order.
+void SGPrefsChanged(void);
+
// Overrides of Spotify's remote-config flags, stored under SGFlagOverridePrefix + flag key;
// nil keeps Spotify's value. Shared/Flags reads them, the All flags page and flag rows write them.
extern NSString *const SGFlagOverridePrefix;
diff --git a/tweak/Sources/Core/SGPrefs.m b/tweak/Sources/Core/SGPrefs.m
index f9d3ce93..50e1655c 100644
--- a/tweak/Sources/Core/SGPrefs.m
+++ b/tweak/Sources/Core/SGPrefs.m
@@ -1,10 +1,45 @@
#import "SGPrefs.h"
+#import <os/lock.h>
+
+// Hooks read switches on every layout and frame, and a defaults read takes CFPreferences' lock: each key's
+// stored value (NSNull for none) is kept after its first read and all are dropped whenever the defaults
+// change, so a write still applies to the next read.
+static os_unfair_lock memoLock = OS_UNFAIR_LOCK_INIT;
+static NSMutableDictionary<NSString *, id> *memo;
+static NSUInteger memoGeneration;
+
+void SGPrefsChanged(void) {
+ os_unfair_lock_lock(&memoLock);
+ [memo removeAllObjects];
+ memoGeneration++;
+ os_unfair_lock_unlock(&memoLock);
+}
+
+static id stored(NSString *key) {
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ memo = [NSMutableDictionary dictionary];
+ // Posted on the writing thread, which a main-queue observer would leave waiting on main.
+ [NSNotificationCenter.defaultCenter addObserverForName:NSUserDefaultsDidChangeNotification object:nil queue:nil
+ usingBlock:^(NSNotification *note) { SGPrefsChanged(); }];
+ });
+ os_unfair_lock_lock(&memoLock);
+ id value = memo[key];
+ NSUInteger generation = memoGeneration;
+ os_unfair_lock_unlock(&memoLock);
+ if (value) return value == NSNull.null ? nil : value;
+ value = [NSUserDefaults.standardUserDefaults objectForKey:key];
+ os_unfair_lock_lock(&memoLock);
+ // A write during the read dropped the memo, and the value read may predate it.
+ if (generation == memoGeneration) memo[key] = value ?: NSNull.null;
+ os_unfair_lock_unlock(&memoLock);
+ return value;
+}
BOOL SGFlag(NSString *key, BOOL fallback) {
- NSUserDefaults *store = NSUserDefaults.standardUserDefaults;
- id value = [store objectForKey:key];
+ id value = stored(key);
if (value) return [value boolValue];
- return fallback && ![store boolForKey:SGKeyStock];
+ return fallback && ![stored(SGKeyStock) boolValue];
}
BOOL SGEnabled(NSString *key) {
@@ -17,15 +52,17 @@ BOOL SGHidden(NSString *key) {
void SGSetEnabled(NSString *key, BOOL on) {
[NSUserDefaults.standardUserDefaults setBool:on forKey:key];
+ SGPrefsChanged();
}
NSInteger SGInt(NSString *key, NSInteger fallback) {
- id value = [NSUserDefaults.standardUserDefaults objectForKey:key];
+ id value = stored(key);
return value ? [value integerValue] : fallback;
}
void SGSetInt(NSString *key, NSInteger value) {
[NSUserDefaults.standardUserDefaults setInteger:value forKey:key];
+ SGPrefsChanged();
}
NSString *const SGFlagOverridePrefix = @"spotifyglass.flag.";
diff --git a/tweak/Sources/Core/SGViewTree.h b/tweak/Sources/Core/SGViewTree.h
index 26c2d8d6..4a2b4fee 100644
--- a/tweak/Sources/Core/SGViewTree.h
+++ b/tweak/Sources/Core/SGViewTree.h
@@ -7,11 +7,20 @@ CGRect SGFrameIn(UIView *view, UIView *target);
BOOL SGIsInside(UIView *view, UIView *root);
// Whether no view from `view` up to (not including) `root` is hidden.
BOOL SGShownUnder(UIView *view, UIView *root);
-// The first wide stack view under `host` with at least two arranged children: a player row, or
-// the row of items in the tab bar.
+// A wide stack view with at least two arranged children: a player row, or the row of items in the tab bar.
+BOOL SGIsRow(UIView *view);
+// The first row (SGIsRow) under `host`.
UIStackView *SGRowIn(UIView *host);
+// Whether `cls`'s name contains `marker`, worked out once per class and marker. Main thread only. `marker`
+// must be a string literal: answers are kept by its address.
+BOOL SGClassNamed(Class cls, NSString *marker);
// Whether any view under `root` has `marker` in its class name.
BOOL SGHasClass(UIView *root, NSString *marker);
+// The first view under `root` (itself included) that `match` accepts, remembered weakly on `root` under
+// `key` and looked for again once it no longer matches or has left `root`. Nothing found is not remembered.
+UIView *SGFindRemembered(UIView *root, const void *key, BOOL (^match)(UIView *view));
+// SGFindRemembered for the first view whose accessibility identifier starts with `prefix`.
+UIView *SGFindIdentifier(UIView *root, NSString *prefix, const void *key);
// Artwork, glyphs, text and thin lines (progress bar) keep their color, everything else goes clear.
BOOL SGKeepsColor(UIView *view);
diff --git a/tweak/Sources/Core/SGViewTree.m b/tweak/Sources/Core/SGViewTree.m
index 61b74781..191fbf9a 100644
--- a/tweak/Sources/Core/SGViewTree.m
+++ b/tweak/Sources/Core/SGViewTree.m
@@ -1,4 +1,5 @@
#import "SGViewTree.h"
+#import <objc/runtime.h>
void SGForEachView(UIView *view, void (^fn)(UIView *)) {
fn(view);
@@ -25,32 +26,82 @@ BOOL SGShownUnder(UIView *view, UIView *root) {
return YES;
}
+BOOL SGIsRow(UIView *view) {
+ return [view isKindOfClass:UIStackView.class] && view.bounds.size.width > 200 && ((UIStackView *)view).arrangedSubviews.count >= 2;
+}
+
+// Depth first, as SGForEachView walks, stopping at the first view `match` accepts.
+static UIView *firstMatch(UIView *view, BOOL (^match)(UIView *view)) {
+ if (match(view)) return view;
+ for (UIView *sub in view.subviews) {
+ UIView *found = firstMatch(sub, match);
+ if (found) return found;
+ }
+ return nil;
+}
+
UIStackView *SGRowIn(UIView *host) {
- __block UIStackView *row = nil;
- SGForEachView(host, ^(UIView *v) {
- if (!row && [v isKindOfClass:UIStackView.class] && v.bounds.size.width > 200 && ((UIStackView *)v).arrangedSubviews.count >= 2) row = (UIStackView *)v;
- });
- return row;
+ return (UIStackView *)firstMatch(host, ^BOOL(UIView *v) { return SGIsRow(v); });
+}
+
+BOOL SGClassNamed(Class cls, NSString *marker) {
+ if (!cls || !marker) return NO;
+ // Markers are literals, so the outer level goes by the pointer and never hashes the string.
+ static NSMapTable<NSString *, NSMutableDictionary *> *cache;
+ if (!cache) cache = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality
+ valueOptions:NSPointerFunctionsStrongMemory];
+ NSMutableDictionary *answers = [cache objectForKey:marker];
+ if (!answers) [cache setObject:(answers = [NSMutableDictionary dictionary]) forKey:marker];
+ NSNumber *answer = answers[(id<NSCopying>)cls];
+ if (!answer) answers[(id<NSCopying>)cls] = answer = @([NSStringFromClass(cls) containsString:marker]);
+ return answer.boolValue;
}
BOOL SGHasClass(UIView *root, NSString *marker) {
__block BOOL found = NO;
SGForEachView(root, ^(UIView *v) {
- if (!found && [NSStringFromClass(v.class) containsString:marker]) found = YES;
+ if (!found && SGClassNamed(v.class, marker)) found = YES;
});
return found;
}
+@interface SGWeakBox : NSObject
+@property (nonatomic, weak) UIView *value;
+@end
+
+@implementation SGWeakBox
+@end
+
+UIView *SGFindRemembered(UIView *root, const void *key, BOOL (^match)(UIView *view)) {
+ if (!root) return nil;
+ SGWeakBox *box = objc_getAssociatedObject(root, key);
+ UIView *cached = box.value;
+ if (cached && match(cached) && [cached isDescendantOfView:root]) return cached;
+ UIView *found = firstMatch(root, match);
+ if (!found) return nil;
+ if (!box) {
+ box = [SGWeakBox new];
+ objc_setAssociatedObject(root, key, box, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ }
+ box.value = found;
+ return found;
+}
+
+UIView *SGFindIdentifier(UIView *root, NSString *prefix, const void *key) {
+ return SGFindRemembered(root, key, ^BOOL(UIView *v) { return [v.accessibilityIdentifier hasPrefix:prefix]; });
+}
+
BOOL SGKeepsColor(UIView *view) {
return [view isKindOfClass:UIImageView.class] || [view isKindOfClass:UILabel.class] || view.bounds.size.height <= 4;
}
void SGStripBackgrounds(UIView *view) {
if ([view isKindOfClass:UIVisualEffectView.class]) return;
+ Class cls = view.class;
// The karaoke views paint nothing to strip and hold a label for every word in sight.
- if ([NSStringFromClass(view.class) hasPrefix:@"SGRKaraoke"]) return;
+ if (SGClassNamed(cls, @"SGRKaraoke")) return;
if (!SGKeepsColor(view)) view.layer.backgroundColor = NULL;
- if ([view.layer isKindOfClass:CAGradientLayer.class] || [NSStringFromClass(view.class) containsString:@"GradientView"]) view.hidden = YES;
+ if ([view.layer isKindOfClass:CAGradientLayer.class] || SGClassNamed(cls, @"GradientView")) view.hidden = YES;
for (CALayer *layer in view.layer.sublayers) {
if ([layer isKindOfClass:CAGradientLayer.class]) layer.hidden = YES;
}
diff --git a/tweak/Sources/Native/Album/Album.x b/tweak/Sources/Native/Album/Album.x
index 53bcf17c..bd6bcb0f 100644
--- a/tweak/Sources/Native/Album/Album.x
+++ b/tweak/Sources/Native/Album/Album.x
@@ -21,14 +21,6 @@ static UIView *albumPageOf(UIView *view) {
return nil;
}
-static UIView *identNamed(UIView *root, NSString *ident) {
- __block UIView *found = nil;
- SGForEachView(root, ^(UIView *v) {
- if (!found && [v.accessibilityIdentifier hasPrefix:ident]) found = v;
- });
- return found;
-}
-
#pragma mark - header buttons
static const struct { __unsafe_unretained NSString *ident, *key; } buttons[] = {
@@ -46,34 +38,38 @@ static NSString *keyFor(UIView *action) {
return nil;
}
+static BOOL buttonHidden(UIView *action) {
+ NSString *key = keyFor(action);
+ return key && SGHidden(key);
+}
+
// The buttons arrive after the page has laid out, and a row that keeps its size lays nothing else out.
%hook UIStackView
- (void)layoutSubviews {
%orig;
- BOOL row = NO;
+ BOOL any = NO;
for (UIView *action in self.subviews) {
- if (keyFor(action)) row = YES;
+ if ((any = buttonHidden(action))) break;
}
- if (!row || !albumPageOf(self)) return;
+ if (!any || !albumPageOf(self)) return;
for (UIView *action in self.subviews) {
- NSString *key = keyFor(action);
- if (key && SGHidden(key)) action.hidden = YES;
+ if (buttonHidden(action)) action.hidden = YES;
}
}
%end
#pragma mark - the cover behind the header
-static char kBackdropKey, kSourceKey;
+static char kBackdropKey, kSourceKey, kArtworkKey;
static void applyBackdrop(UIView *page) {
if (!SGFlag(SGKeyAlbumBackdrop, NO)) return;
__block UIImage *image = nil;
- SGForEachView(identNamed(page, @"CreativeWorkPlatform.Components.UI.ArtWorkElement.WithCoverArt"), ^(UIView *v) {
+ SGForEachView(SGFindIdentifier(page, @"CreativeWorkPlatform.Components.UI.ArtWorkElement.WithCoverArt", &kArtworkKey), ^(UIView *v) {
if (!image && [v isKindOfClass:UIImageView.class]) image = ((UIImageView *)v).image;
});
UIView *header = page.subviews.firstObject;
- if (!image || ![NSStringFromClass(header.class) containsString:@"HeaderView"]) return;
+ if (!image || !SGClassNamed(header.class, @"HeaderView")) return;
UIView *backdrop = objc_getAssociatedObject(header, &kBackdropKey);
if (!backdrop) {
@@ -140,7 +136,7 @@ static NSString *headingIn(UIView *cell) {
SGForEachView(cell, ^(UIView *v) {
if (title) return;
if ([v.accessibilityIdentifier isEqualToString:@"Album.Copyright"]) title = v.accessibilityIdentifier;
- else if (v.accessibilityLabel.length && [NSStringFromClass(v.class) containsString:@"SectionHeadingHome"]) title = v.accessibilityLabel;
+ else if (SGClassNamed(v.class, @"SectionHeadingHome") && v.accessibilityLabel.length) title = v.accessibilityLabel;
});
return title ?: @"";
}
diff --git a/tweak/Sources/Native/Artist/Artist.x b/tweak/Sources/Native/Artist/Artist.x
index 0b3974cd..6a0f66a7 100644
--- a/tweak/Sources/Native/Artist/Artist.x
+++ b/tweak/Sources/Native/Artist/Artist.x
@@ -21,47 +21,41 @@ static BOOL onArtistPage(UIView *view) {
return NO;
}
-static UIView *identNamed(UIView *root, NSString *ident) {
- __block UIView *found = nil;
- SGForEachView(root, ^(UIView *v) {
- if (!found && [v.accessibilityIdentifier hasPrefix:ident]) found = v;
- });
- return found;
-}
-
#pragma mark - header
-static void hide(UIView *view, NSString *key) {
- if (view && SGHidden(key)) view.hidden = YES;
-}
+static const struct { __unsafe_unretained NSString *ident, *key; } buttons[] = {
+ {@"Components.UI.WatchFeedEntityExplorerButton", SGHideArtistExplore},
+ {@"Curation.FollowButtonElementKit.FollowButton", SGHideArtistFollow},
+ {@"Components.UI.ContextMenuButton", SGHideArtistMore},
+ {@"Components.UI.ShuffleButton", SGHideArtistShuffle},
+};
+enum { kButtons = sizeof(buttons) / sizeof(buttons[0]) };
+
+// The header's parts, each remembered on the header once found (Core/SGViewTree.h).
+static char kBadgeKey, kMetadataKey, kTitleKey, kArtworkKey, kButtonKeys[kButtons];
+static NSString *const kBadge = @"ImageHeaderView.VerifiedBadge", *const kMetadata = @"Components.Header.UI.Metadata";
// The identifier sits on the button; the action is the view the button row arranges around it.
static UIView *actionHolding(UIView *button, UIView *header) {
for (UIView *v = button; v.superview && v.superview != header; v = v.superview) {
if (v.superview.superview == header) return v;
- if ([NSStringFromClass(v.superview.class) containsString:@"OverflowStackView"]) return v;
+ if (SGClassNamed(v.superview.class, @"OverflowStackView")) return v;
}
return nil;
}
static void applyHeader(UIView *header) {
- hide(identNamed(header, @"ImageHeaderView.VerifiedBadge"), SGHideArtistVerified);
+ if (SGHidden(SGHideArtistVerified)) SGFindIdentifier(header, kBadge, &kBadgeKey).hidden = YES;
// Its AutoLayoutStackView traps like OverflowStackView below once the label goes hidden.
- if (SGHidden(SGHideArtistListeners)) identNamed(header, @"Components.Header.UI.Metadata").alpha = 0;
-
- static const struct { __unsafe_unretained NSString *ident, *key; } buttons[] = {
- {@"Components.UI.WatchFeedEntityExplorerButton", SGHideArtistExplore},
- {@"Curation.FollowButtonElementKit.FollowButton", SGHideArtistFollow},
- {@"Components.UI.ContextMenuButton", SGHideArtistMore},
- {@"Components.UI.ShuffleButton", SGHideArtistShuffle},
- };
- for (size_t i = 0; i < sizeof(buttons) / sizeof(buttons[0]); i++) {
+ if (SGHidden(SGHideArtistListeners)) SGFindIdentifier(header, kMetadata, &kMetadataKey).alpha = 0;
+
+ for (size_t i = 0; i < kButtons; i++) {
if (!SGHidden(buttons[i].key)) continue;
- UIView *action = actionHolding(identNamed(header, buttons[i].ident), header);
+ UIView *action = actionHolding(SGFindIdentifier(header, buttons[i].ident, &kButtonKeys[i]), header);
if (!action) continue;
// OverflowStackView traps in updateConstraints once its views go hidden (crash 2026-09-15),
// so those only turn invisible and keep their place.
- if ([NSStringFromClass(action.superview.class) containsString:@"OverflowStackView"]) {
+ if (SGClassNamed(action.superview.class, @"OverflowStackView")) {
action.alpha = 0;
action.userInteractionEnabled = NO;
} else {
@@ -85,11 +79,13 @@ static UIView *childOfHeader(UIView *view, UIView *header) {
// the photo: the title block slides down to sit where the lowest of them sat. Transforms, because
// the header's stack views crash on anything that changes their layout.
static void closeUpTitle(UIView *header) {
- UIView *title = childOfHeader(identNamed(header, @"Encore.AdaptiveTitle"), header);
- UIView *badge = identNamed(header, @"ImageHeaderView.VerifiedBadge");
- UIView *listeners = identNamed(header, @"Components.Header.UI.Metadata");
+ // The badge first: an artist without one is left alone before anything else is looked for.
+ UIView *badge = SGFindIdentifier(header, kBadge, &kBadgeKey);
+ if (!badge || badge.superview != header) return;
+ UIView *title = childOfHeader(SGFindIdentifier(header, @"Encore.AdaptiveTitle", &kTitleKey), header);
+ UIView *listeners = SGFindIdentifier(header, kMetadata, &kMetadataKey);
UIView *metadata = childOfHeader(listeners, header);
- if (!title || !badge || !metadata || badge.superview != header) return;
+ if (!title || !metadata) return;
// Walks up from the listeners' line: each shown line lands on the bottom edge the line under it
// left free, keeping its own gap to the line above.
@@ -135,7 +131,7 @@ static CAGradientLayer *fadeMask(CALayer *host, NSArray<NSNumber *> *locations)
static void applyPhotoFade(UIView *header) {
if (!SGFlag(SGKeyArtistPhotoFade, NO)) return;
- UIView *artwork = identNamed(header, @"Components.Header.UI.ArtworkImage");
+ UIView *artwork = SGFindIdentifier(header, @"Components.Header.UI.ArtworkImage", &kArtworkKey);
UIView *clip = childOfHeader(artwork, header);
if (!artwork || !clip || clip == artwork) return;
__block UIImageView *source = nil;
@@ -192,7 +188,7 @@ static void applyPhotoFade(UIView *header) {
- (void)layoutSubviews {
%orig;
UIView *header = self.superview;
- if (![NSStringFromClass(header.class) containsString:@"ImageHeaderKit"]) return;
+ if (!SGClassNamed(header.class, @"ImageHeaderKit")) return;
applyHeader(header);
closeUpTitle(header);
}
@@ -264,7 +260,7 @@ static BOOL anySectionSwitch(void) {
static NSString *headingIn(UIView *cell) {
__block NSString *title = nil;
SGForEachView(cell, ^(UIView *v) {
- if (!title && v.accessibilityLabel.length && [NSStringFromClass(v.class) containsString:@"SectionHeadingHome"]) {
+ if (!title && SGClassNamed(v.class, @"SectionHeadingHome") && v.accessibilityLabel.length) {
title = v.accessibilityLabel;
}
});
@@ -301,12 +297,15 @@ static UICollectionView *listOf(UIView *cell) {
}
static BOOL collapsed(UICollectionViewCell *cell, NSIndexPath *path) {
+ BOOL hideLiked = SGHidden(SGHideArtistLikedSongs), anySection = anySectionSwitch();
+ if (!hideLiked && !anySection) return NO;
for (UIView *v = cell.superview; v; v = v.superview) {
if ([v isKindOfClass:cell.class]) return NO; // a card inside a carousel: its row decides
}
if (!onArtistPage(cell)) return NO;
- if (SGHidden(SGHideArtistLikedSongs) && identNamed(cell, @"Components.UI.LikedSongs.Row")) return YES;
- if (!anySectionSwitch() || !path) return NO;
+ static char likedKey;
+ if (hideLiked && SGFindIdentifier(cell, @"Components.UI.LikedSongs.Row", &likedKey)) return YES;
+ if (!anySection || !path) return NO;
UICollectionView *list = listOf(cell);
if (!list) return NO;
diff --git a/tweak/Sources/Native/Home/HomeDeclutter.x b/tweak/Sources/Native/Home/HomeDeclutter.x
index 470ee274..8dd15534 100644
--- a/tweak/Sources/Native/Home/HomeDeclutter.x
+++ b/tweak/Sources/Native/Home/HomeDeclutter.x
@@ -14,30 +14,44 @@ static const struct { __unsafe_unretained NSString *marker, *key; } sections[] =
{@"Discovery_DJElement", SGHideHomeDJ},
};
-// Class names of everything in the cell. Lists nested in the cell are laid out first so the
-// cells that name the section (shortcut tiles) exist.
-static NSString *classNamesIn(UIView *cell) {
- NSMutableString *names = [NSMutableString string];
+enum { kSections = sizeof(sections) / sizeof(sections[0]) };
+
+static BOOL anySectionSwitch(void) {
+ for (size_t i = 0; i < kSections; i++) {
+ if (SGHidden(sections[i].key)) return YES;
+ }
+ return NO;
+}
+
+// Whether the cell is a section of Home: its first view names the page. Spotify's cell has held it as its own
+// first subview (Redesigned/Home/HomeSections.x) and as its content view's (Native/Player/PlayerDeclutter.x).
+static BOOL onHome(UICollectionViewCell *cell) {
+ return SGClassNamed(cell.subviews.firstObject.class, @"Home_EvoPageImpl")
+ || SGClassNamed(cell.contentView.subviews.firstObject.class, @"Home_EvoPageImpl");
+}
+
+// The first switched-on section a class in the cell names. Lists nested in the cell are laid out first so
+// the cells that name the section (shortcut tiles) exist.
+static NSString *switchedSectionIn(UIView *cell) {
+ unsigned hidden = 0; // a bit per switched-on section (a block cannot capture an array)
+ for (size_t i = 0; i < kSections; i++) if (SGHidden(sections[i].key)) hidden |= 1u << i;
+ __block size_t first = kSections;
SGForEachView(cell, ^(UIView *v) {
if (v != cell && [v isKindOfClass:UICollectionView.class]) [v layoutIfNeeded];
- [names appendString:NSStringFromClass(v.class)];
- [names appendString:@"\n"];
+ for (size_t i = 0; i < first; i++) {
+ if ((hidden & 1u << i) && SGClassNamed(v.class, sections[i].marker)) first = i;
+ }
});
- return names;
+ return first < kSections ? sections[first].key : nil;
}
static NSString *hiddenKeyFor(UICollectionViewCell *cell) {
+ if (!anySectionSwitch() || !onHome(cell)) return nil;
// A cell inside another section's list: the outer section decides.
for (UIView *v = cell.superview; v; v = v.superview) {
if ([v isKindOfClass:cell.class]) return nil;
}
- NSString *names = nil;
- for (size_t i = 0; i < sizeof(sections) / sizeof(sections[0]); i++) {
- if (!SGHidden(sections[i].key)) continue;
- if (!names) names = classNamesIn(cell);
- if ([names containsString:@"Home_EvoPageImpl"] && [names containsString:sections[i].marker]) return sections[i].key;
- }
- return nil;
+ return switchedSectionIn(cell);
}
%hook _TtC12Element_List18CollectionViewCell
diff --git a/tweak/Sources/Native/LocalFiles/LocalCover.x b/tweak/Sources/Native/LocalFiles/LocalCover.x
index a974d7e8..0da1fcec 100644
--- a/tweak/Sources/Native/LocalFiles/LocalCover.x
+++ b/tweak/Sources/Native/LocalFiles/LocalCover.x
@@ -92,7 +92,7 @@ static void fillFront(UIScrollView *list) {
BOOL player = NO;
for (UIView *view = tilt.superview; view; view = view.superview) {
if (isCoverCell(view)) return;
- player = player || [NSStringFromClass(view.class) containsString:@"NowPlaying"];
+ player = player || SGClassNamed(view.class, @"NowPlaying");
}
if (player) fill(largestImageIn(tilt));
}
diff --git a/tweak/Sources/Native/Navbar/Navbar.x b/tweak/Sources/Native/Navbar/Navbar.x
index fb1b05d9..df913abc 100644
--- a/tweak/Sources/Native/Navbar/Navbar.x
+++ b/tweak/Sources/Native/Navbar/Navbar.x
@@ -134,7 +134,7 @@ static NSString *stockID(UIView *item) {
static void measureItem(UIView *item) {
__block UIView *icon = nil, *label = nil;
SGForEachView(item, ^(UIView *v) {
- if (!icon && [NSStringFromClass(v.class) containsString:@"IconView"] && v.bounds.size.width > 1) icon = v;
+ if (!icon && SGClassNamed(v.class, @"IconView") && v.bounds.size.width > 1) icon = v;
if (!label && [v isKindOfClass:UILabel.class] && ((UILabel *)v).text.length) label = v;
});
if (icon) sg_iconBox = SGFrameIn(icon, item);
@@ -321,8 +321,38 @@ void SGRefreshTabBar(void) {
// What the row settled on, logged whenever it changes: `make log` then says whether the items fit,
// what is holding their width, and in what order the bar ended up.
void SGLogTabBarRow(UIView *tabBar) {
- UIStackView *stack = SGRowIn(tabBar);
+ // The row SGComposeTabBar found in this bar on the same pass, just before.
+ UIStackView *stack = sg_row;
if (!stack) return;
+ // Describing the constraints is the costly part, so the row is described again only once its geometry,
+ // its stack settings or its items change. shortcut: items past the 16th are not compared, raise it if a bar
+ // ever holds more.
+ struct {
+ CGRect bar, stack, icon, label;
+ NSInteger axis, distribution, alignment;
+ CGFloat spacing;
+ NSUInteger count;
+ struct { const void *item; CGRect frame; BOOL hidden; } items[16];
+ } key;
+ memset(&key, 0, sizeof key); // padding too, for memcmp
+ key.bar = tabBar.frame;
+ key.stack = stack.frame;
+ key.icon = sg_iconBox;
+ key.label = sg_labelBox;
+ key.axis = stack.axis;
+ key.distribution = stack.distribution;
+ key.alignment = stack.alignment;
+ key.spacing = stack.spacing;
+ for (UIView *item in stack.arrangedSubviews) {
+ NSUInteger i = key.count++;
+ if (i >= 16) continue;
+ key.items[i].item = (__bridge const void *)item;
+ key.items[i].frame = item.frame;
+ key.items[i].hidden = item.hidden;
+ }
+ static typeof(key) lastKey;
+ if (!memcmp(&key, &lastKey, sizeof key)) return;
+ memcpy(&lastKey, &key, sizeof key);
NSMutableString *out = [NSMutableString stringWithFormat:@"row in %@ %@, icon %@ label %@, stack %@ axis %ld dist %ld align %ld spacing %.1f autolayout %d",
NSStringFromClass(tabBar.class), NSStringFromCGRect(tabBar.frame),
NSStringFromCGRect(sg_iconBox), NSStringFromCGRect(sg_labelBox), NSStringFromCGRect(stack.frame),
diff --git a/tweak/Sources/Native/Player/LyricsCard.x b/tweak/Sources/Native/Player/LyricsCard.x
index d35c79f2..50cee2a1 100644
--- a/tweak/Sources/Native/Player/LyricsCard.x
+++ b/tweak/Sources/Native/Player/LyricsCard.x
@@ -15,7 +15,8 @@ static char kCardGlassKey;
// The cell around the card, the view Spotify paints and rounds.
static UIView *cellAround(UIView *view) {
- Class cell = NSClassFromString(@"_TtC12Element_List18CollectionViewCell");
+ static Class cell;
+ if (!cell) cell = NSClassFromString(@"_TtC12Element_List18CollectionViewCell");
for (UIView *v = view; v; v = v.superview) {
if ([v isKindOfClass:cell]) return v;
}
diff --git a/tweak/Sources/Native/Player/Player.x b/tweak/Sources/Native/Player/Player.x
index 42178614..e5ffa5b3 100644
--- a/tweak/Sources/Native/Player/Player.x
+++ b/tweak/Sources/Native/Player/Player.x
@@ -160,7 +160,14 @@ static UIView *backdropIn(UIView *plane) {
tilt.layer.shadowOpacity = 0.45;
tilt.layer.shadowRadius = 32;
tilt.layer.shadowOffset = CGSizeMake(0, 12);
- tilt.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:tilt.bounds cornerRadius:kArtRadius].CGPath;
+ // A path made once per size, kept while the layer still holds that very path: one Spotify sets is replaced.
+ static char kShadowPathKey;
+ CGPathRef path = tilt.layer.shadowPath;
+ if (!path || path != (__bridge CGPathRef)objc_getAssociatedObject(tilt, &kShadowPathKey)
+ || !CGRectEqualToRect(CGPathGetBoundingBox(path), tilt.bounds)) {
+ tilt.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:tilt.bounds cornerRadius:kArtRadius].CGPath;
+ objc_setAssociatedObject(tilt, &kShadowPathKey, (__bridge id)tilt.layer.shadowPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ }
}
%end
diff --git a/tweak/Sources/Native/Player/PlayerDeclutter.x b/tweak/Sources/Native/Player/PlayerDeclutter.x
index 92eb7e78..138e0a4c 100644
--- a/tweak/Sources/Native/Player/PlayerDeclutter.x
+++ b/tweak/Sources/Native/Player/PlayerDeclutter.x
@@ -25,16 +25,35 @@ static const struct { __unsafe_unretained NSString *marker, *key; } cards[] = {
{@"RelatedContentRecommendations", SGHideRecommendations},
};
-// Class names of everything in the cell. Lists nested in the cell are laid out first so the
+enum { kCards = sizeof(cards) / sizeof(cards[0]) };
+
+static BOOL anyCardSwitch(void) {
+ for (size_t i = 0; i < kCards; i++) {
+ if (SGHidden(cards[i].key)) return YES;
+ }
+ return NO;
+}
+
+// Whether the cell is one of the player's cards: its own first subview or its content view's names the page.
+// Spotify's cell has held the name in both places (Redesigned/Player/PlayerCards.x, and the trees above).
+static BOOL onPlayer(UICollectionViewCell *cell) {
+ return SGClassNamed(cell.subviews.firstObject.class, @"NowPlaying_ScrollAPI")
+ || SGClassNamed(cell.contentView.subviews.firstObject.class, @"NowPlaying_ScrollAPI");
+}
+
+// The first switched-on card a class in the cell names. Lists nested in the cell are laid out first so the
// cells that name the card (video cards) exist.
-static NSString *classNamesIn(UIView *cell) {
- NSMutableString *names = [NSMutableString string];
+static NSString *switchedCardIn(UIView *cell) {
+ unsigned hidden = 0; // a bit per switched-on card (a block cannot capture an array)
+ for (size_t i = 0; i < kCards; i++) if (SGHidden(cards[i].key)) hidden |= 1u << i;
+ __block size_t first = kCards;
SGForEachView(cell, ^(UIView *v) {
if (v != cell && [v isKindOfClass:UICollectionView.class]) [v layoutIfNeeded];
- [names appendString:NSStringFromClass(v.class)];
- [names appendString:@"\n"];
+ for (size_t i = 0; i < first; i++) {
+ if ((hidden & 1u << i) && SGClassNamed(v.class, cards[i].marker)) first = i;
+ }
});
- return names;
+ return first < kCards ? cards[first].key : nil;
}
// An ad among the cards (a sponsored playlist's "Advertisement" card, 9.1.78): built of Encore's own views, it is
@@ -48,22 +67,16 @@ static BOOL holdsAd(UIView *cell) {
}
static NSString *hiddenKeyFor(UICollectionViewCell *cell) {
+ // Only the player's cards are looked into: they name the page, which every other list's cells do not.
+ BOOL hideAds = SGHidden(SGKeyHideAds), anyCard = anyCardSwitch();
+ if (!(hideAds || anyCard) || !onPlayer(cell)) return nil;
// A cell inside another card's list: the outer card decides.
for (UIView *v = cell.superview; v; v = v.superview) {
if ([v isKindOfClass:cell.class]) return nil;
}
- NSString *names = nil;
- // Only the player's cards are looked into: their content view names the page, which every other list's does not.
- if (SGHidden(SGKeyHideAds)) {
- UIView *content = cell.contentView.subviews.firstObject;
- if ([NSStringFromClass(content.class) containsString:@"NowPlaying_ScrollAPI"] && holdsAd(cell)) return SGKeyHideAds;
- }
- for (size_t i = 0; i < sizeof(cards) / sizeof(cards[0]); i++) {
- if (!SGHidden(cards[i].key)) continue;
- if (!names) names = classNamesIn(cell);
- if ([names containsString:@"NowPlaying_ScrollAPI"] && [names containsString:cards[i].marker]) return cards[i].key;
- }
- return nil;
+ // The ad card has been seen only with the name on its content view, so only that shape is searched for ads.
+ if (hideAds && SGClassNamed(cell.contentView.subviews.firstObject.class, @"NowPlaying_ScrollAPI") && holdsAd(cell)) return SGKeyHideAds;
+ return anyCard ? switchedCardIn(cell) : nil;
}
%hook _TtC12Element_List18CollectionViewCell
@@ -96,11 +109,13 @@ static void finish(UIViewController *unit, BOOL changed) {
%hook _TtC20NowPlaying_ModesImpl28PlaybackControlsElementsUnit
- (void)viewDidLayoutSubviews {
%orig;
+ BOOL hideShuffle = SGHidden(SGHideShuffle), hideRepeat = SGHidden(SGHideRepeat);
+ if (!hideShuffle && !hideRepeat) return;
NSArray<UIView *> *items = SGRowIn(((UIViewController *)self).viewIfLoaded).arrangedSubviews;
if (items.count != 5 || !SGHasClass(items[2], @"PlayButton")) return;
BOOL changed = NO;
- if (SGHidden(SGHideShuffle)) changed |= vanish(items[0]);
- if (SGHidden(SGHideRepeat)) changed |= vanish(items[4]);
+ if (hideShuffle) changed |= vanish(items[0]);
+ if (hideRepeat) changed |= vanish(items[4]);
finish((UIViewController *)self, changed);
}
%end
@@ -108,15 +123,17 @@ static void finish(UIViewController *unit, BOOL changed) {
%hook _TtC20NowPlaying_ModesImpl18FooterElementsUnit
- (void)viewDidLayoutSubviews {
%orig;
+ BOOL hideConnect = SGHidden(SGHideConnect), hideQueue = SGHidden(SGHideQueue), hideShare = SGHidden(SGHideShare);
+ if (!hideConnect && !hideQueue && !hideShare) return;
BOOL changed = NO;
for (UIView *item in SGRowIn(((UIViewController *)self).viewIfLoaded).arrangedSubviews) {
if (item.hidden || item.bounds.size.width < 20) continue;
if (SGHasClass(item, @"Connect")) {
- if (SGHidden(SGHideConnect)) changed |= vanish(item);
+ if (hideConnect) changed |= vanish(item);
} else if (SGHasClass(item, @"QueueButton")) {
- if (SGHidden(SGHideQueue)) changed |= vanish(item);
+ if (hideQueue) changed |= vanish(item);
} else if (item.bounds.size.width <= 48 && SGHasClass(item, @"EncoreButton")) {
- if (SGHidden(SGHideShare)) changed |= vanish(item);
+ if (hideShare) changed |= vanish(item);
}
}
finish((UIViewController *)self, changed);
diff --git a/tweak/Sources/Native/Playlist/Playlist.x b/tweak/Sources/Native/Playlist/Playlist.x
index 7c7ff266..9765bcf6 100644
--- a/tweak/Sources/Native/Playlist/Playlist.x
+++ b/tweak/Sources/Native/Playlist/Playlist.x
@@ -21,77 +21,81 @@
- (NSLayoutConstraint *)layoutGuideHeightConstraint;
@end
-static UIView *viewNamed(UIView *root, NSString *marker) {
- __block UIView *found = nil;
- SGForEachView(root, ^(UIView *v) {
- if (!found && [NSStringFromClass(v.class) containsString:marker]) found = v;
- });
- return found;
-}
-
-// A prefix, not the whole identifier: the download button carries its state in the tail.
-static UIView *identNamed(UIView *root, NSString *ident) {
- __block UIView *found = nil;
- SGForEachView(root, ^(UIView *v) {
- if (!found && [v.accessibilityIdentifier hasPrefix:ident]) found = v;
- });
- return found;
-}
-
-// Only ever hides. A switch turned off again shows after Spotify restarts, like every other one.
-static void hide(UIView *view, NSString *key) {
- if (view && SGHidden(key)) view.hidden = YES;
+static const struct { __unsafe_unretained NSString *ident, *key; } buttons[] = {
+ {@"Components.UI.WatchFeedEntityExplorerButton", SGHidePlaylistVideo},
+ {@"Components.UI.AddToButton", SGHidePlaylistAddTo},
+ {@"DownloadButton.Granular", SGHidePlaylistDownload},
+ {@"Components.UI.ShareButton", SGHidePlaylistShare},
+ {@"Components.UI.ContextMenuButton", SGHidePlaylistMore},
+};
+enum { kButtons = sizeof(buttons) / sizeof(buttons[0]) };
+
+// Each part's view, remembered on the view it was found under (Core/SGViewTree.h).
+static char kCoverKey, kDescriptionKey, kFindKey, kArtworkKey, kPillsKey, kButtonKeys[kButtons];
+
+static BOOL anyButtonSwitch(void) {
+ for (size_t i = 0; i < kButtons; i++) {
+ if (SGHidden(buttons[i].key)) return YES;
+ }
+ return NO;
}
// The header layout is Encore's own class, so the hook asks whose page it is before touching it.
static UIViewController *playlistHeaderOf(UIView *view) {
for (UIResponder *r = view; r; r = r.nextResponder) {
if (![r isKindOfClass:UIViewController.class]) continue;
- return [NSStringFromClass(r.class) containsString:@"FreeTierPlaylist"] ? (UIViewController *)r : nil;
+ return SGClassNamed(r.class, @"FreeTierPlaylist") ? (UIViewController *)r : nil;
}
return nil;
}
+// Each switch only ever hides, here and below. A switch turned off again shows after Spotify restarts, like
+// every other one.
+
// Title, description, the creator row and the length share one column, and only the description
// names a class of its own, so the column is reached through it and its rows go by what they hold.
// The length is the last row rather than the second stack: a byline without faces is a stack too.
+// A row already hidden is passed over.
static void applyColumn(UIView *header) {
+ BOOL hideDescription = SGHidden(SGHidePlaylistDescription), hideCreator = SGHidden(SGHidePlaylistCreator);
+ BOOL hideLength = SGHidden(SGHidePlaylistLength);
+ if (!hideDescription && !hideCreator && !hideLength) return;
UIView *column = nil;
- for (UIView *v = viewNamed(header, @"ExpandableTextView"); v && v != header; v = v.superview) {
- if (![NSStringFromClass(v.superview.class) containsString:@"AutoLayoutStackView"]) continue;
+ UIView *description = SGFindRemembered(header, &kDescriptionKey, ^BOOL(UIView *v) { return SGClassNamed(v.class, @"ExpandableTextView"); });
+ for (UIView *v = description; v && v != header; v = v.superview) {
+ if (!SGClassNamed(v.superview.class, @"AutoLayoutStackView")) continue;
column = v;
break;
}
for (UIView *row in column.subviews) {
- BOOL last = row == column.subviews.lastObject && [NSStringFromClass(row.class) containsString:@"StackView"];
- if (SGHasClass(row, @"ExpandableTextView")) hide(row, SGHidePlaylistDescription);
- else if (SGHasClass(row, @"FacepileView")) hide(row, SGHidePlaylistCreator);
- else if (last) hide(row, SGHidePlaylistLength);
+ if (row.hidden) continue;
+ BOOL last = row == column.subviews.lastObject && SGClassNamed(row.class, @"StackView");
+ BOOL hide = NO;
+ if (SGHasClass(row, @"ExpandableTextView")) hide = hideDescription;
+ else if (SGHasClass(row, @"FacepileView")) hide = hideCreator;
+ else if (last) hide = hideLength;
+ if (hide) row.hidden = YES;
}
}
// The identifier sits on the button, the stack arranges the action around it, so each switch hides
// the action rather than the button and the row closes up behind it.
+// An action already hidden is passed over.
static void applyActions(UIView *row) {
- static const struct { __unsafe_unretained NSString *ident, *key; } buttons[] = {
- {@"Components.UI.WatchFeedEntityExplorerButton", SGHidePlaylistVideo},
- {@"Components.UI.AddToButton", SGHidePlaylistAddTo},
- {@"DownloadButton.Granular", SGHidePlaylistDownload},
- {@"Components.UI.ShareButton", SGHidePlaylistShare},
- {@"Components.UI.ContextMenuButton", SGHidePlaylistMore},
- };
for (UIView *action in row.subviews) {
- for (size_t i = 0; i < sizeof(buttons) / sizeof(buttons[0]); i++) {
- if (identNamed(action, buttons[i].ident)) hide(action, buttons[i].key);
+ for (size_t i = 0; i < kButtons && !action.hidden; i++) {
+ if (SGHidden(buttons[i].key) && SGFindIdentifier(action, buttons[i].ident, &kButtonKeys[i])) action.hidden = YES;
}
}
}
// Find on page and Sort sit in a header view of their own, one that holds nothing else.
static void applyFindBar(UIView *header) {
- for (UIView *v = viewNamed(header, @"EncoreTextField"); v && v != header; v = v.superview) {
- if (![NSStringFromClass(v.class) containsString:@"HeaderView"]) continue;
- hide(v, SGHidePlaylistFind);
+ if (!SGHidden(SGHidePlaylistFind)) return;
+ UIView *field = SGFindRemembered(header, &kFindKey, ^BOOL(UIView *v) { return SGClassNamed(v.class, @"EncoreTextField"); });
+ for (UIView *v = field; v && v != header; v = v.superview) {
+ if (!SGClassNamed(v.class, @"HeaderView")) continue;
+ v.hidden = YES;
return;
}
}
@@ -146,7 +150,7 @@ static char kBackdropKey, kSourceKey;
static void applyBackdrop(UIView *layout) {
if (!SGFlag(SGKeyPlaylistBackdrop, NO)) return;
UIImage *image = nil;
- for (UIView *v in identNamed(layout, @"EditableHeaderArtworkElement.ImageView").subviews) {
+ for (UIView *v in SGFindIdentifier(layout, @"EditableHeaderArtworkElement.ImageView", &kArtworkKey).subviews) {
if ([v isKindOfClass:UIImageView.class] && ((UIImageView *)v).image) image = ((UIImageView *)v).image;
}
if (!image) return;
@@ -178,8 +182,8 @@ static void applyBackdrop(UIView *layout) {
%orig;
UIViewController *headerVC = playlistHeaderOf((UIView *)self);
if (!headerVC) return;
- UIView *layout = (UIView *)self, *cover = identNamed(layout, @"Components.Header.UI.ArtworkImage");
- hide(cover, SGHidePlaylistArtwork);
+ UIView *layout = (UIView *)self, *cover = SGFindIdentifier(layout, @"Components.Header.UI.ArtworkImage", &kCoverKey);
+ if (SGHidden(SGHidePlaylistArtwork)) cover.hidden = YES;
applyColumn(layout);
applyBackdrop(layout);
if (cover.hidden) collapseCover(headerVC, layout, cover);
@@ -190,9 +194,10 @@ static void applyBackdrop(UIView *layout) {
%hook UIImageView
- (void)setImage:(UIImage *)image {
%orig;
- if (!image || ![self.superview.accessibilityIdentifier isEqualToString:@"EditableHeaderArtworkElement.ImageView"]) return;
+ if (!image || ![self.superview.accessibilityIdentifier isEqualToString:@"EditableHeaderArtworkElement.ImageView"]
+ || !SGFlag(SGKeyPlaylistBackdrop, NO)) return;
for (UIView *v = self.superview; v; v = v.superview) {
- if (![NSStringFromClass(v.class) containsString:@"HeaderContentLayout"]) continue;
+ if (!SGClassNamed(v.class, @"HeaderContentLayout")) continue;
if (playlistHeaderOf(v)) applyBackdrop(v);
return;
}
@@ -204,7 +209,7 @@ static void applyBackdrop(UIView *layout) {
%hook UIStackView
- (void)layoutSubviews {
%orig;
- if ([self.accessibilityIdentifier isEqualToString:@"HeaderActionsRow"] && playlistHeaderOf(self)) applyActions(self);
+ if ([self.accessibilityIdentifier isEqualToString:@"HeaderActionsRow"] && anyButtonSwitch() && playlistHeaderOf(self)) applyActions(self);
}
%end
@@ -224,7 +229,8 @@ static void applyBackdrop(UIView *layout) {
%hook _TtC35ListUXPlatform_FreeTierPlaylistImpl25ElementCollectionViewCell
- (UICollectionViewLayoutAttributes *)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)attributes {
UICollectionViewLayoutAttributes *result = %orig;
- if (!SGHidden(SGHidePlaylistPills) || !identNamed((UIView *)self, @"PlaylistCuration.Row.CurationActionsToolbar")) return result;
+ if (!SGHidden(SGHidePlaylistPills)
+ || !SGFindIdentifier((UIView *)self, @"PlaylistCuration.Row.CurationActionsToolbar", &kPillsKey)) return result;
result.size = CGSizeMake(result.size.width, 0);
((UIView *)self).clipsToBounds = YES;
static dispatch_once_t once;
diff --git a/tweak/Sources/Redesigned/Album/AlbumField.x b/tweak/Sources/Redesigned/Album/AlbumField.x
index 6f171091..58bafe8e 100644
--- a/tweak/Sources/Redesigned/Album/AlbumField.x
+++ b/tweak/Sources/Redesigned/Album/AlbumField.x
@@ -40,22 +40,57 @@ static char kFieldKey;
#pragma mark - the page
+// Where a cell of a list is: the page it is on, and whether it is a row of the page's own list rather than a card
+// inside one of its carousels -- a card is a cell of the same class, and the row that carries the carousel decides
+// for it (Artist/ArtistSections.x). Worked out once the cell is in a window and kept on it, since a cell never
+// leaves its list nor the list its page; every cell of the class asks on every pass, Home's and Search's included.
+@interface SGRAlbumPlace : NSObject
+@property (nonatomic, weak) UIView *page;
+@property (nonatomic) BOOL pageCell;
+// pagesFound when no page was found: a cell measured before Spotify names its page looks again once one turns up.
+@property (nonatomic) NSInteger pagesFound;
+@end
+
+@implementation SGRAlbumPlace
+@end
+
+static char kPlaceKey;
+static NSInteger pagesFound;
+static __weak UIView *lastPage;
+
+static SGRAlbumPlace *placeOf(UIView *cell) {
+ SGRAlbumPlace *place = objc_getAssociatedObject(cell, &kPlaceKey);
+ if (place.page || (place && place.pagesFound == pagesFound)) return place;
+ place = [SGRAlbumPlace new];
+ BOOL nested = NO;
+ for (UIView *v = cell; v; v = v.superview) {
+ if (v != cell && [v isKindOfClass:UICollectionViewCell.class]) nested = YES;
+ if ([v.accessibilityIdentifier isEqualToString:kPageIdentifier]) {
+ place.page = v;
+ place.pageCell = !nested;
+ break;
+ }
+ }
+ if (place.page && place.page != lastPage) {
+ lastPage = place.page;
+ pagesFound++;
+ }
+ place.pagesFound = pagesFound;
+ if (cell.window) objc_setAssociatedObject(cell, &kPlaceKey, place, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ return place;
+}
+
UIView *SGRAlbumPageOf(UIView *view) {
+ if ([view isKindOfClass:UICollectionViewCell.class]) return placeOf(view).page;
for (UIView *v = view; v; v = v.superview) {
if ([v.accessibilityIdentifier isEqualToString:kPageIdentifier]) return v;
}
return nil;
}
-// A cell of the page's own list rather than a card inside one of its carousels: a card is a cell of the
-// same class, and the row that carries the carousel decides for it (Artist/ArtistSections.x). So the walk
-// up to the page stops at the first cell it meets on the way.
static BOOL isPageCell(UIView *cell) {
- for (UIView *v = cell.superview; v; v = v.superview) {
- if ([v isKindOfClass:UICollectionViewCell.class]) return NO;
- if ([v.accessibilityIdentifier isEqualToString:kPageIdentifier]) return YES;
- }
- return NO;
+ SGRAlbumPlace *place = placeOf(cell);
+ return place.pageCell && place.page;
}
#pragma mark - the page's field
diff --git a/tweak/Sources/Redesigned/Album/AlbumHeader.x b/tweak/Sources/Redesigned/Album/AlbumHeader.x
index 4b48da5f..f1e00825 100644
--- a/tweak/Sources/Redesigned/Album/AlbumHeader.x
+++ b/tweak/Sources/Redesigned/Album/AlbumHeader.x
@@ -420,7 +420,7 @@ static NSString *metadataText(UIView *metadata) {
static void applyHeader(UIView *header, UIView *page);
// The Kit's view over the whole header, its content on the header's bottom edge; Spotify's own column goes.
-static SGRHeaderInfo *applyInfo(UIView *header, UIView *page) {
+static SGRHeaderInfo *applyInfo(UIView *header, UIView *page, NSString **artist, NSString **album) {
SGRHeaderInfo *info = objc_getAssociatedObject(header, &kInfoKey);
if (!info) {
info = [[SGRHeaderInfo alloc] initWithFrame:CGRectZero];
@@ -445,11 +445,12 @@ static SGRHeaderInfo *applyInfo(UIView *header, UIView *page) {
}
UIView *parent = SGRFindByIdentifier(header, @"CreativeWorkPlatform.Components.UI.ParentRow", &kParentKey);
UIView *metadata = SGRFindByIdentifier(header, @"Components.UI.MetadataRow", &kMetaKey);
- NSString *length = metadataText(metadata);
- [info showTitle:firstText(title) creator:firstText(parent) ?: trimmed(parent.accessibilityLabel)
- length:length about:nil];
+ NSString *length = metadataText(metadata), *line = firstText(parent);
+ *album = firstText(title);
+ *artist = line ?: trimmed(parent.accessibilityLabel);
+ [info showTitle:*album creator:*artist length:length about:nil];
// The line as it reads, without the accessibility label to fall back on: no line, no row loses its artist.
- SGRAlbumSetArtist(page, firstText(parent));
+ SGRAlbumSetArtist(page, line);
// The kind and the date are cells the metadata row's collection view makes on its own pass, after the
// header's, and nothing lays the header out again when they arrive; the collection is Spotify's own Swift
// class, which cannot be watched. So an empty row is read again a moment later, a few times at most.
@@ -566,7 +567,8 @@ static void applyHeader(UIView *header, UIView *page) {
if (!SGRFindByIdentifier(header, @"CreativeWorkPlatform.Components.UI.TitleRow", &kTitleKey)) return;
SGRAlbumHoldPage(page);
applyWash(page);
- SGRHeaderInfo *info = applyInfo(header, page);
+ NSString *artist, *album;
+ SGRHeaderInfo *info = applyInfo(header, page, &artist, &album);
// The picture reaches to where the content's top is at rest, plus the title and the artist. The header at
// rest is the tallest it has been, so the picture does not change size as the header loads or scrolls.
@@ -576,9 +578,7 @@ static void applyHeader(UIView *header, UIView *page) {
UIView *cover = SGRFindByIdentifier(header, @"CreativeWorkPlatform.Components.UI.ArtWorkElement.WithCoverArt", &kCoverKey);
if (cover) applyHero(header, cover, bottom);
SGRAlbumHero *hero = objc_getAssociatedObject(header, &kHeroKey);
- UIView *title = SGRFindByIdentifier(header, @"CreativeWorkPlatform.Components.UI.TitleRow", &kTitleKey);
- UIView *parent = SGRFindByIdentifier(header, @"CreativeWorkPlatform.Components.UI.ParentRow", &kParentKey);
- [hero playMotionForArtist:firstText(parent) ?: trimmed(parent.accessibilityLabel) album:firstText(title)];
+ [hero playMotionForArtist:artist album:album];
}
static void applyPage(UIView *page) {
diff --git a/tweak/Sources/Redesigned/Artist/ArtistHeader.x b/tweak/Sources/Redesigned/Artist/ArtistHeader.x
index e2206349..9d8c7852 100644
--- a/tweak/Sources/Redesigned/Artist/ArtistHeader.x
+++ b/tweak/Sources/Redesigned/Artist/ArtistHeader.x
@@ -41,7 +41,7 @@ static const CGFloat kMinCover = 80, kMinHero = 120;
// The collapsed ImageHeaderView, Spotify's navigation bar; the text fades out over the last kFade before it.
static const CGFloat kBar = 100, kFade = 150;
-static char kInfoKey, kHeroKey, kHeroHeightKey, kContainerHeightKey, kRowWatchedKey;
+static char kInfoKey, kHeroKey, kHeroHeightKey, kContainerHeightKey, kRowWatchedKey, kSizeKey;
static char kTitleKey, kMetaKey, kShuffleKey, kPlayKey, kFollowKey, kArtworkKey, kBarKey, kMoreKey, kMoreButtonKey;
#pragma mark - Spotify's views
@@ -220,7 +220,7 @@ static UIImageView *photoIn(UIView *artwork) {
// The picture from the top of the container down to `bottom`, which comes from the container at rest and only
// ever grows, so it does not change size while the page loads or scrolls.
-static void applyHero(UIView *container, UIView *artwork, CGFloat bottom) {
+static void applyHero(UIView *container, UIView *artwork, CGFloat bottom, UIColor *fieldColor) {
SGRArtistHero *hero = objc_getAssociatedObject(container, &kHeroKey);
if (!hero) {
hero = [[SGRArtistHero alloc] initWithFrame:CGRectZero];
@@ -237,13 +237,14 @@ static void applyHero(UIView *container, UIView *artwork, CGFloat bottom) {
}
if (height < kMinHero) return;
setFrame(hero, CGRectMake(0, 0, container.bounds.size.width, height));
- hero.fieldColor = SGRArtistFieldColor(container);
+ hero.fieldColor = fieldColor;
[hero followArtwork:photoIn(artwork)];
}
#pragma mark - the header's pass
-static void applyHeader(UIView *header);
+static void applyHeader(UIView *header, BOOL full);
+static void applyContent(UIView *header, UIView *container, SGRHeaderInfo *info, NSString *name, UIView *listeners, UIColor *fieldColor);
// Spotify's navigation bar, the one part of the header kept: collapsed, it is where the name is. Its gradient
// is a flat dark band over the field, as the album's was (Album/AlbumHeader.x); the soft top edge every
@@ -262,10 +263,16 @@ static UIView *keepBar(UIView *header) {
return foreground;
}
-static void applyHeader(UIView *header) {
+// `full` NO is the header's own pass: a step of the collapse (its height changed, its width did not) then only
+// moves and fades, unless the name or the listeners changed; any other pass and the row's take everything again.
+static void applyHeader(UIView *header, BOOL full) {
+ CGSize size = header.bounds.size;
+ NSValue *last = objc_getAssociatedObject(header, &kSizeKey);
+ if (!full) full = !last || last.CGSizeValue.width != size.width || last.CGSizeValue.height == size.height;
UIView *container = containerOf(header);
UIView *artwork = SGRFindByIdentifier(header, @"Components.Header.UI.ArtworkImage", &kArtworkKey);
if (!container || !artwork || !SGRArtistPageOf(container)) return;
+ objc_setAssociatedObject(header, &kSizeKey, [NSValue valueWithCGSize:size], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
UIView *bar = keepBar(header);
for (UIView *sub in header.subviews) {
@@ -293,19 +300,16 @@ static void applyHeader(UIView *header) {
UIView *title = SGRFindByIdentifier(header, @"Encore.AdaptiveTitle", &kTitleKey);
UIView *listeners = SGRFindByIdentifier(header, @"Components.Header.UI.Metadata", &kMetaKey);
NSString *name = firstText(title) ?: firstText(bar);
- [info showTitle:name creator:nil length:firstText(listeners) about:nil];
- showLogo(info, name);
-
- UIView *shuffle = SGRFindByIdentifier(header, @"Components.UI.ShuffleButton", &kShuffleKey);
- UIView *play = SGRFindByIdentifier(header, @"header-play-button", &kPlayKey);
- UIView *follow = SGRFindByIdentifier(header, @"Curation.FollowButtonElementKit.FollowButton", &kFollowKey);
- [info showShuffle:shuffle play:play trailing:follow trailingFallback:nil playColor:SGRArtistFieldColor(container)];
-
- // More, in the top trailing corner of the page itself rather than of the container, which scrolls away
- // with the photo: pinned there it is the same button in the same place on the album and the playlist,
- // and the page keeps it however far down the list one is (issue #57).
- UIView *more = SGRFindByIdentifier(header, @"Components.UI.ContextMenuButton*", &kMoreKey);
- SGRPinnedMore(SGRArtistPageOf(container), &kMoreButtonKey, more);
+ full |= [info showTitle:name creator:nil length:firstText(listeners) about:nil];
+ // Play's glyph and word are drawn in the field's color, which lands whenever the photo's has been read.
+ UIColor *fieldColor = SGRArtistFieldColor(container);
+ full |= ![fieldColor isEqual:info.handedPlayColor];
+ // Until the buttons' row is found and watched, every pass looks for it: it can arrive after the last full one.
+ full |= !info.rowFound;
+ if (full) {
+ info.handedPlayColor = fieldColor;
+ applyContent(header, container, info, name, listeners, fieldColor);
+ }
// Collapsing, the text would pass over Spotify's bar with the name in it: it goes over the last kFade of
// the collapse, from the header's own height, which this pass runs on every step of. More stays: it is
@@ -318,7 +322,23 @@ static void applyHeader(UIView *header) {
CGFloat rest = MAX([objc_getAssociatedObject(container, &kContainerHeightKey) doubleValue], container.bounds.size.height);
objc_setAssociatedObject(container, &kContainerHeightKey, @(rest), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
CGFloat bottom = rest - SGRHeaderInfoBottom - [info contentHeightForWidth:container.bounds.size.width] + SGRHeaderInfoTitleRise;
- applyHero(container, artwork, bottom);
+ applyHero(container, artwork, bottom, fieldColor);
+}
+
+// What the header shows besides its text: the logo, the buttons, More, and the watch on the buttons' row.
+static void applyContent(UIView *header, UIView *container, SGRHeaderInfo *info, NSString *name, UIView *listeners, UIColor *fieldColor) {
+ showLogo(info, name);
+
+ UIView *shuffle = SGRFindByIdentifier(header, @"Components.UI.ShuffleButton", &kShuffleKey);
+ UIView *play = SGRFindByIdentifier(header, @"header-play-button", &kPlayKey);
+ UIView *follow = SGRFindByIdentifier(header, @"Curation.FollowButtonElementKit.FollowButton", &kFollowKey);
+ [info showShuffle:shuffle play:play trailing:follow trailingFallback:nil playColor:fieldColor];
+
+ // More, in the top trailing corner of the page itself rather than of the container, which scrolls away
+ // with the photo: pinned there it is the same button in the same place on the album and the playlist,
+ // and the page keeps it however far down the list one is (issue #57).
+ UIView *more = SGRFindByIdentifier(header, @"Components.UI.ContextMenuButton*", &kMoreKey);
+ SGRPinnedMore(SGRArtistPageOf(container), &kMoreButtonKey, more);
// The buttons arrive after the header has laid out, in a row that keeps its size and so lays nothing out
// again (Native/Artist/Artist.x): the row's own pass is watched, a plain UIStackView.
@@ -328,9 +348,10 @@ static void applyHeader(UIView *header) {
objc_setAssociatedObject(row, &kRowWatchedKey, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
__weak UIView *weakHeader = header;
SGRObserveLayout(row, ^(UIView *view) {
- if (weakHeader) applyHeader(weakHeader);
+ if (weakHeader) applyHeader(weakHeader, YES);
});
}
+ if (row && objc_getAssociatedObject(row, &kRowWatchedKey)) info.rowFound = YES;
static BOOL logged;
if (!logged && header.window && name) {
@@ -369,7 +390,7 @@ static void clearNavigationBar(UIView *header) {
%hook _TtC35CreativeWorkPlatform_ImageHeaderKit15ImageHeaderView
- (void)layoutSubviews {
%orig;
- applyHeader((UIView *)self);
+ applyHeader((UIView *)self, NO);
clearNavigationBar((UIView *)self);
}
%end
diff --git a/tweak/Sources/Redesigned/Artist/ArtistSections.x b/tweak/Sources/Redesigned/Artist/ArtistSections.x
index 0eb97953..e9303e85 100644
--- a/tweak/Sources/Redesigned/Artist/ArtistSections.x
+++ b/tweak/Sources/Redesigned/Artist/ArtistSections.x
@@ -100,6 +100,30 @@ static UICollectionView *listOf(UIView *cell) {
return nil;
}
+static char kPageListKey;
+
+// Bumped each time a different page is found. A cell measured before Spotify names its page keeps a NO only until then.
+static NSInteger pagesFound;
+static __weak UIView *lastPage;
+
+// Whether the cell is a row of the page's own list: a card inside a carousel is a cell of the same class, and its row
+// decides. Worked out once the cell is in a window and kept on it, since a cell never leaves its list nor the list its
+// page; every cell of the class asks on every pass, Home's and Search's included. Kept as -1 for YES, or as
+// pagesFound when it said NO.
+static BOOL onPageList(UICollectionViewCell *cell) {
+ NSNumber *known = objc_getAssociatedObject(cell, &kPageListKey);
+ if (known.integerValue == -1) return YES;
+ if (known && known.integerValue == pagesFound) return NO;
+ UICollectionView *list = listOf(cell);
+ UIView *page = list && ![listOf(list) isKindOfClass:UICollectionView.class] ? SGRArtistPageOf(cell) : nil;
+ if (page && page != lastPage) {
+ lastPage = page;
+ pagesFound++;
+ }
+ if (cell.window) objc_setAssociatedObject(cell, &kPageListKey, @(page ? -1 : pagesFound), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ return page != nil;
+}
+
static void settle(UICollectionViewCell *cell, CGFloat natural) {
UIView *content = cell.contentView;
objc_setAssociatedObject(cell, &kSettledKey, @(natural), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
@@ -160,9 +184,9 @@ static void logOnce(NSString *what) {
%hook _TtC12Element_List18CollectionViewCell
- (UICollectionViewLayoutAttributes *)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)attributes {
UICollectionViewCell *cell = (UICollectionViewCell *)self;
- UICollectionView *list = listOf(cell);
// Only the page's own list: a card inside a carousel is a cell of the same class, and its row decides.
- BOOL page = list && ![listOf(list) isKindOfClass:UICollectionView.class] && SGRArtistPageOf(cell) && attributes.indexPath;
+ BOOL page = onPageList(cell) && attributes.indexPath;
+ UICollectionView *list = page ? listOf(cell) : nil;
if (!page) {
if (objc_getAssociatedObject(cell, &kSettledKey)) unsettle(cell);
return %orig;
@@ -195,8 +219,7 @@ static void logOnce(NSString *what) {
UICollectionViewCell *cell = (UICollectionViewCell *)self;
NSNumber *settled = objc_getAssociatedObject(self, &kSettledKey);
if (settled) settle(cell, settled.doubleValue);
- UICollectionView *list = listOf(cell);
- if (list && ![listOf(list) isKindOfClass:UICollectionView.class] && SGRArtistPageOf(cell)) {
+ if (onPageList(cell)) {
// What the cell paints over the field -- the "You liked" row, every carousel's collection and the
// fade Popular's "See more" draws over its last track (device, trees/continuous/3.txt 2026-09-18).
SGRClearCellPaint(cell);
diff --git a/tweak/Sources/Redesigned/Home/HomeHeader.x b/tweak/Sources/Redesigned/Home/HomeHeader.x
index 7ffe9faf..8c396731 100644
--- a/tweak/Sources/Redesigned/Home/HomeHeader.x
+++ b/tweak/Sources/Redesigned/Home/HomeHeader.x
@@ -333,7 +333,10 @@ static void rise(UIView *part, CGAffineTransform transform, CGFloat alpha) {
// The pill's glass takes no alpha (SGRGlass.h): it rises with the row, and its material goes off once the row is
// half faded and comes back with it.
+static const NSTimeInterval kGlassFade = 0.15;
static BOOL sg_glassShown = YES;
+// When the material's last change ends: until then the glass keeps rising after the row has faded.
+static CFTimeInterval sg_glassFadeEnds;
static void riseGlass(UIView *glass, CGAffineTransform transform, CGFloat alpha) {
if (!glass) return;
if (!CGAffineTransformEqualToTransform(glass.transform, transform)) glass.transform = transform;
@@ -341,17 +344,21 @@ static void riseGlass(UIView *glass, CGAffineTransform transform, CGFloat alpha)
UIView *shape = objc_getAssociatedObject(glass, &kPillGlassKey);
if (!shape || shown == sg_glassShown) return;
sg_glassShown = shown;
- [UIView animateWithDuration:0.15 animations:^{ SGRShowGlass(shape, shown); }];
+ sg_glassFadeEnds = CACurrentMediaTime() + kGlassFade;
+ [UIView animateWithDuration:kGlassFade animations:^{ SGRShowGlass(shape, shown); }];
}
static void followScroll(UIScrollView *scroll) {
UILabel *title = sg_header ? objc_getAssociatedObject(sg_header, &kTitleKey) : nil;
if (!title || !scroll) return;
- CGFloat scrolled = MAX(0, scroll.contentOffset.y + scroll.adjustedContentInset.top);
- CGAffineTransform up = CGAffineTransformMakeTranslation(0, -scrolled);
- CGFloat alpha = 1 - MIN(1, scrolled / MAX(1, title.bounds.size.height));
+ CGFloat scrolled = MAX(0, scroll.contentOffset.y + scroll.adjustedContentInset.top), faded = MAX(1, title.bounds.size.height);
+ CGFloat alpha = 1 - MIN(1, scrolled / faded);
+ // Past the title's height the row has faded out, so it stops rising there and nothing is written again until it
+ // comes back; the glass keeps rising while its material is still going off.
+ CGAffineTransform up = CGAffineTransformMakeTranslation(0, -MIN(scrolled, faded));
+ BOOL glassFading = CACurrentMediaTime() < sg_glassFadeEnds || (alpha > 0.5) != sg_glassShown;
rise(title, up, alpha);
- riseGlass(objc_getAssociatedObject(sg_header, &kGlassKey), up, alpha);
+ riseGlass(objc_getAssociatedObject(sg_header, &kGlassKey), glassFading ? CGAffineTransformMakeTranslation(0, -scrolled) : up, alpha);
rise(objc_getAssociatedObject(sg_header, &kButtonsKey), up, alpha);
if ([sg_face isDescendantOfView:sg_header]) rise(sg_face, up, alpha);
}
diff --git a/tweak/Sources/Redesigned/Kit/SGRAccent.h b/tweak/Sources/Redesigned/Kit/SGRAccent.h
index 067b1375..8a7465b8 100644
--- a/tweak/Sources/Redesigned/Kit/SGRAccent.h
+++ b/tweak/Sources/Redesigned/Kit/SGRAccent.h
@@ -10,6 +10,9 @@
UIColor *SGRAccentColor(void); // nil while Spotify's own green is kept
NSInteger SGRAccentRGB(void); // the color in effect, 0xRRGGBB, Spotify's green included
+// What a UIColor made from these components comes out as: one of Spotify's greens turns into the accent while it is
+// swapped. NO, and the components untouched, for any other color.
+BOOL SGRAccentSwap(CGFloat *r, CGFloat *g, CGFloat *b);
// Plain checkmark (SGRPlainCheck.x): a saved song's circled tick as a plain checkmark in the accent. Off until switched
// on, read at launch.
diff --git a/tweak/Sources/Redesigned/Kit/SGRAccent.x b/tweak/Sources/Redesigned/Kit/SGRAccent.x
index 6f169f2d..2fcc05cb 100644
--- a/tweak/Sources/Redesigned/Kit/SGRAccent.x
+++ b/tweak/Sources/Redesigned/Kit/SGRAccent.x
@@ -25,12 +25,18 @@ static void unpack(uint32_t rgb, CGFloat *r, CGFloat *g, CGFloat *b) {
*b = (rgb & 0xFF) / 255.0;
}
+// Made again only when another color is stored: the pick applies at once, and the key is read per call for it.
UIColor *SGRAccentColor(void) {
+ static NSInteger madeFor = -1;
+ static UIColor *made;
NSInteger rgb = chosen();
if (rgb < 0) return nil;
+ if (made && rgb == madeFor) return made;
CGFloat r, g, b;
unpack((uint32_t)rgb, &r, &g, &b);
- return [UIColor colorWithRed:r green:g blue:b alpha:1];
+ made = [UIColor colorWithRed:r green:g blue:b alpha:1];
+ madeFor = rgb;
+ return made;
}
NSInteger SGRAccentRGB(void) {
@@ -56,6 +62,10 @@ static BOOL swap(CGFloat *r, CGFloat *g, CGFloat *b) {
return NO;
}
+BOOL SGRAccentSwap(CGFloat *r, CGFloat *g, CGFloat *b) {
+ return sg_accent >= 0 && swap(r, g, b);
+}
+
%hook UIColor
- (UIColor *)initWithRed:(CGFloat)r green:(CGFloat)g blue:(CGFloat)b alpha:(CGFloat)a {
swap(&r, &g, &b);
diff --git a/tweak/Sources/Redesigned/Kit/SGRActionRow.m b/tweak/Sources/Redesigned/Kit/SGRActionRow.m
index 662d9d9d..eddb8a4e 100644
--- a/tweak/Sources/Redesigned/Kit/SGRActionRow.m
+++ b/tweak/Sources/Redesigned/Kit/SGRActionRow.m
@@ -44,6 +44,18 @@ static NSString *wordIn(UIView *button) {
return word;
}
+// The capsule's word, made again only when the text size changes: the header feeds the capsule on every step of its collapse.
+static UIFont *capsuleFont(void) {
+ static UIFont *font;
+ static UIContentSizeCategory madeFor;
+ UIContentSizeCategory category = UIApplication.sharedApplication.preferredContentSizeCategory;
+ if (!font || ![category isEqualToString:madeFor]) {
+ font = SGRFont(UIFontTextStyleSubheadline, UIFontWeightSemibold, UIContentSizeCategoryLarge);
+ madeFor = category;
+ }
+ return font;
+}
+
#pragma mark - the Play capsule
@implementation SGRPlayCapsule {
@@ -110,7 +122,7 @@ static NSString *wordIn(UIView *button) {
CGSize size = source.bounds.size;
UIImageView *glyph = glyphIn(source, MIN(size.width, size.height));
- UIFont *font = SGRFont(UIFontTextStyleSubheadline, UIFontWeightSemibold, UIContentSizeCategoryLarge);
+ UIFont *font = capsuleFont();
if (![_title.font isEqual:font]) _title.font = font;
UIColor *content = self.contentColor ?: SGRAccent();
if (![_title.textColor isEqual:content]) _title.textColor = content;
diff --git a/tweak/Sources/Redesigned/Kit/SGRHeaderInfo.h b/tweak/Sources/Redesigned/Kit/SGRHeaderInfo.h
index 0aa02f53..667a68a2 100644
--- a/tweak/Sources/Redesigned/Kit/SGRHeaderInfo.h
+++ b/tweak/Sources/Redesigned/Kit/SGRHeaderInfo.h
@@ -52,6 +52,10 @@ extern const CGFloat SGRHeaderInfoTitleRise; // 56, of the content over the pic
// Where the content starts, from the top; 0 keeps it on the bottom edge. Content that would then run past the
// bottom goes back on the bottom edge.
@property (nonatomic) CGFloat pinnedTop;
+// Kept for the page, which reads them back to tell whether a pass has anything new to hand over: the play color
+// it last handed over, and whether it has found Spotify's buttons' row. The info itself never reads them.
+@property (nonatomic, strong) UIColor *handedPlayColor;
+@property (nonatomic) BOOL rowFound;
@end
// The image view of the leading face on Spotify's creator line `root` -- the playlist header's collaborators
diff --git a/tweak/Sources/Redesigned/Kit/SGRHeaderInfo.m b/tweak/Sources/Redesigned/Kit/SGRHeaderInfo.m
index b62b752d..19727915 100644
--- a/tweak/Sources/Redesigned/Kit/SGRHeaderInfo.m
+++ b/tweak/Sources/Redesigned/Kit/SGRHeaderInfo.m
@@ -63,10 +63,14 @@ UIImageView *SGRCreatorPicture(UIView *root) {
SGRMirrorButton *_shuffle, *_trailing;
SGRPlayCapsule *_play;
__weak UIView *_creatorLink;
+ // contentHeightForWidth:'s last answer, for _measuredWidth; a negative width is none. Cleared when the text or
+ // the title picture changes, the only things it measures.
+ CGFloat _measuredWidth, _measuredHeight;
}
- (instancetype)initWithFrame:(CGRect)frame {
if (!(self = [super initWithFrame:frame])) return nil;
+ _measuredWidth = -1;
_title = infoLabel(self, SGRFont(UIFontTextStyleTitle2, UIFontWeightBold, UIContentSizeCategoryExtraLarge),
SGRPrimary(), 2, NSTextAlignmentCenter);
_title.accessibilityTraits = UIAccessibilityTraitHeader;
@@ -122,6 +126,7 @@ UIImageView *SGRCreatorPicture(UIView *root) {
[self addSubview:_logo];
}
_titleImage = image;
+ _measuredWidth = -1;
_title.accessibilityElementsHidden = image != nil;
if (image) {
if (!_logo.image) [UIView performWithoutAnimation:^{ self->_logo.frame = self->_title.frame; }];
@@ -168,7 +173,10 @@ UIImageView *SGRCreatorPicture(UIView *root) {
changed |= setText(_creator, creator);
changed |= setText(_length, length);
changed |= setText(_about, about);
- if (changed) [self setNeedsLayout];
+ if (changed) {
+ _measuredWidth = -1;
+ [self setNeedsLayout];
+ }
return changed;
}
@@ -261,6 +269,7 @@ UIImageView *SGRCreatorPicture(UIView *root) {
}
- (CGFloat)contentHeightForWidth:(CGFloat)width {
+ if (width == _measuredWidth) return _measuredHeight;
CGFloat text = MAX(0, width - 2 * kSide), height = 0;
UILabel *previous = nil;
for (UILabel *label in @[_title, _creator, _length]) {
@@ -272,6 +281,8 @@ UIImageView *SGRCreatorPicture(UIView *root) {
if (previous) height += kRowAbove;
height += SGRActionHeight;
if (!_about.hidden) height += kAboutAbove + ceil([_about sizeThatFits:CGSizeMake(text, CGFLOAT_MAX)].height);
+ _measuredWidth = width;
+ _measuredHeight = height;
return height;
}
diff --git a/tweak/Sources/Redesigned/Kit/SGRRepaint.x b/tweak/Sources/Redesigned/Kit/SGRRepaint.x
index 23cf134e..126f3b63 100644
--- a/tweak/Sources/Redesigned/Kit/SGRRepaint.x
+++ b/tweak/Sources/Redesigned/Kit/SGRRepaint.x
@@ -10,22 +10,38 @@ __weak UIView *sgr_playlistRoot = nil;
__weak UIView *sgr_albumRoot = nil;
__weak UIView *sgr_artistRoot = nil;
+// One walk up from the view says which roots it is inside, the way SGIsInside would for each: not past a
+// visual effect view. The roots are then taken in their order, not in the order the walk meets them.
+enum { kInNowPlaying = 1, kInLyrics = 2, kInPage = 4 };
+
%hook CALayer
- (void)setBackgroundColor:(CGColorRef)color {
- if (color && (sgr_nowPlayingRoot || sgr_lyricsPageRoot || sgr_playlistRoot || sgr_albumRoot || sgr_artistRoot)) {
+ if (!color) {
+ %orig;
+ return;
+ }
+ UIView *nowPlaying = sgr_nowPlayingRoot, *lyrics = sgr_lyricsPageRoot;
+ UIView *playlist = sgr_playlistRoot, *album = sgr_albumRoot, *artist = sgr_artistRoot;
+ // A page only ever loses the base surface, so another color asks after the player and the lyrics alone.
+ if ((playlist || album || artist) && !SGIsBaseSurface(color)) playlist = album = artist = nil;
+ if (nowPlaying || lyrics || playlist || album || artist) {
UIView *view = (UIView *)self.delegate;
if ([view isKindOfClass:UIView.class] && view.layer == self && !SGKeepsColor(view)) {
- if (SGIsInside(view, sgr_nowPlayingRoot)) {
+ NSUInteger inside = 0;
+ for (UIView *v = view; v && !(inside & kInNowPlaying); v = v.superview) {
+ if ([v isKindOfClass:UIVisualEffectView.class]) break;
+ if (v == nowPlaying) inside |= kInNowPlaying;
+ if (v == lyrics) inside |= kInLyrics;
+ if (v == playlist || v == album || v == artist) inside |= kInPage;
+ }
+ if (inside & kInNowPlaying) {
// Its size is judged when the bar picks its card: Spotify can paint a card before it sizes it.
if (SGIsVisibleColor(color) && ![sgr_nowPlayingPainted containsObject:view]) {
[sgr_nowPlayingPainted addObject:view];
- UIView *bar = sgr_nowPlayingRoot;
- dispatch_async(dispatch_get_main_queue(), ^{ [bar.superview setNeedsLayout]; });
+ dispatch_async(dispatch_get_main_queue(), ^{ [nowPlaying.superview setNeedsLayout]; });
}
color = NULL;
- } else if (SGIsInside(view, sgr_lyricsPageRoot)) {
- color = NULL;
- } else if (SGIsBaseSurface(color) && (SGIsInside(view, sgr_playlistRoot) || SGIsInside(view, sgr_albumRoot) || SGIsInside(view, sgr_artistRoot))) {
+ } else if (inside & (kInLyrics | kInPage)) {
color = NULL;
}
}
diff --git a/tweak/Sources/Redesigned/Kit/SGRRestyle.m b/tweak/Sources/Redesigned/Kit/SGRRestyle.m
index b0af25c8..29a500c6 100644
--- a/tweak/Sources/Redesigned/Kit/SGRRestyle.m
+++ b/tweak/Sources/Redesigned/Kit/SGRRestyle.m
@@ -6,13 +6,6 @@
static char kPlateKey, kImageObserverKey, kLayoutObserverKey;
-@interface SGRWeakBox : NSObject
-@property (nonatomic, weak) id value;
-@end
-
-@implementation SGRWeakBox
-@end
-
#pragma mark - instance subclasses
// A Swift class can lose its metadata when the runtime makes a subclass of it, and an instance KVO
@@ -273,18 +266,8 @@ BOOL SGRIsAvatar(UIView *view) {
UIView *SGRFindByIdentifier(UIView *root, NSString *identifier, const void *cacheKey) {
if (!root || !identifier.length) return nil;
- SGRWeakBox *box = cacheKey ? objc_getAssociatedObject(root, cacheKey) : nil;
- UIView *cached = box.value;
- if (cached && identifierMatches(cached.accessibilityIdentifier, identifier) && [cached isDescendantOfView:root]) return cached;
- UIView *found = findIdentifier(root, identifier);
- if (found && cacheKey) {
- if (!box) {
- box = [SGRWeakBox new];
- objc_setAssociatedObject(root, cacheKey, box, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
- }
- box.value = found;
- }
- return found;
+ if (!cacheKey) return findIdentifier(root, identifier);
+ return SGFindRemembered(root, cacheKey, ^BOOL(UIView *v) { return identifierMatches(v.accessibilityIdentifier, identifier); });
}
@implementation SGRShadowPlate {
@@ -391,7 +374,7 @@ static BOOL aboveFooter(UIView *row) {
NSArray<UIView *> *siblings = row.superview.subviews;
NSUInteger at = [siblings indexOfObject:row];
for (NSUInteger i = at + 1; at != NSNotFound && i + 1 < siblings.count; i++) {
- if ([NSStringFromClass(siblings[i].class) containsString:@"GradientView"] && isFooter(siblings[i + 1])) return YES;
+ if (SGClassNamed(siblings[i].class, @"GradientView") && isFooter(siblings[i + 1])) return YES;
}
return NO;
}
@@ -399,14 +382,15 @@ static BOOL aboveFooter(UIView *row) {
static void clearPaint(UIView *view, UIView *cell, CGFloat wide) {
BOOL full = view.bounds.size.width >= wide;
if (view != cell && !full && [view isKindOfClass:UICollectionViewCell.class]) return;
- CALayer *fade = objc_getAssociatedObject(view, &kRowFadeKey);
- if (fade && view.layer.mask == fade && !aboveFooter(view)) view.layer.mask = nil;
+ // A row's fade is only ever in place as its mask, so an unmasked view has none to take off.
+ CALayer *mask = view.layer.mask;
+ if (mask && mask == objc_getAssociatedObject(view, &kRowFadeKey) && !aboveFooter(view)) view.layer.mask = nil;
if (full) {
// Read off the layer, written through the view, so the two are left saying the same thing: the
// clear color lands on both, and reads back with an alpha the next pass does not take for paint.
CGColorRef color = view.layer.backgroundColor;
if (color && SGIsBaseSurface(color)) view.backgroundColor = UIColor.clearColor;
- if ([NSStringFromClass(view.class) containsString:@"GradientView"]) {
+ if (SGClassNamed(view.class, @"GradientView")) {
if (!view.layer.mask) view.layer.mask = [CALayer layer];
fadeRowsAbove(view);
}
diff --git a/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m b/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m
index 36ae8f95..158b06d9 100644
--- a/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m
+++ b/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m
@@ -19,6 +19,7 @@
#import "Shared/LyricsTranslation/LyricsTranslation.h"
#import "Settings/SGPageStyle.h"
#import "Shared/Player/PlayerEvents.h"
+#import "Shared/Player/PlayerState.h"
#import "Shared/Haptics/Haptics.h"
#import "Redesigned/Kit/SGRGlass.h"
#import "Redesigned/Kit/SGRTokens.h"
@@ -96,6 +97,9 @@ static const double kBreakOut = 0.35, kBreakSwell = 1.2, kBreakSwellShare = 0.35
static const double kBreakSlack = 0.03;
// A position that has not moved for this long is a paused player, not two frames between readings.
static const CFTimeInterval kStillFor = 0.1;
+// How long after the last thing set moving the page's link drops its rate: past the longest placement
+// (0.3 s of delay and a 0.7 s spring) and a sung line's 0.9 s sink.
+static const CFTimeInterval kCalmAfter = 1.5;
@interface CAFilter : NSObject
+ (instancetype)filterWithType:(NSString *)type;
@@ -440,10 +444,11 @@ typedef struct {
} SGRPlace;
static NSUInteger flow(NSArray<SGKaraokeWord *> *words, UIFont *font, CGFloat width, SGRPlace *places) {
- CGFloat space = ceil([@" " sizeWithAttributes:@{NSFontAttributeName: font}].width), x = 0, offset = 0;
+ NSDictionary *attributes = @{NSFontAttributeName: font};
+ CGFloat space = ceil([@" " sizeWithAttributes:attributes].width), x = 0, offset = 0;
NSUInteger row = 0;
for (NSUInteger i = 0; i < words.count; i++) {
- CGFloat wide = ceil([words[i].text sizeWithAttributes:@{NSFontAttributeName: font}].width);
+ CGFloat wide = ceil([words[i].text sizeWithAttributes:attributes].width);
CGFloat lead = x > 0 && !words[i].joined ? space : 0;
if (x > 0 && x + lead + wide > width) {
x = lead = 0;
@@ -613,11 +618,12 @@ static SGRKaraokeLayout *layOut(SGKaraokeLine *line, CGFloat width, SGRKaraokeSt
NSString *translation = style.translation ? line.translation : nil;
// A translator hands back a line already in the language as it was; the line says it once. It stays
// translated, so it is not asked again.
- if (translation.length && [SGLyricsBareText(translation) isEqualToString:SGLyricsBareText(SGKaraokeLineText(line))]) translation = nil;
+ NSString *lineText = translation.length || style.romanised ? SGKaraokeLineText(line) : nil;
+ if (translation.length && [SGLyricsBareText(translation) isEqualToString:SGLyricsBareText(lineText)]) translation = nil;
// A source's own pronunciation, hidden, still reads better than the transform's.
if (style.romanised && !spoken.count) {
layout.romanisedText = line.pronunciation ? SGKaraokeLineText(line.pronunciation)
- : SGLyricsRomanised(SGKaraokeLineText(line), style.japanese);
+ : SGLyricsRomanised(lineText, style.japanese);
}
NSMutableArray<NSNumber *> *parts = [NSMutableArray array];
for (NSNumber *text in style.order) {
@@ -1259,7 +1265,7 @@ typedef struct {
- (BOOL)accessibilityActivate { return self.activate ? self.activate() : NO; }
@end
-@interface SGRKaraokeView () <UIScrollViewDelegate>
+@interface SGRKaraokeView () <UIScrollViewDelegate, SGPlayerStateObserver>
@end
@implementation SGRKaraokeView {
@@ -1270,6 +1276,8 @@ typedef struct {
CGFloat _browseAnchor;
NSInteger _browseBreak;
CADisplayLink *_link;
+ NSTimer *_poll; // looking a few times a second while the link is paused, nothing on the page moving
+ CFTimeInterval _stirredAt; // when something last set the page moving
NSString *_track;
NSArray<SGKaraokeLine *> *_lines;
// The song is placed from its lines' heights alone; views exist for the lines in and near sight.
@@ -1337,6 +1345,7 @@ typedef struct {
[self takeLook];
_shown = [NSMutableDictionary dictionary];
_sightArrangement = NSUIntegerMax;
+ SGAddPlayerStateObserver(self);
_fade = [CAGradientLayer layer];
_fade.colors = @[(id)UIColor.clearColor.CGColor, (id)UIColor.whiteColor.CGColor,
(id)UIColor.whiteColor.CGColor, (id)UIColor.clearColor.CGColor, (id)UIColor.clearColor.CGColor];
@@ -1459,6 +1468,7 @@ typedef struct {
}
- (void)tapped:(UITapGestureRecognizer *)tap {
+ [self stir];
if (_extrasBox && !_extrasBox.hidden && CGRectContainsPoint(_extrasBox.frame, [tap locationInView:self])) return;
if (_sing.userInteractionEnabled && [_sing pointInside:[tap locationInView:_sing] withEvent:nil]) return;
if (_creditLinks.count && !_credit.hidden
@@ -1493,6 +1503,7 @@ typedef struct {
}
- (void)held:(UILongPressGestureRecognizer *)hold {
+ [self stir];
if (hold.state != UIGestureRecognizerStateBegan || !_meanings.count) return;
if (_sing.userInteractionEnabled && [_sing pointInside:[hold locationInView:_sing] withEvent:nil]) return;
CGPoint point = [hold locationInView:_scroll];
@@ -1531,6 +1542,7 @@ typedef struct {
// Lines are placed for a content offset of 0, so following the song means scrolling back to 0.
// While the user browses, placement stands still and every line is sharp.
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
+ [self stir];
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(followSong) object:nil];
if (!_browsing) {
_browseAnchor = self.bounds.size.height * kAnchor;
@@ -1544,6 +1556,7 @@ typedef struct {
// In the caller's animation: the glass dematerializes by its effect and the glyph fades by its alpha, the
// one view of the two with no glass in it.
- (void)setExtrasHidden:(BOOL)hidden {
+ [self stir];
_extrasHidden = hidden;
if (_extrasBox) {
SGRShowGlass(SGRGlassInside(_extrasBox, &kExtrasGlassKey, kExtrasSide), !hidden);
@@ -1580,6 +1593,7 @@ typedef struct {
// the player reports the seek, which takes a few frames. Read before then, the position still on the line
// being sung put the stack back on it, and the seek's arrival then jumped it over to the tapped one.
- (void)glideTo:(NSInteger)ms {
+ [self stir];
_seekTo = ms;
_seekAt = CACurrentMediaTime();
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(followSong) object:nil];
@@ -1621,6 +1635,8 @@ typedef struct {
// scripts/battery-probe.sh. Nothing of the card is seen from the background, so nothing is drawn.
- (void)scheduleLink {
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(startLink) object:nil];
+ [_poll invalidate];
+ _poll = nil;
[_link invalidate];
_link = nil;
if (!self.window) return;
@@ -1634,9 +1650,49 @@ typedef struct {
if (UIApplication.sharedApplication.applicationState != UIApplicationStateActive) return;
_link = [CADisplayLink displayLinkWithTarget:self selector:@selector(tick)];
_link.preferredFrameRateRange = CAFrameRateRangeMake(80, 120, 120);
+ _stirredAt = CACurrentMediaTime();
[_link addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes];
}
+// The frame being drawn, or now while the link is paused.
+- (CFTimeInterval)frameTime {
+ return _link && !_link.paused ? _link.targetTimestamp : CACurrentMediaTime();
+}
+
+// Nothing on the page moves: the link is paused rather than slowed, because a link asking for a low rate,
+// even uncapped, holds the player's 120 Hz animations back (see scheduleLink). A timer, which asks the display
+// for nothing, still watches the track, its lines and the clock a few times a second.
+- (void)calmDown {
+ _link.paused = YES;
+ __weak typeof(self) weakSelf = self;
+ _poll = [NSTimer timerWithTimeInterval:0.2 repeats:YES block:^(NSTimer *timer) { [weakSelf tick]; }];
+ [NSRunLoop.mainRunLoop addTimer:_poll forMode:NSRunLoopCommonModes];
+}
+
+// Something is about to move: the link back at the display's rate before its next frame.
+- (void)stir {
+ _stirredAt = CACurrentMediaTime();
+ if (!_link.paused) return;
+ [_poll invalidate];
+ _poll = nil;
+ _link.paused = NO;
+}
+
+// Play, pause, a new track: the clock is about to move, or the page to change.
+- (void)playerStateDidChange:(SPTPlayerState *)state {
+ [self stir];
+}
+
+// A seek while paused, from Spotify's own scrubber: a report that moves the position. A report that
+// leaves it where it was lets the link stay calm.
+- (void)playerStateDidReport:(SPTPlayerState *)state {
+ if (_plain) return;
+ // The player's position less the Delay, as positionMs reads it, from the state reported.
+ NSInteger ms = _sample ? [self positionMs]
+ : (NSInteger)((state.isPaused ? state.positionAsOfTimestamp : state.position) * 1000) - SGKaraokeDelayMs();
+ if (ms != _reported) [self stir];
+}
+
- (void)playerTransitionChanged:(NSNotification *)note {
[self scheduleLink];
}
@@ -2259,6 +2315,7 @@ static BOOL anyUntranslated(NSArray<SGKaraokeLine *> *lines) {
// later, the further down the later, as Apple Music's do. A line sung over it stays where it is
// below, lit; the stack moves on to it once the line at the anchor is sung out.
- (void)placeLinesAnimated:(BOOL)animated {
+ [self stir];
if (_browsing || !_tops.count) return;
_focusTop = _tops[(NSUInteger)MAX(_focus, 0)].doubleValue;
[self showLinesInSight];
@@ -2358,7 +2415,7 @@ static BOOL anyUntranslated(NSArray<SGKaraokeLine *> *lines) {
// corrections. A seek or a new track is too far off to ease and is taken at once.
- (double)clockMs {
NSInteger raw = [self positionMs];
- CFTimeInterval shown = _link ? _link.targetTimestamp : CACurrentMediaTime();
+ CFTimeInterval shown = [self frameTime];
if (_seekAt) {
// A paused player never moves, so the hold ends by the position or the time, not by motion.
BOOL reported = raw >= 0 && labs(raw - _seekTo) <= kSeekNearMs;
@@ -2371,7 +2428,10 @@ static BOOL anyUntranslated(NSArray<SGKaraokeLine *> *lines) {
_seekAt = 0;
}
BOOL running = raw != _reported; // a paused player reports the same position every frame
- if (running) _stillSince = 0;
+ if (running) {
+ _stillSince = 0;
+ [self stir];
+ }
else if (!_stillSince) _stillSince = shown;
double reported = raw + (running ? (shown - CACurrentMediaTime()) * 1000 : 0);
double predicted = _clock + (running ? (shown - _clockTime) * 1000 : 0);
@@ -2383,6 +2443,10 @@ static BOOL anyUntranslated(NSArray<SGKaraokeLine *> *lines) {
}
- (void)tick {
+ // A paused clock and a page at rest draw nothing new: once what was last set moving has finished, a few
+ // frames a second still watch the track, its lines and the clock, and whatever moves stirs it back.
+ if (_seekAt || _scroll.isTracking || _scroll.isDecelerating) [self stir];
+ else if (_link && !_link.paused && [self frameTime] - _stirredAt > kCalmAfter) [self calmDown];
NSString *track = _sample ? @"sample" : SGKaraokePlayingTrack();
if (!(track == _track || [track isEqualToString:_track])) {
SGLog(@"karaoke: page shows track %@, lyrics %@", track, [self linesFor:track] ? @"captured" : @"not captured yet");
@@ -2436,7 +2500,8 @@ static BOOL anyUntranslated(NSArray<SGKaraokeLine *> *lines) {
double now = [self clockMs];
[self arrangeAt:now glide:_sample != nil]; // the preview coming round glides back to its first line
for (NSUInteger i = 0; i < _sungCount; i++) [_shown[@(_sung[i])] showTime:now];
- if (_dots.superview) [_dots showTime:now running:!_stillSince || _link.targetTimestamp - _stillSince < kStillFor at:_link.targetTimestamp];
+ CFTimeInterval frame = [self frameTime];
+ if (_dots.superview) [_dots showTime:now running:!_stillSince || frame - _stillSince < kStillFor at:frame];
}
// What is sung at `now` lit and the stack arranged around it; a jump of more than a couple of lines is
diff --git a/tweak/Sources/Redesigned/Navbar/Navbar.x b/tweak/Sources/Redesigned/Navbar/Navbar.x
index f62f1b3e..08fbc65d 100644
--- a/tweak/Sources/Redesigned/Navbar/Navbar.x
+++ b/tweak/Sources/Redesigned/Navbar/Navbar.x
@@ -299,10 +299,16 @@ void SGRComposeTabBar(UIView *tabBar) {
// Spotify placed the icon and the label for the width it measured (trees/test5.txt: x 28 in a
// 134pt slot, the center of the 80pt it had with five tabs) and lays the item out no further
-// once the slot changes. Assigning the centers back sends them through the hooks below.
+// once the slot changes. Assigning the centers back sends them through the hooks below, which look no further
+// up for the slot than the deepest of these views sits in one (3 in Spotify's items: trees, 2026-10).
+static NSUInteger sg_slotDepth;
static void centreContents(UIView *item) {
SGForEachView(item, ^(UIView *v) {
- if ([v isKindOfClass:%c(SPTEncoreIconView)] || [v isKindOfClass:%c(SPTEncoreLabel)]) v.center = v.center;
+ if (![v isKindOfClass:%c(SPTEncoreIconView)] && ![v isKindOfClass:%c(SPTEncoreLabel)]) return;
+ NSUInteger depth = 1;
+ for (UIView *up = v.superview; up && up != item; up = up.superview) depth++;
+ if (depth > sg_slotDepth) sg_slotDepth = depth;
+ v.center = v.center;
});
}
@@ -341,7 +347,9 @@ static CGFloat slotCentreX(UIView *view) {
UIStackView *row = sg_row;
if (!row) return NAN;
UIView *slot = nil;
- for (UIView *v = view; v.superview; v = v.superview) if (v.superview == row) { slot = v; break; }
+ // No depth seen yet means no row centred yet: the walk goes all the way up.
+ NSUInteger steps = 0, limit = sg_slotDepth ? sg_slotDepth : NSUIntegerMax;
+ for (UIView *v = view; v.superview && steps++ <= limit; v = v.superview) if (v.superview == row) { slot = v; break; }
if (!slot) return NAN;
return [slot convertPoint:CGPointMake(CGRectGetMidX(slot.bounds), 0) toView:view.superview].x;
}
@@ -413,8 +421,37 @@ void SGRRefreshTabBar(void) {
// What the row settled on, logged whenever it changes: `make log` then says whether the items fit,
// what is holding their width, and in what order the bar ended up.
void SGRLogTabBarRow(UIView *tabBar) {
- UIStackView *stack = SGRowIn(tabBar);
+ // The row SGRComposeTabBar found in this bar on the same pass, just before.
+ UIStackView *stack = sg_row;
if (!stack) return;
+ // The line is written out only when a frame, an item, the stack's settings or the boxes read off them changed. shortcut: items
+ // past the 16th are not compared, raise it if a bar ever holds more.
+ struct {
+ CGRect bar, stack, icon, label;
+ NSInteger axis, distribution, alignment;
+ CGFloat spacing;
+ NSUInteger count;
+ struct { const void *item; CGRect frame; BOOL hidden; } items[16];
+ } key;
+ memset(&key, 0, sizeof key); // padding too, for memcmp
+ key.bar = tabBar.frame;
+ key.stack = stack.frame;
+ key.icon = sg_iconBox;
+ key.label = sg_labelBox;
+ key.axis = stack.axis;
+ key.distribution = stack.distribution;
+ key.alignment = stack.alignment;
+ key.spacing = stack.spacing;
+ for (UIView *item in stack.arrangedSubviews) {
+ NSUInteger i = key.count++;
+ if (i >= 16) continue;
+ key.items[i].item = (__bridge const void *)item;
+ key.items[i].frame = item.frame;
+ key.items[i].hidden = item.hidden;
+ }
+ static typeof(key) lastKey;
+ if (!memcmp(&key, &lastKey, sizeof key)) return;
+ memcpy(&lastKey, &key, sizeof key);
NSMutableString *out = [NSMutableString stringWithFormat:@"row in %@ %@, icon %@ label %@, stack %@ axis %ld dist %ld align %ld spacing %.1f autolayout %d",
NSStringFromClass(tabBar.class), NSStringFromCGRect(tabBar.frame),
NSStringFromCGRect(sg_iconBox), NSStringFromCGRect(sg_labelBox), NSStringFromCGRect(stack.frame),
diff --git a/tweak/Sources/Redesigned/Navbar/TabBar.x b/tweak/Sources/Redesigned/Navbar/TabBar.x
index 595ba6f2..0ddbc17d 100644
--- a/tweak/Sources/Redesigned/Navbar/TabBar.x
+++ b/tweak/Sources/Redesigned/Navbar/TabBar.x
@@ -856,23 +856,41 @@ static UIView *tabBarOf(UIView *item) {
return nil;
}
+// The bar in its own pass, and whether one of its items laid out during it.
+static __weak UIView *sg_passBar;
+static BOOL sg_itemsLaidOut;
+
%hook _TtC23NavigationUI_TabBarImpl10TabBarView
- (void)layoutSubviews {
+ // A pass nested in another (an item's layoutIfNeeded) hands both back, so the outer one still composes.
+ UIView *bar = (UIView *)self, *outer = sg_passBar;
+ BOOL outerLaidOut = sg_itemsLaidOut;
+ sg_passBar = bar;
%orig;
- SGRComposeTabBar((UIView *)self);
- for (UIView *sub in ((UIView *)self).subviews) {
+ SGRComposeTabBar(bar);
+ sg_itemsLaidOut = NO;
+ for (UIView *sub in bar.subviews) {
if (![sub isKindOfClass:SGRTabBarHost.class] && ![sub isKindOfClass:SGRBarFade.class]) [sub layoutIfNeeded];
}
- holdHome((UIView *)self);
- syncBar((UIView *)self);
- SGRLogTabBarRow((UIView *)self);
+ // Items the row's pass laid out are composed once, all together, rather than once each.
+ if (sg_itemsLaidOut) SGRComposeTabBar(bar);
+ sg_passBar = outer;
+ sg_itemsLaidOut = outerLaidOut;
+ holdHome(bar);
+ syncBar(bar);
+ SGRLogTabBarRow(bar);
}
%end
-// The bar's own pass runs before Spotify has filled the row; the items lay out as they arrive.
+// The bar's own pass runs before Spotify has filled the row; the items lay out as they arrive. Inside the bar's
+// pass, the pass composes once after them; outside it, the item composes at once, so no frame shows Spotify's row.
static void itemDidLayOut(UIView *item) {
UIView *bar = tabBarOf(item);
if (!bar) return;
+ if (bar == sg_passBar) {
+ sg_itemsLaidOut = YES;
+ return;
+ }
SGRComposeTabBar(bar);
holdHome(bar);
syncBar(bar);
diff --git a/tweak/Sources/Redesigned/Player/PlayerControls.x b/tweak/Sources/Redesigned/Player/PlayerControls.x
index 94a6d67a..07e6b552 100644
--- a/tweak/Sources/Redesigned/Player/PlayerControls.x
+++ b/tweak/Sources/Redesigned/Player/PlayerControls.x
@@ -31,7 +31,7 @@ static const NSTimeInterval kSpinnerCheck = 0.6;
// one sent before the player caught up, for this long; after it the player's word is final.
static const NSTimeInterval kTapTrust = 1.2;
-static char kPreviousKey, kNextKey, kPlayKey, kGlyphKey, kTakeKey, kRemainingKey;
+static char kPreviousKey, kNextKey, kPlayKey, kGlyphKey, kTakeKey, kRemainingKey, kRowKey;
static __weak UIView *sg_playView;
static __weak UIButton *sg_playButton;
static CFTimeInterval sg_tappedUntil;
@@ -183,7 +183,7 @@ void SGRPlayerPlayGlyphIn(UIView *host) {
UIView *host = ((UIViewController *)self).viewIfLoaded;
if (!host) return;
// The unit lays out before its row does, and the glyphs are centered on the buttons in it.
- [SGRowIn(host) layoutIfNeeded];
+ [SGFindRemembered(host, &kRowKey, ^BOOL(UIView *v) { return SGIsRow(v); }) layoutIfNeeded];
skipGlyph(host, @"SPTNowPlayingPreviousTrackButton", &kPreviousKey, @"backward.fill");
skipGlyph(host, @"SPTNowPlayingNextTrackButton", &kNextKey, @"forward.fill");
SGRPlayerPlayGlyphIn(host);
diff --git a/tweak/Sources/Redesigned/Player/PlayerCoverAccent.x b/tweak/Sources/Redesigned/Player/PlayerCoverAccent.x
index 28c91cbb..6d0a4790 100644
--- a/tweak/Sources/Redesigned/Player/PlayerCoverAccent.x
+++ b/tweak/Sources/Redesigned/Player/PlayerCoverAccent.x
@@ -29,23 +29,45 @@ static void unpack(NSInteger rgb, CGFloat *r, CGFloat *g, CGFloat *b) {
*b = (rgb & 0xFF) / 255.0;
}
+// Made once per cover color: every pass over the stack hands it out.
static UIColor *coverColor(void) {
+ static NSInteger madeFor = -1;
+ static UIColor *made;
+ if (made && madeFor == sg_cover) return made;
CGFloat r, g, b;
unpack(sg_cover, &r, &g, &b);
- return [UIColor colorWithRed:r green:g blue:b alpha:1];
+ made = [UIColor colorWithRed:r green:g blue:b alpha:1];
+ madeFor = sg_cover;
+ return made;
+}
+
+// -[UIColor getHue:saturation:brightness:alpha:] worked out from the components, without making a color for it.
+static void hsv(CGFloat r, CGFloat g, CGFloat b, CGFloat *h, CGFloat *s, CGFloat *v) {
+ CGFloat high = MAX(r, MAX(g, b)), low = MIN(r, MIN(g, b)), range = high - low;
+ *v = high;
+ *s = high > 0 ? range / high : 0;
+ if (range <= 0 || high <= 0) *h = 0;
+ else if (high == r) *h = (g - b) / range;
+ else if (high == g) *h = 2 + (b - r) / range;
+ else *h = 4 + (r - g) / range;
+ *h /= 6;
+ if (*h < 0) *h += 1;
}
// Whether a color is the accent's: its hue within kHueNear, and colorful. Darker shades of it count (a pressed state).
+// A color made from Spotify's green comes out as the accent (Kit/SGRAccent.x), so that green is judged as the accent.
static const CGFloat kHueNear = 0.05, kColorful = 0.35;
static BOOL accentLike(CGFloat r, CGFloat g, CGFloat b) {
static CGFloat accentHue = -1;
if (accentHue < 0) {
- CGFloat ar, ag, ab, s, v, a;
+ CGFloat ar, ag, ab, s, v;
unpack(SGRAccentRGB(), &ar, &ag, &ab);
- [[UIColor colorWithRed:ar green:ag blue:ab alpha:1] getHue:&accentHue saturation:&s brightness:&v alpha:&a];
+ SGRAccentSwap(&ar, &ag, &ab);
+ hsv(ar, ag, ab, &accentHue, &s, &v);
}
- CGFloat h, s, v, a;
- if (![[UIColor colorWithRed:r green:g blue:b alpha:1] getHue:&h saturation:&s brightness:&v alpha:&a]) return NO;
+ CGFloat h, s, v;
+ SGRAccentSwap(&r, &g, &b);
+ hsv(r, g, b, &h, &s, &v);
CGFloat d = fabs(h - accentHue);
return MIN(d, 1 - d) < kHueNear && s > kColorful && v > 0.2;
}
@@ -115,7 +137,8 @@ static void paintBackground(UIView *view) {
original = current;
objc_setAssociatedObject(view, &kOriginalKey, original, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- view.backgroundColor = sg_cover < 0 ? original : coverColor();
+ UIColor *color = sg_cover < 0 ? original : coverColor();
+ if (![view.backgroundColor isEqual:color]) view.backgroundColor = color;
}
static void paintShape(CAShapeLayer *layer) {
@@ -129,6 +152,7 @@ static void paintShape(CAShapeLayer *layer) {
objc_setAssociatedObject(layer, key, original, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
CGColorRef color = sg_cover < 0 ? (__bridge CGColorRef)original : coverColor().CGColor;
+ if (CGColorEqualToColor(current, color)) continue;
if (stroke) layer.strokeColor = color;
else layer.fillColor = color;
}
diff --git a/tweak/Sources/Redesigned/Player/PlayerFooter.x b/tweak/Sources/Redesigned/Player/PlayerFooter.x
index cc344312..060d30db 100644
--- a/tweak/Sources/Redesigned/Player/PlayerFooter.x
+++ b/tweak/Sources/Redesigned/Player/PlayerFooter.x
@@ -45,7 +45,7 @@ static const CGFloat kVolumeMargin = 24;
// And the controls go up this much over it, so the gaps above and below the volume row match.
static const CGFloat kVolumeLift = 10;
-static char kConnectKey, kShareKey, kTrimmerKey, kSharedByKey, kQueueKey, kLyricsGlyphKey, kReachKey;
+static char kConnectKey, kShareKey, kTrimmerKey, kSharedByKey, kQueueKey, kLyricsGlyphKey, kReachKey, kRowKey;
static __weak SGRGlyphButton *sg_lyricsGlyph;
// The view the footer's stack view arranges around `view`.
@@ -273,7 +273,7 @@ void SGRPlayerLowerRow(UIView *row) {
UIView *host = ((UIViewController *)self).viewIfLoaded;
if (!host) return;
// The unit lays out before its row does, and the moves are measured from where the row put things.
- [SGRowIn(host) layoutIfNeeded];
+ [SGFindRemembered(host, &kRowKey, ^BOOL(UIView *v) { return SGIsRow(v); }) layoutIfNeeded];
CGFloat width = host.bounds.size.width, middleY = CGRectGetMidY(host.bounds);
BOOL rtl = host.effectiveUserInterfaceLayoutDirection == UIUserInterfaceLayoutDirectionRightToLeft;
diff --git a/tweak/Sources/Redesigned/Playlist/PlaylistRows.x b/tweak/Sources/Redesigned/Playlist/PlaylistRows.x
index 1cb29cde..c1435d12 100644
--- a/tweak/Sources/Redesigned/Playlist/PlaylistRows.x
+++ b/tweak/Sources/Redesigned/Playlist/PlaylistRows.x
@@ -85,11 +85,16 @@ static UIView *artHolderIn(UIView *row) {
return found;
}
-static void applyRow(UIView *cell) {
+// A playlist's row is an Encore.ListRow; the songs liked by one artist have a Track.Row of the same kit.
+static UIView *rowIn(UIView *cell) {
+ return identified(cell, @"Encore.ListRow", &kRowKey) ?: identified(cell, @"Track.Row", &kTrackRowKey);
+}
+
+// YES when the cell holds a track row.
+static BOOL applyRow(UIView *cell) {
clearSurface(cell);
- // A playlist's row is an Encore.ListRow; the songs liked by one artist have a Track.Row of the same kit.
- UIView *row = identified(cell, @"Encore.ListRow", &kRowKey) ?: identified(cell, @"Track.Row", &kTrackRowKey);
- if (!row) return;
+ UIView *row = rowIn(cell);
+ if (!row) return NO;
clearSurface(row);
CGFloat leading = SGRSideMargin + 48 + kHairlineGap;
@@ -112,6 +117,7 @@ static void applyRow(UIView *cell) {
});
applyHairline(row, leading);
+ return YES;
}
%hook _TtC35ListUXPlatform_FreeTierPlaylistImpl25ElementCollectionViewCell
@@ -120,8 +126,8 @@ static void applyRow(UIView *cell) {
UIView *cell = (UIView *)self;
if (!SGRPlaylistHeaderOf(cell)) return;
SGRClearCellPaint(cell);
- SGRPlaylistTakeCuration(cell);
- applyRow(cell);
+ // A track row is not the curation row, so only the other cells are searched for its toolbar.
+ if (!applyRow(cell)) SGRPlaylistTakeCuration(cell);
}
- (UICollectionViewLayoutAttributes *)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)attributes {
diff --git a/tweak/Sources/Shared/AdBlock/AdBlock.h b/tweak/Sources/Shared/AdBlock/AdBlock.h
index d3212254..3d685f9e 100644
--- a/tweak/Sources/Shared/AdBlock/AdBlock.h
+++ b/tweak/Sources/Shared/AdBlock/AdBlock.h
@@ -26,8 +26,8 @@ void SGAdBlockCountOne(NSString *label);
NSArray<NSString *> *SGAdBlockLabels(void);
NSUInteger SGAdBlockCount(NSString *label);
// What a hook looked at under `label`, stopped or not, so a 0 can tell a hook Spotify never calls from one that
-// found nothing. Kept with the counts but saved only with a stop or as Spotify leaves the screen: some hooks see a
-// request a second. SGAdBlockChecked is NSNotFound for a kind that counts no checks, and 0 for one whose hook has
+// found nothing. Kept with the counts, which are saved as Spotify leaves the screen: some hooks see a request a
+// second. SGAdBlockChecked is NSNotFound for a kind that counts no checks, and 0 for one whose hook has
// not run, which on a new Spotify can mean it never will.
void SGAdBlockSawOne(NSString *label);
NSUInteger SGAdBlockChecked(NSString *label);
diff --git a/tweak/Sources/Shared/AdBlock/AdBlock.m b/tweak/Sources/Shared/AdBlock/AdBlock.m
index fadb12cb..2a8a94ea 100644
--- a/tweak/Sources/Shared/AdBlock/AdBlock.m
+++ b/tweak/Sources/Shared/AdBlock/AdBlock.m
@@ -125,15 +125,26 @@ static NSString *const labels[] = {
@"Ad services", @"Upsell services", @"Popups", @"Page components", @"Feed sections", @"Requests", @"Config rewrites",
};
static NSMutableDictionary<NSString *, NSNumber *> *sg_counts;
-static BOOL sg_unsaved; // checks counted since the counts were last written
+static BOOL sg_unsaved; // stops or checks counted since the counts were last written
+static CFAbsoluteTime sg_savedAt;
+// Made once per label: the hooks count on every request and page component.
static NSString *checkedKey(NSString *label) {
- return [label stringByAppendingString:@" checked"];
+ static NSDictionary<NSString *, NSString *> *keys;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ NSMutableDictionary<NSString *, NSString *> *made = [NSMutableDictionary dictionary];
+ for (NSString *each in SGAdBlockLabels()) made[each] = [each stringByAppendingString:@" checked"];
+ keys = made;
+ });
+ return keys[label];
}
// The kinds whose hooks count what they look at. The services are stubs Spotify loads, with nothing to look at.
+static NSString *const checkedLabels[] = {@"Popups", @"Page components", @"Feed sections", @"Requests", @"Config rewrites"};
+
static BOOL countsChecks(NSString *label) {
- return [@[@"Popups", @"Page components", @"Feed sections", @"Requests", @"Config rewrites"] containsObject:label];
+ return listed(label, checkedLabels, sizeof(checkedLabels) / sizeof(checkedLabels[0]));
}
// Counting happens on whichever thread the hook ran on, the page reads on the main one.
@@ -150,12 +161,22 @@ static NSMutableDictionary<NSString *, NSNumber *> *countsLocked(void) {
return sg_counts;
}
+// Counted in memory, as a stop can come several times a second, and written when Spotify leaves the screen
+// and at most every 30 s while counting goes on, so a kill in the background (no notification comes) loses
+// half a minute at most. Called under the lock.
+static void saveLocked(BOOL now) {
+ if (!sg_unsaved || (!now && CFAbsoluteTimeGetCurrent() - sg_savedAt < 30)) return;
+ [NSUserDefaults.standardUserDefaults setObject:countsLocked() forKey:kCounts];
+ sg_unsaved = NO;
+ sg_savedAt = CFAbsoluteTimeGetCurrent();
+}
+
void SGAdBlockCountOne(NSString *label) {
@synchronized (kCounts) {
NSMutableDictionary<NSString *, NSNumber *> *counts = countsLocked();
counts[label] = @(counts[label].unsignedIntegerValue + 1);
- [NSUserDefaults.standardUserDefaults setObject:counts forKey:kCounts];
- sg_unsaved = NO;
+ sg_unsaved = YES;
+ saveLocked(NO);
}
}
@@ -165,6 +186,7 @@ void SGAdBlockSawOne(NSString *label) {
NSString *key = checkedKey(label);
counts[key] = @(counts[key].unsignedIntegerValue + 1);
sg_unsaved = YES;
+ saveLocked(NO);
}
}
@@ -174,15 +196,11 @@ NSUInteger SGAdBlockChecked(NSString *label) {
}
}
-// The checks counted since the last stop, written as Spotify leaves the screen.
+// Spotify leaving the screen writes what was counted since the last write.
__attribute__((constructor)) static void saveChecksOnLeaving(void) {
[NSNotificationCenter.defaultCenter addObserverForName:UIApplicationWillResignActiveNotification object:nil queue:nil
usingBlock:^(NSNotification *note) {
- @synchronized (kCounts) {
- if (!sg_unsaved) return;
- [NSUserDefaults.standardUserDefaults setObject:countsLocked() forKey:kCounts];
- sg_unsaved = NO;
- }
+ @synchronized (kCounts) { saveLocked(YES); }
}];
}
diff --git a/tweak/Sources/Shared/AdBlock/AdHubs.x b/tweak/Sources/Shared/AdBlock/AdHubs.x
index 2e9e7a83..c2353a4c 100644
--- a/tweak/Sources/Shared/AdBlock/AdHubs.x
+++ b/tweak/Sources/Shared/AdBlock/AdHubs.x
@@ -44,6 +44,9 @@ static BOOL anyKey(NSDictionary *dictionary) {
return NO;
}
+static NSString *const flagKeys[] = {@"ad", @"is_ad", @"is_sponsored"};
+static NSString *const childKeys[] = {@"children", @"rows", @"body"};
+
static BOOL isAd(NSDictionary *component) {
id kind = component[@"component"];
if ([kind isKindOfClass:NSDictionary.class]) {
@@ -55,8 +58,9 @@ static BOOL isAd(NSDictionary *component) {
if (adWord(component[@"id"]) || adWord(component[@"type"])) return YES;
NSDictionary *metadata = component[@"metadata"];
if ([metadata isKindOfClass:NSDictionary.class]) {
- for (NSString *key in @[@"ad", @"is_ad", @"is_sponsored"]) {
- if ([metadata[key] respondsToSelector:@selector(boolValue)] && [metadata[key] boolValue]) return YES;
+ for (size_t i = 0; i < COUNT(flagKeys); i++) {
+ id flag = metadata[flagKeys[i]];
+ if ([flag respondsToSelector:@selector(boolValue)] && [flag boolValue]) return YES;
}
}
if (anyKey(metadata) || anyKey(component[@"custom"])) return YES;
@@ -64,9 +68,11 @@ static BOOL isAd(NSDictionary *component) {
return [logging isKindOfClass:NSDictionary.class] && (adWord(logging[@"type"]) || anyKey(logging));
}
+// The same array when no ad was found in it, so a page without ads is passed on as it came.
static NSArray *filtered(NSArray *components) {
if (![components isKindOfClass:NSArray.class]) return components;
NSMutableArray *kept = [NSMutableArray array];
+ BOOL changed = NO;
for (NSDictionary *component in components) {
if (![component isKindOfClass:NSDictionary.class]) {
[kept addObject:component];
@@ -76,15 +82,21 @@ static NSArray *filtered(NSArray *components) {
if (isAd(component)) {
SGAdBlockCountOne(@"Page components");
SGLog(@"dropped page component %@", component[@"id"] ?: component[@"component"]);
+ changed = YES;
continue;
}
- NSMutableDictionary *copy = [component mutableCopy];
- for (NSString *key in @[@"children", @"rows", @"body"]) {
- if (copy[key]) copy[key] = filtered(copy[key]);
+ NSMutableDictionary *copy = nil;
+ for (size_t i = 0; i < COUNT(childKeys); i++) {
+ id children = component[childKeys[i]];
+ id left = children ? filtered(children) : nil;
+ if (left == children) continue;
+ if (!copy) copy = [component mutableCopy];
+ copy[childKeys[i]] = left;
}
- [kept addObject:copy];
+ changed |= copy != nil;
+ [kept addObject:copy ?: component];
}
- return kept;
+ return changed ? kept : components;
}
%hook HUBViewModelBuilderImplementation
diff --git a/tweak/Sources/Shared/AdBlock/AdNetwork.x b/tweak/Sources/Shared/AdBlock/AdNetwork.x
index f91a6a98..5599cdab 100644
--- a/tweak/Sources/Shared/AdBlock/AdNetwork.x
+++ b/tweak/Sources/Shared/AdBlock/AdNetwork.x
@@ -14,7 +14,7 @@ static BOOL ads, premium;
static NSDate *started;
static NSObject *cacheLock;
static NSData *cachedCustomize; // the last rewritten customize body, for a 304 and the re-fetches
-static char kBufferKey, kServedKey, kPassKey, kCoreAdKey;
+static char kBufferKey, kServedKey, kPassKey, kCoreAdKey, kKindKey;
typedef NS_ENUM(NSInteger, SGNet) { SGNetPass, SGNetBlock, SGNetPatch };
@@ -75,7 +75,8 @@ static BOOL isAd(NSURL *url, NSString *path) {
if (isEsperantoAd(path)) return YES;
NSString *host = url.host.lowercaseString ?: @"";
return has(host, @"doubleclick") || has(host, @"googlesyndication") || [host hasPrefix:@"aet."]
- || [@[@"ad.spotify.com", @"ads.spotify.com", @"aet.spotify.com"] containsObject:host];
+ || [host isEqualToString:@"ad.spotify.com"] || [host isEqualToString:@"ads.spotify.com"]
+ || [host isEqualToString:@"aet.spotify.com"];
}
// The first thirty seconds are a fresh login's: signup/public and customize are part of it, and
@@ -86,14 +87,28 @@ static BOOL isRefetch(NSString *path) {
|| has(path, @"pushka-tokens") || has(path, @"apresolve") || has(path, @"pses/screenconfig") || isCustomize(path);
}
-static SGNet classify(NSURL *url) {
+// What a request's URL makes it, worked out once per task: its data comes in many chunks.
+enum { kBlocked = 1, kRefetch = 2, kPatched = 4 };
+
+static unsigned kindOf(NSURL *url) {
NSString *path = url.path.lowercaseString ?: @"";
- if (premium && isLogout(path)) return SGNetBlock;
- if (ads && isAd(url, path)) return SGNetBlock;
- if (premium && elapsed() > 30 && isRefetch(path)) return SGNetBlock;
- if (premium && (isBootstrap(path) || isCustomize(path))) return SGNetPatch;
- if (ads && isFeed(path)) return SGNetPatch;
- return SGNetPass;
+ return ((premium && isLogout(path)) || (ads && isAd(url, path)) ? kBlocked : 0)
+ | (premium && isRefetch(path) ? kRefetch : 0)
+ | ((premium && (isBootstrap(path) || isCustomize(path))) || (ads && isFeed(path)) ? kPatched : 0);
+}
+
+// The thirty seconds are read at each call, as the task's data and its end arrive.
+// The kind is worked out once per URL the task is on: a redirect moves it to another, which is classified again.
+static SGNet classify(NSURLSessionTask *task) {
+ NSURL *url = task.currentRequest.URL;
+ NSArray *stored = objc_getAssociatedObject(task, &kKindKey); // @[url, kind]
+ if (!stored || (stored[0] != url && ![stored[0] isEqual:url])) {
+ stored = @[url ?: NSNull.null, @(kindOf(url))];
+ objc_setAssociatedObject(task, &kKindKey, stored, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ }
+ unsigned kind = [stored[1] unsignedIntValue];
+ if ((kind & kBlocked) || ((kind & kRefetch) && elapsed() > 30)) return SGNetBlock;
+ return kind & kPatched ? SGNetPatch : SGNetPass;
}
static NSData *cached(void) {
@@ -155,7 +170,7 @@ static NSHTTPURLResponse *replayFor(NSURLSessionTask *task, NSURLResponse *respo
// one whose reply is rewritten when it finishes.
static BOOL holds(NSURLSessionTask *task, NSData *data) {
if (objc_getAssociatedObject(task, &kPassKey)) return NO;
- switch (classify(task.currentRequest.URL)) {
+ switch (classify(task)) {
case SGNetBlock:
return YES;
case SGNetPatch: {
@@ -179,7 +194,7 @@ static void complete(id<NSURLSessionDataDelegate> delegate, NSURLSession *sessio
return;
}
SGAdBlockSawOne(@"Requests");
- switch (classify(url)) {
+ switch (classify(task)) {
case SGNetBlock:
SGAdBlockCountOne(@"Requests");
SGLog(@"answered %@ empty", path);
diff --git a/tweak/Sources/Shared/AdBlock/Feeds.m b/tweak/Sources/Shared/AdBlock/Feeds.m
index 867c7460..7ec31312 100644
--- a/tweak/Sources/Shared/AdBlock/Feeds.m
+++ b/tweak/Sources/Shared/AdBlock/Feeds.m
@@ -21,29 +21,25 @@ static const char *const keepMarkers[] = {"filter", "chip", "pillar", "browse:ch
#define COUNT(list) (sizeof(list) / sizeof(list[0]))
-// ASCII, case-insensitive; the markers are lower case.
-static BOOL contains(NSData *data, const char *needle) {
- const uint8_t *bytes = data.bytes;
- size_t length = data.length, n = strlen(needle);
- for (size_t i = 0; i + n <= length; i++) {
- size_t k = 0;
- while (k < n && tolower(bytes[i + k]) == needle[k]) k++;
- if (k == n) return YES;
- }
- return NO;
-}
-
-static BOOL containsAny(NSData *data, const char *const markers[], size_t count) {
+// The markers are lower case, and each section is lowered once for all of them.
+static BOOL containsAny(const char *text, size_t length, const char *const markers[], size_t count) {
for (size_t i = 0; i < count; i++) {
- if (contains(data, markers[i])) return YES;
+ if (memmem(text, length, markers[i], strlen(markers[i]))) return YES;
}
return NO;
}
static BOOL adSection(NSData *section) {
- if (containsAny(section, hardMarkers, COUNT(hardMarkers))) return YES;
- if (containsAny(section, keepMarkers, COUNT(keepMarkers))) return NO;
- return containsAny(section, intentMarkers, COUNT(intentMarkers)) && containsAny(section, surfaceMarkers, COUNT(surfaceMarkers));
+ size_t length = section.length;
+ const uint8_t *bytes = section.bytes;
+ char *text = malloc(length ?: 1);
+ for (size_t i = 0; i < length; i++) text[i] = tolower(bytes[i]);
+ BOOL ad = containsAny(text, length, hardMarkers, COUNT(hardMarkers))
+ || (!containsAny(text, length, keepMarkers, COUNT(keepMarkers))
+ && containsAny(text, length, intentMarkers, COUNT(intentMarkers))
+ && containsAny(text, length, surfaceMarkers, COUNT(surfaceMarkers)));
+ free(text);
+ return ad;
}
NSData *SGStripFeed(NSData *body) {
diff --git a/tweak/Sources/Shared/AdBlock/RadioModes.m b/tweak/Sources/Shared/AdBlock/RadioModes.m
index e83e1b9f..459aee61 100644
--- a/tweak/Sources/Shared/AdBlock/RadioModes.m
+++ b/tweak/Sources/Shared/AdBlock/RadioModes.m
@@ -34,32 +34,40 @@ static id object(id receiver, SEL selector) {
}
static char sg_radioEvidenceKey;
+static SEL sg_playbackSelector, sg_contextSelector, sg_restrictionsSelector;
+static Class sg_restrictionsClass;
// Some optimistic state updates have empty restrictions until the next core update.
// Keep positive radio evidence only for the same playback and context. An explicit
// non-radio reason replaces it immediately; a different playback starts afresh.
static NSArray *commandReasons(id player, id state) {
- id playback = object(state, sel_registerName("playbackId"));
- id context = object(state, sel_registerName("contextURI"));
- id limits = object(state, sel_registerName("restrictions"));
- if (!playback || !context || ![limits isKindOfClass:objc_getClass("SPTPlayerRestrictions")]) {
+ id playback = object(state, sg_playbackSelector);
+ id context = object(state, sg_contextSelector);
+ id limits = object(state, sg_restrictionsSelector);
+ if (!playback || !context || ![limits isKindOfClass:sg_restrictionsClass]) {
@synchronized (player) {
objc_setAssociatedObject(player, &sg_radioEvidenceKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return nil;
}
- NSArray *identity = @[playback, context];
+ id raw[3];
+ for (NSUInteger i = 0; i < 3; i++) raw[i] = sg_rawReasons[i](limits, sg_reasonSelectors[i]) ?: NSNull.null;
@synchronized (player) {
NSDictionary *prior = objc_getAssociatedObject(player, &sg_radioEvidenceKey);
- NSArray *old = [prior[@"identity"] isEqual:identity] ? prior[@"reasons"] : nil;
+ NSArray *seen = prior[@"inputs"];
+ // Spotify reads the state every frame; the same objects give the same evidence.
+ if (seen[0] == playback && seen[1] == context && seen[2] == raw[0] && seen[3] == raw[1] && seen[4] == raw[2])
+ return prior[@"reasons"];
+ NSArray *old = [seen[0] isEqual:playback] && [seen[1] isEqual:context] ? prior[@"reasons"] : nil;
NSMutableArray *result = [NSMutableArray new];
for (NSUInteger i = 0; i < 3; i++) {
- id reasons = sg_rawReasons[i](limits, sg_reasonSelectors[i]);
+ id reasons = raw[i];
if ([reasons isKindOfClass:NSSet.class] && ![reasons count] && old && SGRadioModeReasonsOnly(old[i]))
reasons = old[i];
- [result addObject:reasons ?: NSNull.null];
+ [result addObject:reasons];
}
NSArray *snapshot = [result copy];
- objc_setAssociatedObject(player, &sg_radioEvidenceKey, @{@"identity":identity, @"reasons":snapshot}, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ objc_setAssociatedObject(player, &sg_radioEvidenceKey,
+ @{@"inputs":@[playback, context, raw[0], raw[1], raw[2]], @"reasons":snapshot}, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
return snapshot;
}
}
@@ -104,6 +112,8 @@ __attribute__((constructor)) static void SGRadioModesInstall(void) {
BOOL compatible = signature(class_getInstanceMethod(options, setOverride), @encode(void), @encode(BOOL)) &&
signature(class_getInstanceMethod(player, stateSelector), @encode(id), NULL) &&
signature(class_getInstanceMethod(objc_getClass("SPTPlayerState"), restrictionsSelector), @encode(id), NULL);
+ sg_playbackSelector = sel_registerName("playbackId"); sg_contextSelector = sel_registerName("contextURI");
+ sg_restrictionsSelector = restrictionsSelector; sg_restrictionsClass = restrictions;
for (NSString *name in @[@"playbackId", @"contextURI"])
compatible &= signature(class_getInstanceMethod(objc_getClass("SPTPlayerState"), NSSelectorFromString(name)), @encode(id), NULL);
char encoding[16];
diff --git a/tweak/Sources/Shared/AnimatedArtwork/LockScreenMotion.x b/tweak/Sources/Shared/AnimatedArtwork/LockScreenMotion.x
index ae03c16a..90fc0d6f 100644
--- a/tweak/Sources/Shared/AnimatedArtwork/LockScreenMotion.x
+++ b/tweak/Sources/Shared/AnimatedArtwork/LockScreenMotion.x
@@ -200,6 +200,7 @@ static void showCover(NSString *picture) {
// background defaults write wait for main, which deadlocks launch while main waits on Spotify's CoreThread.
[NSNotificationCenter.defaultCenter addObserverForName:NSUserDefaultsDidChangeNotification object:nil queue:nil
usingBlock:^(NSNotification *note) {
+ SGPrefsChanged();
dispatch_async(dispatch_get_main_queue(), ^{
SGLockArtwork choice = SGLockScreenArtwork();
if (choice == sg_choice) return;
diff --git a/tweak/Sources/Shared/AnimatedArtwork/LockScreenStar.x b/tweak/Sources/Shared/AnimatedArtwork/LockScreenStar.x
index 2b599dc7..660cf70e 100644
--- a/tweak/Sources/Shared/AnimatedArtwork/LockScreenStar.x
+++ b/tweak/Sources/Shared/AnimatedArtwork/LockScreenStar.x
@@ -114,6 +114,7 @@ static void arm(void) {
// Heard on the writing thread and handed to main without waiting (AGENTS.md).
[NSNotificationCenter.defaultCenter addObserverForName:NSUserDefaultsDidChangeNotification object:nil queue:nil
usingBlock:^(NSNotification *note) {
+ SGPrefsChanged();
dispatch_async(dispatch_get_main_queue(), ^{ arm(); });
}];
SGLog(@"lock star: %@", atLaunch ? @"on, Spotify's like and dislike buttons forced off" : @"off");
diff --git a/tweak/Sources/Shared/Fonts/Fonts.x b/tweak/Sources/Shared/Fonts/Fonts.x
index c1967d0b..1dd36b9b 100644
--- a/tweak/Sources/Shared/Fonts/Fonts.x
+++ b/tweak/Sources/Shared/Fonts/Fonts.x
@@ -10,6 +10,7 @@
static SGAppFont sg_font;
static NSString *sg_family; // the chosen family: one iOS carries, or the imported one once Core Text has it
+static NSCache<NSString *, UIFont *> *sg_made; // the font made for each request of Spotify's: its name, size and weight
// A font name ("SpotifyMixUI-Bold") or family name ("Spotify Mix UI", which is how Spotify's text components ask) of
// Spotify's: the family name has spaces, and matching only the font name left most of the app in Spotify's font.
@@ -18,10 +19,9 @@ static BOOL spotifys(NSString *name) {
return [joined hasPrefix:@"CircularSp"] || [joined hasPrefix:@"SpotifyMix"] || [joined hasPrefix:@"Circular"];
}
-// The weight a descriptor asks for: its traits', else its variable font's weight axis ('wght', 100 to 900), else
+// The weight a descriptor's attributes ask for: its traits', else its variable font's weight axis ('wght', 100 to 900), else
// none, for the name to say.
-static NSNumber *weightAsked(UIFontDescriptor *descriptor) {
- NSDictionary *attributes = descriptor.fontAttributes;
+static NSNumber *weightAsked(NSDictionary *attributes) {
NSNumber *trait = attributes[UIFontDescriptorTraitsAttribute][UIFontWeightTrait];
if ([trait isKindOfClass:NSNumber.class]) return trait;
NSNumber *axis = attributes[(__bridge NSString *)kCTFontVariationAttribute][@(0x77676874)]; // 'wght'
@@ -108,18 +108,30 @@ static CGFloat fitScale(UIFontWeight weight) {
%hook UIFont
+ (UIFont *)fontWithName:(NSString *)name size:(CGFloat)size {
- UIFont *font = spotifys(name) ? systemFor(name, size * fitScale(weightOf(name))) : nil;
+ if (!spotifys(name)) return %orig;
+ NSString *key = [NSString stringWithFormat:@"%@ %a", name, size];
+ UIFont *font = [sg_made objectForKey:key];
+ if (!font && (font = systemFor(name, size * fitScale(weightOf(name))))) [sg_made setObject:font forKey:key];
return font ?: %orig;
}
+// Every font made in the app comes through here, so its attributes are built once. objectForKey: would be no
+// cheaper: it resolves the font, and answers a name, traits and weight axis the descriptor never asked for.
+ (UIFont *)fontWithDescriptor:(UIFontDescriptor *)descriptor size:(CGFloat)size {
- NSString *name = descriptor.fontAttributes[UIFontDescriptorNameAttribute] ?: descriptor.fontAttributes[UIFontDescriptorFamilyAttribute];
+ NSDictionary *attributes = descriptor.fontAttributes;
+ NSString *name = attributes[UIFontDescriptorNameAttribute] ?: attributes[UIFontDescriptorFamilyAttribute];
if (!spotifys(name)) return %orig;
- NSNumber *weight = weightAsked(descriptor);
- CGFloat points = (size > 0 ? size : descriptor.pointSize) * fitScale(weight ? weight.doubleValue : weightOf(name));
- UIFont *font = !weight ? systemFor(name, points)
- : sg_font >= SGAppFontCustom ? family(points, weight.doubleValue)
- : designed([UIFont systemFontOfSize:points weight:weight.doubleValue]);
+ NSNumber *weight = weightAsked(attributes);
+ CGFloat asked = size > 0 ? size : descriptor.pointSize;
+ NSString *key = [NSString stringWithFormat:@"%@ %a %@", name, asked, weight];
+ UIFont *font = [sg_made objectForKey:key];
+ if (!font) {
+ CGFloat points = asked * fitScale(weight ? weight.doubleValue : weightOf(name));
+ font = !weight ? systemFor(name, points)
+ : sg_font >= SGAppFontCustom ? family(points, weight.doubleValue)
+ : designed([UIFont systemFontOfSize:points weight:weight.doubleValue]);
+ if (font) [sg_made setObject:font forKey:key];
+ }
return font ?: %orig;
}
%end
@@ -180,6 +192,7 @@ NSArray<NSString *> *SGAppFontFamilies(void) {
}
sg_family = name;
}
+ sg_made = [NSCache new];
%init;
if (sg_font >= SGAppFontRounded) %init(Designs);
SGLog(@"fonts: %@ in place of Spotify's", sg_family ?: SGAppFontNames()[sg_font]);
diff --git a/tweak/Sources/Shared/LiveActivity/LiveActivity.x b/tweak/Sources/Shared/LiveActivity/LiveActivity.x
index ecae5bd1..62fabe4b 100644
--- a/tweak/Sources/Shared/LiveActivity/LiveActivity.x
+++ b/tweak/Sources/Shared/LiveActivity/LiveActivity.x
@@ -95,6 +95,14 @@ static NSDate *sg_lastSent;
static SGLiveActivityTab sg_tab;
static void tick(void) API_AVAILABLE(ios(17.0));
+// When ActivityKit last said none is showing, with the app in the background; until kRefresh on, nothing is sent.
+static NSDate *sg_noneAt;
+
+// In the background with none showing, as ActivityKit said within kRefresh: send() sends nothing.
+static BOOL heldBack(void) {
+ return sg_noneAt && -sg_noneAt.timeIntervalSinceNow < kRefresh
+ && UIApplication.sharedApplication.applicationState != UIApplicationStateActive;
+}
// An NSTimer cannot be asked to change pace, so changing it is putting one down and another up.
static void startTimer(NSTimeInterval every) API_AVAILABLE(ios(17.0)) {
@@ -110,10 +118,9 @@ static void send(NSString *shown, void (^show)(void)) API_AVAILABLE(ios(17.0)) {
// ActivityKit is asked only when there is something to send: each question is a round trip to the system,
// and this runs four times a second. An activity ended from outside is started again within kRefresh.
if ([shown isEqualToString:sg_shown] && -sg_lastSent.timeIntervalSinceNow < kRefresh) return;
- static NSDate *noneAt; // when ActivityKit last said none is showing, with the app in the background
+ if (heldBack()) return;
+ sg_noneAt = nil;
BOOL background = UIApplication.sharedApplication.applicationState != UIApplicationStateActive;
- if (background && noneAt && -noneAt.timeIntervalSinceNow < kRefresh) return;
- noneAt = nil;
BOOL showing = SGLiveActivityBridge.isShowing;
NSDate *started = showing ? SGLiveActivityBridge.startedAt : nil;
NSTimeInterval age = started ? -started.timeIntervalSinceNow : 0;
@@ -129,7 +136,7 @@ static void send(NSString *shown, void (^show)(void)) API_AVAILABLE(ios(17.0)) {
// Nothing to send to, and none can start in the background: asked again after kRefresh.
static NSUInteger told;
if (told++ < 5) SGLog(@"live activity: none showing, not sent in the background");
- noneAt = [NSDate date];
+ sg_noneAt = [NSDate date];
return;
}
if (sg_lastStart && -sg_lastStart.timeIntervalSinceNow < kStartRetry) return;
@@ -286,6 +293,12 @@ static void tick(void) API_AVAILABLE(ios(17.0)) {
// Only the lyrics follow the song line by line; the other views' bar runs by itself from its dates.
NSTimeInterval every = paused || view != SGLiveActivityLyrics ? kPausedTick : kTick;
if (sg_timer && sg_tickEvery != every) startTimer(every);
+ // send() would send nothing yet, so nothing is worked out for it.
+ // The lyrics are still asked for, so they are there when it sends again.
+ if (heldBack()) {
+ if (view == SGLiveActivityLyrics && !SGKaraokeLinesForTrack(trackID)) SGKaraokeRequestLyrics(trackID);
+ return;
+ }
NSString *line = @"", *next = @"", *translation = nil;
BOOL noLyrics = NO;
if (view == SGLiveActivityLyrics) line = lyricsLine(trackID, &next, &translation, &noLyrics);
@@ -531,8 +544,10 @@ void SGSetLiveActivityEnabled(BOOL on) {
// long gone. On, a fresh one starts once it is: until then the first ticks update the leftover, which is
// harmless, an update after the end being ignored. A launch in the background (a play from AirPods,
// CarPlay or the lock screen) keeps it, since no new one can start there, and the first tick updates it.
+ // Off, it is ended only if one shows, so nothing is queued for the many who never turned it on.
dispatch_async(dispatch_get_main_queue(), ^{
- if (!on || UIApplication.sharedApplication.applicationState != UIApplicationStateBackground) [SGLiveActivityBridge end];
+ if ((!on && SGLiveActivityBridge.isShowing) || (on && UIApplication.sharedApplication.applicationState != UIApplicationStateBackground))
+ [SGLiveActivityBridge end];
if (on) SGSetLiveActivityEnabled(YES);
});
}
diff --git a/tweak/Sources/Shared/LiveActivity/LiveActivityBridge.swift b/tweak/Sources/Shared/LiveActivity/LiveActivityBridge.swift
index 5b8ca53e..c2fb44b8 100644
--- a/tweak/Sources/Shared/LiveActivity/LiveActivityBridge.swift
+++ b/tweak/Sources/Shared/LiveActivity/LiveActivityBridge.swift
@@ -79,7 +79,8 @@ public final class SGLiveActivityBridge: NSObject {
if pending.sending, let at = pending.sentAt, Date().timeIntervalSince(at) < kStuckAfter { return false }
if pending.sending { log.notice("[spotifyglass] live activity: an update has not landed in \(kStuckAfter, privacy: .public) s, sending on past it") }
pending.sending = true
- pending.sentAt = nil
+ // Set now, not when send() takes its first change: a nil here reads as stuck to the next call.
+ pending.sentAt = Date()
return true
}
if start { Task { await send() } }
@@ -136,6 +137,22 @@ public final class SGLiveActivityBridge: NSObject {
return true
}
+ // The last state sent, to tell which updates are worth the second copy.
+ private static let lastSent = OSAllocatedUnfairLock<State?>(initialState: nil)
+
+ // A dropped line is replaced by the next line or kRefresh's resend within seconds, and an unchanged state
+ // was already sent, so only a change to the track, controls or timer gets the second copy.
+ private static func onlyLinesChanged(_ state: State) -> Bool {
+ lastSent.withLock { last in
+ defer { last = state }
+ guard var before = last else { return false }
+ before.line = state.line
+ before.nextLine = state.nextLine
+ before.translation = state.translation
+ return before == state
+ }
+ }
+
private static func send() async {
// One task over the whole run of queued changes, so none of them goes out without it.
let task = BackgroundTask()
@@ -152,8 +169,9 @@ public final class SGLiveActivityBridge: NSObject {
}) {
switch change {
case .update(let id, let content, let background):
+ let again = !onlyLinesChanged(content.state) && background
await update(id, content)
- if background, await quietForASecond(since: taken) { await update(id, content) }
+ if again, await quietForASecond(since: taken) { await update(id, content) }
case .end(let ids, let background):
await end(ids)
// Rare, and ending one already ended does nothing: a second later it goes again whatever came since.
diff --git a/tweak/Sources/Shared/LockScreenLyrics/LockScreenLyrics.x b/tweak/Sources/Shared/LockScreenLyrics/LockScreenLyrics.x
index 4ee1ba51..c327d8ed 100644
--- a/tweak/Sources/Shared/LockScreenLyrics/LockScreenLyrics.x
+++ b/tweak/Sources/Shared/LockScreenLyrics/LockScreenLyrics.x
@@ -1,18 +1,18 @@
// Spotify's now playing info passes through with the artist swapped for the current line, and a timer
// sends it again each time the line changes. Spotify itself only ever sees its own dictionary back.
//
-// The timer follows the playback rate rather than running from launch: a paused player's line does not
-// move, so working it out four times a second only wakes the phone. The lock screen keeps the line it
-// was left on until the sound starts again.
+// The timer runs only while the sound moves, and wakes once for the next time the line can change: the
+// next start or end of a line or word the line shown hangs on. While the lyrics or the player's track
+// are not in yet it looks four times a second. The lock screen keeps the line it was left on until the
+// sound starts again.
#import <MediaPlayer/MediaPlayer.h>
#import "Core/SGCore.h"
#import "LockScreenLyrics.h"
#import "Shared/Lyrics/Lyrics.h"
#import "Headers/SPTPlayer.h"
+// How often to look while the line cannot be worked out yet.
static const NSTimeInterval kTick = 0.25;
-// Past a line's sung end by this much, with the next line at least this far off, the artist comes back.
-static const NSInteger kBreakMs = 4000;
// About what the lock screen's artist row fits before it cuts the text off.
static const NSUInteger kMaxChars = 30;
@@ -23,6 +23,7 @@ static CFAbsoluteTime sg_spotifyInfoAt;
static NSString *sg_shownLine;
static BOOL sg_resending;
static dispatch_source_t sg_timer;
+static CFAbsoluteTime sg_due;
static NSString *textOf(NSArray<SGKaraokeWord *> *words) {
SGKaraokeLine *line = [SGKaraokeLine new];
@@ -62,8 +63,11 @@ static double elapsedAt(NSDictionary *info, CFAbsoluteTime reportedAt, CFAbsolut
return [info[MPNowPlayingInfoPropertyElapsedPlaybackTime] doubleValue] + rate * (now - reportedAt);
}
-// nil between lines and for a track without synced lyrics, plain text included.
-static NSString *lineFor(NSDictionary *info, double elapsed) {
+// nil between lines and for a track without synced lyrics, plain text included. Past a line's end by
+// SGKaraokeBreakMs, with the next line at least that far off, the artist comes back. `wait` is the playback
+// time in seconds until it can change: kTick while it cannot be worked out yet, negative for not again.
+static NSString *lineFor(NSDictionary *info, double elapsed, NSTimeInterval *wait) {
+ *wait = kTick;
SPTPlayerState *state = [(id<SPTPlayer>)SGKaraokePlayer() state];
// The player's track can lag behind the now playing info; its lyrics would then be another song's.
if (![state.track.trackTitle isEqualToString:info[MPMediaItemPropertyTitle]]) return nil;
@@ -73,13 +77,18 @@ static NSString *lineFor(NSDictionary *info, double elapsed) {
SGKaraokeRequestLyrics(trackID);
return nil;
}
+ *wait = -1;
// Plain text has no line being sung to show.
if (SGKaraokeLinesTiming(lines) == SGKaraokeTimingNone) return nil;
NSInteger position = (NSInteger)(elapsed * 1000) - SGKaraokeDelayMs();
NSInteger index = SGKaraokeLeadLine(lines, position);
+ // The pieces below turn over at the shown line's word starts.
+ NSInteger ms = SGKaraokeMsToChange(lines, position, index);
+ // A ms on, past the truncation of `position` above.
+ if (ms > 0) *wait = (ms + 1) / 1000.0;
if (index < 0) return nil;
- BOOL nextFarOff = index + 1 == (NSInteger)lines.count || lines[index + 1].start - position > kBreakMs;
- if (position > lines[index].end + kBreakMs && nextFarOff) return nil;
+ BOOL nextFarOff = index + 1 == (NSInteger)lines.count || lines[index + 1].start - position > SGKaraokeBreakMs;
+ if (position > lines[index].end + SGKaraokeBreakMs && nextFarOff) return nil;
NSString *shown = nil;
for (NSArray<SGKaraokeWord *> *piece in piecesOf(lines[index])) {
if (!shown || piece.firstObject.start <= position) shown = textOf(piece);
@@ -97,6 +106,39 @@ static NSDictionary *withLine(NSDictionary *info, NSString *line, double elapsed
return shown;
}
+// The rate the song's time moves at; 1 for one Spotify left out, as elapsedAt counts it.
+static double rateOf(NSDictionary *info) {
+ NSNumber *rate = info[MPNowPlayingInfoPropertyPlaybackRate];
+ return rate.doubleValue > 0 ? rate.doubleValue : 1;
+}
+
+static void tick(void);
+
+// Main thread, as everything the timer touches is. Stops the timer, or arms it to look again `wait`
+// seconds of the song's time from now; a negative wait leaves it to Spotify's next info.
+static void lookIn(NSTimeInterval wait, NSDictionary *info) {
+ if (wait < 0) {
+ if (sg_timer) dispatch_source_cancel(sg_timer);
+ sg_timer = nil;
+ return;
+ }
+ if (!sg_timer) {
+ // A strict GCD timer: the main run loop's timers are throttled while the screen is off, and the lines
+ // stood still on a locked phone.
+ sg_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, DISPATCH_TIMER_STRICT, dispatch_get_main_queue());
+ dispatch_source_set_event_handler(sg_timer, ^{
+ static int late;
+ CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
+ if (now - sg_due > 2 && late++ < 5) SGLog(@"%s: ticked %.1f s late", __FILE_NAME__, now - sg_due);
+ tick();
+ });
+ dispatch_resume(sg_timer);
+ }
+ NSTimeInterval seconds = wait / rateOf(info);
+ sg_due = CFAbsoluteTimeGetCurrent() + seconds;
+ dispatch_source_set_timer(sg_timer, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), DISPATCH_TIME_FOREVER, 10 * NSEC_PER_MSEC);
+}
+
static void tick(void) {
NSDictionary *info;
CFAbsoluteTime reportedAt;
@@ -107,7 +149,9 @@ static void tick(void) {
if (!info[MPNowPlayingInfoPropertyElapsedPlaybackTime]) return;
CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
double elapsed = elapsedAt(info, reportedAt, now);
- NSString *line = lineFor(info, elapsed);
+ NSTimeInterval wait;
+ NSString *line = lineFor(info, elapsed, &wait);
+ lookIn(wait, info);
if (line == sg_shownLine || [line isEqualToString:sg_shownLine]) return;
sg_shownLine = line;
sg_resending = YES;
@@ -115,30 +159,6 @@ static void tick(void) {
sg_resending = NO;
}
-// Main thread, as everything the timer touches is.
-static void setTicking(BOOL on) {
- if (on == (sg_timer != nil)) return;
- if (!on) {
- dispatch_source_cancel(sg_timer);
- sg_timer = nil;
- return;
- }
- // A strict GCD timer: the main run loop's timers are throttled while the screen is off, and the lines stood
- // still on a locked phone.
- sg_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, DISPATCH_TIMER_STRICT, dispatch_get_main_queue());
- uint64_t every = (uint64_t)(kTick * NSEC_PER_SEC);
- dispatch_source_set_timer(sg_timer, dispatch_time(DISPATCH_TIME_NOW, every), every, 10 * NSEC_PER_MSEC);
- dispatch_source_set_event_handler(sg_timer, ^{
- static CFAbsoluteTime last;
- static int late;
- CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
- if (last && now - last > 2 && late++ < 5) SGLog(@"%s: ticked %.1f s late", __FILE_NAME__, now - last - kTick);
- last = now;
- tick();
- });
- dispatch_resume(sg_timer);
-}
-
// Whether the sound is moving. A rate Spotify did not report at all counts as moving: the line would
// stand still either way, and a missing key is no reason to leave the feature switched off for good.
static BOOL playingBy(NSDictionary *info) {
@@ -146,6 +166,15 @@ static BOOL playingBy(NSDictionary *info) {
return !rate || rate.doubleValue > 0;
}
+// Looks again at once while the sound moves, for something other than the clock that moves the line.
+static void lookNow(void) {
+ NSDictionary *info;
+ @synchronized (sg_lock) {
+ info = sg_spotifyInfo;
+ }
+ if (playingBy(info) && info[MPNowPlayingInfoPropertyElapsedPlaybackTime]) lookIn(0, info);
+}
+
%hook MPNowPlayingInfoCenter
- (void)setNowPlayingInfo:(NSDictionary *)info {
if (sg_resending) {
@@ -158,18 +187,19 @@ static BOOL playingBy(NSDictionary *info) {
sg_spotifyInfoAt = now;
}
BOOL playing = playingBy(info) && info[MPNowPlayingInfoPropertyElapsedPlaybackTime] != nil;
- // Karaoke's lyrics are main-thread state; off it the info goes out as it is and the next tick adds the line.
+ // Karaoke's lyrics are main-thread state; off it the info goes out as it is and a tick at once adds the line.
if (!NSThread.isMainThread || !info[MPNowPlayingInfoPropertyElapsedPlaybackTime]) {
dispatch_async(dispatch_get_main_queue(), ^{
sg_shownLine = nil;
- setTicking(playing);
+ lookIn(playing ? 0 : -1, info);
});
%orig;
return;
}
- setTicking(playing);
double elapsed = elapsedAt(info, now, now);
- NSString *line = lineFor(info, elapsed);
+ NSTimeInterval wait;
+ NSString *line = lineFor(info, elapsed, &wait);
+ lookIn(playing ? wait : -1, info);
sg_shownLine = line;
%orig(withLine(info, line, elapsed));
}
@@ -187,6 +217,22 @@ static BOOL playingBy(NSDictionary *info) {
if (!SGFlag(SGKeyLockScreenLyrics, NO)) return;
sg_lock = [NSObject new];
%init;
+ // Lines kept for a track, or replaced by better timed ones, can change the line at once.
+ [NSNotificationCenter.defaultCenter addObserverForName:SGKaraokeLinesKeptNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
+ lookNow();
+ }];
+ // The lyrics' delay applies at once, and moves the next change. Every write in the app posts this, so it is
+ // compared on the writing thread and handed to main without waiting only when it moved (AGENTS.md).
+ static NSInteger delay;
+ delay = SGKaraokeDelayMs();
+ [NSNotificationCenter.defaultCenter addObserverForName:NSUserDefaultsDidChangeNotification object:nil queue:nil
+ usingBlock:^(NSNotification *note) {
+ SGPrefsChanged();
+ NSInteger now = SGKaraokeDelayMs();
+ if (now == delay) return;
+ delay = now;
+ dispatch_async(dispatch_get_main_queue(), ^{ lookNow(); });
+ }];
// The timer waits for Spotify to report a playing track; nothing before that has a line to show.
SGLog(@"lock screen lyrics: on");
}
diff --git a/tweak/Sources/Shared/LockScreenLyrics/LyricsArtwork.x b/tweak/Sources/Shared/LockScreenLyrics/LyricsArtwork.x
index 222d239e..789bd947 100644
--- a/tweak/Sources/Shared/LockScreenLyrics/LyricsArtwork.x
+++ b/tweak/Sources/Shared/LockScreenLyrics/LyricsArtwork.x
@@ -1,6 +1,8 @@
// The lock screen's full-screen artwork as the lyrics, a clip per line (SGLyricsClip.h draws it). A timer
// works out the line being sung and hands the lock screen a new artwork under a new ID each time it
-// changes. Nothing is drawn until the lock screen asks for that artwork's video, so lines sung with the
+// changes. It wakes for the next time the line can change, and again for whatever else changes the
+// artwork: a player state, the lines kept, the moving artwork handed over or failing, the phone's heat,
+// the style. Nothing is drawn until the lock screen asks for that artwork's video, so lines sung with the
// screen off cost nothing. It rides on Spotify's now playing info as an extra (NowPlayingExtras.h), like
// the moving artwork it takes the place of.
//
@@ -18,10 +20,8 @@
#import "Shared/Player/NowPlayingExtras.h"
#import "Shared/Player/PlayerState.h"
+// How often to look while the line cannot be worked out yet.
static const NSTimeInterval kTick = 0.25;
-// Past a line's sung end by this much, with the next line at least this far off, the line is let go and
-// only the next one shows, dimmed (as the artist row does in LockScreenLyrics.x).
-static const NSInteger kBreakMs = 4000;
// A line's clip over moving artwork lasts from the line's start to the next one's, a second longer for the
// lock screen showing it late, and between these: the cost of a clip is its length.
static const double kShortest = 2, kLongest = 8;
@@ -39,6 +39,21 @@ static const double kShortest = 2, kLongest = 8;
@end
static dispatch_source_t sg_timer;
+static CFAbsoluteTime sg_due;
+// Where the song was, how fast it went and when, as the timer was armed: a report that strays from it is a seek.
+static NSInteger sg_armedMs;
+static double sg_armedSpeed;
+static CFAbsoluteTime sg_armedAt;
+// Lyrics are picked and the player is not paused: only then does the timer run.
+static BOOL sg_running;
+static void tick(void);
+
+// Looks again on main, while the timer runs, for something other than the clock that changes the artwork.
+static void tickSoon(void) {
+ dispatch_async(dispatch_get_main_queue(), ^{
+ if (sg_running) tick();
+ });
+}
static NSString *sg_motionURI; // the track the moving artwork is for, and its file (SGLyricsArtworkSetMotion)
static NSURL *sg_motion;
// Paths of moving artwork that would not draw (turned, its frames another size than it states, cut short, or
@@ -58,6 +73,7 @@ static void markMotionFailed(NSURL *file, NSString *artworkID) {
[sg_failedMotion addObject:file.path];
}
SGLog(@"lock lyrics: %@ would not draw for %@, the lines go over the cover for it", file.lastPathComponent, artworkID);
+ tickSoon();
}
static NSString *sg_track; // the track the clips are for
static UIImage *sg_cover; // its cover, once Spotify's now playing info has one for it
@@ -209,6 +225,7 @@ void SGLyricsArtworkSetMotion(NSString *uri, NSURL *file) {
}
sg_motionURI = uri;
sg_motion = file;
+ tickSoon();
}
// What the artwork for line `index` shows, `resting` once its break has come (index -1, before the first line,
@@ -223,20 +240,25 @@ static SGLockLine *lineAt(NSArray<SGKaraokeLine *> *lines, NSInteger index, BOOL
shown.cover = cover;
shown.style = style;
shown.motion = motion;
- NSInteger start = index < 0 ? 0 : resting ? SGKaraokeSungEnd(lines[index]) + kBreakMs : lines[index].start;
- NSInteger end = index + 1 < (NSInteger)lines.count ? lines[index + 1].start : index < 0 ? start : SGKaraokeSungEnd(lines[index]) + kBreakMs;
+ NSInteger start = index < 0 ? 0 : resting ? SGKaraokeSungEnd(lines[index]) + SGKaraokeBreakMs : lines[index].start;
+ NSInteger end = index + 1 < (NSInteger)lines.count ? lines[index + 1].start
+ : index < 0 ? start : SGKaraokeSungEnd(lines[index]) + SGKaraokeBreakMs;
shown.from = start / 1000.0;
shown.seconds = MIN(MAX((end - start) / 1000.0 + 1, kShortest), kLongest);
return shown;
}
-static void tick(void) {
+// Offers the artwork for where the song is, and says in how many seconds of the song's time to look again:
+// kTick while it cannot be worked out yet, negative for not until something else changes. Past a line's sung
+// end by SGKaraokeBreakMs, with the next line at least that far off, the line rests: it is let go and only the
+// next one shows, dimmed (as the artist row does in LockScreenLyrics.x).
+static NSTimeInterval update(void) {
if (@available(iOS 26.0, *)) {
SPTPlayerState *state = SGPlayerState();
NSString *trackID = SGKaraokePlayingTrack();
if (!trackID || !state) {
clear();
- return;
+ return kTick;
}
if (![trackID isEqualToString:sg_track]) {
sg_track = trackID;
@@ -259,14 +281,17 @@ static void tick(void) {
}
clear();
SGLockMotionShowPlain(YES);
- return;
+ return lines ? -1 : kTick;
}
NSInteger position = SGKaraokePositionMs();
- if (position < 0) return;
+ if (position < 0) return kTick;
position -= SGKaraokeDelayMs();
NSInteger index = SGKaraokeLeadLine(lines, position);
- BOOL nextFarOff = index + 1 == (NSInteger)lines.count || lines[index + 1].start - position > kBreakMs;
- BOOL resting = index < 0 || (position > SGKaraokeSungEnd(lines[index]) + kBreakMs && nextFarOff);
+ NSInteger ms = SGKaraokeMsToChange(lines, position, -1);
+ // A ms on, past the truncation of the position.
+ NSTimeInterval wait = ms > 0 ? (ms + 1) / 1000.0 : -1;
+ BOOL nextFarOff = index + 1 == (NSInteger)lines.count || lines[index + 1].start - position > SGKaraokeBreakMs;
+ BOOL resting = index < 0 || (position > SGKaraokeSungEnd(lines[index]) + SGKaraokeBreakMs && nextFarOff);
SGLyricsClipStyle style = (SGLyricsClipStyle)SGInt(SGKeyLockScreenLyricsStyle, SGLyricsClipStill);
NSURL *motion = SGLockScreenArtwork() == SGLockArtworkMotionLyrics && [sg_motionURI isEqualToString:SGURIString(state.track.URI)]
? sg_motion : nil;
@@ -281,7 +306,7 @@ static void tick(void) {
}
NSString *look = SGLyricsClipLook(motion, style);
NSString *artworkID = [NSString stringWithFormat:@"%@-%ld%@-%@", trackID, (long)index, resting ? @"r" : @"", look];
- if ([artworkID isEqualToString:sg_shownID]) return;
+ if ([artworkID isEqualToString:sg_shownID]) return wait;
// Spotify's request block for its cover, read on main and kept once it is this track's.
if (!sg_cover) {
NSDictionary *info = MPNowPlayingInfoCenter.defaultCenter.nowPlayingInfo;
@@ -301,31 +326,43 @@ static void tick(void) {
NSString *ahead = [NSString stringWithFormat:@"%@-%ld-%@", trackID, (long)index + 1, look];
drawAhead(ahead, lineAt(lines, index + 1, NO, motion, sg_cover, style));
}
+ return wait;
}
+ return -1;
}
-// Main thread, as everything the timer touches is.
-static void setTicking(BOOL on) {
- if (on == (sg_timer != nil)) return;
- if (!on) {
- dispatch_source_cancel(sg_timer);
- sg_timer = nil;
+static void stopTicking(void) {
+ if (sg_timer) dispatch_source_cancel(sg_timer);
+ sg_timer = nil;
+}
+
+// Main thread, as everything the timer touches is. Offers the artwork for now and, while sg_running, arms the
+// timer for the next look; else stops it.
+static void tick(void) {
+ NSTimeInterval wait = update();
+ if (!sg_running || wait < 0) {
+ stopTicking();
return;
}
- // A strict GCD timer: the main run loop's timers are throttled while the screen is off, and the lines stood
- // still on a locked phone.
- sg_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, DISPATCH_TIMER_STRICT, dispatch_get_main_queue());
- uint64_t every = (uint64_t)(kTick * NSEC_PER_SEC);
- dispatch_source_set_timer(sg_timer, dispatch_time(DISPATCH_TIME_NOW, every), every, 10 * NSEC_PER_MSEC);
- dispatch_source_set_event_handler(sg_timer, ^{
- static CFAbsoluteTime last;
- static int late;
- CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
- if (last && now - last > 2 && late++ < 5) SGLog(@"%s: ticked %.1f s late", __FILE_NAME__, now - last - kTick);
- last = now;
- tick();
- });
- dispatch_resume(sg_timer);
+ if (!sg_timer) {
+ // A strict GCD timer: the main run loop's timers are throttled while the screen is off, and the lines stood
+ // still on a locked phone.
+ sg_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, DISPATCH_TIMER_STRICT, dispatch_get_main_queue());
+ dispatch_source_set_event_handler(sg_timer, ^{
+ static int late;
+ CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
+ if (now - sg_due > 2 && late++ < 5) SGLog(@"%s: ticked %.1f s late", __FILE_NAME__, now - sg_due);
+ tick();
+ });
+ dispatch_resume(sg_timer);
+ }
+ double speed = SGPlayerState().playbackSpeed;
+ NSTimeInterval seconds = wait / (speed > 0 ? speed : 1);
+ sg_armedMs = SGKaraokePositionMs();
+ sg_armedSpeed = speed;
+ sg_armedAt = CFAbsoluteTimeGetCurrent();
+ sg_due = sg_armedAt + seconds;
+ dispatch_source_set_timer(sg_timer, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), DISPATCH_TIME_FOREVER, 10 * NSEC_PER_MSEC);
}
@interface SGLyricsArtwork : NSObject <SGPlayerStateObserver>
@@ -336,9 +373,22 @@ static void setTicking(BOOL on) {
// each time, so a change on the Lock screen page applies at once.
- (void)playerStateDidChange:(SPTPlayerState *)state {
BOOL on = SGLockArtworkShowsLyrics(SGLockScreenArtwork());
- setTicking(on && !state.isPaused);
+ sg_running = on && !state.isPaused;
if (on) tick();
- else clear();
+ else {
+ stopTicking();
+ clear();
+ }
+}
+// A seek, or a new speed, moves the next change; a report where the song is where it was headed does not.
+- (void)playerStateDidReport:(SPTPlayerState *)state {
+ if (!sg_running) return;
+ double speed = sg_armedSpeed > 0 ? sg_armedSpeed : 1;
+ double expected = sg_armedMs + (CFAbsoluteTimeGetCurrent() - sg_armedAt) * 1000 * speed;
+ // As SGKaraokePositionMs reads it, from the state reported.
+ double position = (state.isPaused ? state.positionAsOfTimestamp : state.position) * 1000;
+ // An unknown position is looked at kTick anyway.
+ if (!sg_timer || (sg_armedMs >= 0 && (state.playbackSpeed != sg_armedSpeed || fabs(position - expected) > 500))) tick();
}
@end
@@ -353,18 +403,39 @@ static void setTicking(BOOL on) {
static SGLyricsArtwork *observer;
observer = [SGLyricsArtwork new];
SGAddPlayerStateObserver(observer);
- // Heard on the writing thread and handed to main without waiting (AGENTS.md).
+ // Every write in the app posts this, so the settings are compared on the writing thread and handed to main
+ // without waiting only when one moved (AGENTS.md).
static SGLockArtwork choice;
+ static NSInteger style, delay;
choice = SGLockScreenArtwork();
+ style = SGInt(SGKeyLockScreenLyricsStyle, SGLyricsClipStill);
+ delay = SGKaraokeDelayMs();
[NSNotificationCenter.defaultCenter addObserverForName:NSUserDefaultsDidChangeNotification object:nil queue:nil
usingBlock:^(NSNotification *note) {
+ // The style and the lyrics' delay apply at once, and move the artwork or its next change.
+ SGPrefsChanged();
+ NSInteger nowStyle = SGInt(SGKeyLockScreenLyricsStyle, SGLyricsClipStill), nowDelay = SGKaraokeDelayMs();
+ if (nowStyle != style || nowDelay != delay) {
+ style = nowStyle;
+ delay = nowDelay;
+ tickSoon();
+ }
+ SGLockArtwork picked = SGLockScreenArtwork();
+ if (picked == choice) return;
+ choice = picked;
dispatch_async(dispatch_get_main_queue(), ^{
- if (SGLockScreenArtwork() == choice) return;
- choice = SGLockScreenArtwork();
- SGLog(@"lock lyrics: %@", !SGLockArtworkShowsLyrics(choice) ? @"no longer picked" : choice == SGLockArtworkLyrics ? @"picked" : @"picked over the moving artwork");
+ SGLog(@"lock lyrics: %@", !SGLockArtworkShowsLyrics(picked) ? @"no longer picked" : picked == SGLockArtworkLyrics ? @"picked" : @"picked over the moving artwork");
[observer playerStateDidChange:SGPlayerState()];
});
}];
+ // Lines kept for the track, or better timed ones in their place, are posted on main.
+ [NSNotificationCenter.defaultCenter addObserverForName:SGKaraokeLinesKeptNotification object:nil queue:nil
+ usingBlock:^(NSNotification *note) {
+ if (sg_running) tick();
+ }];
+ // A hot phone puts the lines over the cover, and they go back over the motion once it cools.
+ [NSNotificationCenter.defaultCenter addObserverForName:NSProcessInfoThermalStateDidChangeNotification object:nil queue:nil
+ usingBlock:^(NSNotification *note) { tickSoon(); }];
SGLog(@"lock lyrics: %@, the lock screen takes %@", !SGLockArtworkShowsLyrics(choice) ? @"off" : choice == SGLockArtworkLyrics ? @"on" : @"on over the moving artwork",
MPNowPlayingInfoCenter.supportedAnimatedArtworkKeys);
}
diff --git a/tweak/Sources/Shared/Lossless/Lossless.x b/tweak/Sources/Shared/Lossless/Lossless.x
index fb405f4c..2059282d 100644
--- a/tweak/Sources/Shared/Lossless/Lossless.x
+++ b/tweak/Sources/Shared/Lossless/Lossless.x
@@ -11,21 +11,33 @@
static const int kTries = 3; // failed anchors in a row before waiting for the next change of source
static const double kRetrySeconds = 2;
+// The store's lookups read the folder and open untagged files, so they run here, one at a time.
+static dispatch_queue_t sg_storeQueue;
@interface SGLosslessCoordinator : NSObject <SGPlayerStateObserver>
@end
@implementation SGLosslessCoordinator {
NSString *_track, *_path;
- BOOL _busy, _looked, _nextHas;
+ BOOL _busy, _looked, _looking, _nextHas, _nextLooking;
NSString *_next;
+ NSTimer *_ticker;
NSDate *_folderChanged;
int _failures;
uint64_t _gaveUpEpoch;
double _retryAt;
}
+// Position reports are not change callbacks, and a seek or resume shows only in the source's epoch: while
+// Spotify plays, a tick each second catches those, and a file that arrives while the song before plays.
- (void)playerStateDidChange:(SPTPlayerState *)state {
+ BOOL playing = state.isPlaying && !state.isPaused;
+ if (playing && !_ticker) {
+ _ticker = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer *timer) { [self tick]; }];
+ } else if (!playing) {
+ [_ticker invalidate];
+ _ticker = nil;
+ }
[self tick];
}
@@ -41,11 +53,24 @@ static const double kRetrySeconds = 2;
_gaveUpEpoch = 0;
}
// A track's first report can come before its title and length: look again until both are known.
- if (track && !_looked) {
- NSString *title = state.track.trackTitle;
- _path = SGLosslessStoreFile(track, title ?: @"", state.duration);
- _looked = _path || (title.length && state.duration > 0);
- if (_looked) SGLog(@"lossless: %@ (%.1f s): %@", track, state.duration, _path.lastPathComponent ?: @"no file");
+ if (track && !_looked && !_looking) {
+ _looking = YES;
+ NSString *title = state.track.trackTitle ?: @"";
+ double duration = state.duration;
+ dispatch_async(sg_storeQueue, ^{
+ NSString *path = SGLosslessStoreFile(track, title, duration);
+ dispatch_async(dispatch_get_main_queue(), ^{
+ self->_looking = NO;
+ if ([track isEqualToString:self->_track]) {
+ self->_path = path;
+ self->_looked = path || (title.length && duration > 0);
+ // Not looked yet: the next tick looks again, not this one.
+ if (!self->_looked) return;
+ SGLog(@"lossless: %@ (%.1f s): %@", track, duration, path.lastPathComponent ?: @"no file");
+ }
+ [self tick];
+ });
+ });
}
// Spotify fetches a song as it starts, so its quality is set while the one before plays.
id future = [state respondsToSelector:@selector(future)] ? state.future : nil;
@@ -54,12 +79,25 @@ static const double kRetrySeconds = 2;
NSString *nextURI = SGURIString(next.URI);
// Again when the folder changes: a file can arrive while the song before plays.
NSDate *changed = [NSFileManager.defaultManager attributesOfItemAtPath:SGLosslessStoreDirectory() error:NULL].fileModificationDate;
- if (![nextURI isEqualToString:_next] || ![changed isEqualToDate:_folderChanged]) {
+ if (!_nextLooking && (![nextURI isEqualToString:_next] || ![changed isEqualToDate:_folderChanged])) {
_next = nextURI;
_folderChanged = changed;
- _nextHas = nextURI && SGLosslessStoreHas(nextURI, next.trackTitle ?: @"");
+ _nextHas = NO;
+ if (nextURI) {
+ // Spotify's quality stays as it is until the answer is in; a tick then sets it.
+ _nextLooking = YES;
+ NSString *title = next.trackTitle ?: @"";
+ dispatch_async(sg_storeQueue, ^{
+ BOOL has = SGLosslessStoreHas(nextURI, title);
+ dispatch_async(dispatch_get_main_queue(), ^{
+ self->_nextLooking = NO;
+ self->_nextHas = has;
+ [self tick];
+ });
+ });
+ }
}
- SGLosslessLowerQuality(_nextHas);
+ if (!_nextLooking) SGLosslessLowerQuality(_nextHas);
if (!_path || _busy || SGLosslessPlaying()) return;
if (!state.isPlaying || state.isPaused || fabs(state.playbackSpeed - 1) > 0.001 || SGSingOn()) return;
@@ -98,11 +136,10 @@ static const double kRetrySeconds = 2;
%ctor {
if (!SGHidden(SGKeyLossless)) return;
+ sg_storeQueue = dispatch_queue_create("spotifyglass.lossless.store", dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0));
dispatch_async(dispatch_get_main_queue(), ^{
static SGLosslessCoordinator *coordinator;
coordinator = [SGLosslessCoordinator new];
SGAddPlayerStateObserver(coordinator);
- // Position reports are not change callbacks, and a seek or resume shows only in the source's epoch.
- [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer *timer) { [coordinator tick]; }];
});
}
diff --git a/tweak/Sources/Shared/Lossless/SGLosslessStore.m b/tweak/Sources/Shared/Lossless/SGLosslessStore.m
index ef088638..3e5c00bf 100644
--- a/tweak/Sources/Shared/Lossless/SGLosslessStore.m
+++ b/tweak/Sources/Shared/Lossless/SGLosslessStore.m
@@ -19,7 +19,8 @@ static NSString *folded(NSString *text) {
stringByFoldingWithOptions:NSCaseInsensitiveSearch | NSWidthInsensitiveSearch locale:nil];
}
-// A file's title tag and length, read once per file and kept by name and modification date.
+// A file's title tag and length, read once per file and kept by name and modification date. Lossless.x
+// looks things up on one serial queue, which is all that touches the cache.
static NSDictionary *tags(NSString *path) {
static NSMutableDictionary<NSString *, NSDictionary *> *cache;
if (!cache) cache = [NSMutableDictionary dictionary];
diff --git a/tweak/Sources/Shared/Lyrics/KaraokeSource.x b/tweak/Sources/Shared/Lyrics/KaraokeSource.x
index 5c7a7217..30734ad4 100644
--- a/tweak/Sources/Shared/Lyrics/KaraokeSource.x
+++ b/tweak/Sources/Shared/Lyrics/KaraokeSource.x
@@ -440,10 +440,18 @@ void SGKaraokeSeek(NSInteger ms) {
}
// A Spotify track by its base62 id, a local file by its URI (Shared/LocalFiles/LocalFiles.h).
+// The id is kept on the track, which the page asks for on every frame; a local file's key is not,
+// as a rename changes it.
+static char sg_trackIDKey;
static NSString *idOf(SPTPlayerTrack *track) {
+ NSString *kept = track ? objc_getAssociatedObject(track, &sg_trackIDKey) : nil;
+ if (kept) return kept;
id uri = track.URI;
NSString *text = [uri isKindOfClass:NSURL.class] ? ((NSURL *)uri).absoluteString : [uri description];
- return [text hasPrefix:@"spotify:track:"] ? [text substringFromIndex:@"spotify:track:".length] : SGLocalFileLyricsKey(text);
+ if (![text hasPrefix:@"spotify:track:"]) return SGLocalFileLyricsKey(text);
+ NSString *trackID = [text substringFromIndex:@"spotify:track:".length];
+ objc_setAssociatedObject(track, &sg_trackIDKey, trackID, OBJC_ASSOCIATION_RETAIN);
+ return trackID;
}
// Tracks come in from the player and from every list that reads their metadata, so when the table
@@ -465,10 +473,8 @@ SPTPlayerTrack *SGKaraokeTrackFor(NSString *trackID) {
@synchronized (sg_seenTracks) { return sg_seenTracks[trackID]; }
}
-void SGKaraokeRememberTrack(SPTPlayerTrack *track) {
- if (!sg_seenTracks) return;
- NSString *trackID = idOf(track);
- if (trackID) remember(track, trackID);
+void SGKaraokeRememberTrack(SPTPlayerTrack *track, NSString *trackID) {
+ if (sg_seenTracks && trackID) remember(track, trackID);
}
// With a source of the mod's on, the walk for a track starts the moment the player moves to it and,
diff --git a/tweak/Sources/Shared/Lyrics/KaraokeTiming.m b/tweak/Sources/Shared/Lyrics/KaraokeTiming.m
index 7da2b0a0..583e840c 100644
--- a/tweak/Sources/Shared/Lyrics/KaraokeTiming.m
+++ b/tweak/Sources/Shared/Lyrics/KaraokeTiming.m
@@ -56,6 +56,24 @@ NSInteger SGKaraokeLeadLine(NSArray<SGKaraokeLine *> *lines, NSInteger ms) {
return last;
}
+NSInteger SGKaraokeMsToChange(NSArray<SGKaraokeLine *> *lines, NSInteger position, NSInteger wordsOf) {
+ NSInteger next = NSIntegerMax;
+ for (SGKaraokeLine *line in lines) {
+ NSInteger sungEnd = SGKaraokeSungEnd(line);
+ NSInteger ats[] = {line.start, line.start - SGKaraokeBreakMs, sungEnd, line.end + SGKaraokeBreakMs + 1,
+ sungEnd + SGKaraokeBreakMs + 1};
+ for (size_t i = 0; i < sizeof ats / sizeof *ats; i++) {
+ if (ats[i] > position && ats[i] < next) next = ats[i];
+ }
+ }
+ if (wordsOf >= 0) {
+ for (SGKaraokeWord *word in lines[(NSUInteger)wordsOf].words) {
+ if (word.start > position && word.start < next) next = word.start;
+ }
+ }
+ return next == NSIntegerMax ? -1 : next - position;
+}
+
// Japanese, Chinese and Korean, and the punctuation set with them. Kana and Hangul are listed as
// well as the ideographs: a line of either is written without spaces just the same.
static NSCharacterSet *unspacedScript(void) {
diff --git a/tweak/Sources/Shared/Lyrics/Lyrics.h b/tweak/Sources/Shared/Lyrics/Lyrics.h
index 8c5afbc6..1f001aa0 100644
--- a/tweak/Sources/Shared/Lyrics/Lyrics.h
+++ b/tweak/Sources/Shared/Lyrics/Lyrics.h
@@ -95,6 +95,13 @@ NSInteger SGKaraokeSungEnd(SGKaraokeLine *line);
// this is the earliest line still being sung; between lines, the last one begun; -1 before the first.
// The lock screen and the Live Activity show this one.
NSInteger SGKaraokeLeadLine(NSArray<SGKaraokeLine *> *lines, NSInteger ms);
+// Past a line's end by this much, with the next line at least this far off, the lock screen lets the line go.
+static const NSInteger SGKaraokeBreakMs = 4000;
+// The ms after `position` at which the lock screen's line can next change, -1 for never: where SGKaraokeLeadLine
+// or a break turns over (each line's start, SGKaraokeBreakMs before it, its sung end, and a ms past
+// SGKaraokeBreakMs after its end and its sung end), and the word starts of line `wordsOf`, -1 for none. Some are
+// only a wake that finds the same line.
+NSInteger SGKaraokeMsToChange(NSArray<SGKaraokeLine *> *lines, NSInteger position, NSInteger wordsOf);
// Whether the text is written in a script that does not space its words, so the pieces of a line
// are words in their own right rather than halves of one.
BOOL SGKaraokeUnspacedScript(NSString *text);
@@ -174,5 +181,5 @@ id SGKaraokePlayer(void); // SPTEsperantoPlayer, nil before the a
// A track the player has reported, by its base62 id; nil for one it has not played this session.
@class SPTPlayerTrack;
SPTPlayerTrack *SGKaraokeTrackFor(NSString *trackID);
-// Keeps a track seen elsewhere, so a source can name it before the player has reported it.
-void SGKaraokeRememberTrack(SPTPlayerTrack *track);
+// Keeps a track seen elsewhere, by its base62 id, so a source can name it before the player has reported it.
+void SGKaraokeRememberTrack(SPTPlayerTrack *track, NSString *trackID);
diff --git a/tweak/Sources/Shared/Lyrics/Romanise.m b/tweak/Sources/Shared/Lyrics/Romanise.m
index e69c32c5..18b8e96c 100644
--- a/tweak/Sources/Shared/Lyrics/Romanise.m
+++ b/tweak/Sources/Shared/Lyrics/Romanise.m
@@ -11,12 +11,21 @@
NSNotificationName const SGLyricsRomanisedDidChangeNotification = @"spotifyglass.lyricsRomanisedDidChange";
-static BOOL has(NSString *text, NSString *pattern) {
- return [text rangeOfString:pattern options:NSRegularExpressionSearch].location != NSNotFound;
+typedef NS_ENUM(NSUInteger, SGScript) { SGScriptKana, SGScriptNotLatin, SGScriptHan };
+
+// Compiled once: every line on the page is looked at.
+static BOOL has(NSString *text, SGScript script) {
+ static NSRegularExpression *patterns[3];
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ NSArray<NSString *> *sources = @[@"[\\p{Hiragana}\\p{Katakana}]", @"[\\p{L}&&[^\\p{Latin}]]", @"\\p{Han}"];
+ for (NSUInteger i = 0; i < 3; i++) patterns[i] = [NSRegularExpression regularExpressionWithPattern:sources[i] options:0 error:NULL];
+ });
+ return [patterns[script] rangeOfFirstMatchInString:text options:0 range:NSMakeRange(0, text.length)].location != NSNotFound;
}
static BOOL hasKana(NSString *text) {
- return has(text, @"[\\p{Hiragana}\\p{Katakana}]");
+ return has(text, SGScriptKana);
}
BOOL SGLyricsLooksJapanese(NSArray<SGKaraokeLine *> *lines) {
@@ -50,18 +59,22 @@ static NSString *readJapanese(NSString *text) {
}
NSString *SGLyricsRomanised(NSString *text, BOOL japanese) {
- // Only a line with a letter of another script: Latin with accents (German, Vietnamese) is left alone.
- if (!text.length || !has(text, @"[\\p{L}&&[^\\p{Latin}]]")) return nil;
+ if (!text.length) return nil;
static NSCache<NSString *, NSString *> *kept;
static dispatch_once_t once;
dispatch_once(&once, ^{ kept = [NSCache new]; });
NSString *key = japanese ? [@"ja:" stringByAppendingString:text] : text;
NSString *romanised = [kept objectForKey:key];
if (romanised) return romanised.length ? romanised : nil;
+ // Only a line with a letter of another script: Latin with accents (German, Vietnamese) is left alone.
+ if (!has(text, SGScriptNotLatin)) {
+ [kept setObject:@"" forKey:key];
+ return nil;
+ }
BOOL kana = japanese || hasKana(text);
NSString *source = kana ? readJapanese(text) : text;
// Han left over is Chinese: its pinyin keeps the tones, and only its punctuation is made ASCII.
- NSString *transform = !kana && has(text, @"\\p{Han}") ? @"Any-Latin; [[:P:][:Zs:]] Latin-ASCII" : @"Any-Latin; Latin-ASCII";
+ NSString *transform = !kana && has(text, SGScriptHan) ? @"Any-Latin; [[:P:][:Zs:]] Latin-ASCII" : @"Any-Latin; Latin-ASCII";
romanised = [[source stringByApplyingTransform:transform reverse:NO]
stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet] ?: @"";
if ([romanised caseInsensitiveCompare:text] == NSOrderedSame) romanised = @"";
diff --git a/tweak/Sources/Shared/LyricsSources/LyricsHook.x b/tweak/Sources/Shared/LyricsSources/LyricsHook.x
index 20d654d7..c0bd580c 100644
--- a/tweak/Sources/Shared/LyricsSources/LyricsHook.x
+++ b/tweak/Sources/Shared/LyricsSources/LyricsHook.x
@@ -578,13 +578,20 @@ static void completed(id delegate, NSURLSession *session, NSURLSessionTask *task
if (!track) return metadata;
BOOL has = [@"true" isEqual:metadata[@"has_lyrics"]];
SGLyricsNoteSpotifyHas(track, has);
- SGKaraokeRememberTrack(self);
+ SGKaraokeRememberTrack(self, track);
if (has || !SGLyricsMayHave(track)) return metadata;
static dispatch_once_t once;
dispatch_once(&once, ^{ SGLog(@"lyrics: has_lyrics forced on, first for spotify:track:%@", track); });
+ // The track keeps its metadata, so its forced copy is made once and kept beside the dictionary it copies.
+ static char kForcedKey;
+ NSArray *kept = metadata ? objc_getAssociatedObject(self, &kForcedKey) : nil;
+ if (kept && kept.firstObject == metadata) return kept.lastObject;
NSMutableDictionary *forced = metadata ? [metadata mutableCopy] : [NSMutableDictionary dictionary];
forced[@"has_lyrics"] = @"true";
- return forced;
+ if (!metadata) return forced;
+ NSDictionary *shared = [forced copy]; // handed out again, so as unchangeable as the one Spotify hands out
+ objc_setAssociatedObject(self, &kForcedKey, @[metadata, shared], OBJC_ASSOCIATION_RETAIN);
+ return shared;
}
%end
diff --git a/tweak/Sources/Shared/Player/SpeedPitch.x b/tweak/Sources/Shared/Player/SpeedPitch.x
index eb8973c7..4ec594e9 100644
--- a/tweak/Sources/Shared/Player/SpeedPitch.x
+++ b/tweak/Sources/Shared/Player/SpeedPitch.x
@@ -824,19 +824,28 @@ static OSStatus setProperty(AudioUnit unit, AudioUnitPropertyID property, AudioU
static OSStatus (*sg_startOutput)(AudioUnit unit);
-// The silence check, a couple of times a second from Spotify's first start; it returns at once unless two
-// outputs run.
-static void startChecking(void) {
- static dispatch_once_t once;
- static dispatch_source_t timer; // kept, or it stops with its last reference
- dispatch_once(&once, ^{
+// The silence check, a couple of times a second while two outputs run, as it does nothing with fewer. Under
+// sg_outputsLock, after any output starts, stops or goes.
+static void updateChecking(void) {
+ static dispatch_source_t timer; // kept for good: a source must not be released while suspended
+ static BOOL checking;
+ if (!timer) {
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, sg_outputsQueue);
- dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, 0), (uint64_t)(kCheckEvery * NSEC_PER_SEC), NSEC_PER_SEC / 10);
dispatch_source_set_event_handler(timer, ^{
checkSilence();
});
- dispatch_resume(timer);
- });
+ }
+ int running = 0;
+ for (int i = 0; i < kMaxOutputs; i++) running += atomic_load(&sg_outputs[i].unit) && atomic_load(&sg_outputs[i].running);
+ if ((running > 1) == checking) return;
+ checking = running > 1;
+ if (!checking) {
+ dispatch_suspend(timer);
+ return;
+ }
+ uint64_t every = (uint64_t)(kCheckEvery * NSEC_PER_SEC);
+ dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, (int64_t)every), every, NSEC_PER_SEC / 10);
+ dispatch_resume(timer);
}
static OSStatus startOutput(AudioUnit unit) {
@@ -844,11 +853,11 @@ static OSStatus startOutput(AudioUnit unit) {
pthread_mutex_lock(&sg_outputsLock);
Output *output = outputFor(unit);
if (output) {
- startChecking();
AudioStreamBasicDescription client, hardware;
NSString *why = settle(output, &client, &hardware);
markEvent(output);
atomic_store(&output->running, true);
+ updateChecking();
if (!output->listened) {
output->listened = YES;
AudioUnitAddRenderNotify(unit, rendered, output);
@@ -873,6 +882,7 @@ static OSStatus stopOutput(AudioUnit unit) {
pthread_mutex_lock(&sg_outputsLock);
Output *output = outputOf(unit);
if (output && atomic_exchange(&output->running, false)) {
+ updateChecking();
reselect(NO, @"its output stopped");
SGLog(@"audio: output %p stopped (Spotify's side %.0f Hz); the processors are on %@", unit, rateOf(&output->client), describe(music()));
}
@@ -907,7 +917,10 @@ static OSStatus disposeUnit(AudioComponentInstance unit) {
changed = YES;
}
}
- if (changed) reselect(NO, @"a unit disposed");
+ if (changed) {
+ updateChecking();
+ reselect(NO, @"a unit disposed");
+ }
// Under the lock, so its slot is not used again while its last render may still be running.
OSStatus status = sg_dispose(unit);
pthread_mutex_unlock(&sg_outputsLock);
diff --git a/tweak/Sources/Shared/Player/SpotifySleepTimer.m b/tweak/Sources/Shared/Player/SpotifySleepTimer.m
index b702fc5d..45a8949c 100644
--- a/tweak/Sources/Shared/Player/SpotifySleepTimer.m
+++ b/tweak/Sources/Shared/Player/SpotifySleepTimer.m
@@ -3,12 +3,12 @@
// player core keeps that timer and pauses at its end; this only reads it off the player's state
// (SPTPlayerState's sleepTimer, Headers/SPTPlayer.h) and never pauses or changes anything of Spotify's.
//
-// A check four times a second runs while Spotify plays, or while one of its timers is followed or has just
-// gone off; a player state observer starts and stops it. Over the last seconds before the time, or before
-// the end of the track, the gain comes down. Once the timer is up (its time came, the track it ended changed,
-// Spotify paused or dropped the timer within a couple of seconds of its end) the gain stays down until
-// Spotify's pause has landed and comes back a second later, or 5 s on without a pause. A timer canceled or
-// moved later brings the gain back at once. The core may keep a timer that went off in its state for a while,
+// A check four times a second runs while Spotify has a timer set, or while one is followed or has just gone
+// off; a player state observer, told of every state Spotify reports, starts and stops it. Over the last
+// seconds before the time, or before the end of the track, the gain comes down. Once the timer is up (its
+// time came, the track it ended changed, Spotify paused or dropped the timer within a couple of seconds of
+// its end) the gain stays down until Spotify's pause has landed and comes back a second later, or 5 s on
+// without a pause. A timer canceled or moved later brings the gain back at once. The core may keep a timer that went off in its state for a while,
// so one that went off is not followed again.
//
// It stands aside while the mod's own timer runs, which has the gain then, and while Spotify's own fade is
@@ -35,8 +35,17 @@ static const NSTimeInterval kRestoreAfter = 1;
static const NSTimeInterval kPauseWait = 5;
static NSTimer *sg_check;
-// The timer followed, as "type|timestamp", and one that went off; nil for none.
-static NSString *sg_following, *sg_wentOff;
+// A timer of Spotify's: its type, 0 for none, and for a time its end in ms since 1970.
+typedef struct {
+ NSUInteger type;
+ long long atMs;
+} SGSpotifyTimer;
+// The timer followed, and one that went off.
+static SGSpotifyTimer sg_following, sg_wentOff;
+
+static BOOL sameTimer(SGSpotifyTimer a, SGSpotifyTimer b) {
+ return a.type == b.type && a.atMs == b.atMs;
+}
// For End of track, the track whose end it is.
static NSString *sg_track;
// Seconds to its end at the last check, -1 for not known.
@@ -62,16 +71,17 @@ static void restoreGain(BOOL now) {
static void wentOff(NSString *why) {
SGLog(@"sleep timer: Spotify's up (%@, %.1f s left), gain held until its pause", why, sg_left);
sg_wentOff = sg_following;
- sg_following = nil;
+ sg_following = (SGSpotifyTimer){0};
sg_left = -1;
sg_holdUntil = [NSDate dateWithTimeIntervalSinceNow:kPauseWait];
}
-// Fades for the timer `key` (of `type`, ending at `at` for a time), or finds it went off.
-static void follow(SPTPlayerState *state, NSString *key, NSUInteger type, NSDate *at) {
+// Fades for `timer` (ending at `at` for a time), or finds it went off.
+static void follow(SPTPlayerState *state, SGSpotifyTimer timer, NSDate *at) {
+ NSUInteger type = timer.type;
NSString *track = SGURIString(state.track.URI);
- if (![key isEqualToString:sg_following]) {
- sg_following = key;
+ if (!sameTimer(timer, sg_following)) {
+ sg_following = timer;
sg_track = track;
sg_stoodAside = NO;
SGLog(@"sleep timer: Spotify's set (type %lu, %@), fade %.0f s", (unsigned long)type,
@@ -112,9 +122,22 @@ static void follow(SPTPlayerState *state, NSString *key, NSUInteger type, NSDate
static void check(void);
-// Runs the check while Spotify plays or a timer of its needs it.
+// Spotify's timer in `state`, its end as a date to `at` unless NULL. With none, the one that went off is
+// forgotten: a timer set after it is a new one.
+static SGSpotifyTimer timerIn(SPTPlayerState *state, NSDate **at) {
+ SPTSleepTimer *timer = [state respondsToSelector:@selector(sleepTimer)] ? state.sleepTimer : nil;
+ NSUInteger type = [timer respondsToSelector:@selector(type)] ? timer.type : 0;
+ NSDate *end = type == kAtTime && [timer respondsToSelector:@selector(timestamp)] ? timer.timestamp : nil;
+ if (type != kEndOfTrack && !(type == kAtTime && [end isKindOfClass:NSDate.class])) type = 0;
+ if (!type) sg_wentOff = (SGSpotifyTimer){0};
+ if (at) *at = end;
+ return (SGSpotifyTimer){type, type == kAtTime ? llround(end.timeIntervalSince1970 * 1000) : 0};
+}
+
+// Runs the check while Spotify has a timer not yet gone off, or one of its needs it.
static void watch(SPTPlayerState *state) {
- BOOL needed = (state.isPlaying && !state.isPaused) || sg_following || sg_holdUntil || sg_lowered;
+ SGSpotifyTimer timer = timerIn(state, NULL);
+ BOOL needed = (timer.type && !sameTimer(timer, sg_wentOff)) || sg_following.type || sg_holdUntil || sg_lowered;
if (needed == (sg_check != nil)) return;
if (!needed) {
[sg_check invalidate];
@@ -128,12 +151,8 @@ static void watch(SPTPlayerState *state) {
static void check(void) {
SPTPlayerState *state = [(id<SPTPlayer>)SGKaraokePlayer() state];
if (!state) return; // the player not reached yet: keep checking until it is
- SPTSleepTimer *timer = [state respondsToSelector:@selector(sleepTimer)] ? state.sleepTimer : nil;
- NSUInteger type = [timer respondsToSelector:@selector(type)] ? timer.type : 0;
- NSDate *at = type == kAtTime && [timer respondsToSelector:@selector(timestamp)] ? timer.timestamp : nil;
- if (type != kEndOfTrack && !(type == kAtTime && [at isKindOfClass:NSDate.class])) type = 0;
- NSString *key = type ? [NSString stringWithFormat:@"%lu|%.3f", (unsigned long)type, at.timeIntervalSince1970] : nil;
- if (!key) sg_wentOff = nil;
+ NSDate *at;
+ SGSpotifyTimer timer = timerIn(state, &at);
if (sg_holdUntil) {
if (state.isPaused || sg_holdUntil.timeIntervalSinceNow <= 0) {
@@ -143,14 +162,14 @@ static void check(void) {
}
} else if (SGSleepTimerCurrentMode() != SGSleepTimerOff) {
sg_lowered = NO; // the mod's own timer has the gain
- sg_following = nil;
- } else if (key && ![key isEqualToString:sg_wentOff]) {
- follow(state, key, type, at);
- } else if (sg_following) {
- if (!key && sg_left >= 0 && sg_left < kUpWithin) wentOff(@"timer cleared at its end");
+ sg_following = (SGSpotifyTimer){0};
+ } else if (timer.type && !sameTimer(timer, sg_wentOff)) {
+ follow(state, timer, at);
+ } else if (sg_following.type) {
+ if (!timer.type && sg_left >= 0 && sg_left < kUpWithin) wentOff(@"timer cleared at its end");
else {
SGLog(@"sleep timer: Spotify's canceled%@", sg_lowered ? @", gain back" : @"");
- sg_following = nil;
+ sg_following = (SGSpotifyTimer){0};
sg_left = -1;
if (sg_lowered) restoreGain(YES);
}
@@ -163,6 +182,9 @@ static void check(void) {
@implementation SGSpotifySleepTimerWatch
- (void)playerStateDidChange:(SPTPlayerState *)state {
+}
+// A timer set or canceled changes none of what playerStateDidChange: is told about.
+- (void)playerStateDidReport:(SPTPlayerState *)state {
watch(state);
}
@end