Skip to content

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

C

feat: import LRC files for local and Spotify tracks under either look

My-Name-Is-Jeff82cd8d1e2689
diff --git a/docs/tweaks.md b/docs/tweaks.md
index cc6eaf01..51d1380c 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -128,8 +128,15 @@ Shared:
lyrics are kept under the URI and asked of the sources by name, since Spotify never asks for them;
with no source switched on, of LRCLIB alone, which then gets the file's title, artist, album and
length. A rename gives a new key (a cover alone does not), asked for at once while the file plays.
- A miss is asked again a few times, in case it was a lost request. The model is checked on the Mac
- against harness/local-files/, the row and the editor in the simulator against its sim/
+ A miss is asked again a few times, in case it was a lost request. The user's own .lrc files
+ (LocalLyrics.m), imported from Files on the Imported LRC files page under Lyrics' sources and kept
+ as UTF-8 in Documents/Vitrine/Lyrics, come before any source: a file linked to the local file
+ playing (Import for current track) is its lyrics whatever its tags say, and any other is matched by
+ [ti:] and [ar:], or a name of "Artist - Title", folded; an import or a delete has the engine forget
+ what it kept for local files and ask again. SGImportedLRCAsk is the same as a source for the
+ order, which moves it on top at the first import and at every link once LyricsSources lists it.
+ The model and the LRC reading are checked on the Mac against harness/local-files/, the row and
+ the editor in the simulator against its sim/
Navigation/ the page transition fix (PageTransition.x) and opening a spotify: link (Links.x)
Player/ the player's open and close announced (PlayerEvents.x), what the player is doing read through
one hook for every feature that wants it (PlayerState.x), the lock screen widget's flags, and in the
@@ -241,6 +248,10 @@ Native:
(LyricsCard.x), the gestures' hookup and the hold on either side of the cover that plays at 2x until
the finger lifts (PlayerGestures.x), the Queue & devices flags
Lyrics/ the full screen lyrics page on glass (LyricsPage.x)
+ LocalFiles/ a lyrics button on the player's footer for a local file with an LRC file linked to it, a fifth of the
+ way in from the leading edge, which opens a page of the lines on black that follows the song
+ (LocalLyrics.h lists its files); the file's metadata says has_lyrics. Checked in the simulator
+ against harness/local-files/lyrics/
Home/ the Home gradient, Home's sections and pills hidden (HomeDeclutter.x), the Home & Library page
Playlist/ the playlist header and pills, hidden one switch each
Album/, Artist/ their pages' parts hidden, and the cover or photo behind their headers
diff --git a/harness/local-files/README.md b/harness/local-files/README.md
index 1d98bf55..9a1a18aa 100644
--- a/harness/local-files/README.md
+++ b/harness/local-files/README.md
@@ -10,8 +10,14 @@ back, that no other path comes back through it, and that a replaced or dropped c
It runs on the Mac as a Mac Catalyst binary with `CFFIXED_USER_HOME` set to `build/home`, so its
defaults and its covers never reach the Mac's own.
-It does not cover the hooks in `LocalFileInfo.x` or the lyrics engine asking for the
-new key (`Shared/Lyrics/KaraokeSource.x`).
+It then builds `lrc.m` against `LocalLyrics.m` and the engine's line timing: an `.lrc` import (empty,
+over 1 MB and tagless files refused, UTF-16 kept as UTF-8, a taken name numbered), the stamps read
+(several on a line, every fraction form, `[offset:]`, untimed text), a file linked to a local file through
+a rename's key and gone with a delete, and the match by title and artist, folded, with an
+"Artist - Title" name's sides worked out from the track.
+
+It does not cover the hooks in `LocalFileInfo.x`, the lyrics engine asking for the new key
+(`Shared/Lyrics/KaraokeSource.x`) or the Imported LRC files page.
## Edit info in the simulator
@@ -26,3 +32,16 @@ largest accessibility text size, where each label goes above its field, and sets
THEOS=$HOME/theos sim/build-sim.sh <udid> [large]
It does not cover the pickers themselves, the keyboard over the sheet, or Spotify's own menu closing.
+
+## The lyrics pages in the simulator
+
+`lyrics/build.sh <udid>` builds the native look's lyrics page for a local file
+(`Native/LocalFiles/LocalLyricsPage.m`) with `LocalLyrics.m` as the tweak compiles them, over a stand-in
+player whose clock runs at four times the song's speed. It imports and links an `.lrc` file, opens the
+page, checks that every line shows and that the line being sung is the one lit, then moves to a track with
+no file and checks that the lines go. `settings` as the second argument shows the Imported LRC files page
+instead. Screenshots go into `build/lyrics/shots/`.
+
+ lyrics/build.sh <udid> [settings]
+
+It does not cover the button on Spotify's footer, Files, or a swipe to delete.
diff --git a/harness/local-files/build.sh b/harness/local-files/build.sh
index 7bce901b..9e80d32a 100755
--- a/harness/local-files/build.sh
+++ b/harness/local-files/build.sh
@@ -10,3 +10,9 @@ xcrun -sdk macosx clang -target arm64-apple-ios17.0-macabi -isysroot "$SDK" -ifr
-fobjc-arc -g -Wall -Werror -I"$SRC" "$HERE/check.m" "$SRC/Shared/LocalFiles/LocalFiles.m" \
-framework UIKit -framework CoreGraphics -framework Foundation -o "$HERE/build/check"
CFFIXED_USER_HOME="$HERE/build/home" "$HERE/build/check"
+# The imported LRC files, with the lyrics engine's line timing as the tweak has it.
+xcrun -sdk macosx clang -target arm64-apple-ios17.0-macabi -isysroot "$SDK" -iframework "$SDK/System/iOSSupport/System/Library/Frameworks" \
+ -fobjc-arc -g -Wall -Werror -I"$SRC" "$HERE/lrc.m" "$SRC/Shared/LocalFiles/LocalLyrics.m" "$SRC/Shared/LocalFiles/LocalFiles.m" \
+ "$SRC/Shared/Lyrics/KaraokeTiming.m" "$SRC/Shared/AdBlock/Protobuf.m" \
+ -framework UIKit -framework CoreGraphics -framework Foundation -o "$HERE/build/lrc"
+CFFIXED_USER_HOME="$HERE/build/home" "$HERE/build/lrc"
diff --git a/harness/local-files/lrc.m b/harness/local-files/lrc.m
new file mode 100644
index 00000000..de327815
--- /dev/null
+++ b/harness/local-files/lrc.m
@@ -0,0 +1,115 @@
+// Checks LocalLyrics.m as the tweak compiles it: an .lrc file imported (the refusals, the name kept, a
+// taken name numbered), read into lines (several stamps on a line, the fraction's forms, the offset,
+// untimed text), linked to a local file and matched by title and artist, folded, with the sides of an
+// "Artist - Title" name worked out from the track. Runs in its own home, so nothing of the Mac's is
+// touched. Exits non-zero on the first wrong answer.
+#import <UIKit/UIKit.h>
+#import "Shared/LocalFiles/LocalFiles.h"
+#import "Shared/LocalFiles/LocalLyrics.h"
+
+#define CHECK(cond) do { if (!(cond)) { fprintf(stderr, "FAILED line %d: %s\n", __LINE__, #cond); exit(1); } } while (0)
+
+// What LyricsSources.m and KaraokeSource.x give the tweak, here as little as the file needs.
+@implementation SGLyricsResult
+@end
+@implementation SGLyricsQuery
+@end
+@implementation SGLyricsProvider
+@end
+static NSArray<NSString *> *sg_order;
+NSArray<NSString *> *SGLyricsOrder(void) { return sg_order ?: @[]; }
+void SGLyricsSetOrder(NSArray<NSString *> *keys) { sg_order = keys; }
+SGLyricsProvider *SGLyricsProviderFor(NSString *key) {
+ SGLyricsProvider *provider = [SGLyricsProvider new];
+ provider.key = key;
+ return provider;
+}
+void SGLyricsPageLines(NSArray<SGKaraokeLine *> *lines, NSArray<NSNumber *> **starts, NSArray<NSString *> **texts) {
+ NSMutableArray *at = [NSMutableArray array], *said = [NSMutableArray array];
+ for (SGKaraokeLine *line in lines) {
+ [at addObject:@(line.start)];
+ [said addObject:SGKaraokeLineText(line)];
+ }
+ *starts = at;
+ *texts = said;
+}
+SPTPlayerTrack *SGKaraokeTrackFor(NSString *trackID) { return nil; }
+
+static NSURL *fileNamed(NSString *name, NSData *data) {
+ NSURL *url = [[NSURL fileURLWithPath:NSTemporaryDirectory()] URLByAppendingPathComponent:name];
+ [data writeToURL:url atomically:YES];
+ return url;
+}
+
+static NSURL *lrc(NSString *name, NSString *text) {
+ return fileNamed(name, [text dataUsingEncoding:NSUTF8StringEncoding]);
+}
+
+int main(void) {
+ @autoreleasepool {
+ NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
+ [NSFileManager.defaultManager removeItemAtPath:[documents stringByAppendingPathComponent:@"Vitrine/Lyrics"] error:nil];
+ [NSUserDefaults.standardUserDefaults removeObjectForKey:SGKeyImportedLRCLinks];
+ sg_order = @[@"lrclib"];
+ NSError *error = nil;
+
+ // Refusals: empty, too large, no "]".
+ CHECK(!SGImportLRC(lrc(@"empty.lrc", @""), nil, &error) && error);
+ CHECK(!SGImportLRC(fileNamed(@"big.lrc", [NSMutableData dataWithLength:1024 * 1024 + 1]), nil, &error));
+ CHECK(!SGImportLRC(lrc(@"words.lrc", @"just some words"), nil, &error));
+ CHECK(SGImportedLRCFiles().count == 0);
+
+ // Several stamps on a line, every fraction form, an offset, a line with no text skipped.
+ NSString *sheet = @"[ti:Halo]\n[ar:Beyoncé]\n[offset:+500]\n[00:10.5][01:00:250]Remember\n[00:20.25]those walls\n[00:30]\n[1:05.123]I built\n";
+ NSString *name = SGImportLRC(lrc(@"halo.lrc", sheet), nil, &error);
+ CHECK([name isEqualToString:@"halo.lrc"]);
+ CHECK([SGLyricsOrder().firstObject isEqualToString:SGImportedLRCKey]); // the first import goes on top
+ SGLyricsResult *found = SGImportedLRCFor(@"spotify:track:x", @"HALO", @"beyonce");
+ CHECK(found.synced && found.karaokeLines.count == 4);
+ NSArray<NSNumber *> *starts = [found.karaokeLines valueForKey:@"start"];
+ CHECK([starts isEqualToArray:(@[@10000, @19750, @59750, @64623])]);
+ CHECK([SGKaraokeLineText(found.karaokeLines[2]) isEqualToString:@"Remember"]);
+ CHECK([found.title isEqualToString:@"Halo"] && [found.provider isEqualToString:@"Imported LRC"]);
+ CHECK(!SGImportedLRCFor(@"spotify:track:x", @"Halo", @"Someone else"));
+ CHECK(!SGImportedLRCFor(@"spotify:track:x", nil, @"Beyoncé")); // never without a title
+
+ // A taken name is numbered.
+ CHECK([SGImportLRC(lrc(@"halo.lrc", sheet), nil, &error) isEqualToString:@"halo (2).lrc"]);
+ CHECK(SGDeleteImportedLRC(@"halo (2).lrc"));
+
+ // "Artist - Title" and "Title – Artist" with no tags: the sides come from the track.
+ SGImportLRC(lrc(@"Daft Punk - One More Time.lrc", @"[00:01.00]One more time"), nil, &error);
+ SGImportLRC(lrc(@"Around the World – Daft Punk.lrc", @"[00:01.00]Around the world"), nil, &error);
+ CHECK(SGImportedLRCFor(@"spotify:track:y", @"one more time!", @"DAFT PUNK"));
+ CHECK(SGImportedLRCFor(@"spotify:track:y", @"Around The World", @"Daft Punk"));
+ CHECK(!SGImportedLRCFor(@"spotify:track:y", @"One More Time", @"Justice"));
+ CHECK(!SGImportedLRCFor(@"spotify:track:y", @"Discovery", @"Daft Punk"));
+
+ // A local file named by its URI; one linked has its file whatever the names say, and keeps it
+ // through a rename's lyrics key. Untimed text drops the lines that open with "[".
+ NSString *uri = @"spotify:local:Daft+Punk:Discovery:One+More+Time:320";
+ CHECK(SGImportedLRCFor(uri, nil, nil));
+ NSString *other = @"spotify:local:::Track+01:200";
+ CHECK(!SGImportedLRCFor(other, nil, nil));
+ sg_order = @[@"lrclib", SGImportedLRCKey];
+ NSString *plain = SGImportLRC(lrc(@"notes.lrc", @"[by:me]\nFirst line\n\nSecond line\n[x] dropped"), other, &error);
+ CHECK([SGLyricsOrder().firstObject isEqualToString:SGImportedLRCKey]); // a link goes on top
+ CHECK([SGImportedLRCLinkedTo([other stringByAppendingString:@"#123"]) isEqualToString:plain]);
+ found = SGImportedLRCFor(other, nil, nil);
+ CHECK(found && !found.synced && found.karaokeLines.count == 2 && [found.title isEqualToString:@"Track 01"]);
+ CHECK(!SGImportLRC(lrc(@"skip.lrc", @"[00:01]x"), @"spotify:track:z", &error) || !SGImportedLRCLinkedTo(@"spotify:track:z"));
+
+ // Deleting the file takes its link and its lyrics.
+ CHECK(SGDeleteImportedLRC(plain));
+ CHECK(!SGImportedLRCLinkedTo(other) && !SGImportedLRCFor(other, nil, nil));
+ CHECK(![[NSUserDefaults.standardUserDefaults dictionaryForKey:SGKeyImportedLRCLinks] count]);
+
+ // UTF-16 is read and kept as UTF-8.
+ NSString *utf16 = SGImportLRC(fileNamed(@"wide.lrc", [@"[ti:Wide]\n[00:02.00]wide" dataUsingEncoding:NSUTF16StringEncoding]), nil, &error);
+ NSString *kept = [NSString stringWithContentsOfFile:[documents stringByAppendingPathComponent:[@"Vitrine/Lyrics" stringByAppendingPathComponent:utf16]]
+ encoding:NSUTF8StringEncoding error:nil];
+ CHECK([kept hasPrefix:@"[ti:Wide]"]);
+ printf("lrc: all checks passed\n");
+ }
+ return 0;
+}
diff --git a/harness/local-files/lyrics/build.sh b/harness/local-files/lyrics/build.sh
new file mode 100755
index 00000000..e6dc31de
--- /dev/null
+++ b/harness/local-files/lyrics/build.sh
@@ -0,0 +1,52 @@
+#!/bin/sh
+# build.sh: builds the native look's lyrics page for a local file and the Imported LRC files page as the
+# tweak compiles them into an app for the simulator and, given a booted simulator's UDID, runs it and saves
+# a screenshot at each SHOT into ../build/lyrics/shots/. `settings` as the second argument shows the
+# settings page instead of the lyrics page.
+#
+# ./build.sh [<udid> [settings]]
+set -e
+HERE=$(cd "$(dirname "$0")" && pwd)
+SRC=$(cd "$HERE/../../../tweak/Sources" && pwd)
+OUT="$HERE/../build/lyrics" # harness/*/build/ is ignored
+rm -rf "$OUT/LocalLyricsHarness.app"; mkdir -p "$OUT/LocalLyricsHarness.app" "$OUT/shots"
+SDK=$(xcrun --sdk iphonesimulator --show-sdk-path)
+xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-arc -g -O0 -Wall -Werror \
+ -I"$SRC" -isysroot "$SDK" \
+ "$HERE/main.m" "$HERE/../../scene.m" "$SRC/Native/LocalFiles/LocalLyricsPage.m" \
+ "$SRC/Shared/LocalFiles/LocalLyricsPage.m" "$SRC/Shared/LocalFiles/LocalLyrics.m" "$SRC/Shared/LocalFiles/LocalFiles.m" \
+ "$SRC/Shared/Lyrics/KaraokeTiming.m" "$SRC/Shared/AdBlock/Protobuf.m" \
+ "$SRC/Settings/SGPage.m" "$SRC/Settings/SGPageStyle.m" "$SRC/Core/SGGlass.m" "$SRC/Core/SGLog.m" "$SRC/Core/SGPrefs.m" "$SRC/Core/SGViewTree.m" "$SRC/Core/SGUIMode.m" \
+ -framework UIKit -framework QuartzCore -framework CoreGraphics -framework UniformTypeIdentifiers -framework Foundation \
+ -o "$OUT/LocalLyricsHarness.app/LocalLyricsHarness"
+cat > "$OUT/LocalLyricsHarness.app/Info.plist" <<'PLIST'
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0"><dict>
+<key>CFBundleExecutable</key><string>LocalLyricsHarness</string>
+<key>CFBundleIdentifier</key><string>com.vitrine.locallyricsharness</string>
+<key>CFBundleName</key><string>LocalLyricsHarness</string>
+<key>CFBundleVersion</key><string>1</string>
+<key>CFBundleShortVersionString</key><string>1.0</string>
+<key>UIUserInterfaceStyle</key><string>Dark</string>
+<key>UILaunchScreen</key><dict/>
+<key>UIApplicationSceneManifest</key><dict>
+ <key>UIApplicationSupportsMultipleScenes</key><false/>
+ <key>UISceneConfigurations</key><dict>
+ <key>UIWindowSceneSessionRoleApplication</key><array><dict>
+ <key>UISceneConfigurationName</key><string>Default</string>
+ <key>UISceneDelegateClassName</key><string>SGRHarnessScene</string>
+ </dict></array>
+ </dict>
+</dict>
+</dict></plist>
+PLIST
+echo "built $OUT/LocalLyricsHarness.app"
+[ -n "$1" ] || exit 0
+UDID=$1
+xcrun simctl install "$UDID" "$OUT/LocalLyricsHarness.app"
+xcrun simctl launch --console-pty "$UDID" com.vitrine.locallyricsharness ${2:-page} 2>&1 | tr -ud '\r' | while IFS= read -r line; do
+ echo "$line"
+ case "$line" in *"[harness] SHOT "*) xcrun simctl io "$UDID" screenshot "$OUT/shots/${line##*SHOT }.png" >/dev/null 2>&1 & ;; esac
+done
+exit 0
diff --git a/harness/local-files/lyrics/main.m b/harness/local-files/lyrics/main.m
new file mode 100644
index 00000000..80d29197
--- /dev/null
+++ b/harness/local-files/lyrics/main.m
@@ -0,0 +1,165 @@
+// The native look's lyrics page for a local file (Native/LocalFiles/LocalLyricsPage.m) and the Imported
+// LRC files page (Shared/LocalFiles/LocalLyricsPage.m), as the tweak compiles them, over a stand-in for
+// Spotify's player that plays a local file with an LRC file linked to it. The clock is the harness's own
+// and runs at four times the song's speed, so a few seconds cover the lines. Each step logs a SHOT for
+// build.sh's screenshot and PASS or FAIL for what it checks.
+#import <UIKit/UIKit.h>
+#import "Shared/LocalFiles/LocalFiles.h"
+#import "Shared/LocalFiles/LocalLyrics.h"
+#import "Native/LocalFiles/LocalLyrics.h"
+#import "Shared/Player/PlayerState.h"
+
+#pragma mark - the player, standing in
+
+@interface SGFakeTrack : NSObject
+@property (nonatomic, copy) NSString *URI, *trackTitle, *artistName;
+@property (nonatomic, copy) NSDictionary *metadata;
+@end
+@implementation SGFakeTrack
+@end
+
+@interface SGFakeState : NSObject
+@property (nonatomic, strong) SGFakeTrack *track;
+@property (nonatomic) BOOL isPaused;
+@property (nonatomic) double positionAsOfTimestamp;
+@end
+@implementation SGFakeState
+static CFTimeInterval sg_started;
+- (double)position {
+ return self.positionAsOfTimestamp + (CACurrentMediaTime() - sg_started) * 4;
+}
+@end
+
+static SGFakeState *sg_state;
+SPTPlayerState *SGPlayerState(void) { return (SPTPlayerState *)sg_state; }
+NSString *SGURIString(id uri) { return [uri isKindOfClass:NSString.class] ? uri : nil; }
+void SGAddPlayerStateObserver(id<SGPlayerStateObserver> observer) {}
+
+// What LyricsSources.m and KaraokeSource.x give the tweak.
+@implementation SGLyricsResult
+@end
+@implementation SGLyricsQuery
+@end
+NSArray<NSString *> *SGLyricsOrder(void) { return @[]; }
+void SGLyricsSetOrder(NSArray<NSString *> *keys) {}
+SGLyricsProvider *SGLyricsProviderFor(NSString *key) { return nil; }
+void SGLyricsPageLines(NSArray<SGKaraokeLine *> *lines, NSArray<NSNumber *> **starts, NSArray<NSString *> **texts) {
+ *starts = @[];
+ *texts = @[];
+}
+SPTPlayerTrack *SGKaraokeTrackFor(NSString *trackID) { return nil; }
+
+#pragma mark - the run
+
+static void say(NSString *what) {
+ printf("[harness] %s\n", what.UTF8String);
+ fflush(stdout);
+}
+
+static void check(BOOL ok, NSString *what) {
+ say([NSString stringWithFormat:@"%@ %@", ok ? @"PASS" : @"FAIL", what]);
+}
+
+static void after(NSTimeInterval seconds, dispatch_block_t block) {
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), dispatch_get_main_queue(), block);
+}
+
+static NSArray<UILabel *> *labelsIn(UIView *view) {
+ NSMutableArray<UILabel *> *found = [NSMutableArray array];
+ for (UIView *sub in view.subviews) {
+ if ([sub isKindOfClass:UIStackView.class]) {
+ for (UIView *line in ((UIStackView *)sub).arrangedSubviews) [found addObject:(UILabel *)line];
+ }
+ [found addObjectsFromArray:labelsIn(sub)];
+ }
+ return found;
+}
+
+@interface SGHarnessDelegate : UIResponder <UIApplicationDelegate>
+@property (nonatomic, strong) UIWindow *window;
+@end
+
+@implementation SGHarnessDelegate
+
+- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options {
+ NSString *uri = @"spotify:local:Vitrine:Demos:A+Song+of+Our+Own:120";
+ SGFakeTrack *track = [SGFakeTrack new];
+ track.URI = uri;
+ track.trackTitle = @"A Song of Our Own";
+ track.artistName = @"Vitrine";
+ sg_state = [SGFakeState new];
+ sg_state.track = track;
+
+ NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
+ [NSFileManager.defaultManager removeItemAtPath:[documents stringByAppendingPathComponent:@"Vitrine/Lyrics"] error:nil];
+ [NSUserDefaults.standardUserDefaults removeObjectForKey:SGKeyImportedLRCLinks];
+ NSMutableString *sheet = [NSMutableString string];
+ for (NSInteger i = 0; i < 24; i++) {
+ [sheet appendFormat:@"[00:%02ld.00]Line %ld of the song, long enough to wrap onto a second row here\n", (long)(i * 2), (long)i + 1];
+ }
+ NSURL *file = [[NSURL fileURLWithPath:NSTemporaryDirectory()] URLByAppendingPathComponent:@"Vitrine - A Song of Our Own.lrc"];
+ [sheet writeToURL:file atomically:YES encoding:NSUTF8StringEncoding error:nil];
+ check(SGImportLRC(file, uri, nil) != nil, @"imported and linked");
+
+ self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
+ UIViewController *player = [UIViewController new];
+ player.view.backgroundColor = UIColor.darkGrayColor;
+ self.window.rootViewController = player;
+ [self.window makeKeyAndVisible];
+
+ NSString *mode = NSProcessInfo.processInfo.arguments.count > 1 ? NSProcessInfo.processInfo.arguments[1] : @"page";
+ if ([mode isEqualToString:@"settings"]) {
+ after(1, ^{
+ UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:SGImportedLRCPage()];
+ nav.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
+ [player presentViewController:nav animated:NO completion:nil];
+ after(1.5, ^{
+ say(@"SHOT settings");
+ after(1, ^{ exit(0); });
+ });
+ });
+ return YES;
+ }
+
+ after(1, ^{
+ sg_started = CACurrentMediaTime();
+ UIViewController *page = SGLocalLyricsPage();
+ [player presentViewController:page animated:NO completion:nil];
+ after(0.3, ^{ say(@"SHOT start"); });
+ // 3 s at four times speed is 12 s of song: line 7 (from 12 s) is being sung.
+ after(3, ^{
+ NSArray<UILabel *> *lines = labelsIn(page.view);
+ check(lines.count == 24, [NSString stringWithFormat:@"24 lines shown (%lu)", (unsigned long)lines.count]);
+ UILabel *lit = nil;
+ for (UILabel *line in lines) {
+ if (line.alpha == 1) lit = line;
+ }
+ check([lit.text hasPrefix:@"Line 7 "], [NSString stringWithFormat:@"line 7 lit (%@)", lit.text]);
+ say(@"SHOT playing");
+ after(4, ^{
+ say(@"SHOT later");
+ // Another track with nothing linked or matching.
+ SGFakeTrack *other = [SGFakeTrack new];
+ other.URI = @"spotify:local:Someone:Else:Untitled:90";
+ other.trackTitle = @"Untitled";
+ other.artistName = @"Someone";
+ sg_state.track = other;
+ after(1, ^{
+ check(labelsIn(page.view).count == 0, @"a track with no file shows no lines");
+ say(@"SHOT none");
+ [page dismissViewControllerAnimated:NO completion:nil];
+ after(0.5, ^{ exit(0); });
+ });
+ });
+ });
+ });
+ return YES;
+}
+
+@end
+
+int main(int argc, char *argv[]) {
+ @autoreleasepool {
+ return UIApplicationMain(argc, argv, nil, NSStringFromClass(SGHarnessDelegate.class));
+ }
+}
diff --git a/tweak/Sources/Native/LocalFiles/LocalLyrics.h b/tweak/Sources/Native/LocalFiles/LocalLyrics.h
new file mode 100644
index 00000000..7b8382d5
--- /dev/null
+++ b/tweak/Sources/Native/LocalFiles/LocalLyrics.h
@@ -0,0 +1,10 @@
+// The native look's lyrics for a local file with an imported LRC file linked to it (Shared/LocalFiles/
+// LocalLyrics.h): Spotify turns its own lyrics off for local files before it asks its lyrics service,
+// so the player's footer gets a button of the mod's that opens a page of its own.
+//
+// LocalLyricsButton.x the button on the footer, and has_lyrics for a linked local file
+// LocalLyricsPage.m the page: the lines on black, following the song
+#import <UIKit/UIKit.h>
+
+// The page for whatever plays, full screen.
+UIViewController *SGLocalLyricsPage(void);
diff --git a/tweak/Sources/Native/LocalFiles/LocalLyricsButton.x b/tweak/Sources/Native/LocalFiles/LocalLyricsButton.x
new file mode 100644
index 00000000..44bb1287
--- /dev/null
+++ b/tweak/Sources/Native/LocalFiles/LocalLyricsButton.x
@@ -0,0 +1,100 @@
+// A lyrics button on the player's footer for a local file with an LRC file linked to it (LocalLyrics.h).
+//
+// NowPlaying_ModesImpl's units are child controllers whose views hold one row each (Native/Player/
+// Player.x); the footer's is FooterElementsUnit (-viewDidLoad, objc-methods). The button is the mod's
+// own view on the unit's view, not one of the row's, so it is free to hide. It sits a fifth of the way
+// in from the leading edge, mirrored for a right-to-left language by the leading and trailing anchors.
+//
+// The track's metadata also says has_lyrics "true" for such a file, so the player builds its lyrics
+// affordance. Spotify's Now Playing lyrics service (Lyrics_NPVElementsKitImpl.NPVElementsKitServiceImpl)
+// is not told the same: its hasLyrics is a Swift protocol requirement with no Objective-C method on the
+// class or its protocols in the binary, so Swift reaches it through its witness table and a method added
+// for a hook would never be called.
+#import "Core/SGCore.h"
+#import "Headers/SPTPlayer.h"
+#import "Shared/LocalFiles/LocalFiles.h"
+#import "Shared/LocalFiles/LocalLyrics.h"
+#import "Shared/Player/PlayerState.h"
+#import "LocalLyrics.h"
+
+static NSHashTable<UIButton *> *sg_buttons;
+
+static BOOL playingLinked(void) {
+ return SGImportedLRCLinkedTo(SGURIString(SGPlayerState().track.URI)) != nil;
+}
+
+static void showButtons(void) {
+ BOOL linked = playingLinked();
+ for (UIButton *button in sg_buttons) button.hidden = !linked;
+}
+
+@interface SGLocalLyricsButtons : NSObject <SGPlayerStateObserver>
+@end
+
+@implementation SGLocalLyricsButtons
+- (void)playerStateDidChange:(SPTPlayerState *)state {
+ showButtons();
+}
+@end
+
+static void addButton(UIViewController *unit) {
+ UIView *host = unit.view;
+ UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
+ [button setImage:[UIImage systemImageNamed:@"quote.bubble" withConfiguration:[UIImageSymbolConfiguration configurationWithPointSize:20 weight:UIImageSymbolWeightRegular]]
+ forState:UIControlStateNormal];
+ button.tintColor = UIColor.whiteColor;
+ button.accessibilityLabel = @"Lyrics";
+ button.translatesAutoresizingMaskIntoConstraints = NO;
+ __weak UIViewController *weakUnit = unit;
+ [button addAction:[UIAction actionWithHandler:^(UIAction *action) {
+ [weakUnit presentViewController:SGLocalLyricsPage() animated:YES completion:nil];
+ }] forControlEvents:UIControlEventTouchUpInside];
+ [host addSubview:button];
+
+ UILayoutGuide *fifth = [UILayoutGuide new];
+ [host addLayoutGuide:fifth];
+ [NSLayoutConstraint activateConstraints:@[
+ [fifth.leadingAnchor constraintEqualToAnchor:host.leadingAnchor],
+ [fifth.widthAnchor constraintEqualToAnchor:host.widthAnchor multiplier:0.2],
+ [fifth.topAnchor constraintEqualToAnchor:host.topAnchor],
+ [fifth.heightAnchor constraintEqualToConstant:0],
+ [button.centerXAnchor constraintEqualToAnchor:fifth.trailingAnchor],
+ [button.centerYAnchor constraintEqualToAnchor:host.centerYAnchor],
+ [button.widthAnchor constraintEqualToConstant:44],
+ [button.heightAnchor constraintEqualToConstant:44],
+ ]];
+ [sg_buttons addObject:button];
+ button.hidden = !playingLinked();
+}
+
+%hook _TtC20NowPlaying_ModesImpl18FooterElementsUnit
+- (void)viewDidLoad {
+ %orig;
+ addButton((UIViewController *)self);
+}
+%end
+
+// Read for every track in every list many times a second: a prefix check for any other track.
+%hook SPTPlayerTrack
+- (NSDictionary *)metadata {
+ NSDictionary *metadata = %orig;
+ NSString *uri = SGURIString(self.URI);
+ if (!SGLocalFileIs(uri) || [@"true" isEqual:metadata[@"has_lyrics"]] || !SGImportedLRCLinkedTo(uri)) return metadata;
+ NSMutableDictionary *linked = metadata ? [metadata mutableCopy] : [NSMutableDictionary dictionary];
+ linked[@"has_lyrics"] = @"true";
+ return linked;
+}
+%end
+
+%ctor {
+ if (!SGNativeUI()) return;
+ %init;
+ sg_buttons = [NSHashTable weakObjectsHashTable];
+ static SGLocalLyricsButtons *observer;
+ observer = [SGLocalLyricsButtons new];
+ SGAddPlayerStateObserver(observer);
+ // An import for the track playing, or the delete of its file, changes the button with no new track.
+ [NSNotificationCenter.defaultCenter addObserverForName:SGImportedLRCDidChangeNotification object:nil queue:nil
+ usingBlock:^(NSNotification *note) { showButtons(); }];
+ SGRequireClasses(@[@"_TtC20NowPlaying_ModesImpl18FooterElementsUnit", @"SPTPlayerTrack"]);
+}
diff --git a/tweak/Sources/Native/LocalFiles/LocalLyricsPage.m b/tweak/Sources/Native/LocalFiles/LocalLyricsPage.m
new file mode 100644
index 00000000..f2c37f04
--- /dev/null
+++ b/tweak/Sources/Native/LocalFiles/LocalLyricsPage.m
@@ -0,0 +1,225 @@
+// The lyrics page for a local file in the native look (LocalLyrics.h): the title and the artist, then
+// the lines on black, the one being sung white and a little larger, the rest grey, scrolled to keep it
+// in the middle. Read four times a second from the player's state, which is plenty for lines; the clock
+// stops when the page goes. A new track while it is open brings its lines, or says it has none.
+#import "Core/SGCore.h"
+#import "Shared/Lyrics/Lyrics.h"
+#import "Shared/LocalFiles/LocalLyrics.h"
+#import "Shared/Player/PlayerState.h"
+#import "LocalLyrics.h"
+
+static const NSTimeInterval kTick = 0.25;
+static const CGFloat kSide = 24;
+// The line being sung grows this much; the rest are dimmed to grey, #808080 on black, 5.3:1.
+static const CGFloat kCurrentScale = 1.06, kOtherAlpha = 0.5;
+
+@interface SGLocalLyricsViewer : UIViewController
+@end
+
+@implementation SGLocalLyricsViewer {
+ UIButton *_close;
+ UILabel *_title, *_artist, *_status;
+ UIScrollView *_scroll;
+ UIStackView *_stack;
+ NSTimer *_timer;
+ NSString *_uri;
+ NSArray<SGKaraokeLine *> *_lines;
+ NSArray<UILabel *> *_labels;
+ BOOL _timed;
+ NSInteger _current;
+}
+
+static char kCloseGlassKey;
+
+static UILabel *label(UIFontTextStyle style, UIFontWeight weight, CGFloat size, UIColor *color) {
+ UILabel *label = [UILabel new];
+ label.font = [[UIFontMetrics metricsForTextStyle:style] scaledFontForFont:[UIFont systemFontOfSize:size weight:weight]];
+ label.adjustsFontForContentSizeCategory = YES;
+ label.textColor = color;
+ label.numberOfLines = 0;
+ label.translatesAutoresizingMaskIntoConstraints = NO;
+ return label;
+}
+
+- (instancetype)init {
+ if (!(self = [super initWithNibName:nil bundle:nil])) return nil;
+ self.modalPresentationStyle = UIModalPresentationFullScreen;
+ self.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
+ _current = -1;
+ return self;
+}
+
+- (UIStatusBarStyle)preferredStatusBarStyle {
+ return UIStatusBarStyleLightContent;
+}
+
+- (void)viewDidLoad {
+ [super viewDidLoad];
+ UIView *view = self.view;
+ view.backgroundColor = UIColor.blackColor;
+
+ _close = [UIButton buttonWithType:UIButtonTypeSystem];
+ [_close setImage:[UIImage systemImageNamed:@"xmark" withConfiguration:[UIImageSymbolConfiguration configurationWithPointSize:17 weight:UIImageSymbolWeightSemibold]]
+ forState:UIControlStateNormal];
+ _close.tintColor = UIColor.whiteColor;
+ _close.accessibilityLabel = @"Close";
+ _close.translatesAutoresizingMaskIntoConstraints = NO;
+ [_close addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
+
+ _title = label(UIFontTextStyleTitle2, UIFontWeightBold, 22, UIColor.whiteColor);
+ _title.accessibilityTraits = UIAccessibilityTraitHeader;
+ _artist = label(UIFontTextStyleBody, UIFontWeightRegular, 17, [UIColor colorWithWhite:1 alpha:kOtherAlpha]);
+
+ _scroll = [UIScrollView new];
+ _scroll.translatesAutoresizingMaskIntoConstraints = NO;
+ _scroll.showsVerticalScrollIndicator = NO;
+ _stack = [UIStackView new];
+ _stack.axis = UILayoutConstraintAxisVertical;
+ _stack.spacing = 20;
+ _stack.translatesAutoresizingMaskIntoConstraints = NO;
+ [_scroll addSubview:_stack];
+
+ _status = label(UIFontTextStyleBody, UIFontWeightRegular, 17, [UIColor colorWithWhite:1 alpha:kOtherAlpha]);
+ _status.textAlignment = NSTextAlignmentCenter;
+
+ for (UIView *sub in @[_scroll, _title, _artist, _status, _close]) [view addSubview:sub];
+ UILayoutGuide *safe = view.safeAreaLayoutGuide;
+ [NSLayoutConstraint activateConstraints:@[
+ [_close.topAnchor constraintEqualToAnchor:safe.topAnchor constant:8],
+ [_close.leadingAnchor constraintEqualToAnchor:safe.leadingAnchor constant:16],
+ [_close.widthAnchor constraintEqualToConstant:44],
+ [_close.heightAnchor constraintEqualToConstant:44],
+ [_title.topAnchor constraintEqualToAnchor:_close.bottomAnchor constant:16],
+ [_title.leadingAnchor constraintEqualToAnchor:safe.leadingAnchor constant:kSide],
+ [_title.trailingAnchor constraintEqualToAnchor:safe.trailingAnchor constant:-kSide],
+ [_artist.topAnchor constraintEqualToAnchor:_title.bottomAnchor constant:2],
+ [_artist.leadingAnchor constraintEqualToAnchor:_title.leadingAnchor],
+ [_artist.trailingAnchor constraintEqualToAnchor:_title.trailingAnchor],
+ [_scroll.topAnchor constraintEqualToAnchor:_artist.bottomAnchor constant:16],
+ [_scroll.leadingAnchor constraintEqualToAnchor:view.leadingAnchor],
+ [_scroll.trailingAnchor constraintEqualToAnchor:view.trailingAnchor],
+ [_scroll.bottomAnchor constraintEqualToAnchor:view.bottomAnchor],
+ [_stack.topAnchor constraintEqualToAnchor:_scroll.contentLayoutGuide.topAnchor],
+ [_stack.bottomAnchor constraintEqualToAnchor:_scroll.contentLayoutGuide.bottomAnchor],
+ [_stack.leadingAnchor constraintEqualToAnchor:safe.leadingAnchor constant:kSide],
+ [_stack.trailingAnchor constraintEqualToAnchor:safe.trailingAnchor constant:-kSide],
+ [_status.centerYAnchor constraintEqualToAnchor:_scroll.centerYAnchor],
+ [_status.leadingAnchor constraintEqualToAnchor:_title.leadingAnchor],
+ [_status.trailingAnchor constraintEqualToAnchor:_title.trailingAnchor],
+ ]];
+}
+
+- (void)viewDidLayoutSubviews {
+ [super viewDidLayoutSubviews];
+ UIVisualEffectView *glass = SGGlassFor(_close, &kCloseGlassKey);
+ glass.frame = _close.bounds;
+ SGShapeGlass(glass, _close.bounds.size.height / 2, YES);
+ // Room above the first line and below the last for either to be scrolled to the middle.
+ CGFloat half = _scroll.bounds.size.height / 2;
+ _scroll.contentInset = UIEdgeInsetsMake(24, 0, half, 0);
+}
+
+- (void)viewWillAppear:(BOOL)animated {
+ [super viewWillAppear:animated];
+ [self tick];
+ [_timer invalidate];
+ __weak typeof(self) weakSelf = self;
+ _timer = [NSTimer timerWithTimeInterval:kTick repeats:YES block:^(NSTimer *timer) { [weakSelf tick]; }];
+ // Common modes, so the line still moves on while the lines are dragged.
+ [NSRunLoop.mainRunLoop addTimer:_timer forMode:NSRunLoopCommonModes];
+}
+
+- (void)viewDidDisappear:(BOOL)animated {
+ [super viewDidDisappear:animated];
+ [_timer invalidate];
+ _timer = nil;
+}
+
+- (void)dismiss {
+ [self dismissViewControllerAnimated:YES completion:nil];
+}
+
+#pragma mark - the lines
+
+- (void)load:(SPTPlayerState *)state uri:(NSString *)uri {
+ _uri = uri;
+ _lines = nil;
+ _current = -1;
+ for (UIView *line in _stack.arrangedSubviews) [line removeFromSuperview];
+ _labels = @[];
+ NSString *title = state.track.trackTitle, *artist = state.track.artistName;
+ _title.text = title;
+ _artist.text = artist;
+ _status.text = @"Loading lyrics…";
+ _status.hidden = NO;
+ // The file is read off the main thread the first time; after that it is kept.
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
+ SGLyricsResult *lyrics = SGImportedLRCFor(uri, title, artist);
+ dispatch_async(dispatch_get_main_queue(), ^{
+ if ([uri isEqualToString:self->_uri]) [self show:lyrics];
+ });
+ });
+}
+
+- (void)show:(SGLyricsResult *)lyrics {
+ _lines = lyrics.karaokeLines;
+ _timed = SGKaraokeLinesTiming(_lines) != SGKaraokeTimingNone;
+ if (!_lines.count) {
+ _status.text = SGImportedLRCLinkedTo(_uri) ? @"This LRC file has no lines to show." : @"No imported lyrics for this track.";
+ return;
+ }
+ _status.hidden = YES;
+ NSMutableArray<UILabel *> *labels = [NSMutableArray array];
+ for (SGKaraokeLine *line in _lines) {
+ UILabel *text = label(UIFontTextStyleTitle2, UIFontWeightBold, 24, UIColor.whiteColor);
+ text.text = SGKaraokeLineText(line);
+ text.textAlignment = NSTextAlignmentCenter;
+ text.alpha = _timed ? kOtherAlpha : 1;
+ [_stack addArrangedSubview:text];
+ [labels addObject:text];
+ }
+ _labels = labels;
+ [_stack layoutIfNeeded];
+ [_scroll setContentOffset:CGPointMake(0, -_scroll.contentInset.top) animated:NO];
+}
+
+// Fades and scales only, a short ease out; with Reduce Motion the line is not scaled and the list jumps.
+- (void)light:(NSInteger)current {
+ NSInteger previous = _current;
+ _current = current;
+ BOOL still = UIAccessibilityIsReduceMotionEnabled();
+ void (^change)(void) = ^{
+ for (NSInteger i = 0; i < (NSInteger)self->_labels.count; i++) {
+ if (i != previous && i != current) continue;
+ UILabel *text = self->_labels[(NSUInteger)i];
+ BOOL lit = i == current;
+ text.alpha = lit ? 1 : kOtherAlpha;
+ text.transform = lit && !still ? CGAffineTransformMakeScale(kCurrentScale, kCurrentScale) : CGAffineTransformIdentity;
+ }
+ };
+ [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionBeginFromCurrentState
+ animations:change completion:nil];
+ // A finger on the lines has them; the page follows again once they come to rest.
+ if (current < 0 || _scroll.isTracking || _scroll.isDecelerating) return;
+ UILabel *text = _labels[(NSUInteger)current];
+ CGFloat middle = [_scroll convertPoint:text.center fromView:_stack].y - _scroll.bounds.size.height / 2;
+ CGFloat lowest = MAX(_scroll.contentSize.height + _scroll.contentInset.bottom - _scroll.bounds.size.height, -_scroll.contentInset.top);
+ middle = MIN(MAX(middle, -_scroll.contentInset.top), lowest);
+ [_scroll setContentOffset:CGPointMake(0, middle) animated:!still];
+}
+
+- (void)tick {
+ SPTPlayerState *state = SGPlayerState();
+ NSString *uri = SGURIString(state.track.URI);
+ if (uri && ![uri isEqualToString:_uri]) [self load:state uri:uri];
+ if (!_timed || !_labels.count) return;
+ NSInteger ms = (NSInteger)((state.isPaused ? state.positionAsOfTimestamp : state.position) * 1000);
+ NSInteger current = SGKaraokeLeadLine(_lines, ms);
+ if (current != _current && current < (NSInteger)_labels.count) [self light:current];
+}
+
+@end
+
+UIViewController *SGLocalLyricsPage(void) {
+ return [SGLocalLyricsViewer new];
+}
diff --git a/tweak/Sources/Shared/LocalFiles/LocalFiles.h b/tweak/Sources/Shared/LocalFiles/LocalFiles.h
index 743e4bf0..fb732647 100644
--- a/tweak/Sources/Shared/LocalFiles/LocalFiles.h
+++ b/tweak/Sources/Shared/LocalFiles/LocalFiles.h
@@ -6,6 +6,7 @@
// LocalFileInfo.x the edits applied: the player's track metadata, the cover's image request and
// the system's now playing artwork
// EditInfoMenu.x Edit info in the player's ⋯ menu while a local file plays, and its editor
+// LocalLyrics.h the user's own .lrc files, linked to a local file or matched by its names
//
// The file itself is never written: Spotify read its tags when it scanned it, and writing them back
// would take a tag writer per format. So an edit is stored by URI and laid over what Spotify read.
diff --git a/tweak/Sources/Shared/LocalFiles/LocalLyrics.h b/tweak/Sources/Shared/LocalFiles/LocalLyrics.h
new file mode 100644
index 00000000..46242e66
--- /dev/null
+++ b/tweak/Sources/Shared/LocalFiles/LocalLyrics.h
@@ -0,0 +1,41 @@
+// Imported LRC files: the user's own .lrc files, for the local files no source has lyrics for (rare
+// or self-made recordings), under either look. Kept in Documents/Vitrine/Lyrics as UTF-8, each by the
+// name it came with. A file is linked to a local file's URI ("Import for current track"), and that file
+// is the track's whatever its tags say; any other track is matched against every file by title and
+// artist, folded (case, diacritics, width and everything but letters and digits ignored).
+//
+// LocalLyrics.m the files, the links, the LRC read into lines and the match
+// LocalLyricsPage.m the Imported LRC files page on the Lyrics page
+//
+// The lyrics engine asks for a local file's imported lines before any source (Shared/Lyrics/KaraokeSource.x).
+#import <UIKit/UIKit.h>
+#import "Shared/LyricsSources/LyricsSources.h"
+
+// Local file URI -> the name of the file linked to it.
+#define SGKeyImportedLRCLinks @"spotifyglass.localFiles.lrcLinks"
+
+// The source's key in the lyrics sources order, and its ask: it needs no name, since a linked file is
+// found by the track's URI. The order moves it to the top at the first import and at every link, once
+// LyricsSources lists a provider by this key.
+extern NSString *const SGImportedLRCKey;
+extern SGLyricsAsk SGImportedLRCAsk;
+
+// The imported files' names, sorted. Safe from any thread.
+NSArray<NSString *> *SGImportedLRCFiles(void);
+// Copies an .lrc file in (empty, over 1 MB, not UTF-8 or UTF-16, or with no "]" is refused, with an
+// error to show), linked to `uri` when that is a local file's. The name it is kept under, nil on a refusal.
+// Main thread.
+NSString *SGImportLRC(NSURL *url, NSString *uri, NSError **error);
+// Removes the file and any link to it. Main thread.
+BOOL SGDeleteImportedLRC(NSString *name);
+// The file linked to a local file, by its URI or its lyrics key; nil for none. Safe from any thread.
+NSString *SGImportedLRCLinkedTo(NSString *uri);
+// The lines for a track: its linked file, else the first file whose title and artist match the names
+// given (for a local file, nil names are read from the file's URI and the player's track). nil when no
+// file has it. Safe from any thread.
+SGLyricsResult *SGImportedLRCFor(NSString *trackID, NSString *title, NSString *artist);
+// Posted on the main thread after an import or a delete.
+extern NSNotificationName const SGImportedLRCDidChangeNotification;
+
+// LocalLyricsPage.m
+UIViewController *SGImportedLRCPage(void);
diff --git a/tweak/Sources/Shared/LocalFiles/LocalLyrics.m b/tweak/Sources/Shared/LocalFiles/LocalLyrics.m
new file mode 100644
index 00000000..c2ade416
--- /dev/null
+++ b/tweak/Sources/Shared/LocalFiles/LocalLyrics.m
@@ -0,0 +1,378 @@
+// LocalLyrics.h says what is kept and how a track finds its file.
+//
+// Threading: the lyrics engine and the sources ask on the main queue, the native look's metadata hook
+// on whatever thread Spotify reads a track on, so the links are swapped whole under a lock and the read
+// files are kept under one; the files are written on the main thread.
+#import <os/lock.h>
+#import "Core/SGCore.h"
+#import "Shared/Lyrics/Lyrics.h"
+#import "Headers/SPTPlayer.h"
+#import "LocalFiles.h"
+#import "LocalLyrics.h"
+
+NSString *const SGImportedLRCKey = @"importedLRC";
+NSNotificationName const SGImportedLRCDidChangeNotification = @"spotifyglass.localFiles.lrcDidChange";
+
+static NSString *const kErrorDomain = @"spotifyglass.lrc";
+static NSString *const kCredit = @"Imported LRC";
+// A sheet of lyrics is a few kilobytes; anything near this is not one.
+static const NSUInteger kMostBytes = 1024 * 1024;
+
+#pragma mark - the files
+
+static NSString *directory(void) {
+ static NSString *path;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ // Documents, which the app's backups keep, beside the audio effects' libraries.
+ NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
+ path = [documents stringByAppendingPathComponent:@"Vitrine/Lyrics"];
+ });
+ return path;
+}
+
+NSArray<NSString *> *SGImportedLRCFiles(void) {
+ NSMutableArray<NSString *> *names = [NSMutableArray array];
+ for (NSString *name in [NSFileManager.defaultManager contentsOfDirectoryAtPath:directory() error:nil]) {
+ if ([name.pathExtension.lowercaseString isEqualToString:@"lrc"]) [names addObject:name];
+ }
+ return [names sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
+}
+
+#pragma mark - the links
+
+static NSDictionary<NSString *, NSString *> *sg_links;
+static os_unfair_lock sg_linksLock = OS_UNFAIR_LOCK_INIT;
+
+static NSDictionary<NSString *, NSString *> *allLinks(void) {
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ id stored = [NSUserDefaults.standardUserDefaults dictionaryForKey:SGKeyImportedLRCLinks];
+ os_unfair_lock_lock(&sg_linksLock);
+ sg_links = [stored isKindOfClass:NSDictionary.class] ? stored : @{};
+ os_unfair_lock_unlock(&sg_linksLock);
+ });
+ os_unfair_lock_lock(&sg_linksLock);
+ NSDictionary *links = sg_links;
+ os_unfair_lock_unlock(&sg_linksLock);
+ return links;
+}
+
+static void storeLinks(NSDictionary<NSString *, NSString *> *links) {
+ os_unfair_lock_lock(&sg_linksLock);
+ sg_links = [links copy];
+ os_unfair_lock_unlock(&sg_linksLock);
+ if (links.count) [NSUserDefaults.standardUserDefaults setObject:links forKey:SGKeyImportedLRCLinks];
+ else [NSUserDefaults.standardUserDefaults removeObjectForKey:SGKeyImportedLRCLinks];
+}
+
+// A lyrics key carries "#<number>" after the URI once the file's names are edited (LocalFiles.h); the
+// link is to the file, so it holds through a rename.
+static NSString *bareURI(NSString *uri) {
+ if (!SGLocalFileIs(uri)) return nil;
+ NSRange mark = [uri rangeOfString:@"#" options:NSBackwardsSearch];
+ return mark.location == NSNotFound ? uri : [uri substringToIndex:mark.location];
+}
+
+NSString *SGImportedLRCLinkedTo(NSString *uri) {
+ NSString *bare = bareURI(uri);
+ if (!bare) return nil;
+ id name = allLinks()[bare];
+ return [name isKindOfClass:NSString.class] ? name : nil;
+}
+
+#pragma mark - reading LRC
+
+@interface SGLRCSheet : NSObject
+@property (nonatomic, copy) NSString *title, *artist; // [ti:] and [ar:], nil without them
+@property (nonatomic, copy) NSArray<SGKaraokeLine *> *lines;
+@property (nonatomic, copy) NSArray<NSNumber *> *starts; // as Spotify's own page takes them
+@property (nonatomic, copy) NSArray<NSString *> *texts;
+@property (nonatomic) BOOL synced;
+@end
+
+@implementation SGLRCSheet
+@end
+
+static NSString *trimmed(NSString *text) {
+ return [text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
+}
+
+// [01:02], [01:02.3], [01:02.34], [01:02.345], [101:02:34]: minutes of one to three digits, and a ":"
+// before the fraction as some editors write it. A line sung more than once carries a stamp per time.
+static SGLRCSheet *sheetFrom(NSString *lrc) {
+ static NSRegularExpression *stamp, *tag;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ stamp = [NSRegularExpression regularExpressionWithPattern:@"\\[(\\d{1,3}):(\\d{1,2})(?:[.:](\\d{1,3}))?\\]" options:0 error:nil];
+ tag = [NSRegularExpression regularExpressionWithPattern:@"^\\[(ti|ar|offset)\\s*:([^\\]]*)\\]" options:NSRegularExpressionCaseInsensitive error:nil];
+ });
+ SGLRCSheet *sheet = [SGLRCSheet new];
+ NSInteger offset = 0;
+ NSMutableArray<NSArray *> *stamped = [NSMutableArray array]; // [ms, text]
+ NSMutableArray<NSString *> *plain = [NSMutableArray array];
+ for (NSString *raw in [lrc componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) {
+ NSString *row = trimmed([raw stringByReplacingOccurrencesOfString:@"" withString:@""]);
+ NSTextCheckingResult *named = [tag firstMatchInString:row options:0 range:NSMakeRange(0, row.length)];
+ if (named) {
+ NSString *which = [row substringWithRange:[named rangeAtIndex:1]].lowercaseString;
+ NSString *value = trimmed([row substringWithRange:[named rangeAtIndex:2]]);
+ if ([which isEqualToString:@"ti"] && value.length) sheet.title = value;
+ else if ([which isEqualToString:@"ar"] && value.length) sheet.artist = value;
+ else if ([which isEqualToString:@"offset"]) offset = value.integerValue; // "+250" and "-250" both read
+ continue;
+ }
+ NSArray<NSTextCheckingResult *> *found = [stamp matchesInString:row options:0 range:NSMakeRange(0, row.length)];
+ if (!found.count) {
+ if (row.length && ![row hasPrefix:@"["]) [plain addObject:row];
+ continue;
+ }
+ NSString *text = trimmed([stamp stringByReplacingMatchesInString:row options:0 range:NSMakeRange(0, row.length) withTemplate:@""]);
+ if (!text.length) continue;
+ for (NSTextCheckingResult *match in found) {
+ NSInteger minutes = [row substringWithRange:[match rangeAtIndex:1]].integerValue;
+ NSInteger seconds = [row substringWithRange:[match rangeAtIndex:2]].integerValue;
+ NSInteger fraction = 0;
+ NSRange part = [match rangeAtIndex:3];
+ if (part.location != NSNotFound) {
+ NSString *digits = [row substringWithRange:part];
+ fraction = digits.integerValue * (digits.length == 1 ? 100 : digits.length == 2 ? 10 : 1);
+ }
+ [stamped addObject:@[@((minutes * 60 + seconds) * 1000 + fraction), text]];
+ }
+ }
+ if (stamped.count) {
+ [stamped sortWithOptions:NSSortStable usingComparator:^NSComparisonResult(NSArray *a, NSArray *b) {
+ return [a[0] compare:b[0]];
+ }];
+ NSMutableArray<NSNumber *> *starts = [NSMutableArray array];
+ NSMutableArray<NSString *> *texts = [NSMutableArray array];
+ // A positive offset brings the lyrics in sooner.
+ for (NSArray *line in stamped) {
+ [starts addObject:@(MAX([line[0] integerValue] - offset, 0))];
+ [texts addObject:line[1]];
+ }
+ sheet.lines = SGKaraokeEstimatedLines(starts, texts);
+ sheet.synced = YES;
+ NSArray<NSNumber *> *pageStarts;
+ NSArray<NSString *> *pageTexts;
+ SGLyricsPageLines(sheet.lines, &pageStarts, &pageTexts);
+ sheet.starts = pageStarts;
+ sheet.texts = pageTexts;
+ } else if (plain.count) {
+ sheet.lines = SGKaraokeStaticLines(plain);
+ NSMutableArray<NSNumber *> *zeros = [NSMutableArray array];
+ for (NSUInteger i = 0; i < plain.count; i++) [zeros addObject:@0];
+ sheet.starts = zeros;
+ sheet.texts = plain;
+ }
+ return sheet;
+}
+
+// Read once each; an import or a delete starts over.
+static NSMutableDictionary<NSString *, SGLRCSheet *> *sg_sheets;
+
+static SGLRCSheet *sheetNamed(NSString *name) {
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{ sg_sheets = [NSMutableDictionary dictionary]; });
+ @synchronized (sg_sheets) {
+ SGLRCSheet *kept = sg_sheets[name];
+ if (kept) return kept;
+ }
+ NSString *text = [NSString stringWithContentsOfFile:[directory() stringByAppendingPathComponent:name] encoding:NSUTF8StringEncoding error:nil];
+ SGLRCSheet *sheet = text ? sheetFrom(text) : nil;
+ if (!sheet) return nil;
+ @synchronized (sg_sheets) { sg_sheets[name] = sheet; }
+ return sheet;
+}
+
+static void forgetSheets(void) {
+ if (!sg_sheets) return;
+ @synchronized (sg_sheets) { [sg_sheets removeAllObjects]; }
+}
+
+#pragma mark - matching
+
+// Case, diacritics and width ignored, and anything but letters and digits: "Beyoncé – Halo (Live)"
+// and "beyonce halo live" fold the same.
+static NSString *folded(NSString *text) {
+ if (![text isKindOfClass:NSString.class]) return @"";
+ NSString *plain = [text stringByFoldingWithOptions:NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch locale:nil].lowercaseString;
+ return [[plain componentsSeparatedByCharactersInSet:NSCharacterSet.alphanumericCharacterSet.invertedSet] componentsJoinedByString:@""];
+}
+
+static NSString *nonEmpty(id value) {
+ return [value isKindOfClass:NSString.class] && [value length] ? value : nil;
+}
+
+// A file named "Artist - Title" or "Title - Artist" (a hyphen, en dash or em dash between spaces) with no
+// [ti:]: the side equal to the track's title is the title and the other the artist.
+static BOOL sheetMatches(SGLRCSheet *sheet, NSString *name, NSString *title, NSArray<NSString *> *artists) {
+ NSString *wanted = folded(title);
+ if (!wanted.length) return NO;
+ NSString *fileTitle = sheet.title, *fileArtist = sheet.artist;
+ if (!fileTitle) {
+ NSString *base = name.stringByDeletingPathExtension;
+ fileTitle = base;
+ for (NSString *dash in @[@" - ", @" – ", @" — "]) {
+ NSRange split = [base rangeOfString:dash];
+ if (split.location == NSNotFound) continue;
+ NSString *left = [base substringToIndex:split.location], *right = [base substringFromIndex:NSMaxRange(split)];
+ if ([folded(right) isEqualToString:wanted]) {
+ fileTitle = right;
+ fileArtist = fileArtist ?: left;
+ } else if ([folded(left) isEqualToString:wanted]) {
+ fileTitle = left;
+ fileArtist = fileArtist ?: right;
+ }
+ break;
+ }
+ }
+ if (![folded(fileTitle) isEqualToString:wanted]) return NO;
+ if (!fileArtist.length) return YES;
+ NSString *artist = folded(fileArtist);
+ for (NSString *one in artists) {
+ if ([folded(one) isEqualToString:artist]) return YES;
+ }
+ return NO;
+}
+
+// What a local file is called when no names were given: the player's track model, the tags its metadata
+// may carry under other keys when the model's are empty, and last the parts of its URI.
+static void localNames(NSString *trackID, NSString **title, NSMutableArray<NSString *> *artists) {
+ SPTPlayerTrack *track = SGKaraokeTrackFor(trackID);
+ NSDictionary *metadata = [track.metadata isKindOfClass:NSDictionary.class] ? track.metadata : nil;
+ NSString *named = nonEmpty(track.trackTitle);
+ for (NSString *key in @[@"track_title", @"title", @"name"]) named = named ?: nonEmpty(metadata[key]);
+ *title = named ?: SGLocalFileInfo(trackID)[@"title"];
+
+ NSString *artist = nonEmpty(track.artistName);
+ for (NSString *key in @[@"artist_name", @"artist"]) artist = artist ?: nonEmpty(metadata[key]);
+ if (artist) [artists addObject:artist];
+ id listed = metadata[@"artists"];
+ for (id one in [listed isKindOfClass:NSArray.class] ? listed : @[]) {
+ NSString *each = nonEmpty(one) ?: ([one isKindOfClass:NSDictionary.class] ? nonEmpty(one[@"name"]) : nil);
+ if (each) [artists addObject:each];
+ }
+ for (NSUInteger i = 1; nonEmpty(metadata[[NSString stringWithFormat:@"artist_name:%lu", (unsigned long)i]]); i++) {
+ [artists addObject:metadata[[NSString stringWithFormat:@"artist_name:%lu", (unsigned long)i]]];
+ }
+ NSString *tagged = SGLocalFileInfo(trackID)[@"artist"];
+ if (!artists.count && tagged) [artists addObject:tagged];
+}
+
+static SGLyricsResult *resultOf(SGLRCSheet *sheet, NSString *title, NSString *artist) {
+ if (!sheet.lines.count) return nil;
+ SGLyricsResult *result = [SGLyricsResult new];
+ result.provider = kCredit;
+ result.synced = sheet.synced;
+ result.karaokeLines = sheet.lines;
+ result.starts = sheet.starts;
+ result.texts = sheet.texts;
+ result.title = sheet.title ?: title;
+ result.artist = sheet.artist ?: artist;
+ return result;
+}
+
+SGLyricsResult *SGImportedLRCFor(NSString *trackID, NSString *title, NSString *artist) {
+ NSString *linked = SGImportedLRCLinkedTo(trackID);
+ NSMutableArray<NSString *> *artists = [NSMutableArray array];
+ if (SGLocalFileIs(trackID) && !title.length) localNames(trackID, &title, artists);
+ else if (artist.length) [artists addObject:artist];
+ if (linked) return resultOf(sheetNamed(linked), title, artists.firstObject);
+ for (NSString *name in SGImportedLRCFiles()) {
+ SGLRCSheet *sheet = sheetNamed(name);
+ if (sheet.lines.count && sheetMatches(sheet, name, title, artists)) return resultOf(sheet, nil, nil);
+ }
+ return nil;
+}
+
+SGLyricsAsk SGImportedLRCAsk = ^(SGLyricsQuery *query, void (^done)(SGLyricsResult *result)) {
+ done(SGImportedLRCFor(query.trackID, query.title, query.artist));
+};
+
+#pragma mark - importing and deleting
+
+static NSError *refusal(NSString *reason) {
+ return [NSError errorWithDomain:kErrorDomain code:1 userInfo:@{NSLocalizedDescriptionKey: reason}];
+}
+
+// Once LyricsSources lists the source, the first import and every link put it first in the order.
+static void moveToTop(void) {
+ if (!SGLyricsProviderFor(SGImportedLRCKey)) return;
+ NSMutableArray<NSString *> *order = [SGLyricsOrder() mutableCopy];
+ [order removeObject:SGImportedLRCKey];
+ [order insertObject:SGImportedLRCKey atIndex:0];
+ SGLyricsSetOrder(order);
+}
+
+static void changed(void) {
+ forgetSheets();
+ [NSNotificationCenter.defaultCenter postNotificationName:SGImportedLRCDidChangeNotification object:nil];
+}
+
+// The name it came with, "/" made safe, and " (2)", " (3)" and on when one by that name is kept.
+static NSString *freeName(NSString *given) {
+ NSString *name = [given stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
+ NSString *base = name.stringByDeletingPathExtension, *extension = name.pathExtension;
+ if (!base.length || [base hasPrefix:@"."]) base = [@"Lyrics" stringByAppendingString:base];
+ name = [base stringByAppendingPathExtension:extension];
+ for (NSUInteger n = 2; [NSFileManager.defaultManager fileExistsAtPath:[directory() stringByAppendingPathComponent:name]]; n++) {
+ name = [[NSString stringWithFormat:@"%@ (%lu)", base, (unsigned long)n] stringByAppendingPathExtension:extension];
+ }
+ return name;
+}
+
+NSString *SGImportLRC(NSURL *url, NSString *uri, NSError **error) {
+ BOOL scoped = [url startAccessingSecurityScopedResource];
+ NSError *readError = nil;
+ NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&readError];
+ if (scoped) [url stopAccessingSecurityScopedResource];
+ NSString *reason = nil, *text = nil;
+ if (!data) reason = readError.localizedDescription ?: @"The file could not be read.";
+ else if (!data.length) reason = @"The file is empty.";
+ else if (data.length > kMostBytes) reason = @"The file is over 1 MB, too large for lyrics.";
+ else {
+ text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]
+ ?: [[NSString alloc] initWithData:data encoding:NSUTF16StringEncoding];
+ if (!text) reason = @"The file is not UTF-8 or UTF-16 text.";
+ else if (![text containsString:@"]"]) reason = @"The file has no LRC tags or timestamps.";
+ }
+ if (reason) {
+ if (error) *error = refusal(reason);
+ return nil;
+ }
+ BOOL first = SGImportedLRCFiles().count == 0;
+ NSString *name = freeName(url.lastPathComponent);
+ NSError *writeError = nil;
+ [NSFileManager.defaultManager createDirectoryAtPath:directory() withIntermediateDirectories:YES attributes:nil error:&writeError];
+ if (![text writeToFile:[directory() stringByAppendingPathComponent:name] atomically:YES encoding:NSUTF8StringEncoding error:&writeError]) {
+ SGLog(@"lrc: %@ not written: %@", name, writeError);
+ if (error) *error = writeError;
+ return nil;
+ }
+ NSString *bare = bareURI(uri);
+ if (bare) {
+ NSMutableDictionary *links = [allLinks() mutableCopy];
+ links[bare] = name;
+ storeLinks(links);
+ }
+ if (first || bare) moveToTop();
+ SGLog(@"lrc: imported %@%@", name, bare ? [@" for " stringByAppendingString:bare] : @"");
+ changed();
+ return name;
+}
+
+BOOL SGDeleteImportedLRC(NSString *name) {
+ if (!name.length || name.pathComponents.count != 1) return NO;
+ NSError *error = nil;
+ if (![NSFileManager.defaultManager removeItemAtPath:[directory() stringByAppendingPathComponent:name] error:&error]) {
+ SGLog(@"lrc: %@ not deleted: %@", name, error);
+ return NO;
+ }
+ NSMutableDictionary *links = [allLinks() mutableCopy];
+ [links removeObjectsForKeys:[links allKeysForObject:name]];
+ storeLinks(links);
+ changed();
+ return YES;
+}
diff --git a/tweak/Sources/Shared/LocalFiles/LocalLyricsPage.m b/tweak/Sources/Shared/LocalFiles/LocalLyricsPage.m
new file mode 100644
index 00000000..3d308102
--- /dev/null
+++ b/tweak/Sources/Shared/LocalFiles/LocalLyricsPage.m
@@ -0,0 +1,178 @@
+// Imported LRC files, on the Lyrics page beside the sources: the files kept (a swipe deletes one), Import
+// for current track…, which links the file to the local file playing, and Import LRC…, matched by title
+// and artist. Both open Files and copy the file in.
+#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
+#import "Core/SGCore.h"
+#import "Settings/SGPage.h"
+#import "Settings/SGPageStyle.h"
+#import "Shared/Player/PlayerState.h"
+#import "LocalFiles.h"
+#import "LocalLyrics.h"
+
+typedef NS_ENUM(NSInteger, SGLRCImportRow) {
+ SGLRCImportForTrack,
+ SGLRCImportByName,
+ SGLRCImportRowCount,
+};
+
+static void showAlert(UIViewController *owner, NSString *title, NSString *message) {
+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
+ [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]];
+ [owner presentViewController:alert animated:YES completion:nil];
+}
+
+// The local file playing, nil for anything else.
+static NSString *playingLocalFile(void) {
+ NSString *uri = SGURIString(SGPlayerState().track.URI);
+ return SGLocalFileIs(uri) ? uri : nil;
+}
+
+@interface SGImportedLRCFilesPage : SGPage <UIDocumentPickerDelegate>
+@end
+
+@implementation SGImportedLRCFilesPage {
+ NSArray<NSString *> *_files;
+ UIView *_footer;
+ // The local file playing when Files opened for Import for current track, nil for Import LRC….
+ NSString *_linkTo;
+}
+
+- (instancetype)init {
+ if (!(self = [super initWithStyle:UITableViewStyleInsetGrouped])) return nil;
+ self.title = @"Imported LRC files";
+ return self;
+}
+
+- (void)viewDidLoad {
+ [super viewDidLoad];
+ _footer = SGNote(@"Import for current track links the file to the local file playing, whatever its tags say. "
+ "Import LRC… keeps a file for any track whose title and artist match its [ti:] and [ar:] tags, "
+ "or its name as \"Artist - Title\". Swipe left on a file to delete it.");
+ self.tableView.tableFooterView = _footer;
+}
+
+- (void)viewWillLayoutSubviews {
+ [super viewWillLayoutSubviews];
+ SGFitNote(self.tableView, _footer, 16, 24);
+}
+
+- (void)viewDidLayoutSubviews {
+ [super viewDidLayoutSubviews];
+ SGInsetForBars(self.tableView);
+}
+
+- (void)viewWillAppear:(BOOL)animated {
+ [super viewWillAppear:animated];
+ _files = SGImportedLRCFiles();
+ [self.tableView reloadData];
+}
+
+- (NSInteger)numberOfSectionsInTableView:(UITableView *)table {
+ return 2;
+}
+
+- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
+ return section == 0 ? MAX((NSInteger)_files.count, 1) : SGLRCImportRowCount;
+}
+
+- (UIView *)tableView:(UITableView *)table viewForHeaderInSection:(NSInteger)section {
+ return section == 0 ? SGSectionHeader(table, @"Files") : nil;
+}
+
+- (CGFloat)tableView:(UITableView *)table heightForHeaderInSection:(NSInteger)section {
+ return section == 0 ? SGSectionHeaderHeight : SGSectionGap;
+}
+
+- (UIView *)tableView:(UITableView *)table viewForFooterInSection:(NSInteger)section {
+ return nil;
+}
+
+- (CGFloat)tableView:(UITableView *)table heightForFooterInSection:(NSInteger)section {
+ return CGFLOAT_MIN;
+}
+
+- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
+ if (path.section == 1) {
+ UITableViewCell *cell = SGDequeueCell(table, @"import");
+ if (path.row == SGLRCImportByName) {
+ SGFillCell(cell, @"Import LRC…", @"Matched by title and artist", nil, @"square.and.arrow.down");
+ } else {
+ NSString *uri = playingLocalFile();
+ NSString *title = SGLocalFileInfo(uri)[@"title"] ?: @"The local file playing";
+ SGFillCell(cell, @"Import for current track…", uri ? title : @"Start playing a local track first",
+ uri ? nil : SGGrey(), @"music.note");
+ }
+ BOOL enabled = path.row == SGLRCImportByName || playingLocalFile();
+ cell.selectionStyle = enabled ? UITableViewCellSelectionStyleDefault : UITableViewCellSelectionStyleNone;
+ cell.accessibilityTraits = enabled ? UIAccessibilityTraitButton : UIAccessibilityTraitButton | UIAccessibilityTraitNotEnabled;
+ return cell;
+ }
+ UITableViewCell *cell = SGDequeueCell(table, @"file");
+ if (!_files.count) {
+ SGFillCell(cell, @"No imported files", nil, SGGrey(), nil);
+ return cell;
+ }
+ SGFillCell(cell, _files[(NSUInteger)path.row], nil, nil, nil);
+ return cell;
+}
+
+- (BOOL)tableView:(UITableView *)table shouldHighlightRowAtIndexPath:(NSIndexPath *)path {
+ return path.section == 1 && (path.row == SGLRCImportByName || playingLocalFile());
+}
+
+- (void)tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
+ [table deselectRowAtIndexPath:path animated:YES];
+ if (path.section != 1) return;
+ _linkTo = path.row == SGLRCImportForTrack ? playingLocalFile() : nil;
+ if (path.row == SGLRCImportForTrack && !_linkTo) return;
+ // .lrc is nobody's registered type, so Files offers any file and the name is checked after.
+ UIDocumentPickerViewController *picker = [[UIDocumentPickerViewController alloc] initForOpeningContentTypes:@[UTTypeData] asCopy:YES];
+ picker.delegate = self;
+ [self presentViewController:picker animated:YES completion:nil];
+}
+
+- (UISwipeActionsConfiguration *)tableView:(UITableView *)table trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)path {
+ if (path.section != 0 || !_files.count) return nil;
+ NSString *name = _files[(NSUInteger)path.row];
+ UIContextualAction *delete = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"Delete"
+ handler:^(UIContextualAction *action, UIView *view, void (^done)(BOOL)) {
+ BOOL deleted = SGDeleteImportedLRC(name);
+ if (deleted) [self reloadFiles];
+ else showAlert(self, @"Could not delete the file", nil);
+ done(deleted);
+ }];
+ delete.image = [UIImage systemImageNamed:@"trash"];
+ return [UISwipeActionsConfiguration configurationWithActions:@[delete]];
+}
+
+- (void)reloadFiles {
+ _files = SGImportedLRCFiles();
+ [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
+}
+
+- (void)documentPicker:(UIDocumentPickerViewController *)picker didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
+ NSURL *url = urls.firstObject;
+ if (!url) return;
+ if (![url.pathExtension.lowercaseString isEqualToString:@"lrc"]) {
+ showAlert(self, @"Not an LRC file", @"Pick a file whose name ends in .lrc.");
+ return;
+ }
+ NSError *error = nil;
+ NSString *name = SGImportLRC(url, _linkTo, &error);
+ if (!name) {
+ showAlert(self, @"Could not import the file", error.localizedDescription);
+ return;
+ }
+ [self reloadFiles];
+ if (_linkTo) {
+ NSString *title = SGLocalFileInfo(_linkTo)[@"title"];
+ showAlert(self, @"Lyrics linked", [NSString stringWithFormat:@"%@ now gives the lyrics for %@.", name,
+ title ? [NSString stringWithFormat:@"\"%@\"", title] : @"this local file"]);
+ }
+}
+
+@end
+
+UIViewController *SGImportedLRCPage(void) {
+ return [SGImportedLRCFilesPage new];
+}
diff --git a/tweak/Sources/Shared/Lyrics/KaraokeSource.x b/tweak/Sources/Shared/Lyrics/KaraokeSource.x
index 94593cd4..d794bc15 100644
--- a/tweak/Sources/Shared/Lyrics/KaraokeSource.x
+++ b/tweak/Sources/Shared/Lyrics/KaraokeSource.x
@@ -7,6 +7,7 @@
#import "Core/SGCore.h"
#import "Lyrics.h"
#import "Shared/LocalFiles/LocalFiles.h"
+#import "Shared/LocalFiles/LocalLyrics.h"
#import "Shared/LockScreenLyrics/LockScreenLyrics.h"
#import "Shared/AnimatedArtwork/AnimatedArtwork.h"
#import "Shared/LyricsSources/LyricsSources.h"
@@ -273,8 +274,15 @@ static BOOL askLrcLib(NSString *trackID, void (^done)(SGLyricsResult *lyrics)) {
// Main queue only.
void SGKaraokeRequestLyrics(NSString *trackID) {
if (!trackID || sg_lyrics[trackID] || [sg_requested containsObject:trackID]) return;
- // spclient has nothing for a local file, which only the sources can name.
+ // spclient has nothing for a local file, which only the sources can name. A file of the user's own,
+ // linked to it or matching its names, comes before every source.
BOOL local = SGLocalFileIs(trackID);
+ SGLyricsResult *imported = local ? SGImportedLRCFor(trackID, nil, nil) : nil;
+ if (imported) {
+ keep(trackID, imported.karaokeLines);
+ SGLyricsSetCredit(trackID, imported.provider);
+ return;
+ }
if (!sg_ownSources && !local) {
requestFromSpotify(trackID);
return;
@@ -471,6 +479,22 @@ static void prefetch(SPTPlayerTrack *track, NSString *trackID, SPTPlayerState *s
NSString *key = SGLocalFileLyricsKey(note.object);
if (key && [key isEqualToString:SGKaraokePlayingTrack()]) SGKaraokeRequestLyrics(key);
}];
+ // An imported or deleted LRC file can change any local file's lyrics, found or missed: they are
+ // forgotten, but for a look still out, and the file playing is asked for again.
+ [NSNotificationCenter.defaultCenter addObserverForName:SGImportedLRCDidChangeNotification object:nil queue:nil
+ usingBlock:^(NSNotification *note) {
+ for (NSString *track in [sg_requested setByAddingObjectsFromArray:sg_lyrics.allKeys]) {
+ if (!SGLocalFileIs(track) || [sg_looking containsObject:track]) continue;
+ [sg_lyrics removeObjectForKey:track];
+ [sg_requested removeObject:track];
+ [sg_asking removeObject:track];
+ [sg_losses removeObjectForKey:track];
+ }
+ NSString *playing = SGKaraokePlayingTrack();
+ if (!SGLocalFileIs(playing)) return;
+ SGKaraokeRequestLyrics(playing);
+ announce(playing);
+ }];
%init;
SGLog(@"karaoke: on");
SGRequireClasses(@[
diff --git a/tweak/Sources/Shared/Lyrics/LyricsSettings.m b/tweak/Sources/Shared/Lyrics/LyricsSettings.m
index fd9d5acb..f8adffe6 100644
--- a/tweak/Sources/Shared/Lyrics/LyricsSettings.m
+++ b/tweak/Sources/Shared/Lyrics/LyricsSettings.m
@@ -2,6 +2,7 @@
#import "Core/SGCore.h"
#import "Settings/SGModPage.h"
#import "Lyrics.h"
+#import "Shared/LocalFiles/LocalLyrics.h"
#import "Shared/LockScreenLyrics/LockScreenLyrics.h"
#import "Shared/LyricsSources/LyricsSources.h"
@@ -12,7 +13,12 @@ SGModSection *SGLyricsSourcesSection(BOOL namingSource) {
for (NSString *key in SGLyricsOrder()) [names addObject:SGLyricsProviderFor(key).name];
return names.count ? [names componentsJoinedByString:@", "] : @"Off";
};
- NSMutableArray<SGModRow *> *rows = [NSMutableArray arrayWithObjects:sources,
+ SGModRow *imported = SGPageRow(@"Imported LRC files", ^UIViewController *{ return SGImportedLRCPage(); });
+ imported.value = ^NSString *{
+ NSUInteger count = SGImportedLRCFiles().count;
+ return count ? @(count).stringValue : @"None";
+ };
+ NSMutableArray<SGModRow *> *rows = [NSMutableArray arrayWithObjects:sources, imported,
SGOptionRow(@"Lyrics for every track", @"Even where Spotify has none", SGKeyLyricsAllTracks), SGSpicyLyricsKeyRow(), nil];
if (namingSource) [rows addObject:SGOptionRow(@"Show source", nil, SGKeyLyricsCredit)];
return SGSection(@"Sources", rows);
diff --git a/tweak/Sources/Shared/LyricsSources/LyricsSources.m b/tweak/Sources/Shared/LyricsSources/LyricsSources.m
index cb3e8a3a..bec08b8e 100644
--- a/tweak/Sources/Shared/LyricsSources/LyricsSources.m
+++ b/tweak/Sources/Shared/LyricsSources/LyricsSources.m
@@ -11,6 +11,7 @@
#import "LyricsSources.h"
#import "Shared/Lyrics/Lyrics.h"
#import "Shared/LocalFiles/LocalFiles.h"
+#import "Shared/LocalFiles/LocalLyrics.h"
#import "Headers/SPTPlayer.h"
#import <stdatomic.h>
@@ -162,6 +163,7 @@ NSArray<SGLyricsProvider *> *SGLyricsAllProviders(void) {
make(SGSpicyLyricsKey, @"Spicy Lyrics", @"Community word syncs, your own key", SGSpicyLyricsAsk),
make(@"qqmusic", @"QQ Music", @"Line timing, Chinese catalogue", SGQQMusicAsk),
make(@"kugou", @"KuGou", @"Word timing, Chinese catalogue", SGKuGouAsk),
+ make(SGImportedLRCKey, @"Imported LRC", @"Your own .lrc files", SGImportedLRCAsk),
];
});
return all;