Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: line meanings from Genius on the lyrics, a bubble for the artist's own and an underline for the rest, opened in a sheet
Vojtěch Škopek950baf778f6a
diff --git a/harness/lyrics/build.sh b/harness/lyrics/build.shindex ee577d7e..d182aead 100755--- a/harness/lyrics/build.sh+++ b/harness/lyrics/build.sh@@ -21,6 +21,7 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar"$HERE/main.m" "$HERE/stubs.m" \"$SRC"/Redesigned/Lyrics/SGRKaraokeView.m $( [ -f "$SRC"/Redesigned/Lyrics/LyricsText.m ] && echo "$SRC"/Redesigned/Lyrics/LyricsText.m ) "$SRC"/Shared/Lyrics/KaraokeTiming.m "$SRC"/Shared/Lyrics/Protobuf.m \"$SRC"/Shared/LyricsSources/SGTTML.m "$SRC"/Redesigned/Kit/SGRTokens.m \+ $( [ -f "$SRC"/Shared/LyricsMeanings/Meanings.m ] && echo "$SRC"/Shared/LyricsMeanings/Meanings.m "$SRC"/Redesigned/Lyrics/MeaningSheet.m ) \"$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGGlass.m \-framework UIKit -framework QuartzCore -framework CoreGraphics -framework CoreText -framework Foundation \-o "$APP/LyricsHarness"diff --git a/harness/lyrics/stubs.m b/harness/lyrics/stubs.mindex 8a56f877..7b90a8ee 100644--- a/harness/lyrics/stubs.m+++ b/harness/lyrics/stubs.m@@ -16,6 +16,27 @@ NSString *SGLyricsCreditFor(NSString *trackID) { return @"the harness"; }// -translateTo es: the language the Lyrics page would ask translations for.NSString *SGLyricsTranslationLanguage(void) { return [NSUserDefaults.standardUserDefaults stringForKey:@"translateTo"]; }+// Line meanings: -title and -artist name the track Genius is searched for, and the setting's key+// (-spotifyglass.lyricsMeanings 3) turns them on.+@interface SGHarnessTrack : NSObject+@property (nonatomic, copy) NSString *trackTitle, *artistName;+@end+@implementation SGHarnessTrack+@end+id SGKaraokeTrackFor(NSString *trackID) {+ SGHarnessTrack *track = [SGHarnessTrack new];+ track.trackTitle = [NSUserDefaults.standardUserDefaults stringForKey:@"title"];+ track.artistName = [NSUserDefaults.standardUserDefaults stringForKey:@"artist"];+ return track;+}+id SGChoiceRow(NSString *title, NSString *subtitle, NSString *key, NSArray *choices, NSInteger fallback) { return nil; }+UIViewController *SGTopController(void) {+ UIWindowScene *scene = (UIWindowScene *)UIApplication.sharedApplication.connectedScenes.anyObject;+ UIViewController *top = scene.windows.firstObject.rootViewController;+ while (top.presentedViewController) top = top.presentedViewController;+ return top;+}+static NSArray<SGKaraokeLine *> *sg_lines;static double sg_from = -1, sg_rate = 1, sg_pauseAt = -1, sg_holdFor = 0;static CFTimeInterval sg_since, sg_heldAt;diff --git a/tweak/Sources/App/Pages.m b/tweak/Sources/App/Pages.mindex 408b2a5c..1e10448d 100644--- a/tweak/Sources/App/Pages.m+++ b/tweak/Sources/App/Pages.m@@ -5,6 +5,7 @@#import "Shared/ArtistBlock/ArtistBlock.h"#import "Shared/Gestures/Gestures.h"#import "Shared/Lyrics/Lyrics.h"+#import "Shared/LyricsMeanings/Meanings.h"#import "Shared/Player/PlayerSettings.h"#import "Native/Appearance/Appearance.h"#import "Native/Navbar/Navbar.h"@@ -69,14 +70,14 @@ UIViewController *SGNavbarPage(void) {return SGRedesignedUIStored() ? SGRNavbarSettingsPage() : SGNavbarSettingsPage();}-// Pronunciation, translation and word sweeping exist only in the redesign's lyrics view.+// Pronunciation, translation, word sweeping and line meanings exist only in the redesign's lyrics view.static UIViewController *lyricsPage(void) {BOOL redesigned = SGRedesignedUIStored();NSMutableArray<SGModRow *> *more = [NSMutableArray arrayWithObject:SGLockScreenLyricsRow()];if (!redesigned) [more insertObject:SGGlassLyricsRow() atIndex:0];NSMutableArray<SGModSection *> *sections = [NSMutableArray arrayWithObject:SGLyricsSourcesSection(redesigned)];if (redesigned) {- [sections addObject:SGSection(@"Display", @[SGLyricsWordTimingRow(), SGRLyricsTextSizesRow(), SGLyricsTranslationLanguageRow()])];+ [sections addObject:SGSection(@"Display", @[SGLyricsWordTimingRow(), SGRLyricsTextSizesRow(), SGLyricsTranslationLanguageRow(), SGLyricsMeaningsRow()])];}[sections addObject:SGSection(nil, more)];return [[SGModPage alloc] initWithTitle:@"Lyrics" intro:SGRestartNote sections:sections footer:nil];diff --git a/tweak/Sources/Redesigned/Lyrics/MeaningSheet.h b/tweak/Sources/Redesigned/Lyrics/MeaningSheet.hnew file mode 100644index 00000000..2a8eb46b--- /dev/null+++ b/tweak/Sources/Redesigned/Lyrics/MeaningSheet.h@@ -0,0 +1,5 @@+// A line's Genius explanations in a sheet over the lyrics, which keep playing behind it.+#import <UIKit/UIKit.h>+#import "Shared/LyricsMeanings/Meanings.h"++void SGRShowMeanings(NSString *lineText, NSArray<SGLyricsMeaning *> *meanings);diff --git a/tweak/Sources/Redesigned/Lyrics/MeaningSheet.m b/tweak/Sources/Redesigned/Lyrics/MeaningSheet.mnew file mode 100644index 00000000..73a5bf55--- /dev/null+++ b/tweak/Sources/Redesigned/Lyrics/MeaningSheet.m@@ -0,0 +1,160 @@+#import "Core/SGCore.h"+#import "Settings/SGPageStyle.h"+#import "MeaningSheet.h"+#import "Redesigned/Kit/SGRTokens.h"++static const CGFloat kSide = 24, kTop = 28, kGap = 12;++static NSString *authorName(SGLyricsMeaningAuthor author) {+ switch (author) {+ case SGLyricsMeaningByArtist: return @"From the artist";+ case SGLyricsMeaningByEditors: return @"Genius editors";+ case SGLyricsMeaningByCommunity: return @"Genius community";+ }+ return nil;+}++static NSString *authorSymbol(SGLyricsMeaningAuthor author) {+ return author == SGLyricsMeaningByArtist ? @"checkmark.seal.fill" : author == SGLyricsMeaningByEditors ? @"checkmark.circle" : @"person.2";+}++@interface SGRMeaningSheet : UIViewController+@end++@implementation SGRMeaningSheet {+ NSString *_lineText;+ NSArray<SGLyricsMeaning *> *_meanings;+ NSUInteger _index;+ UIScrollView *_scroll;+ UILabel *_quote, *_body, *_count;+ UIButton *_author, *_next, *_open;+}++- (instancetype)initWithLine:(NSString *)lineText meanings:(NSArray<SGLyricsMeaning *> *)meanings {+ self = [super initWithNibName:nil bundle:nil];+ if (!self) return nil;+ _lineText = [lineText copy];+ _meanings = [meanings copy];+ self.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;+ self.modalPresentationStyle = UIModalPresentationPageSheet;+ UISheetPresentationController *sheet = self.sheetPresentationController;+ sheet.detents = @[UISheetPresentationControllerDetent.mediumDetent, UISheetPresentationControllerDetent.largeDetent];+ sheet.prefersGrabberVisible = YES;+ sheet.prefersScrollingExpandsWhenScrolledToEdge = YES;+ return self;+}++- (UILabel *)labelWithFont:(UIFont *)font color:(UIColor *)color {+ UILabel *label = [UILabel new];+ label.numberOfLines = 0;+ label.font = font;+ label.textColor = color;+ label.adjustsFontForContentSizeCategory = YES;+ [_scroll addSubview:label];+ return label;+}++- (UIButton *)buttonWithTitle:(NSString *)title action:(SEL)action {+ UIButtonConfiguration *config = [UIButtonConfiguration plainButtonConfiguration];+ config.title = title;+ config.contentInsets = NSDirectionalEdgeInsetsZero;+ config.baseForegroundColor = SGRAccent();+ config.titleTextAttributesTransformer = ^NSDictionary *(NSDictionary *attributes) {+ NSMutableDictionary *out = [attributes mutableCopy];+ out[NSFontAttributeName] = [UIFont systemFontOfSize:15 weight:UIFontWeightSemibold];+ return out;+ };+ UIButton *button = [UIButton buttonWithConfiguration:config primaryAction:nil];+ [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];+ [_scroll addSubview:button];+ return button;+}++- (void)viewDidLoad {+ [super viewDidLoad];+ self.view.backgroundColor = UIColor.systemBackgroundColor;+ _scroll = [[UIScrollView alloc] initWithFrame:self.view.bounds];+ _scroll.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;+ _scroll.alwaysBounceVertical = YES;+ [self.view addSubview:_scroll];++ _quote = [self labelWithFont:[UIFont systemFontOfSize:20 weight:UIFontWeightBold] color:SGRPrimary()];+ UIButtonConfiguration *badge = [UIButtonConfiguration filledButtonConfiguration];+ badge.cornerStyle = UIButtonConfigurationCornerStyleCapsule;+ badge.buttonSize = UIButtonConfigurationSizeMini;+ badge.imagePadding = 4;+ badge.contentInsets = NSDirectionalEdgeInsetsMake(4, 10, 4, 10);+ badge.baseBackgroundColor = [SGRAccent() colorWithAlphaComponent:0.2];+ badge.baseForegroundColor = SGRAccent();+ _author = [UIButton buttonWithConfiguration:badge primaryAction:nil];+ _author.userInteractionEnabled = NO;+ [_scroll addSubview:_author];+ _body = [self labelWithFont:[UIFont preferredFontForTextStyle:UIFontTextStyleBody] color:SGRPrimary()];+ _count = [self labelWithFont:[UIFont systemFontOfSize:13 weight:UIFontWeightRegular] color:SGRTertiary()];+ _count.numberOfLines = 1;+ _next = [self buttonWithTitle:@"Next" action:@selector(showNext)];+ _open = [self buttonWithTitle:@"View on Genius" action:@selector(openGenius)];+ [self show];+}++- (void)show {+ SGLyricsMeaning *meaning = _meanings[_index];+ _quote.text = [NSString stringWithFormat:@"“%@”", _lineText];+ UIButtonConfiguration *badge = _author.configuration;+ badge.title = authorName(meaning.author);+ badge.image = [UIImage systemImageNamed:authorSymbol(meaning.author)+ withConfiguration:[UIImageSymbolConfiguration configurationWithPointSize:11 weight:UIImageSymbolWeightSemibold]];+ _author.configuration = badge;+ _body.text = meaning.body;+ _count.text = _meanings.count > 1 ? [NSString stringWithFormat:@"Genius · %lu of %lu", (unsigned long)_index + 1, (unsigned long)_meanings.count]+ : @"Genius";+ _next.hidden = _meanings.count < 2;+ _open.hidden = !meaning.url.length;+ [self.view setNeedsLayout];+}++- (void)viewDidLayoutSubviews {+ [super viewDidLayoutSubviews];+ CGFloat width = self.view.bounds.size.width - 2 * kSide;+ CGFloat y = kTop;+ _quote.frame = CGRectMake(kSide, y, width, [_quote sizeThatFits:CGSizeMake(width, CGFLOAT_MAX)].height);+ y = CGRectGetMaxY(_quote.frame) + kGap;+ CGSize badge = [_author sizeThatFits:CGSizeMake(width, CGFLOAT_MAX)];+ _author.frame = CGRectMake(kSide, y, MIN(width, badge.width), badge.height);+ y = CGRectGetMaxY(_author.frame) + kGap + 4;+ _body.frame = CGRectMake(kSide, y, width, [_body sizeThatFits:CGSizeMake(width, CGFLOAT_MAX)].height);+ y = CGRectGetMaxY(_body.frame) + kGap * 2;+ _count.frame = CGRectMake(kSide, y, [_count sizeThatFits:CGSizeMake(width, 22)].width, 22);+ CGFloat right = kSide + width;+ if (!_next.hidden) {+ CGSize size = [_next sizeThatFits:CGSizeZero];+ _next.frame = CGRectMake(right - size.width, y, size.width, 22);+ right = CGRectGetMinX(_next.frame) - 20;+ }+ if (!_open.hidden) {+ CGSize size = [_open sizeThatFits:CGSizeZero];+ _open.frame = CGRectMake(right - size.width, y, size.width, 22);+ }+ _scroll.contentSize = CGSizeMake(self.view.bounds.size.width, y + 22 + kTop + self.view.safeAreaInsets.bottom);+}++- (void)showNext {+ _index = (_index + 1) % _meanings.count;+ [UIView transitionWithView:_scroll duration:0.2 options:UIViewAnimationOptionTransitionCrossDissolve+ animations:^{ [self show]; [self.view layoutIfNeeded]; } completion:nil];+ [_scroll setContentOffset:CGPointMake(0, -_scroll.adjustedContentInset.top) animated:NO];+}++- (void)openGenius {+ NSURL *url = [NSURL URLWithString:_meanings[_index].url];+ if (url) [UIApplication.sharedApplication openURL:url options:@{} completionHandler:nil];+}++@end++void SGRShowMeanings(NSString *lineText, NSArray<SGLyricsMeaning *> *meanings) {+ if (!meanings.count) return;+ UIViewController *top = SGTopController();+ if (!top || [top isKindOfClass:SGRMeaningSheet.class]) return;+ [top presentViewController:[[SGRMeaningSheet alloc] initWithLine:lineText meanings:meanings] animated:YES completion:nil];+}diff --git a/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m b/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.mindex f0d4cbb0..9e9ac706 100644--- a/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m+++ b/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m@@ -10,6 +10,7 @@#import "Core/SGCore.h"#import "SGRKaraokeView.h"#import "LyricsText.h"+#import "MeaningSheet.h"#import "Shared/LyricsSources/LyricsSources.h"#import "Shared/Player/PlayerEvents.h"#import "Shared/Haptics/Haptics.h"@@ -22,6 +23,10 @@ static const CGFloat kEdgeFade = 0.1; // the lines fade out over this share atstatic const CGFloat kBlurPerLine = 1.4, kMaxBlur = 6;// The (oh, aye) hanging under a line: smaller, a little dimmer, and just clear of it.static const CGFloat kBackingScale = 0.62, kBackingAlpha = 0.8, kBackingGap = 4;+// The mark of a line Genius explains: a bubble after it for the artist's own word, a dotted underline+// for anyone else's.+static const CGFloat kBubbleSide = 22, kBubbleGap = 8, kBubbleGlyph = 11, kBubbleAlpha = 0.75, kBubbleReach = 14;+static const CGFloat kUnderlineDrop = 1, kUnderlineWidth = 2, kUnderlineAlpha = 0.35;// The line naming the source, under the lyrics and outside the fade so it does not dim with them.static const CGFloat kCreditSize = 12, kCreditAlpha = 0.4, kCreditBottom = 10;// The button for the pronunciation and the translation, in the bottom leading corner as Apple Music@@ -614,6 +619,9 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {- (void)showTime:(double)ms;// Every word lit and left so, for lyrics with no timing: nothing is sung, so nothing is dim.- (void)showPlain;+- (void)markMeaning:(NSArray<SGLyricsMeaning *> *)meanings;+// Where the bubble can be tapped, in the line's own space; CGRectNull without one.+@property (nonatomic, readonly) CGRect bubbleTarget;@end// The translation of a line being sung, brighter than a line waiting but never as bright as the words.@@ -622,6 +630,9 @@ static const CGFloat kTranslationLit = 0.6;@implementation SGRKaraokeLineView {NSArray<SGRKaraokeSweep *> *_sweeps; // the line's words, then their pronunciation's where shownNSArray<SGRKaraokeWordView *> *_words; // every word of both+ NSArray<SGRKaraokeWordView *> *_lyricWords;+ UIImageView *_bubble;+ CAShapeLayer *_underline;UILabel *_translation;NSUInteger _generation;SGRKaraokeLineView *_backing;@@ -669,6 +680,7 @@ static double wholeFrom(SGKaraokeLine *run, BOOL sweepsEstimates) {if (spoken) [sweeps addObject:spoken];_sweeps = sweeps;_words = [sung.words ?: @[] arrayByAddingObjectsFromArray:spoken.words ?: @[]];+ _lyricWords = sung.words;if (!CGRectIsNull(layout.translation)) {_translation = [[UILabel alloc] initWithFrame:layout.translation];@@ -778,6 +790,66 @@ static const NSUInteger kLinesPerFrame = 4;[_backing showPlain];}+- (CGRect)bubbleTarget {+ return _bubble ? CGRectInset(_bubble.frame, -kBubbleReach, -kBubbleReach) : CGRectNull;+}++- (void)markMeaning:(NSArray<SGLyricsMeaning *> *)meanings {+ [_bubble removeFromSuperview];+ _bubble = nil;+ [_underline removeFromSuperlayer];+ _underline = nil;+ if (!meanings.count || !_lyricWords.count) return;+ if (meanings.firstObject.author == SGLyricsMeaningByArtist) {+ SGRKaraokeWordView *last = _lyricWords.lastObject;+ BOOL rightToLeft = readsRightToLeft(SGKaraokeLineText(_line));+ CGRect word = CGRectMake(last.center.x - last.bounds.size.width / 2, last.center.y - last.bounds.size.height / 2,+ last.bounds.size.width, last.bounds.size.height);+ CGFloat x = rightToLeft ? CGRectGetMinX(word) - kBubbleGap - kBubbleSide : CGRectGetMaxX(word) + kBubbleGap;+ UIImage *glyph = [UIImage systemImageNamed:@"quote.opening" withConfiguration:+ [UIImageSymbolConfiguration configurationWithPointSize:kBubbleGlyph weight:UIImageSymbolWeightBold]];+ _bubble = [[UIImageView alloc] initWithImage:glyph];+ _bubble.contentMode = UIViewContentModeCenter;+ _bubble.tintColor = UIColor.blackColor;+ _bubble.backgroundColor = UIColor.whiteColor;+ _bubble.layer.cornerRadius = kBubbleSide / 2;+ _bubble.alpha = kBubbleAlpha;+ _bubble.frame = CGRectMake(x, CGRectGetMidY(word) - kBubbleSide / 2, kBubbleSide, kBubbleSide);+ _bubble.isAccessibilityElement = YES;+ _bubble.accessibilityLabel = @"Meaning from the artist";+ [self addSubview:_bubble];+ return;+ }+ // One dotted stroke under each row the line's words wrap onto.+ UIBezierPath *path = [UIBezierPath bezierPath];+ CGFloat rowY = NAN, from = 0, to = 0;+ for (SGRKaraokeWordView *word in _lyricWords) {+ CGFloat bottom = word.center.y + word.bounds.size.height / 2 + kUnderlineDrop;+ CGFloat left = word.center.x - word.bounds.size.width / 2, right = left + word.bounds.size.width;+ if (bottom != rowY) {+ if (!isnan(rowY)) {+ [path moveToPoint:CGPointMake(from, rowY)];+ [path addLineToPoint:CGPointMake(to, rowY)];+ }+ rowY = bottom;+ from = left;+ to = right;+ continue;+ }+ from = MIN(from, left);+ to = MAX(to, right);+ }+ [path moveToPoint:CGPointMake(from, rowY)];+ [path addLineToPoint:CGPointMake(to, rowY)];+ _underline = [CAShapeLayer layer];+ _underline.path = path.CGPath;+ _underline.strokeColor = [UIColor colorWithWhite:1 alpha:kUnderlineAlpha].CGColor;+ _underline.lineWidth = kUnderlineWidth;+ _underline.lineCap = kCALineCapRound;+ _underline.lineDashPattern = @[@0, @5];+ [self.layer insertSublayer:_underline atIndex:0];+}+@end#pragma mark - a break@@ -1003,6 +1075,8 @@ typedef struct {CFTimeInterval _clockTime;BOOL _sweepsEstimates; // the Lyrics page's "Simulate word-by-word timing", read once like the creditBOOL _plain; // the song has no timing at all: every line lit, nothing follows the clock+ NSDictionary<NSNumber *, NSArray<SGLyricsMeaning *> *> *_meanings; // Genius's, by line+ NSUInteger _meaningsAsked;}- (instancetype)initWithFrame:(CGRect)frame {@@ -1038,6 +1112,7 @@ typedef struct {_sweepsEstimates = SGFlag(SGKeyLyricsSimulateWords, NO);[self addSubview:_credit];[self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)]];+ [self addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(held:)]];[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(playerTransitionChanged:) name:SGPlayerTransitionNotification object:nil];[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(playerTransitionChanged:) name:SGPlayerTransitionEndedNotification object:nil];[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(restyle) name:SGRLyricsTextDidChangeNotification object:nil];@@ -1056,8 +1131,14 @@ typedef struct {- (void)tapped:(UITapGestureRecognizer *)tap {if (_extras && !_extras.hidden && CGRectContainsPoint(_extras.frame, [tap locationInView:self])) return;- if (_plain) return; // a line with no time has nowhere to seek toCGPoint point = [tap locationInView:_scroll];+ for (SGRKaraokeLineView *view in _shown.allValues) {+ CGRect target = view.bubbleTarget;+ if (CGRectIsNull(target) || !CGRectContainsPoint(target, [_scroll convertPoint:point toView:view])) continue;+ [self explainLine:view];+ return;+ }+ if (_plain) return; // a line with no time has nowhere to seek tofor (SGRKaraokeLineView *view in _shown.allValues) {if (!CGRectContainsPoint(CGRectInset(view.frame, -_margin, -_lineGap / 2), point)) continue;SGKaraokeSeek(view.line.start);@@ -1067,6 +1148,38 @@ typedef struct {}}+- (void)held:(UILongPressGestureRecognizer *)hold {+ if (hold.state != UIGestureRecognizerStateBegan || !_meanings.count) return;+ CGPoint point = [hold locationInView:_scroll];+ for (SGRKaraokeLineView *view in _shown.allValues) {+ if (!CGRectContainsPoint(CGRectInset(view.frame, -_margin, -_lineGap / 2), point)) continue;+ [self explainLine:view];+ return;+ }+}++- (void)explainLine:(SGRKaraokeLineView *)view {+ NSNumber *index = [_shown allKeysForObject:view].firstObject;+ NSArray<SGLyricsMeaning *> *meanings = index ? _meanings[index] : nil;+ if (!meanings.count) return;+ SGPlayFeedback(SGFeedbackSkip);+ SGRShowMeanings(SGKaraokeLineText(view.line), meanings);+}++// Genius is asked once the song's lines are in; lines that change under it are matched again.+- (void)askMeanings {+ _meanings = nil;+ NSUInteger asked = ++_meaningsAsked;+ NSArray<SGKaraokeLine *> *lines = _lines;+ __weak SGRKaraokeView *weakSelf = self;+ SGLyricsMeaningsFor(_track, lines, ^(NSDictionary<NSNumber *, NSArray<SGLyricsMeaning *> *> *byLine) {+ SGRKaraokeView *page = weakSelf;+ if (!page || asked != page->_meaningsAsked || lines != page->_lines) return;+ page->_meanings = byLine;+ for (NSNumber *key in page->_shown) [page->_shown[key] markMeaning:byLine[key]];+ });+}+#pragma mark - scrolling by hand// Lines are placed for a content offset of 0, so following the song means scrolling back to 0.@@ -1209,6 +1322,7 @@ typedef struct {_hasTranslation = _hasTranslation || line.translation.length;}[self offerExtras];+ [self askMeanings];}// Measures the song for the width and, once that is in, places it; Spotify's own lines stay in view@@ -1366,6 +1480,7 @@ typedef struct {view = [[SGRKaraokeLineView alloc] initWithLine:_lines[index] width:_builtWidth - 2 * _margin style:_style under:nilblurred:_maxBlur > 0 && !_plain sweepsEstimates:_sweepsEstimates];if (_plain) [view showPlain];+ [view markMeaning:_meanings[@(index)]];[_scroll addSubview:view];_shown[@(index)] = view;[self placeLine:view at:index animated:NO];diff --git a/tweak/Sources/Shared/LyricsMeanings/Meanings.h b/tweak/Sources/Shared/LyricsMeanings/Meanings.hnew file mode 100644index 00000000..e67099f7--- /dev/null+++ b/tweak/Sources/Shared/LyricsMeanings/Meanings.h@@ -0,0 +1,38 @@+// What the lines mean: Genius's annotations on the song, matched by their text to the lines the+// lyrics view shows, whichever source those came from. Genius's own web endpoints, which take no key.+#import <UIKit/UIKit.h>+#import "Shared/Lyrics/Lyrics.h"++// Whose annotations show, as SGLyricsMeaningsLevel; unset is off.+#define SGKeyLyricsMeanings @"spotifyglass.lyricsMeanings"++typedef NS_ENUM(NSInteger, SGLyricsMeaningsLevel) {+ SGLyricsMeaningsOff = 0,+ SGLyricsMeaningsArtist, // written or verified by the artist+ SGLyricsMeaningsEditors, // and the ones Genius's editors accepted+ SGLyricsMeaningsAll, // and the community's not yet reviewed+};++// Ordered as they are listed, the artist's first.+typedef NS_ENUM(NSUInteger, SGLyricsMeaningAuthor) {+ SGLyricsMeaningByArtist = 0,+ SGLyricsMeaningByEditors,+ SGLyricsMeaningByCommunity,+};++@interface SGLyricsMeaning : NSObject+@property (nonatomic, copy) NSString *fragment; // the words it explains, as Genius has them+@property (nonatomic, copy) NSString *body;+@property (nonatomic) SGLyricsMeaningAuthor author;+@property (nonatomic, copy) NSString *url;+@end++SGLyricsMeaningsLevel SGLyricsMeaningsShown(void);+@class SGModRow;+SGModRow *SGLyricsMeaningsRow(void);++// The meanings of the lines by index into `lines`, on the main queue: empty when Genius has none for+// the song or it could not be told apart, never called while the setting is off. Genius is asked once+// per track; the matching is done again for each set of lines.+void SGLyricsMeaningsFor(NSString *trackID, NSArray<SGKaraokeLine *> *lines,+ void (^done)(NSDictionary<NSNumber *, NSArray<SGLyricsMeaning *> *> *byLine));diff --git a/tweak/Sources/Shared/LyricsMeanings/Meanings.m b/tweak/Sources/Shared/LyricsMeanings/Meanings.mnew file mode 100644index 00000000..7d8343ed--- /dev/null+++ b/tweak/Sources/Shared/LyricsMeanings/Meanings.m@@ -0,0 +1,287 @@+#import "Core/SGCore.h"+#import "Settings/SGModPage.h"+#import "Headers/SPTPlayer.h"+#import "Meanings.h"++static NSString *const kSearch = @"https://genius.com/api/search/song";+static NSString *const kReferents = @"https://genius.com/api/referents";+static const NSUInteger kMostPages = 5, kPerPage = 50;+// Shorter than this, a fragment found inside a line is more likely a common phrase than the line.+static const NSUInteger kLeastContained = 10;+static const double kLeastShared = 0.75;++@implementation SGLyricsMeaning+@end++SGLyricsMeaningsLevel SGLyricsMeaningsShown(void) {+ NSInteger level = SGInt(SGKeyLyricsMeanings, SGLyricsMeaningsOff);+ return level >= SGLyricsMeaningsOff && level <= SGLyricsMeaningsAll ? level : SGLyricsMeaningsOff;+}++SGModRow *SGLyricsMeaningsRow(void) {+ SGModRow *row = SGChoiceRow(@"Line meanings", nil, SGKeyLyricsMeanings,+ @[@"Off", @"From the artist", @"Artist and editors", @"Everyone"], SGLyricsMeaningsOff);+ row.choiceFooter = @"Explanations from Genius. Tap the bubble after a line, or hold the line.";+ return row;+}++#pragma mark - text++// Letters and digits only, lowercase, accents gone and apostrophes closed up, so "Don’t" and "dont"+// read alike across sources.+static NSString *folded(NSString *text) {+ static NSCharacterSet *kept;+ static dispatch_once_t once;+ dispatch_once(&once, ^{ kept = NSCharacterSet.alphanumericCharacterSet; });+ NSString *plain = [text stringByFoldingWithOptions:NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch+ locale:nil];+ NSMutableString *out = [NSMutableString stringWithCapacity:plain.length];+ BOOL space = NO;+ for (NSUInteger i = 0; i < plain.length; i++) {+ unichar c = [plain characterAtIndex:i];+ if (c == '\'' || c == 0x2019 || c == 0x2018 || c == '`') continue;+ if ([kept characterIsMember:c]) {+ if (space && out.length) [out appendString:@" "];+ space = NO;+ [out appendFormat:@"%C", c];+ } else {+ space = YES;+ }+ }+ return out;+}++// "Song (feat. X) - Remastered 2011" as Genius titles it: "Song".+static NSString *bareTitle(NSString *title) {+ NSString *bare = title ?: @"";+ NSRange dash = [bare rangeOfString:@" - "];+ if (dash.location != NSNotFound) bare = [bare substringToIndex:dash.location];+ static NSRegularExpression *brackets;+ static dispatch_once_t once;+ dispatch_once(&once, ^{ brackets = [NSRegularExpression regularExpressionWithPattern:@"\\s*[\\(\\[][^\\)\\]]*[\\)\\]]" options:0 error:nil]; });+ bare = [brackets stringByReplacingMatchesInString:bare options:0 range:NSMakeRange(0, bare.length) withTemplate:@""];+ return [bare stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];+}++static BOOL sameLine(NSString *a, NSString *b) {+ if (!a.length || !b.length) return NO;+ if ([a isEqualToString:b]) return YES;+ if (MIN(a.length, b.length) >= kLeastContained && ([a containsString:b] || [b containsString:a])) return YES;+ NSArray<NSString *> *wordsA = [a componentsSeparatedByString:@" "], *wordsB = [b componentsSeparatedByString:@" "];+ if (MIN(wordsA.count, wordsB.count) < 4) return NO;+ NSCountedSet *left = [[NSCountedSet alloc] initWithArray:wordsA];+ NSUInteger shared = 0;+ for (NSString *word in wordsB) {+ if (![left countForObject:word]) continue;+ [left removeObject:word];+ shared++;+ }+ return (double)shared / MAX(wordsA.count, wordsB.count) >= kLeastShared;+}++// A fragment's lines as they can be matched, the [Chorus] headings left out.+static NSArray<NSString *> *fragmentLines(NSString *fragment) {+ NSMutableArray<NSString *> *lines = [NSMutableArray array];+ for (NSString *row in [fragment componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) {+ NSString *trimmed = [row stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];+ if ([trimmed hasPrefix:@"["] && [trimmed hasSuffix:@"]"]) continue;+ NSString *text = folded(trimmed);+ if (text.length) [lines addObject:text];+ }+ return lines;+}++#pragma mark - Genius++static NSDictionary<NSString *, NSString *> *headers(void) {+ return @{@"User-Agent": @"Mozilla/5.0 (iPhone; CPU iPhone OS 26_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148",+ @"Accept": @"application/json"};+}++static void getJSON(NSString *base, NSDictionary<NSString *, NSString *> *query, void (^done)(NSDictionary *response)) {+ NSURLComponents *url = [NSURLComponents componentsWithString:base];+ NSMutableArray<NSURLQueryItem *> *items = [NSMutableArray array];+ [query enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSString *value, BOOL *stop) {+ [items addObject:[NSURLQueryItem queryItemWithName:name value:value]];+ }];+ url.queryItems = items;+ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url.URL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData+ timeoutInterval:10];+ [headers() enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSString *value, BOOL *stop) {+ [request setValue:value forHTTPHeaderField:name];+ }];+ [[NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *reply, NSError *error) {+ NSInteger status = [reply isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)reply).statusCode : 0;+ id root = !error && status < 400 && data.length ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;+ id response = [root isKindOfClass:NSDictionary.class] ? root[@"response"] : nil;+ if (![response isKindOfClass:NSDictionary.class]) {+ SGLog(@"meanings: %@ answered %ld, error %@", url.path, (long)status, error);+ response = nil;+ }+ dispatch_async(dispatch_get_main_queue(), ^{ done(response); });+ }] resume];+}++static NSString *stringIn(id value) {+ return [value isKindOfClass:NSString.class] ? value : nil;+}++// The hit whose title and artist both agree with the track's; a song only near it would explain+// lines it does not have.+static NSNumber *songIn(NSDictionary *response, NSString *title, NSString *artist) {+ NSString *wantTitle = folded(bareTitle(title));+ NSString *wantArtist = folded([artist componentsSeparatedByString:@", "].firstObject);+ id sections = response[@"sections"];+ for (NSDictionary *section in [sections isKindOfClass:NSArray.class] ? sections : @[]) {+ id hits = [section isKindOfClass:NSDictionary.class] ? section[@"hits"] : nil;+ for (NSDictionary *hit in [hits isKindOfClass:NSArray.class] ? hits : @[]) {+ NSDictionary *song = [hit isKindOfClass:NSDictionary.class] ? hit[@"result"] : nil;+ if (![song isKindOfClass:NSDictionary.class] || ![song[@"id"] isKindOfClass:NSNumber.class]) continue;+ NSString *hitTitle = folded(bareTitle(stringIn(song[@"title"])));+ NSString *hitArtists = folded(stringIn(song[@"artist_names"]) ?: @"");+ BOOL titled = [hitTitle isEqualToString:wantTitle];+ BOOL byArtist = wantArtist.length && hitArtists.length+ && ([hitArtists containsString:wantArtist] || [wantArtist containsString:hitArtists]);+ if (titled && byArtist) return song[@"id"];+ }+ }+ return nil;+}++// By the annotation, not the referent: a referent the artist spoke to is "verified" as a whole, the+// editors' annotations under it too.+static SGLyricsMeaningAuthor authorOf(NSDictionary *annotation) {+ NSString *state = stringIn(annotation[@"state"]);+ if ([annotation[@"verified"] boolValue] || [state isEqualToString:@"verified"]) return SGLyricsMeaningByArtist;+ if ([state isEqualToString:@"accepted"]) return SGLyricsMeaningByEditors;+ return SGLyricsMeaningByCommunity;+}++static void addMeanings(NSDictionary *response, NSMutableArray<SGLyricsMeaning *> *into) {+ id referents = response[@"referents"];+ for (NSDictionary *referent in [referents isKindOfClass:NSArray.class] ? referents : @[]) {+ if (![referent isKindOfClass:NSDictionary.class] || [referent[@"is_description"] boolValue]) continue;+ NSString *fragment = stringIn(referent[@"fragment"]);+ id annotations = referent[@"annotations"];+ if (!fragment.length || ![annotations isKindOfClass:NSArray.class]) continue;+ for (NSDictionary *annotation in annotations) {+ if (![annotation isKindOfClass:NSDictionary.class] || [annotation[@"deleted"] boolValue]) continue;+ if ([stringIn(annotation[@"state"]) isEqualToString:@"rejected"]) continue;+ id body = annotation[@"body"];+ NSString *text = [stringIn([body isKindOfClass:NSDictionary.class] ? body[@"plain"] : nil)+ stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];+ if (!text.length) continue;+ SGLyricsMeaning *meaning = [SGLyricsMeaning new];+ meaning.fragment = fragment;+ meaning.body = text;+ meaning.author = authorOf(annotation);+ meaning.url = stringIn(annotation[@"share_url"]) ?: stringIn(referent[@"url"]);+ [into addObject:meaning];+ }+ }+}++static void fetchReferents(NSNumber *song, NSUInteger page, NSMutableArray<SGLyricsMeaning *> *into, void (^done)(void)) {+ getJSON(kReferents, @{@"song_id": song.stringValue, @"text_format": @"plain",+ @"per_page": @(kPerPage).stringValue, @"page": @(page).stringValue}, ^(NSDictionary *response) {+ addMeanings(response, into);+ id next = response[@"next_page"];+ if ([next isKindOfClass:NSNumber.class] && page < kMostPages) fetchReferents(song, page + 1, into, done);+ else done();+ });+}++#pragma mark - asking once per track++// Main queue only: every meaning Genius has for a track, empty for none.+static NSMutableDictionary<NSString *, NSArray<SGLyricsMeaning *> *> *sg_meanings;+static NSMutableDictionary<NSString *, NSMutableArray *> *sg_waiting;++static void answer(NSString *trackID, NSArray<SGLyricsMeaning *> *meanings, BOOL keep) {+ if (keep) sg_meanings[trackID] = meanings;+ NSArray *waiting = sg_waiting[trackID];+ [sg_waiting removeObjectForKey:trackID];+ for (void (^each)(NSArray<SGLyricsMeaning *> *) in waiting) each(meanings);+}++static void meaningsOf(NSString *trackID, void (^done)(NSArray<SGLyricsMeaning *> *meanings)) {+ if (!sg_meanings) {+ sg_meanings = [NSMutableDictionary dictionary];+ sg_waiting = [NSMutableDictionary dictionary];+ }+ NSArray<SGLyricsMeaning *> *known = sg_meanings[trackID];+ if (known) {+ done(known);+ return;+ }+ if (sg_waiting[trackID]) {+ [sg_waiting[trackID] addObject:[done copy]];+ return;+ }+ sg_waiting[trackID] = [NSMutableArray arrayWithObject:[done copy]];++ SPTPlayerTrack *track = SGKaraokeTrackFor(trackID);+ NSString *title = track.trackTitle, *artist = track.artistName;+ // Not kept: the player may name the track later.+ if (!title.length || !artist.length) {+ answer(trackID, @[], NO);+ return;+ }+ NSString *q = [NSString stringWithFormat:@"%@ %@", bareTitle(title), artist];+ getJSON(kSearch, @{@"q": q, @"per_page": @"10"}, ^(NSDictionary *response) {+ NSNumber *song = songIn(response, title, artist);+ if (!song) {+ SGLog(@"meanings: no Genius song for %@ by %@", title, artist);+ answer(trackID, @[], response != nil); // a failed search is asked again next time+ return;+ }+ NSMutableArray<SGLyricsMeaning *> *meanings = [NSMutableArray array];+ fetchReferents(song, 1, meanings, ^{+ SGLog(@"meanings: Genius song %@ for %@ has %lu annotations", song, title, (unsigned long)meanings.count);+ answer(trackID, meanings, YES);+ });+ });+}++// Each meaning goes to every line its fragment's first matchable line matches, so a chorus explained+// once is explained wherever it is sung.+static NSDictionary<NSNumber *, NSArray<SGLyricsMeaning *> *> *matched(NSArray<SGLyricsMeaning *> *meanings,+ NSArray<SGKaraokeLine *> *lines,+ SGLyricsMeaningsLevel level) {+ NSMutableArray<NSString *> *texts = [NSMutableArray arrayWithCapacity:lines.count];+ for (SGKaraokeLine *line in lines) [texts addObject:folded(SGKaraokeLineText(line))];+ SGLyricsMeaningAuthor furthest = level == SGLyricsMeaningsArtist ? SGLyricsMeaningByArtist+ : level == SGLyricsMeaningsEditors ? SGLyricsMeaningByEditors : SGLyricsMeaningByCommunity;+ NSMutableDictionary<NSNumber *, NSMutableArray<SGLyricsMeaning *> *> *byLine = [NSMutableDictionary dictionary];+ for (SGLyricsMeaning *meaning in meanings) {+ if (meaning.author > furthest) continue;+ for (NSString *wanted in fragmentLines(meaning.fragment)) {+ BOOL found = NO;+ for (NSUInteger i = 0; i < texts.count; i++) {+ if (!sameLine(wanted, texts[i])) continue;+ found = YES;+ NSMutableArray<SGLyricsMeaning *> *list = byLine[@(i)] ?: (byLine[@(i)] = [NSMutableArray array]);+ // A chorus annotated at each of its places carries the same words at every one.+ if (![[list valueForKey:@"body"] containsObject:meaning.body]) [list addObject:meaning];+ }+ if (found) break;+ }+ }+ for (NSMutableArray<SGLyricsMeaning *> *list in byLine.allValues) {+ [list sortWithOptions:NSSortStable usingComparator:^NSComparisonResult(SGLyricsMeaning *a, SGLyricsMeaning *b) {+ return a.author < b.author ? NSOrderedAscending : a.author > b.author ? NSOrderedDescending : NSOrderedSame;+ }];+ }+ return byLine;+}++void SGLyricsMeaningsFor(NSString *trackID, NSArray<SGKaraokeLine *> *lines,+ void (^done)(NSDictionary<NSNumber *, NSArray<SGLyricsMeaning *> *> *byLine)) {+ SGLyricsMeaningsLevel level = SGLyricsMeaningsShown();+ if (level == SGLyricsMeaningsOff || !trackID.length || !lines.count) return;+ meaningsOf(trackID, ^(NSArray<SGLyricsMeaning *> *meanings) {+ NSDictionary *byLine = meanings.count ? matched(meanings, lines, level) : @{};+ if (meanings.count) SGLog(@"meanings: %lu of %lu lines of %@ explained", (unsigned long)byLine.count, (unsigned long)lines.count, trackID);+ done(byLine);+ });+}